I've got a Dialogflow agent for which I'm using the Inline Editor (powered by Cloud Functions for Firebase). When I try to get external api data by using request-promise-native I keep getting Ignoring exception from a finished function in my firebase console.
function video(agent) {
agent.add(`You are now being handled by the productivity intent`);
const url = "https://reqres.in/api/users?page=2";
return request.get(url)
.then(jsonBody => {
var body = JSON.parse(jsonBody);
agent.add(body.data[0].first_name)
return Promise.resolve(agent);
});
}
Your code looks correct. The exception in this case might be that you're not using a paid account, so network access outside Google is blocked. You can probably see the exact exception by adding a catch block:
function video(agent) {
agent.add(`You are now being handled by the productivity intent`);
const url = "https://reqres.in/api/users?page=2";
return request.get(url)
.then(jsonBody => {
var body = JSON.parse(jsonBody);
agent.add(body.data[0].first_name)
return Promise.resolve(agent);
})
.catch(err => {
console.error('Problem making network call', err);
agent.add('Unable to get result');
return Promise.resolve(agent);
});
}
(If you do this, you may want to update your question with the exact error from the logs.)
Inline Editor uses Firebase. If you do not have a paid account with Firebase, you will not be able to access external APIs.
Related
While developing a client application that uses its own styling, but also IBM Watson Assistant under the hood, problems have been discovered when the webhook's time is exceeded. The composition is as follows: a client app sends a request to Watson Assistant, from there the Assistant triggers a webhook, which after that triggers an IBM Cloud Function.
Following this link, a man can see that in one of the FAQs is stated, that the time limit (8 seconds) can not be extended. Does it include also the case when a call is made to a IBM Cloud Function?
Update:
async function main(){
try {
const orders = await db.getOrders();
if(orders.quantity > 0){
return {data: 'there are some orders'};
} else {
return {data: 'there are no orders'};
}
} catch(err) {
return {error: err.message};
}
}
Apologies if you are already doing this, but why not return a promise from your cloud function. That way the return is almost immediate falling within your 8 seconds, but the processing would become asynchronous.
eg.
function main (args) {
return new Promise((resolve, reject) => {
...
});
}
This is correct the 8 seconds limit is still in effect. It will most likely change in the future
I've been trying to listen to Stripe webhooks with firebase functions.
here is my code:
exports.stripeEvents = functions.https.onRequest((request, response) =>
{
try
{
const stripesignature = request.headers['stripe-signature'] as string;
let stripeevent:Stripe.Event;
try
{
stripeevent = stripe.webhooks.constructEvent(request.rawBody, stripesignature, config.stripewebhooksecretkey);
}
catch (error)
{
sentry.captureException(error);
response.status(400).end();
return;
}
response.sendStatus(200);
}
catch(error)
{
sentry.captureException(error);
throw error;
}
});
and I keep getting this error:
No signatures found matching the expected signature for payload.
Are you passing the raw request body you received from Stripe? https://github.com/stripe/stripe-node#webhook-signing
I have tried changing request.rawBody to request.rawBody.toString() but of no avail. The same firebase function works perfectly when I do a test webhook run from the stripe website.
What could I be missing?
Stripe official documentation on how to do it: https://stripe.com/docs/webhooks/signatures
This may not be an immediate solution, but here are a few suggestions to try:
Check whether changing const stripesignature to a variable produces different behaviour
Log the values of all 3 inputs immediately before that line, then inspect to determine if they are as anticipated (or a substring of each instead, for the more security-minded)
See if you can narrow it down to which input is causing the issue (e.g. request.rawBody, or stripesignature).
On the other hand, although an incorrect webhook secret would be expected to produce a different error, there may be little harm checking it is propagating correctly from config and matching the one in the configured endpoint setting in the dashboard.
Dart function (passing token to sendToDevice):
Future<void> _sendNotification() async {
CloudFunctions functions = CloudFunctions.instance;
HttpsCallable callable = functions.getHttpsCallable(functionName: "sendToDevice");
callable.call({
'token': await FirebaseMessaging().getToken(),
});
}
index.ts file where I have defined sendToDevice method.
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp();
const fcm = admin.messaging();
export const sendToDevice = functions.firestore
.document('users/uid')
.onCreate(async snapshot => {
const payload: admin.messaging.MessagingPayload = {
notification: {
title: 'Dummy title',
body: `Dummy body`,
click_action: 'FLUTTER_NOTIFICATION_CLICK'
}
};
return fcm.sendToDevice(tokens, payload); // how to get tokens here passed from above function?
}
);
Questions:
How can I receive tokens passed from my Dart function _sendNotification to Typescript's sendToDevice function.
When I was directly passing tokens inside index.ts file, I was getting this exception:
[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(functionsError, Cloud function failed with exception., {code: UNAUTHENTICATED, details: null, message: UNAUTHENTICATED})
Can anyone please explain if I am supposed to authenticate something here? The command firebase login shows I am already signed in. I am very new to Typescript so please bear with these stupid questions.
Your Flutter side of code seems right, what's wrong is on the Cloud Function.
The sendToDevice function is not a callable function. It is a Cloud Firestore Triggers, it is only meant to be automatically called whenever a document matches users/{uid} is created.
Instead, you'll want to create a Callable Function, see below
export const sendToDevice = functions.https
.onCall(async (data) => {
const { token } = data; // Data is what you'd send from callable.call
const payload: admin.messaging.MessagingPayload = {
notification: {
title: 'Dummy title',
body: `Dummy body`,
click_action: 'FLUTTER_NOTIFICATION_CLICK'
}
};
return fcm.sendToDevice(token, payload);
}
);
You have created a database trigger, what you should do is create a callable function as shown below
exports.sendToDevice = functions.https.onCall(async (data, context) => {
const payload: admin.messaging.MessagingPayload = {
notification: {
title: 'Dummy title',
body: `Dummy body`,
click_action: 'FLUTTER_NOTIFICATION_CLICK'
}
};
return await fcm.sendToDevice(data.token, payload);
});
There are few things to mention here:
1st The function used in 'getHttpsCallable' must be triggered by https trigger (reference here). Here we have a function triggered by firestore document create, so it won't work.
2nd You do not have parameter of your function, but you call it with parameters. If you need example of calling cloud function with parameter you can find it on pud.dev
3rd I do not have at the moment possibility to play with it, but I think that if you implement https triggered function with token parameter you should be able to pass this parameter.
I hope it will help!
UPDATE:
According to doc https triggered function has to be created with functions.https. There is a nice example in the doc. To function triggered this way you can add request body when you can pass needed data.
This answer might not solve your problem but will give you a few things to try, and you'll learn along the way. Unfortunately I wasn't able to get the callable https working with the emulator. I'll probably submit a github issue about it soon. The flutter app keeps just getting different types of undecipherable errors depending on the local URL I try.
It's good that you've fixed one of the problems: you were using document trigger (onCreate) instead of a https callable. But now, you're running a https callable and the Flutter apps needs to communicate with your functions directly. In the future, you could run the functions emulator locally, and do a lot of console.log'ing to understand if it actually gets triggered.
I have a few questions/ things you can try:
Is your user logged in the flutter app? FirebaseAuth.instance.currentUser() will tell you.
Does this problem happen on both iOS and android?
Add some logs to your typescript function, and redeploy. Read the latest logs through StackDriver or in terminal, firebase functions:log --only sendToDevice. (sendToDevice is your callable function name)
Are you deploying to the cloud and testing with the latest deployment of your functions? You can actually test with a local emulator. On Android, the url is 10.0.2.2:5001 as shown above. You also need to run adb reverse tcp:5001 tcp:5001 in the terminal. If you're on the cloud, then firebase login doesn't matter, I think your functions should already have the credentials.
To call the emulator https callable:
HttpsCallable callable = CloudFunctions.instance
.useFunctionsEmulator(origin: "http://10.0.2.2:5001")
.getHttpsCallable(functionName: "sendToDevice");
And iOS you need to follow the solution here.
One mistake I spotted. You should at least do return await fcm.sendToDevice() where you wait for the promise to resolve, because otherwise the cloud function runtime will terminate your function before it resolves. Alternatively, for debugging, instead of returning sendToDevice in your cloud function, you could have saved it into a variable, and console.log'd it. You would see its actually a promise (or a Future in dart's terminology) that hadn't actually resolved.
const messagingDevicesResponse: admin.messaging.MessagingDevicesResponse = await fcm.sendToDevice(
token,
payload
);
console.log({ messagingDevicesResponse });
return;
Make the function public
The problem is asociated with credentials. You can change the security policy of the CF and sheck if the problem is fixed. Se how to manage permisions on CF here
I'm walking through the Javascript demos of pg-promise-demo and I have a question about the route /api/users/:name.
Running this locally works, the user is entered into the database, but is there a reason this wouldn't be a POST? Is there some sort of advantage to creating a user in the database using GET?
// index.js
// --------
app.get('/api/users/:name', async (req, res) => {
try {
const data = (req) => {
return db.task('add-user', async (t) => {
const user = await t.users.findByName(req.params.name);
return user || t.users.add(req.params.name);
});
};
} catch (err) {
// do something with error
}
});
For brevity I'll omit the code for t.users.findByName(name) and t.users.add(name) but they use QueryFile to execute a SQL command.
EDIT: Update link to pg-promise-demo.
The reason is explained right at the top of that file:
IMPORTANT:
Do not re-use the HTTP-service part of the code from here!
It is an over-simplified HTTP service with just GET handlers, because:
This demo is to be tested by typing URL-s manually in the browser;
The focus here is on a proper database layer only, not an HTTP service.
I think it is pretty clear that you are not supposed to follow the HTTP implementation of the demo, rather its database layer only. The demo's purpose is to teach you how to organize a database layer in a large application, and not how to develop HTTP services.
I'm trying to get a print out of the events my cloud function is privy to. I tried console.log(event)in the Atom console but I get this error:
Uncaught Error: Cannot find module 'firebase-functions'
at Module._resolveFilename (module.js:455:15)
at Module._resolveFilename
I'm not familiar with Javascript or Atom, so I don't know why I'm not getting the expected behaviors, my guess is that I need to authorize the script that is trying to access my secure backend on Firebase.
Here's my cloud function so far:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendPushNotification = functions.database.ref('/
iMessenger/{Messages}/{id}').onWrite(event => {
//I really want to see all that's inside of 'event'. How do I see this info??
console.log(event)
const payload = {
notification: {
title:'New message arrived',
body:'Hello World',
badge:'1',
sound:'default',
}
};
return admin.database().ref('/iMessenger/{Messages}/{id}/toUserDisplayName').once('value').then(allToken => {
if (allToken.val()){
const token = Object.keys(allToken.val());
return admin.messaging().sendToDevice(token, payload).then(response => {
});
};
});
});
using console.dir(event) will list every available method and parameter within event
Console.log(event) shows up in your cloud function logs in firebase. And the missing module was because my editor couldn’t exactly interface with the firebase modules I figure, as firebase accepts my functions and the notification are coming through; a testament to successful implementation.