invertase / react-native-firebase

🔥 A well-tested feature-rich modular Firebase implementation for React Native. Supports both iOS & Android platforms for all Firebase services.
https://rnfirebase.io
Other
11.53k stars 2.19k forks source link

InvalidRegistration error on fcm token #3476

Closed umangshuMTX closed 3 years ago

umangshuMTX commented 4 years ago

Issue

Getting InvalidRegistration while sending fcm message.

On the App side, it is configured as per the setup guide.

const registerForNotification = async () => {
  // await requestNotifications(['alert', 'badge', 'sound']);
  await messaging().registerDeviceForRemoteMessages();
};

const requestForNotificationPermission = async () => {
  const granted = await messaging().requestPermission();

  if (granted) {
    console.log('User granted messaging permissions!');
  } else {
    console.log('User declined messaging permissions :(');
  }
};

const getDeviceToken = async () => {
  await requestForNotificationPermission();
  const result = await registerForNotification();
  console.log(result);
  // await messaging().deleteToken();
  const fcmToken = await messaging().getToken();
  return fcmToken;
};

Above give us the fcm token which we are sending to the Firestore and a could function send the fcm message. But sometimes it works and sometimes it sends InvalidRegistration.

{
    "multicast_id": 8080343189913405045,
    "success": 0,
    "failure": 1,
    "canonical_ids": 0,
    "results": [
        {
            "error": "InvalidRegistration"
        }
    ]
}

Project Files

Javascript

Click To Expand

#### `package.json`: ```json { "react": "16.9.0", "react-native": "0.61.5", "@react-native-firebase/app": "^6.4.0", "@react-native-firebase/auth": "^6.4.0", "@react-native-firebase/functions": "^6.4.0", "@react-native-firebase/messaging": "^6.4.0", } ``` #### `firebase.json` for react-native-firebase v6: ```json # N/A ```

iOS

Click To Expand

#### `ios/Podfile`: - [ ] I'm not using Pods - [x] I'm using Pods and my Podfile looks like: ```ruby # N/A ``` #### `AppDelegate.m`: ```objc // N/A ```


Android

Click To Expand

#### Have you converted to AndroidX? - [ ] my application is an AndroidX application? - [ ] I am using `android/gradle.settings` `jetifier=true` for Android compatibility? - [ ] I am using the NPM package `jetifier` for react-native compatibility? #### `android/build.gradle`: ```groovy // N/A ``` #### `android/app/build.gradle`: ```groovy // N/A ``` #### `android/settings.gradle`: ```groovy // N/A ``` #### `MainApplication.java`: ```java // N/A ``` #### `AndroidManifest.xml`: ```xml ```


Environment

Click To Expand

**`react-native info` output:** ``` OUTPUT GOES HERE ``` - **Platform that you're experiencing the issue on**: - [ ] iOS - [ ] Android - [ ] **iOS** but have not tested behavior on Android - [ ] **Android** but have not tested behavior on iOS - [ ] Both - **`react-native-firebase` version you're using that has this issue:** - `e.g. 5.4.3` - **`Firebase` module(s) you're using that has the issue:** - `e.g. Instance ID` - **Are you using `TypeScript`?** - `Y/N` & `VERSION`


mikehardy commented 4 years ago

You should try the @next tag to make sure you get the fixes from #3339 - many users have reported success with it, no current known problems - install that and re-test and please report back?

romainmarchand commented 4 years ago

@mikehardy

Hi! This issue is still actual on iOS for versions 6.4.1-alpha.0 (@next) and 6.7.1. I don't have any issue with Android.

I struggled with this these days and noticed it happens as soon as the auth module is installed (works perfectly fine when auth module is not installed). The issue happens even without any import and use of the auth module, just installing it.

Description: the messaging device token seems to get randomly unregistered, most likely when closing the app by swiping it away. It happens around 50% of the time when closing app. Then the server app (nodejs with 'firebase-admin' lib for me) fails to send its next message with error:

errorInfo: {
      code: 'messaging/invalid-registration-token',
      message: 'Invalid registration token provided. Make sure it matches the registration token the client app receives from registering with FCM.'
}

and all following messages with:

 errorInfo: {
      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.'
}

(I am 100% confident there is no mistake with the token on server side - it's exactly the same token and it suddenly stops working) I believe the first error is different than all following errors because the first error might cause "APNS Feedback Service to report the APNS token as invalid", as per the docs (at messaging/registration-token-not-registered): https://firebase.google.com/docs/cloud-messaging/send-message#admin

Tested with :

index.js:

/**
 * @format
 */

import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import notifee, { Importance } from '@notifee/react-native';
import messaging from '@react-native-firebase/messaging';

function onMessageReceived(message) {
  notifee.displayNotification(JSON.parse(message.data.notifee));
}

messaging().onMessage(onMessageReceived);
messaging().setBackgroundMessageHandler(onMessageReceived);

async function onAppBootstrap() {
  await messaging().registerDeviceForRemoteMessages();

  const channelId = await notifee.createChannel({
    id: 'default',
    name: 'Default Channel',
    importance: Importance.HIGH,
  });
}

notifee.onBackgroundEvent(async ({ type, detail }) => {
  const { notification, pressAction } = detail;
    // do nothing for now
});

onAppBootstrap();

AppRegistry.registerComponent(appName, () => App);

Unfortunatly its making messaging module quite unsuable for iOS in my case. If you have any suggestion or need more info I'm here.

Ehesp commented 4 years ago

Can you try setting up a token refresh listener? https://rnfirebase.io/reference/messaging#onTokenRefresh

Auth maybe causing this to refresh on "some event".

romainmarchand commented 4 years ago

Hi, so I tried setting up onTokenRefresh but I get an error everytime it's called, on both iOS and Android. The same error as reported in this issue : https://github.com/invertase/react-native-firebase/issues/3556

onTokenRefresh seems to be called at the first launch of the app, and then each time the messaging token is unregistered, e.g : 1 - Lauching the app. 2 - Crash due to onTokenRefresh. 3 - Launching the app. 4 - Foreground Messaging works well. 5 - Putting the app in background without closing. 6 - Background Messaging works well. 7 - Closing the app. 8 - Background messaging randomly continue working OR stop working. 9 - If it stopped working and I relaunch the app : Crash due to onTokenRefresh.

I made a public repo if you want to check my complete code, I only removed GoogleService-Info.plist and notifee.config.json: https://github.com/romainmarchand/rnfmessaging-test

AnhVu23 commented 4 years ago

Do we have any updates on this issue? I have the same issue with @romainmarchand.

dan-arkhipov commented 4 years ago

We are getting same issue here, any update on that?

rm167 commented 4 years ago

@AnhVu23 @dan-arkhipov On what device(s) does this issue occur for you guys? For me it is an old iPhone SE... I wonder if this issue also happens on recent iPhones...

(from @romainmarchand)

AnhVu23 commented 4 years ago

@rm167 We have issues with iPhone X and XR. After updating to newest firebase version, the function onTokenRefresh seems to work, but I sometimes get the error (like 10% of total tests).

romainmarchand commented 4 years ago

Ok, I guess it can occur on any kind of iPhone then. I am still having the invalid registration error as well for last versions: @react-native-firebase/app: 7.0.1 @react-native-firebase/auth: 7.0.2 @react-native-firebase/messaging: 7.0.1

hiren2728 commented 4 years ago

I am testing on iPhone SE (iOS 13.4) and having an invalid registration error for the latest version. "@react-native-firebase/app": "^7.0.1", "@react-native-firebase/auth": "^7.0.2", "@react-native-firebase/messaging": "^7.0.1", On iOS, Its work for a couple of minutes and getting notification but suddenly it's throwing error in cloud function for token which was working minute ago.

dan-arkhipov commented 4 years ago

@mikehardy by any chance you know if this issue could be prioritized or suggest a workaround in the meantime? This seems like it is blocking quite a lot of people now.

mikehardy commented 4 years ago

Sorry - I have no say in priorities other than when I go to fix things that directly affect me, and this one hasn't (yet) so I haven't put any effort into it

dan-arkhipov commented 4 years ago

@mikehardy we are happy to have a look, however we never had experience contributing before. Could you please guide us where do we start to look in order to tackle this problem effectively?

mikehardy commented 4 years ago

I think the best way to start is probably just to assume that all the code in node_modules/@react-native-firebase/* is your code too. You can go in there and instrument all you want, add debug statements all you want, breakpoints etc. So I'd take all the parts of code in there that wrap upstream SDK statements and at minimum I'd add log statements that show the current state of all objects going in to and coming out of the API calls to make sure things matched expectations

Note that 'patch-package' can be very useful for this as it can persist your Obj-C changes into git and they can be reproduced across all developer and CI machines so things are stable and you don't have some magic troubleshooting machine where the special code is

dan-arkhipov commented 4 years ago

@mikehardy thanks for that, given you are well familiar with the product, could you please direct us where exactly we should start looking in the code at the first place. We think that something invalidates the token or when token gets refreshed our .onTokenRefresh method is not firing.

mikehardy commented 4 years ago

Unfortunately I'm not familiar with this area at all - sorry, I think @Ehesp was the last one in there during the big sweep that was #3339

romainmarchand commented 4 years ago

@dan-arkhipov It's most likely something invalidating the token, because in normal behavior token are not refreshed very often.

Yesterday I looked into Auth module's index.js file (https://github.com/invertase/react-native-firebase/blob/master/packages/auth/lib/index.js) and noticed that the token wasn't unregistered anymore when commenting out some lines (but background messaging was not working either...), but the thing is that debugging iOS is a real pain for me (because I don't actually own a mac: I just use a slow remote mac, and I have to archive at every build, so it take's almost 1 hour and I can't get my real phone's logs). So I wasn't able to precisely find which part of the code is causing the issue and gave up for now. But if your mac setup is better than mine, maybe you could start by commenting out stuff in this file (like event listeners or other files imports). Just a suggestion though, I don't know much about how the library works...

There's also this file from messaging module, with a reference to Auth module at line 103 : https://github.com/invertase/react-native-firebase/blob/master/packages/messaging/ios/RNFBMessaging/RNFBMessaging%2BAppDelegate.m

I wonder if some part of messaging is handled by Auth module instead of Messaging module (as soon as Auth module is installed). If it's the case, it might be because of the phone number authentication process, that uses silent notifications. But again, just wild thoughts..

dan-arkhipov commented 4 years ago

@romainmarchand do you know if there is an official process in iOS to invalidate a token? I wonder if we can reverse engineer it by finding a method that does the invalidation and work backwards.

I can try to debug that and post here my findings here. Please feel free to suggest a few more things I should try to do.

romainmarchand commented 4 years ago

About invalidation, I don't know... About token change:

APNs issues a new device token to your app when certain events happen. The device token is guaranteed to be different, for example, when a user restores a device from a backup, when the user installs your app on a new device, and when the user reinstalls the operating system.

https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/HandlingRemoteNotifications.html#//apple_ref/doc/uid/TP40008194-CH6-SW1

stale[bot] commented 4 years ago

Hello 👋, to help manage issues we automatically close stale issues. This issue has been automatically marked as stale because it has not had activity for quite some time. Has this issue been fixed, or does it still require the community's attention?

This issue will be closed in 15 days if no further activity occurs. Thank you for your contributions.

roni-castro commented 4 years ago

I am having the same problem on iOS. When a token is generated it works fine, but when I close/reopen the app several times and send push during this process, it gets a previous token but for some reason it is invalid, even though it is returned by the messaging().getToken(). After trying to open/close the app a few times I get a new token, but it takes like 1 - 3 minutes, and during this period no push is received because of the InvalidRegistration or Not registered error and the fact the device does not have any valid token. It seems like the getToken returns an invalid token while it's generating a new one.

This almost always happens in this flow, and on this order:

-Push sent correctly (First request):

valid token

-InvalidRegistration Error (Second request, after closing and reopening the app a few times and opening it though notification)

InvalidRegistration

-Not registered Error (Third request made, just after the second one)

Captura de Tela 2020-06-20 às 01 27 48

From now on, all requests will return NotRegistered and no push is received

After some action of close/open the app, a new token is generated and returned by the messaging().getToken() and the flow mentioned above happens all again.

Observations:

roni-castro commented 4 years ago

Apparently this problem just happen on iOS if I am running on the release scheme of XCode. I released a new AdHoc version on AppCenter and the app stopped having the refresh token problem, maybe is something related to the Metro Bundler of RN or something related to the APNs key, I don't know... Apple stuff is just terrible to debug since it existence.

devpascoe commented 4 years ago

I am facing this on iOS only, android is fine. Worked without issue in the 5x days, followed upgrade paths to 6x and running into this. I use the firebase console to test. I can send to the iOS device for a while, then it stops receiving. If i send a push via firebaseadmin-sdk i get the registration-token-not-registered error. Just seems to drop off after a while. And i have also implemented the token refresh handler.

For now i am trying what @romainmarchand suggested and removing the auth module to see if that yields any result. So far initial pushes work. Will exit the app and periodically test throughout the day. fingers crossed we can narrow down an area to focus on to resolve this.

devpascoe commented 4 years ago

Update from me, after 2 days with the auth module omitted as per @romainmarchand suggested i am not receiving those fcm dropouts and the device gets every push note. I'll give it another day then will try re-adding auth again to prove that is where an issue may lie.

dan-arkhipov commented 4 years ago

Hey @devpascoe thank you very much for your input. Could you please let us know more what changes have you done and which files you have commented out? Does it have effect on authentication?

Thank you

romainmarchand commented 4 years ago

I am not sure why but it seems to work fine for me now. I choose another type of distribution for the archive, as @roni-castro suggested. I used to choose "Development - Distribute to members of your team." (signed with development certificate). Now I distribute with App Store Connect (distribution certificate) and I test with "Test Flight", and the issue doesn't occur anymore. I also updated react-native-firebase : react-native-firebase/app: 7.2.1 react-native-firebase/auth: 8.0.6 react-native-firebase/messaging: 7.1.6

CatalinVoss commented 3 years ago

Also seeing nightmare-ish inconsistency. This only happens for me on our app center build. Never locally, in debug mode.

stale[bot] commented 3 years ago

Hello 👋, to help manage issues we automatically close stale issues. This issue has been automatically marked as stale because it has not had activity for quite some time. Has this issue been fixed, or does it still require the community's attention?

This issue will be closed in 15 days if no further activity occurs. Thank you for your contributions.

stale[bot] commented 3 years ago

Closing this issue after a prolonged period of inactivity. If this is still present in the latest release, please feel free to create a new issue with up-to-date information.

lestarcdog commented 3 years ago

Happened consistantly that after the first initial iOS notification was received that the token become invalid. We have distributed the .apk with the development certs build within XCode

Publishing it on testflight with the production cert the notifications were received everytime. (Same device same code, firebase auth module is included)

dooleyb1 commented 3 years ago

This is currently happening to our production app with "react-native-firebase": "^5.5.5". Just recently finished a migration to the following more up to date versions which I hope will resolve the issue:

        "@react-native-firebase/analytics": "^7.6.4",
        "@react-native-firebase/app": "^8.4.3",
        "@react-native-firebase/auth": "^9.2.3",
        "@react-native-firebase/crashlytics": "8.3.0",
        "@react-native-firebase/messaging": "^7.8.6",
        "@react-native-firebase/remote-config": "^9.0.5",

This is affecting a large number of our users fcmTokens. Ran a dryRun test for notifications to all fcmTokens in our database and got the following results:

{ success: 8457, error: 5459 }

{
  'messaging/registration-token-not-registered': 5458,
  'messaging/invalid-registration-token': 1
}

@romainmarchand did you manage to get anywhere with the issue you were encountering?

romainmarchand commented 3 years ago

Hi @dooleyb1, I don't work on this anymore, but after my last message this issue didn't occur again for me (using App Store Connect).

freerider7777 commented 3 years ago

@dooleyb1 Is the issue resolved?

dooleyb1 commented 3 years ago

@dooleyb1 Is the issue resolved?

Not particularly, I've decided to just presume that these users with registration-token-not-registered have uninstalled the app and as a result their fcmToken has been unregistered. Not 100% on this though.

anujraghuvanshi commented 3 years ago

Any Solutions?

IngyuTae commented 3 years ago

Try to remove @react-native-firebase/analytics. I think there's a race condition issue between analytics and messaging modules. (don't forget to uninstall the pod as well after removing the package)

stackcru-tech commented 3 years ago

i am still receiving this , can anyone please help me? my versions "@react-native-firebase/app": "^6.7.1", "@react-native-firebase/auth": "^6.7.1", "@react-native-firebase/messaging": "^7.0.1", Error: '{"multicast_id":xxxxxxx,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"NotRegistered"}]}'

mikehardy commented 3 years ago

@stackcru-tech the first step to receiving help is to make sure you're on current stable versions, there is no telling how many issues have been found and resolved between your versions and v11.4.1 (current stable)

But the upgrade process itself isn't that hard! check the changelogs of the app auth and messaging packages for breaking changes until we hit v10, then all the changelog notes are in the main changelog - and there really aren't that many changes, we are just really strict on making a major version if there is any breaking change at all - https://invertase.io/blog/react-native-firebase-versioning

stackcru-tech commented 3 years ago

@mikehardy i am upgrading the versions to the latest stable version, 11.4.1 now i am facing this issue { [Error: [messaging/unknown] FIS_AUTH_ERROR] whenever i am getting the token Here is my code await messaging().registerDeviceForRemoteMessages(); await messaging().registerDeviceForRemoteMessages(); const token = await messaging().getToken(); i am facing this in ANDROID. i had also try implementation "com.google.firebase:firebase-messaging:20.1.0" but still facing the same issue

mikehardy commented 3 years ago

Probably need fresh Google plist and json coming from the versions you had, also enable devicecheck API (check firebase android auth docs)

stackcru-tech commented 3 years ago

@mikehardy I had done this but still facing the same issue.

mikehardy commented 3 years ago

You may want to open a new issue with full details vs posting on an old one but I can attest 100% that it works. The module works. So you have something project-specific and it will likely then not get a huge amount of priority as it will not result in any change in the module.

stackcru-tech commented 3 years ago

can you please let me now why this issue occurs?

stackcru-tech commented 3 years ago

@mikehardy i am also facing this, i had check all the logs in abd

Firebase Installations Service is unavailable. Please try again later.

mikehardy commented 3 years ago

@stackcru-tech I can't tell you why it is happening for your project, no. I can say that your versions were old enough you should look at it almost as a completely fresh integration and re-read the docs from that perspective. I also encourage you to try a fresh playground / toy app as a proof of concept it works, and I have a script that generates a full example skeleton so you may do so easily https://github.com/mikehardy/rnfbdemo/blob/master/make-demo.sh

I'm sorry you're having a difficult time with the upgrade, I know that is frustrating. But something is wrong with your project from the perspective of current firebase native libraries and you'll just have to slowly work through things to figure out what

RajeshSFS commented 2 years ago

Happened consistantly that after the first initial iOS notification was received that the token become invalid. We have distributed the .apk with the development certs build within XCode

Publishing it on testflight with the production cert the notifications were received everytime. (Same device same code, firebase auth module is included)

Can anyone explain, why it is working in production build and not development build?

Here are configuration at my side: "@react-native-firebase/admob": "^11.4.1" "@react-native-firebase/app": "^11.4.1" "@react-native-firebase/dynamic-links": "^11.4.1" "@react-native-firebase/messaging": "^11.4.1"

React native: 0.63.3 Xcode: 12.2 ios devices os: 14.6, 14.2

although it is working fine in testflight, but still want to know, if we missed any configuration, that's why it is not working in development builds.

suretarget commented 2 years ago

Happened consistantly that after the first initial iOS notification was received that the token become invalid. We have distributed the .apk with the development certs build within XCode

Publishing it on testflight with the production cert the notifications were received everytime. (Same device same code, firebase auth module is included)

I have the same issue “token become invalid” after first time received notification but after uninstall @react-native-firebase/analytics every working fine. If I’m not mistaken there is an open issue regarding this problem.

cmg-sovann commented 1 year ago

I am having the same problem on iOS. When a token is generated it works fine, but when I close/reopen the app several times and send push during this process, it gets a previous token but for some reason it is invalid, even though it is returned by the messaging().getToken(). After trying to open/close the app a few times I get a new token, but it takes like 1 - 3 minutes, and during this period no push is received because of the InvalidRegistration or Not registered error and the fact the device does not have any valid token. It seems like the getToken returns an invalid token while it's generating a new one.

This almost always happens in this flow, and on this order:

-Push sent correctly (First request):

valid token

-InvalidRegistration Error (Second request, after closing and reopening the app a few times and opening it though notification)

InvalidRegistration

-Not registered Error (Third request made, just after the second one)

Captura de Tela 2020-06-20 às 01 27 48

From now on, all requests will return NotRegistered and no push is received

After some action of close/open the app, a new token is generated and returned by the messaging().getToken() and the flow mentioned above happens all again.

Observations:

  • I am using this lib with notifee with a license on release mode.
  • The APNsToken returned by the messaging().getAPNSToken() never changed during several tests, while the FCMToken have refreshed more than three times. If I don't send any push notification the fcm token does not expires even doing a lot of close/open action. It just expired for me when I close/open the app and receives a notification between these actions.
  • I don't know if it is related to this problem, but during the tests the FCM server returned InternalServerError a few times, but the problem also happened when I received zero InternalServerError:
Captura de Tela 2020-06-20 às 01 45 55 Captura de Tela 2020-06-20 às 01 46 28

@roni-castro Have you found solution for this issues?