Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send push notifications using Cloud Functions for Firebase

Tags:

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?

like image 695
Tudor Lozba Avatar asked Jun 14 '17 14:06

Tudor Lozba


People also ask

Can you send push notifications with Firebase?

Firebase Cloud Messaging (FCM) provides a reliable and battery-efficient connection between your server and devices that allows you to deliver and receive messages and notifications on iOS, Android, and the web at no cost.

How do I automate firebase cloud messaging?

Go to the app build gradle file, in the dependencies section, add the Firebase Cloud Messaging dependency and Sync the project. Once the process is finished create a new class call PushNotification Service and have it extend the FirebaseMessagingService class.

Can I send push notifications without FCM?

Without FCM, you'd need to build more than three notification systems. You'd need one each for iOS and Android, but then you'd also need to accommodate all the different types of browsers for the web application to deliver push notifications without a hitch.


2 Answers

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);     }); }) 
like image 139
Tudor Lozba Avatar answered Sep 21 '22 17:09

Tudor Lozba


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. 
like image 44
Gsilveira Avatar answered Sep 20 '22 17:09

Gsilveira