Cloud Functions for Firebase - 将 FCM 消息发送到多个令牌

Cloud Functions for Firebase - Send FCM message to multiple tokens

当在我的实时数据库中创建节点时,我必须向许多令牌发送消息。
我使用那个代码,但所有通知都丢失了(人们没有收到它)。

 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);
            });              
      });
    });
});

"return" 承诺对吗?我想我必须等待所有“admin.messagging() Promise,但我不知道我该怎么做。

非常感谢。

您可以向令牌数组发送通知。我正在使用此代码发送通知

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

我想你可以在这里找到更多信息 https://firebase.google.com/docs/cloud-messaging/admin/legacy-fcm

这是将 FCM 发送到令牌数组的方式:

  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);
  });

为了 return 所有发送操作的 Promise,将您的代码修改为:

 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);
    });