简体   繁体   中英

Cloud Functions for Firebase - Send FCM message to multiple tokens

I have to send a message to many token when a node is created in my realtime database.
I use that's code, but any notification are lost (people not receive its).

 exports.sendMessage = functions.database.ref('/messages/{messageId}')
.onCreate((snapshot, context) => {
 const original = snapshot.val();

 let msg = {
    message: {
        data: {
            title: 'title2 test',
            body: 'body2 test',
            notify_type: 'chat_message',
            notify_id: ((new Date()).getTime()).toString(),
        },
        apns: {
            headers: {
                'apns-priority': '10',
                'apns-expiration': '0'
            },
            payload: {
                aps: { contentAvailable: true, sound:'' },
                'acme1': 'bar',
                title: 'title test',
                body: 'body test',
                notify_type: 'chat_message',
                notify_id: ((new Date()).getTime()).toString()
            }
        },
        token: token
    }
};

 var query = firebase.database().ref("users");
 return query.once("value")
      .then(function(snapshot) {
        snapshot.forEach(function(childSnapshot) {
          var user = childSnapshot.val();
          var token = user.token;
          var username = user.username;
          msg.message.token = token;
          admin.messaging().send(msg.message).then((response) => {
                console.log('message sent to '+username);
            }).catch((error) => {
                console.log(error);
            });              
      });
    });
});

Is the "return" Promise right ? I think I have to wait all "admin.messagging() Promise, but I don't know how can I do this.

Thank you so much.

This is how you send a FCM to an array of tokens:

  return Promise.all([admin.database().ref(`/users/${user}/account/tokensArray`).once('value')]).then(results => {
    const tokens = results[0];
    if (!tokens.hasChildren()) return null;
    let payload = {
      notification: {
        title: 'title',
        body: 'message',
        icon: 'icon-192x192.png'
      }
    };
    const tokensList = Object.keys(tokens.val());
    return admin.messaging().sendToDevice(tokensList, payload);
  });

You can send notifications to an array of tokens. I am using this code to send notifications

return admin.messaging().sendToDevice(deviceTokenArray, payload, options).then(response => {
  console.log("Message successfully sent : " + response.successCount)
  console.log("Message unsuccessfully sent : " + response.failureCount)
});

I think you can find more information here https://firebase.google.com/docs/cloud-messaging/admin/legacy-fcm

To return a Promise for all the send actions, modify your code to this:

 return query.once("value")
      .then(function(snapshot) {
        var allPromises = [];
        snapshot.forEach(function(childSnapshot) {
          var user = childSnapshot.val();
          var token = user.token;
          var username = user.username;
          msg.message.token = token;
          const promise = admin.messaging().send(msg.message).then((response) => {
                console.log('message sent to '+username);
            }).catch((error) => {
                console.log(error);
            });
          allPromises.push(promise);              
      });
      return Promise.all(allPromises);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM