vijju
vijju

Reputation: 462

How to send push notifications to multiple device with FCM tokens using cloud functions

First I generated a FCM token and stored in firestore. After that I wrote a cloud functions to send notifications based on FCM token. and I deployed cloud functions it says successfully sent notifications with status ok. But it doesn't displays in mobile device. My Index.js is

'use strict';
const functions = require('firebase-functions');
const Firestore = require('@google-cloud/firestore');
const admin = require('firebase-admin');
const firestore = new Firestore();
const db = admin.firestore();
admin.initializeApp(functions.config().firebase);
exports.hellouser = functions.firestore
    .document('users/{token}')
    .onWrite(event =>{
    var document = event.data.data();
    console.log("tokens",document); 
    var token = ['cdNN0AbYKU0:APA91bEyL0zo3zwHZD8H43Vp7bxAfYgehlVI8LrKktPO2eGuByVDdioysIGxHe5wocwq8ynxRToJPpOve_M59YY_MIRbWLnF9AIgoTwJORXZbw6VBw7']// this is my FCM token.
    if(
    const payload = {
        notification: {
            title: "Message",
            body: "hi hello",
            sound: "default"
        }
    };
    return admin.messaging().sendToDevice(token, payload).then((response)=> {

    console.info("Successfully sent notification")
    }).catch(function(error) {
        console.warn("Error sending notification " , error)
    });
});

How to send notifications based on the FCMtoken.

Upvotes: 3

Views: 1080

Answers (1)

If it's the exact code you use then check syntax near if(. This may help you.
Next write some code to go through your response object. Firebase may take your tokens and payload, process them and return 200 OK response but in the response you will have errors.
Response has general structure like this:

{ results: [ { //stuff related to one token },{ //stuff related to one token } ], canonicalRegistrationTokenCount: 0, failureCount: 1, successCount: 0, multicastId: SOME_LONG_NUMBER }

Take in mind that response.results array has status of each message sent to token in the same order as tokens in your token array.

You can see all posible errors in Firebase Documentation.

If response.failureCount > 0 then no messages were sent and you should get corresponding error in response.results.
Also learn about options variable. options.priority must be 'high' to guarantee fast message delivery.

Maybe this will help.

Upvotes: 3

Related Questions