I'm trying to implement push notification using firebase in my project but not being able to do so.Below is my index.js file, i have very little knowledge about javascript and nodejs and thats why not being able to figure out the problem.
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.database.ref('/Notifications/{receiver_id}/{notification_id}').onWrite((data,context) =>
{
const receiver_id = context.params.receiver_id;
const notification_id = context.params.notification_id;
console.log('We have new notification to send to : ', receiver_id);
/*if(!context.data.val()){
return console.log('A notification has been deleted from the databse : ', notification_id);
}*/
const deviceToken = admin.database().ref(`Users/${receiver_id}/device_token`).once('value');
return deviceToken.then(result => {
const token_id = result.val();
const payload = {
notification: {
title : "Friend Request",
body : "You've received a new Friend Request",
icon : "default"
}
};
return admin.messaging().sendToDevice(token_id,payload).then(response => {
console.log('This was the notification feature');
return true;
});
});
});
Can anyone please explain me this code and help out with my problem.
Every device has a different token. Seems you are storing only one token for one user. That's why you can send the notification to only one device. If you want to send it to multiple devices you have to store multiple device tokens and send the notification to all those devices.
Related
My application is simply order app and I want admin get notification when new order is placed.
So to do that I send notification to device with token Id by using firebase functions.
'use-strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('admin/{user_id}/notification/{notification_id}').onCreate((snapshot, context) => {
console.log("hehehehehehehehe");
const user_id=context.params.user_id;
const getDeviceTokensPromise = admin.database().ref(`admin/${user_id}`).once('value');
//let tokensSnapshot;
//let tokes;
return Promise.all([getDeviceTokensPromise]).then(result => {
//const registrationToken= result[0].tokenid.val();
//console.log(registrationToken);
const payload = {
notification: {
title: 'You have a new follower!',
body: 'Yeni sifaris var',
}
};
return admin.messaging().sendToDevice('fOCU86Rhhb4:APA91bHwJZInZYGp9cIDc7PyCw48QcEvvMOMuFepYcCTvkxlCJp8_Ieq1Ikwd9xNoU2rfTA9paRqCTLAuhUlZgF952AvpBstGdGRWMK8lCR2MHgHn6xzbvyxFEu-auRYexnPYmOnlTB1',payload).then((response) => {
return console.log('Successfully sent message:', response);
}).catch((error) => {
return console.log('Error sending message:', error);
});
});
});
Although I got the success response message in console log, my android phone couldn't get any notification.
Successfully sent message: { results: [ { messageId: '0:1542910779596746%095eb9af095eb9af' } ],
canonicalRegistrationTokenCount: 0,
failureCount: 0,
successCount: 1,
multicastId: 6551370257673400000 }
What is wrong with my code. I am new to firebase. I need your help.
This question already has answers here:
Firebase functions how to send a notification in Android
(1 answer)
Firebase functions: cannot read property 'user_id' of undefined
(1 answer)
Firebase cloud functions stopped working - event.data undefined
(2 answers)
node js function onWrite is not working properly in google cloud function
(1 answer)
Closed 4 years ago.
I'm working with Notifications but the Notification is not working and getting this error, I am new to this so i can't fully understand this and getting tilted by the error. Any help would be appreciated, I don't find any related solutions about this
ReferenceError: event is not defined
at exports.sendNotification.functions.database.ref.onWrite (/user_code/index.js:9:31)
at cloudFunctionNewSignature (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:105:23)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:135:20)
at /var/tmp/worker/worker.js:744:24
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
and Here is my index.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification =
functions.database.ref('/notifications/{user_id}/{notification_id}')
.onWrite((change, context) => {
const user_id = event.params.user_id;
const notification = event.params.notification;
console.log('We have a notification to send to: ', user_id);
if(!event.data.val())
{
return console.log('A Notification has been deleted from database: ', notification_id);
}
const fromUser = admin.database().ref(`/notifications/${user_id}/${notification_id}`);
return fromUser.then(fromUserResult => {
const from_user_id = fromUserResult.val().from;
console.log('You have new Notification from: ', from_user_id);
const userQuery = admin.database().ref(`Users/${from_user_id}/name`).once('value');
const deviceToken = admin.database().ref(`/Users/${user_id}/device_token`).once('value');
return Promise.all([userQuery, deviceToken]).then(result => {
const userName = result[0].val();
const token_id = result[1].val();
const payload = {
notification: {
title: "Message Request",
body: `${userName} has sent you a Message Request`,
icon: "logo.png",
click_action: "com.example.gab.quadrantms_TARGET_NOTIFICATION"
},
data : {
from_user_id : from_user_id
}
};
return admin.messaging().sendtoDevice(token_id, payload).then(response =>{
console.log('This was the Notification Feature');
return true;
});
});
});
});
Just as the error says, event isn't defined anywhere. It looks like you should be using context instead.
const user_id = context.params.user_id;
const notification = context.params.notification;
Here are the docs for EventContext: https://firebase.google.com/docs/reference/functions/functions.EventContext
And RefBuilder.onWrite: https://firebase.google.com/docs/reference/functions/functions.database.RefBuilder#onWrite
I'm working with Firebase notifications using node.js.
After compile, when I'm sending request to other user of app (request makes notification), firebase log shows error:
TypeError: Cannot read property 'receiver_id' of undefined
at exports.sendNotification.functions.database.ref.onWrite.event (/user_code/index.js:12:36)
at Object. (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
at /var/tmp/worker/worker.js:700:26
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
Index.js code:
'use strict'
const functions = require('firebase-functions');
const admin = require ('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification =
functions.database.ref('/Notifications/{receiver_id}/{notification_id}')
.onWrite(event =>
{
const receiver_id = event.params.receiver_id;
const notification_id = event.params.notification_id;
console.log('We have a notification to send to :', receiver_id);
if(!event.data.val())
{
return console.log('A notification has been deleted from the database: ', notification_id);
}
const deviceToken = admin.database().ref(`/Users/${receiver_id}/device_token`).once('value');
return deviceToken.then(result =>
{
const token_id = result.val();
const payload =
{
notification:
{
title: "Friend Request",
body: "you have received a new friend request",
icon: "default"
}
};
return admin.messaging().sendToDevice(token_id, payload)
.then(response =>
{
console.log('This was the notification feature.');
});
});
});
I have read about new APIs on site:
https://firebase.google.com/docs/functions/beta-v1-diff
I think I must change event to context, but I don't know how.
Is anybody know what's the issue?
Thank's for any Help :)
The Firebase documentation on the new data and context shows where the params now live:
The context parameter provides information about the function's execution. Identical across asynchronous functions types, context contains the fields eventId, timestamp, eventType, resource, and params.
So to get rid of that error, you'll need to change the first bit of your function to:
exports.sendNotification =
functions.database.ref('/Notifications/{receiver_id}/{notification_id}')
.onWrite((data, context) =>
{
const receiver_id = context.params.receiver_id;
const notification_id = context.params.notification_id;
...
There are more, similar changes that you'll need to make. If you're having a hard time making those yourself, I recommend you check back in with where you got the code from.
I am trying to make a cloud function that sends a push notification to a given user.
The user makes some changes and the data is added/updated under a node in firebase database (The node represents an user id). Here i want to trigger a function that sends a push notification to the user.
I have the following structure for the users in DB.
Users
- UID
- - email
- - token
- UID
- - email
- - token
Until now i have this function:
exports.sendNewTripNotification = functions.database.ref('/{uid}/shared_trips/').onWrite(event=>{
const uuid = event.params.uid;
console.log('User to send notification', uuid);
var ref = admin.database().ref('Users/{uuid}');
ref.on("value", function(snapshot){
console.log("Val = " + snapshot.val());
},
function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
When i get the callback, the snapshot.val() returns null. Any idea how to solve this? And maybe how to send the push notification afterwards?
I managed to make this work. Here is the code that sends a notification using Cloud Functions that worked for me.
exports.sendNewTripNotification = functions.database.ref('/{uid}/shared_trips/').onWrite(event=>{
const uuid = event.params.uid;
console.log('User to send notification', uuid);
var ref = admin.database().ref(`Users/${uuid}/token`);
return ref.once("value", function(snapshot){
const payload = {
notification: {
title: 'You have been invited to a trip.',
body: 'Tap here to check it out!'
}
};
admin.messaging().sendToDevice(snapshot.val(), payload)
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
})
Just answering the question from Jerin A Mathews...
Send message using Topics:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
//Now we're going to create a function that listens to when a 'Notifications' node changes and send a notificcation
//to all devices subscribed to a topic
exports.sendNotification = functions.database.ref("Notifications/{uid}")
.onWrite(event => {
//This will be the notification model that we push to firebase
var request = event.data.val();
var payload = {
data:{
username: request.username,
imageUrl: request.imageUrl,
email: request.email,
uid: request.uid,
text: request.text
}
};
//The topic variable can be anything from a username, to a uid
//I find this approach much better than using the refresh token
//as you can subscribe to someone's phone number, username, or some other unique identifier
//to communicate between
//Now let's move onto the code, but before that, let's push this to firebase
admin.messaging().sendToTopic(request.topic, payload)
.then((response) => {
console.log("Successfully sent message: ", response);
return true;
})
.catch((error) => {
console.log("Error sending message: ", error);
return false;
})
})
//And this is it for building notifications to multiple devices from or to one.
Return this function call.
return ref.on("value", function(snapshot){
console.log("Val = " + snapshot.val());
},
function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
This will keep the cloud function alive until the request is complete. Learn more about returning promises form the link give by Doug in the comment.
Send Notification for a Topic In Cloud function
Topics a basically groups you can send notification for the selected group
var topic = 'NOTIFICATION_TOPIC';
const payload = {
notification: {
title: 'Send through Topic',
body: 'Tap here to check it out!'
}
};
admin.messaging().sendToTopic(topic,payload);
You can register the device for any new or existing topic from mobile side
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotificationToTopic =
functions.firestore.document('Users/{uuid}').onWrite(async (event) => {
//let title = event.after.get('item_name');
//let content = event.after.get('cust_name');
var message = {
notification: {
title: "TGC - New Order Recieved",
body: "A New Order Recieved on TGC App",
},
topic: 'orders_comming',
};
let response = await admin.messaging().send(message);
console.log(response);
});
For sending notifications to a topic, The above code works well for me, if you have any doubt, let me know.
I have an android Client Application and and Admin Application using Firebase. Whenever a user registers in Client Application, I need to send a push notification to Admin app. I am trying to use Cloud Functions for Firebase. I have exported the function, and i can see that on firebase console as well.
This is my index.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendMessageToAdmin = functions.database.ref('/tokens/users/{userId}/{regToken}').onWrite(event => {
if (event.data.previous.exists()) {
return;
}
const userId = event.params.userId;
const regToken = event.params.regToken;
// Notification details.
const payload = {
notification: {
title: 'You have a new User.',
body: `${userId} is the id.`,
}
};
return admin.messaging().sendToDevice(regToken, payload);
});
Here is my database structure at firebase :
If i use any online portal to send push or even FCM to send push to admin app for testing purpose, i am receiving the push. But this Cloud Function is not sending the push. Can someone guide me whats wrong i am doing.
EDIT
If i change the function to the following , then it works. But i am still wondering why the above function didn't work.
exports.sendMessageToAdmin = functions.database.ref('/tokens/users/{userId}').onWrite(event => {
if (event.data.previous.exists()) {
return;
}
const userId = event.params.userId;
var eventSnapshot = event.data;
const regToken = eventSnapshot.child("regToken").val();
Notification details.
const payload = {
notification: {
title: 'You have a new User.',
body: `${userId} is the id.`,
}
};
return admin.messaging().sendToDevice(regToken, payload);
});
In your original code, you have:
const regToken = event.params.regToken;
event.params.regToken does not return the value of regToken it returns the value of the wildcard path segment in your reference.