本文介绍了如何使“过期"的 Firebase 实例 ID 令牌无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

AFAIK,Firebase Instance Token 将在以下 4 个条件下刷新:

AFAIK, the Firebase Instance Token will be refreshed under the following 4 conditions:

  1. 应用删除实例 ID

  1. App deletes Instance ID

应用在新设备上恢复

用户卸载/重新安装应用

User uninstalls/reinstall the app

用户清除应用数据

假设用户使用令牌 A 作为他的FCM 地址".每次他登录应用程序时,他都会将令牌 A 与该用户的 UUID 一起注册到 Firestore,以便可以向他发送用户特定的云消息.当他登出时,系统会向firestore发出请求以删除令牌A记录.

Suppose a user is using Token A as his 'FCM address'. Every time when he logs in the app, he will register the Token A to the Firestore along with this user's UUID so user-specific cloud message can be sent to him. When he logs out, the system will fire a request to firestore for removing the token A record.

现在,当用户重新安装应用程序时,实例 id 会刷新并生成新的 Token B.令牌 A 变得无用.不幸的是,如果用户在卸载之前没有注销,令牌 A 将永远保留在 Firestore 中.

Now, when the user reinstalls the app, the instance id is refreshed and a new Token B is generated. The Token A becomes useless. Unfortunately, if the user does not log out before the uninstallation, token A will stay in the firestore forever.

任何解决方法或更明智的方法来处理这种情况?

Any workaround or wiser way to handle this case?

推荐答案

使您的令牌注册表保持最新需要两个步骤:

Keeping your token registry up to date requires two steps:

  1. 从您的应用程序代码中删除过时的令牌.
  2. 检查过时的令牌并在您发送消息时将其删除.
  1. Remove outdated tokens from your application code.
  2. Check for outdated tokens and remove them when you send messages.

您删除不再使用的令牌的方法是 #1.

Your approach of removing a token that is no longer used, is #1.

第二步是在您获得 messaging/invalid-registration-tokenmessaging/registration-token-not-registered 尝试向其发送消息时的响应.functions-samples repo包含一个很好的例子:

The second step though is to remove tokens from your registry/database when you get a messaging/invalid-registration-token or messaging/registration-token-not-registered response when trying to send a message to it. The functions-samples repo contains a great example of this:

admin.messaging().sendToDevice(tokens, payload).then((response) => {
  // 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') {
        // TODO: remove the token from your registry/database
      }
    }
  });
});

上述代码使用 Firebase Admin SDK for Node.js,但同样的逻辑也可以应用于其他平台或通过 HTTPS 端点发送消息时.

The above code uses the Firebase Admin SDK for Node.js, but the same logic could also be applied to other platforms or when sending messages through the HTTPS endpoints.

这篇关于如何使“过期"的 Firebase 实例 ID 令牌无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 15:32