首页 > 解决方案 > 检测多个过期的 Firebase 云消息传递令牌

问题描述

我知道我可以知道令牌是否已过期,如 Google 文档中所述:

https://developers.google.com/instance-id/reference/server#get_information_about_app_instances

问题是我有数百个令牌,我想每周知道它们是否过期。为每个令牌发送请求并不是很好。无论如何,是否可以发送一个带有这些令牌数组或类似内容的单个请求?谢谢!

标签: firebase-cloud-messaging

解决方案


处理过期令牌的常用方法是在尝试向它们发送消息时收到“令牌过期”响应时将其删除。而且由于您可以一次向多个令牌发送消息,因此无需为每个令牌执行单独的调用。

有关如何执行此操作的一个很好的示例,请参阅Cloud Functions 示例中的以下片段,该示例通过 Admin SDK 使用 FCM

 // Listing all tokens as an array.
  tokens = Object.keys(tokensSnapshot.val());
  // Send notifications to all tokens.
  const response = await admin.messaging().sendToDevice(tokens, payload);
  // For each message check if there was an error.
  const tokensToRemove = [];
  response.results.forEach((result, index) => {
    const error = result.error;
    if (error) {
      console.error('Failure sending notification to', tokens[index], error);
      // Cleanup the tokens who are not registered anymore.
      if (error.code === 'messaging/invalid-registration-token' ||
          error.code === 'messaging/registration-token-not-registered') {
        tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
      }
    }
  });
  return Promise.all(tokensToRemove);

推荐阅读