【问题标题】:firebase-admin: Get token of failed notification delivery resultfirebase-admin:获取通知传递失败结果的令牌
【发布时间】:2019-12-01 07:45:24
【问题描述】:

假设我们想像这样向两个registrationTokens(只有Android设备,没有iOS)发送一个通知:

const tokens = ['tokenA', 'tokenB'];

const payload = {badge: 1, title: 'Hello', body: 'world'};
const options = {priority: 'high',contentAvailable: false, timeToLive: 60 * 60 * 24};

const admin = FirebaseAdmin.initializeApp({/*config here...*/});

admin.messaging().sendToDevice(deviceTokens, payload, options)
  .then((response) => {

    response.results.forEach((deviceResult) => {
      if (deviceResult.error) {
        console.log('Delivery failed. Showing result:\n', deviceResult);
      }
    });

});

曾经在tokenB 注册过设备的用户从他的设备中删除了该应用。因此,该令牌不再向 Firebase 注册。 错误对象如下所示:

Delivery failed. Showing result:


{"error":
  {
    "code":"messaging/registration-token-not-registered",
    "message":"The provided registration token is not registered. A previously valid registration token can be unregistered for a variety of reasons. See the error documentation for more details. Remove this registration token and stop using it to send messages."
  }
}

问题: 我的问题是,我只知道其中一个交付失败。但我不知道错误与哪个令牌有关。因此我无法从数据库中删除过时的令牌。

问题: 有没有办法找出交付失败的代币?

Github 问题链接:https://github.com/firebase/firebase-admin-node/issues/600

【问题讨论】:

标签: node.js push-notification firebase-admin


【解决方案1】:

您需要使用forEach 中的索引并从您传入sendToDevice 的数组中获取令牌。

官方文档:https://firebase.google.com/docs/reference/admin/node/admin.messaging.MessagingDevicesResponse

这似乎是一种 hack,但是当我拥有单个用户的多个设备令牌时它对我有用,因为我必须在他们登录时存储新的设备令牌。

const tokens = ['tokenA', 'tokenB'];

const payload = {badge: 1, title: 'Hello', body: 'world'};
const options = {priority: 'high',contentAvailable: false, timeToLive: 60 * 60 * 24};

const admin = FirebaseAdmin.initializeApp({/*config here...*/});

admin.messaging().sendToDevice(deviceTokens, payload, options)
  .then((response) => {

    response.results.forEach((deviceResult,index) => {
      if (deviceResult.error) {
        let failedToken = tokens[index];
        // Now use this token to delete it from your DB, or mark it failed according to your requirements.
      }
    });

});

此方法也用于 firbease 样本:https://github.com/firebase/functions-samples/blob/master/fcm-notifications/functions/index.js

【讨论】:

  • 感谢您的回答。这是一个有价值的信息,我可以用它来解决问题。我想知道这有多可靠,我不想冒险删除已注册的令牌。如果这是correct way to do it,firebase 人员应该将其添加到他们的文档中。
  • 是的,他们应该将其添加到文档中。关于可靠性,我认为 FCM 服务器的响应保持数组的顺序,参见上述链接中的实现代码。
  • 是的,但我不喜欢“假设” FCM 保持数组的顺序。我需要证据。文档中的注释就足够了。
  • 我会在我最近创建的 GitHub 问题中提到你的解决方案 github.com/firebase/firebase-admin-node/issues/600
  • 在问题中也添加指向他们示例的链接。
猜你喜欢
  • 2017-12-06
  • 2016-09-23
  • 2019-12-15
  • 2019-11-19
  • 2019-12-05
  • 1970-01-01
  • 1970-01-01
  • 2013-04-22
  • 2014-01-13
相关资源
最近更新 更多