Push Notification Using Google Cloud Functions and Google Firebase - android

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.

Related

Firebase Push Notification not being sent to the second device

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.

Firebase Notifications using node.js

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.

Firebase Admin SDK sendToTopic not working

I'm deploying a mobile application (for Android and iOS) through which the admin can send alert to users registered to a specific topic. To do that I'm using Realtime Database to store alerts and cloud functions to send notifications to topic.
I've the following cloud function deployed:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNewAlertNotification = functions.database.ref('/alerts').onWrite(event => {
const getValuePromise = admin.database()
.ref('alerts')
.orderByKey()
.limitToLast(1)
.once('value');
return getValuePromise.then(snapshot => {
const { text, topics, author } = snapshotToArray(snapshot)[0];
const payload = {
data: {
title: 'Avviso',
body: text,
icon: 'ic_stat_notify',
sound: 'default',
color: '#F3E03B',
tag: 'alerts',
ticker: 'Nuovo avviso',
subtitle: 'Avvisi',
author: JSON.stringify(author)
}
};
const options = {
priority: 'high',
timeToLive: 60 * 60 * 24 * 2, // 48 hours
collapseKey: 'it.bmsoftware.caliup'
// contentAvailable: true
};
if (topics.length > 1) {
let condition = '';
topics.forEach((topic, index) => {
condition += `'${topic}' in topics`
if (index < topics.length - 1) {
condition += ' || '
}
});
console.log(`Sending alert to condition '${condition}' -> ${JSON.stringify(payload)}`);
return admin.messaging().sendToCondition(condition, payload, options);
} else if (topics.length === 1) {
let topic = topics[0];
console.log(`Sending alert to topic '${topic}' -> ${JSON.stringify(payload)}`);
return admin.messaging().sendToTopic(topic, payload, options);
} else {
console.log(`No topics found`);
}
});
});
const snapshotToArray = (snapshot) => {
let result = []
if (!snapshot || !snapshot.val())
return result
snapshot.forEach((childSnapshot) => {
let item = childSnapshot.val()
item.key = childSnapshot.key
result.push(item)
})
return result
}
When I insert a new message on the realtime database, the above function fetch that message correctly and in the log section (on the firebase console) I see the correct custom log and a log that says status 'ok'.
Despite this, no notification arrives on devices. If I test the same topic from firebase console directly it works fine so devices are properly registered.
Is there something wrong with the cloud function that I'm missing?
I believe that you should uncomment // contentAvailable: true if you are sending only data payload, at least for iOS. That way you'll be able to show and trigger the notification yourself on the app code. If you want the notification to pop up without having to process the data payload, you should pass a notification object on payload.
Notification is limited to these fields tho: https://firebase.google.com/docs/reference/admin/node/admin.messaging.NotificationMessagePayload

Firebase Messaging - Can't receive notifications from subscriptions

Here is the situation: I have a firebase cloud function that is running on every write to a certain database collection (called "jamrooms"). The NodeJS script is as follows:
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.newJamroom = functions.database.ref('/jamrooms/{jamroomId}').onWrite(event => {
// Grab the current value of what was written to the Realtime Database.
var jamroomId = event.params.jamroomId;
var topic = "new-jamroom";
var payload = {
data: {
title: "New jamroom available !",
body: String("Jamroom id = ").concat(jamroomId)
}
};
// Send a message to devices subscribed to the provided topic.
return admin.messaging().sendToTopic(topic, payload)
.then(function (response) {
// See the MessagingTopicResponse reference documentation for the
// contents of response.
console.log("Successfully sent message:", response);
})
.catch(function (error) {
console.log("Error sending message:", error);
});
});
On the client side (Android), I've subscribed to the topic "new-jamroom":
FirebaseMessaging.getInstance().subscribeToTopic("new-jamroom");
The script is successfully executed each time a new key-value pair is added to the collection:
but the client never receives the notification, either in background or in foreground.
I don't know where to look at to understand what's not going right.
Update
Even sending notifications from the console (using topic "new-jamroom", that exists in the console) doesn't send it to the client (Firebase records 0 sent).
Because your payload contains the data key, you are sending a data-only message, not a notification:
var payload = {
data: {
title: "New jamroom available !",
body: String("Jamroom id = ").concat(jamroomId)
}
Data messages and notification messages are handled differently by the receiver. Data-only messages cause onMessageReceived() to be invoked in the receiver. To generate a notification, build your payload with the notification key:
var payload = {
notification: { // <= CHANGED
title: "New jamroom available !",
body: String("Jamroom id = ").concat(jamroomId)
}

Send push notifications using Cloud Functions for Firebase

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.

Categories

Resources