Flutter Firebase Google Cloud functions error with .onCreate trigger to send notification to device with FCM token Type Error - flutter

I've been stuck a while now and would appreciate any help. I've never worked with Cloud Functions before and there may be a fairly easy solution here. I save the FCM token and other proper variables in my documents. The way my firestore database is organized is the following. Trips/{tripId}/proposedRides/{proposedRideId}/. The proposedRides subCollection creates a new document when a potential passenger requests to join a trip. This is where I want a notification sent to the driver via cloud functions and FCM.
I thought I could make a simple function like this. It is authenticated and setup properly to my knowledge. I added the .json credentials in an env variable and all that jazz. Here's what I've been trying:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendProposedRideNotification =
functions.region('southamerica-east1').firestore.document('proposedRides/{rideId}')
.onCreate(async(snapshot, context) => {
// Get the tripId and passengerName associated with the proposedRide
const tripData = snapshot.data();
if (!tripData.proposedByName || !tripData.proposedToDriverFCMToken) {
console.error('Required fields are missing');
return;
}
const passengerName = tripData.proposedByName;
const proposedToDriverFCMToken = tripData.proposedToDriverFCMToken;
// Send the notification to the driver's device
const payload = {
notification: {
title: 'New Proposed Ride',
body: `A new proposed ride has
been created from ${passengerName}!`
}
};
const options = {
priority: 'high',
timeToLive: 60 * 60 * 24
};
return admin.messaging().sendToDevice(proposedToDriverFCMToken, payload, options);
});
I'll then check out firebase functions:logs and get the error
Snapshot has no readTime. Using now()
and
TypeError: Cannot read properties of undefined (reading 'proposedByName')
This is strange because when I test the 'proposedByName' field is created in the document. I've tried changing the beginning of the function to
functions.region('southamerica-east1').firestore.document('trips/{tripId}/proposedRides/{rideId}')
.onCreate(async(snapshot, context) => {
but I had the same errors.

Related

how to fix UNAUTHENTICATED error while trying to create an asset report using PLAID? Plaid createAssetReport using cloud function

I'm trying to create an asset report from Plaid, I'm using Cloud Functions for these calls, all the other cloud functions work (link, transactions, balance) but assetReportCreate fails and return UNAUTHENTICATED

The Plaid logs do not show the call...so I guess something is wrong in my Cloud Function, but the Google Console Logs show status 200.
has anybody experienced the same issue and know how to fix it?
PS: just double checked today to make sure I'm authenticated and I am...
//create ASSET report
exports.createAssetReport = functions.https.onCall(async (data, context) => {
const accessToken = data.accessToken;
const daysRequested = data.daysRequested;
// const options = {
// client_report_id: '123',
// webhook: "https://www.example.com", //to let you know when report is ready, get link from cloud console
// };
const configuration = new Configuration({
basePath: PlaidEnvironments[functions.config().app.env],
baseOptions: {
headers: {
"PLAID-CLIENT-ID": functions.config().plaid.client_id,
"PLAID-SECRET": functions.config().plaid.secret,
},
},
});
const plaidClient = new PlaidApi(configuration);
//call the createLinkToken METHOD of the plaidClient instance!
return plaidClient
.assetReportCreate({
access_tokens: [accessToken],
days_requested: daysRequested,
//options,
})
.then((response) => {
const assetReportId = response.data.asset_report_id;
const assetReportToken = response.data.asset_report_token;
return assetReportToken; //token is needed to retrieve the report via //pdf/get
})
.catch((err) => {
console.log(err);
throw new functions.https.HttpsError(
"internal",
" Unable to create asset report: " + err
);
});
});
I found that for whatever reason the function wasn't open for all users to invoke, adding a principal with role: "cloud functions invoker" fixed the issue, shame on you google cloud, I spent two full days on this!! jk, thanks for your services but fix these small details and you could become the #1 cloud provider

Can't access Firestore docs data after getting the doc object

I'm trying to fetch a single field value from a doc in a collection (stored in Firestore).
The following function is called (by the triggered function) to perform this query and return the result.
Firestore data structure:
After I fetch the query result into helper_token object - I cannot access the DATA (fields) in it.
I tried many things, including:
helper_token[0].device_token;
helper_token.data().device_token;
JSON.stringify(helper_token);
Nothing works for me.
The log always shows results like these:
helper_token = {}
helper_token = undefined
What am I missing? how can I get the device_token based on user?
const admin = require('firebase-admin'); //required to access the FB RT DB
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
function getHelperToken(helperId) {
//Get token from Firestore
const tokensRef = db.collection('tokens');
const helper_token = tokensRef.where('user', '==', 'TM1EOV4lYlgEIly0cnGHVmCnybT2').get();
if (helper_token.empty) {
functions.logger.log('helper_token EMPTY');
}
functions.logger.log('helper_token=' + JSON.stringify(helper_token));
return helper_token.device_token;
};
For completeness, adding here the full calling function to the above function:
//DB triggered function - upon writing a child in the HElpersInvitations reference
exports.sendHelperInvitation = functions.database.ref('/HelpersInvitations/{helper_invitation_id}')
.onCreate((snapshot, context) => {
const helperId = snapshot.val().helperId;
const title = snapshot.val().title;
const body = snapshot.val().body;
//Get the helper token by Id
functions.logger.log('HelperID=' + helperId);
functions.logger.log('getHelperToken=' + getHelperToken(helperId));
const helper_token2 = getHelperToken(helperId);
//Notification payload
const payload = {
notification: {
title: title,
body: body,
icon: 'default',
click_action: 'com.skillblaster.app.helperinvitationnotification'
}
}
// //Send the notification
functions.logger.log('helper_token [BEFORE sendToDevice]=' + helper_token2);
return admin.messaging().sendToDevice(helper_token2, payload);
});
You need to consider that the get() call is asynchornous and also that you get a list of documents and not a single doc. Can you try it with this code:
const admin = require("firebase-admin"); //required to access the FB RT DB
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
async function getHelperToken(helperId) {
//Get token from Firestore
const tokensRef = db.collection("tokens");
const helperTokens = await tokensRef
.where("user", "==", "TM1EOV4lYlgEIly0cnGHVmCnybT2")
.get();
let helper_token = "";
helperTokens.forEach((token) => {
helper_token = token.data();
});
functions.logger.log("helper_token=" + JSON.stringify(helper_token));
return helper_token.device_token;
}
As the get() call in Firestore is asynchronous you need to use an asynchronous function. You can go through this article to know more about why Firebase APIs are asynchronous. Next when we query with the where clause in Firestore we get a list of documents even if there is only one document in the list. So we have to run a for loop to get the document inside the list of documents. Now as you are returning the value from an asynchronous function the return value will be a promise in pending state. So to get the value from the promise we need to use the then() block while calling the function.
Also I think the parameter helperId you are using in the function definition is not used anywhere in the function. Though it will not make a difference I would suggest you remove it if it is not required in the function.
So consider using the following code -
const admin = require(‘firebase-admin’);
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
async function getHelperToken() {
//Get token from Firestore
const tokensRef = db.collection(‘tokens’);
const helper_token = await tokensRef.where(‘user’, ‘==’, ‘TM1EOV4lYlgEIly0cnGHVmCnybT2’).get();
let helper_token_needed;
helper_token.forEach((token) => {
helper_token_needed = token.data();
});
console.log(helper_token_needed.device_token);
return helper_token_needed.device_token;
}
//when calling to the function use then() block to get the value as a promise is returned from asynchronous function
getHelperToken().then((value)=>{console.log(value)});

Getting Undefined value for SignIn.status during account linking

I am working on the Account Linking & set google Sign-IN in Linking type in Google.
I have created two intents, one will call the google Sign-In feature and the second one will read the data from google account for. eg. email id, name.
In Intent 1, I have enabled the webhook call for this intent.
In Intent 2, I have set Event to actions_intent_SIGN_IN & enabled the webhook call for this intent.
Though my these functions (Intents results) in Inline Editors are successfully executing, still I am getting Undefined value for SignIn.status, code is given below, please help.
'use strict';
const {dialogflow, SignIn} = require('actions-on-google');
const app = dialogflow({
clientId: "174911074867-tuffsr7ec28vg7brppr0ntkjutthfq8n.apps.googleusercontent.com",
});
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
function accountlinking(agent) {
var signin=new SignIn('To get your account details');
}
function testsignData(agent) {
console.log("status :"+SignIn.status);
}
let intentMap = new Map();
intentMap.set('Intent1', accountlinking);
intentMap.set('Intent2', testsignData);
agent.handleRequest(intentMap);
});
1). On my Action calling, it is asking for the Google Account linking first and after linking process only it is moving ahead. But I need to get into the action, have a little conversation and when required only then asking for the Linking. I need to call via my intent. How to do that?
2). Though my these functions (Intents results) are successfully executing, still I am getting Undefined value for SignIn.status
Your testSigninData() function is calling Signin.status, but you don't have any variable called SignIn in this function, so that is why it is undefined. Try changing your function so it accepts a conv, params and signin object that are given during a sign-in.
If you have a look at the account linking documentation you can see which parameters are provided during the accountlinking process.
Example accountlinking setup for Actions on Google
const {dialogflow, SignIn} = require('actions-on-google');
const app = dialogflow({
// REPLACE THE PLACEHOLDER WITH THE CLIENT_ID OF YOUR ACTIONS PROJECT
clientId: CLIENT_ID,
});
// Intent that starts the account linking flow.
app.intent('Start Signin', (conv) => {
conv.ask(new SignIn('To get your account details'));
});
// Create a Dialogflow intent with the `actions_intent_SIGN_IN` event.
app.intent('Get Signin', (conv, params, signin) => {
if (signin.status === 'OK') {
const payload = conv.user.profile.payload;
conv.ask(`I got your account details, ${payload.name}. What do you want to do next?`);
} else {
conv.ask(`I won't be able to save your data, but what do you want to do next?`);
}
});
The above code uses the actions on google dialogflow handler called app. In your code you are using the WebhookClient object to handle dialogflow intents. I'm not sure if you can use the WebhookClient for actions on google accountlinking.
If it still doesn't work after you changed the testSigninDate function parameters, it might be worth trying to remove the webhookclient and see if you can use the app.intent() calls to handle your intents just like the above code example.

Flutter Cloud Messaging: how to send notification from the app (not from firebase console)

Is it possible to send the notification from within the app instead of a cloud function on firebase?
The reason is, I want to do something similar to: FCM Push Notifications for Flutter, where they have this function that will be deployed to firebase:
export const sendToTopic = functions.firestore
.document('puppies/{puppyId}')
.onCreate(async snapshot => {
const puppy = snapshot.data();
const payload: admin.messaging.MessagingPayload = {
notification: {
title: 'New Puppy!',
body: `${puppy.name} is ready for adoption`,
icon: 'your-icon-url',
click_action: 'FLUTTER_NOTIFICATION_CLICK' // required only for onResume or onLaunch callbacks
}
};
return fcm.sendToTopic('puppies', payload);
});
this method works as intended on firebase cloud functions, however I need the path
.document('puppies/{puppyId}')
to be dynamic depending on which chatroom a user is in, so he would get a notification everytime i new message is send, so the 'chatroom22' would be a variable:
.document('chatroom22/{roomId}')
So is it possible to do this in the app-code, or can this be done in the deployed function?
In response to Doug Stevensons answer
Okay, that makes sence, and works. However, now everybody get the notifications. I want only the people in a given chatroom to receive the notification. I've tried something like this, where the users device token is saved for a given chat-room, then I want to notiffy all those tokens:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().functions);
var newData;
exports.myTrigger = functions.firestore.document('messages/{messageId}/room/{roomId}/message/{messageId2}').onCreate(async (snapshot, context) => {
//
if (snapshot.empty) {
console.log('No Devices');
return;
}
newData = snapshot.data();
const deviceIdTokens = await admin
.firestore()
.collection('messages/{messageId}/room/{roomId}/tokens/{tokenId}')
.get();
var tokens = [];
for (var token of deviceIdTokens.docs) {
tokens.push(token.data().device_token);
}
var payload = {
notification: {
title: `${newData.sender}`,
body: `${newData.message}`,
sound: 'default',
},
data: {
push_key: 'Push Key Value',
key1: newData.message,
},
};
try {
const response = await admin.messaging().sendToDevice(tokens, payload);
console.log('Notification sent successfully');
} catch (err) {
console.log(err);
}
});
But it doesnt seem to work with wildcards.. how can I get the specific destination for each chatroom?
You can use a wildcard for the collection in the path:
functions.firestore.document('{collectionId}/{documentId}')
But this will trigger for all documents in all top-level collecitons, which is probably not what you want.
In fact, using variable names for top-level collections is actually not the preferred way to model data in Firestore. Consider instead having a top-level collection for all rooms, then use subcollections to contain their messages. If you do that, then you function becomes more more clearly defined as:
functions.firestore.document('rooms/{roomId}/messages/{messageId}')
Cloud Fuctions only allows wildcards for full path segments like this. There are no other patterns or regular expressions.

How to query firestore with the Dialogflow inline editor to get information

I am using the inline editor within Dialogflow with the aim of making queries to the database I have created within Firestore.
In short, the user requests a list of courses, I'd like the chatbot to then grab that information form the db and display that back to the user.
Below I have tried to create a function that will do this, I want to take the user input, say "Art Courses" and have my db return those results.
So far, I have created a function that is triggered when the intent is matched, like so;
function getCourses(agent){
let courseRequest = agent.parameters.courseRequest;
if (getCourses){
console.log('Here is the list you requested for ${getCourses}' + parameters.courseRequest);
return admin.firestore().collection('Course_Information').doc.where('CoureTypes').get();
}
}
Are there any notable things I need to add to my function to perform what I wish to achieve?
Thank you.
UPDATE
This code deploys fine, but when I communicate with my bot and trigger the CourseEnquiry intent, cloud Functions shows this error:
admin.collection is not a function
Whilst this seems self explanatory I can't make sure of what it means, I thought declaring const admin = require('firebase-admin');enables me to use admin.collection
// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const admin = require('firebase-admin');
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function getDate(agent){
var today = new Date();
}
function welcome(agent) {
agent.add(`Welcome to my agent!`);
}
function test(agent){
agent.add("The test is successful");
}
function getCourses(agent){
// Get the database collection and document
const getCourseDoc = admin.collection('Course_Information').doc('Course_Types');
return getCourseDoc.get()
.then(doc => {
if (!doc.exists) {
agent.add('No data found in the database!');
} else {
agent.add(doc.data().entry);
}
return Promise.resolve('Here is the information you wanted');
}).catch(() => {
agent.add('Error reading entry from the Firestore database.');
});
}
function getSubmissionDateSep(agent){
agent.add('Your next submission date is for coursework 1 is');
}
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Test_Test', test);
intentMap.set('CourseEnquiry', getCourses);
intentMap.set('Submission_Dates - sept', getSubmissionDateSep);
agent.handleRequest(intentMap);
});
UPDATE #2
Hey guys, still not got anywhere with this, I have tried adding:
admin.initializeApp(functions.config().firebase);
const db = admin.firestore();
According to this document but I get this error when deploying:
The deployment of your Cloud Function failed:
Function load error: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: Error: Firebase config variables are not available. Please use the latest version of the Firebase CLI to deploy this function.
You don't show how you're responding to the user with your results, but you'll want to make sure you handle that as part of the then() clause in a Promise. Since the get() in the firestore collection returns a Promise, and you are returning it from your function, you need to make sure that the calling function treats it as a Promise, has a then() clause, and sends back the result as part of something inside this clause.