【问题标题】:How to send notification to multiple device token using firebase cloud functions如何使用 Firebase 云功能向多个设备令牌发送通知
【发布时间】:2019-12-23 07:32:34
【问题描述】:

我是使用 Firebase Cloud Functions 和 JavaScript 的新手,我能够使用 Firebase Cloud Functions(JavaScript) 向单个设备发送通知。现在我正在尝试向多个设备令牌发送推送通知,但我认为我遇到了问题。

我想将通知发送到我的 firebase 数据库中的这些设备令牌:

/receivers
      /event1
           /uid1: device_token1
           /uid2: device_token2
           /uid3: device_token3
           /uid4: device_token4

这是我目前的代码,但它不起作用..

exports.sendSOSNotif = functions.database.ref('/SOSNotifs/{sosId}').onWrite((data, context) => {

  const eventId=data.after.child("eventId").val();
  const uid=data.after.child("uid").val();
  const displayName=data.after.child("displayName").val();
  const photoUrl=data.after.child("photoUrl").val();
  const status=data.after.child("status").val();

  console.log("eventId:", eventId);
  console.log("displayName:", displayName);
  console.log("uid", uid);

  const payload = {
    notification: {
        title: "SOS Alert",
        body: displayName + " sent an alert!",
        sound: "default"
    },

    data: {
        eventId: eventId,
        displayName: displayName
    }
  };

return Promise.all([admin.database().ref("/receivers/event1").once('value')]).then(results => {
const tokens = results[0];
if (!tokens.hasChildren()) return null;

const tokensList = Object.keys(tokens.val());
return admin.messaging().sendToDevice(tokensList, payload);

});
});

【问题讨论】:

    标签: javascript firebase firebase-realtime-database firebase-cloud-messaging google-cloud-functions


    【解决方案1】:

    首先,如果您是这样组织数据库的,则不应添加如下所示的标记。单个 uid 可能有多个令牌

    /receivers
      /event1
           /uid1: device_token1
           /uid2: device_token2
           /uid3: device_token3
           /uid4: device_token4
    

    为了向多个 UID 发送通知,我编写了一个脚本 here

    另外,更新您的问题,了解您所面临的具体问题。

    【讨论】:

    • 那么存储令牌的最佳方式是什么?
    猜你喜欢
    • 2019-06-13
    • 1970-01-01
    • 2021-04-04
    • 2021-05-25
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 2018-08-05
    相关资源
    最近更新 更多