firebase-admin:获取通知传递失败结果的令牌

firebase-admin: Get token of failed notification delivery result

假设我们要像这样向两个注册令牌(仅 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 问题 Link:https://github.com/firebase/firebase-admin-node/issues/600

您需要使用 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