Check if Firebase registration token is invalid

二次信任 提交于 2021-02-05 09:48:46

问题


I have an app where a user can register/login via Firebase. A user can have multiple devices among which all his data is being shared (of course he must be logged in). I keep track of all devices by their firebase device token and send appropriate update notifications when the user updates something on a particular device

Now I know that the firebase token is being refreshed, but how do I know that a token is invalid? Lets say a user has 4 devices where he is logged with one account. Now he delete the app on one of them, and installs it again, so he gets a new token. This means that now I have 5 device tokens on my server but still just 4 devices. The best approach would be to tie a token to some non-changeable device id like MAC oder IMEI but because of privacy policies that is not possible. Is there some other way to fish out the tokens that have been revoked/invalidated?


回答1:


The common way to detect expired/revoked FCM tokens is during sending of messages. FCM will at that point tell you exactly which tokens have expired, and you can then remove them from your database.

For an example of this, see this Node.js code from the functions-samples repo:

 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);


来源:https://stackoverflow.com/questions/65479140/check-if-firebase-registration-token-is-invalid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!