Home > database >  How to send notifications to a user
How to send notifications to a user

Time:10-31

I am able to send notifications to android and apple devices using the "Compose notification" on firebase. firebase compose notification pic

I am trying to send a message using cloud functions but I am having a hard time.

I can see all the data I want from the following code snip (cloud function)

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();


exports.onUpdate = functions.firestore
    .document("chat messages/{docId}")
    .onCreate((snapshot, context) => {
      console.log("1");
      console.log(snapshot.data());
      console.log("2");
      console.log(snapshot.data()["User id"] );
      console.log(snapshot.data()["Chat message"] );

      console.log("3");
    });

now I need to target the phone to send the notification. How do I do this?

CodePudding user response:

Did you see the FCM documentation on sending messages, specifically on sending to a specific device?

I also recommend having a look at the Cloud Functions sample on notifying the user when something interesting happens. While it triggers on the Realtime Database instead of Firestore, the approach will be very similar to what you need.

CodePudding user response:

here is the solution that worked for me

/*
to fix issues:
(cd functions && npx eslint . --fix)
to upload code:
firebase deploy
to do both:
(cd functions && npx eslint . --fix)
firebase deploy
*/


const functions = require("firebase-functions");
const admin = require("firebase-admin");
// eslint-disable-next-line max-len
const tokens = ["eYjutmxDT4CWNHedTOpTQF:APA91bGb4ospqr1z-rr5XquN6EJ11sAWznaQfKWDhM0rVxi2wMZ-MPBoRDsgzXSXl0umQw7dzqiWg5e48zREYk1BrwUzjFuEfZJ_TFaqaqfSf8-vnoXe1OpF90GmaLHAVR_SoHtHKSqP"];

admin.initializeApp();

exports.onCreate = functions.firestore
    .document("chat/{docId}")
    .onCreate((snapshot, context) => {
      console.log(snapshot.data());
      console.log("fake data");
    });

exports.onUpdate = functions.firestore
    .document("chat messages/{docId}")
    .onCreate( (snapshot, context) => {
      const payload = {
        // eslint-disable-next-line max-len
        notification: {title: "Push Title", body: "Push Body", sound: "default"},
        // eslint-disable-next-line max-len
        data: {click_action: "FLUTTER_NOTIFICATION_CLICK", message: "Sample Push Message"},
      };

      try {
        admin.messaging().sendToDevice(tokens, payload);
        console.log("NOTIFICATION SEND SUCCESFULLY");
      } catch (e) {
        console.log("ERROR SENDING NOTIFICATION");
        console.log(e);
      }
    });

  • Related