Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Help wanted: firebase.messaging().getToken() returns null #1429

Closed
chinalwb opened this issue Aug 23, 2018 · 29 comments · Fixed by #1724
Closed

Help wanted: firebase.messaging().getToken() returns null #1429

chinalwb opened this issue Aug 23, 2018 · 29 comments · Fixed by #1724
Labels
Service: Messaging FCM only - ( messaging() ) - do not use for Notifications

Comments

@chinalwb
Copy link

chinalwb commented Aug 23, 2018

Issue

By following the guide of Cloud Messaging, the following code:

firebase.messaging().getToken()
  .then(fcmToken => {
    if (fcmToken) {
      // user has a device token
    } else {
      // user doesn't have a device token yet -- **my problem is here**
    } 
  });

My problem is getToken() returns null. Want to know what to do to re-get the token.

const playService = firebase.utils().playServicesAvailability
console.log('play service', playService)

It prints:

play service {isAvailable: true, status: 0}

P.S.: I can get the token on my Android Studio emulator, but for the above case, I cannot get the token on my real device, it is a HuaWei Honor 8, runs Android 7.0.

Environment

  1. Application Target Platform: Android
  1. Development Operating System: macOS Sierra
  1. Build Tools: Android Studio
  1. React Native version: 0.55.4
  1. React Native Firebase Version: 4.3.0
  1. Firebase Module: messaging
  1. Are you using typescript? no

Loving react-native-firebase? Please consider supporting them with any of the below:

@Ehesp
Copy link
Member

Ehesp commented Sep 6, 2018

Could you check the result of hasPermission()?

@Ehesp Ehesp added the Service: Messaging FCM only - ( messaging() ) - do not use for Notifications label Sep 6, 2018
@cx5168
Copy link

cx5168 commented Sep 11, 2018

 my solution:

      const res = Firebase.messaging().requestPermission();
      await res.promise;
      setTimeout(() => {Firebase.messaging().getToken().then(()=>{...})},3000)

You can have a try.

@chinalwb
Copy link
Author

@Ehesp

firebase.messaging().hasPermission()
      .then(enabled => {
        if (enabled) {
          // user has permissions
          console.log('User has fcm permission')
          this.registerFcmMessageListener()
        } else {
          // user doesn't have permission
          console.log('User doesn\'t have fcm permission')
          firebase.messaging().requestPermission()
            .then(() => {
              // User has authorised
              console.log('User has authorised fcm')
              this.registerFcmMessageListener()
            })
            .catch(error => {
              // User has rejected permissions
              console.log('User has rejected fcm permissions, error = ', error)
            })
        }
      })

The above code prints 'User has fcm permission'

@chinalwb
Copy link
Author

@cx5168 Thank you, but this still doesn't work for me.

Here is my code:

  getFcmToken() {
    firebase.messaging().getToken()
      .then(fcmToken => {
        if (fcmToken) {
          console.debug('fcm token ==', fcmToken)
          this.props.dispatch(fcmRegister(fcmToken))
        } else {
          // user doesn't have a device token yet
          console.debug('User doesn\'t have a device token yet, token = ', fcmToken)
          firebase.messaging().requestPermission()
          setTimeout(() => {
            this.getFcmToken()
          }, 3000)
        }
      })
  }

@cx5168
Copy link

cx5168 commented Sep 11, 2018

@chinalwb
It takes time for the server to generate tokens, and getToken can't get tokens without waiting for the server to return the promise.

In addition, the firebase version of the build.gradle file is recommended to upgrade to the latest.
app/build.gradle:

implementation "com.google.firebase:firebase-messaging:17.3.0"
implementation "com.google.android.gms:play-services-base:15.0.1"
implementation "com.google.firebase:firebase-core:16.0.3"

End of the document to add:
com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true

I hope you can succeed.

@Ehesp
Copy link
Member

Ehesp commented Sep 11, 2018

@chinalwb requestPermission is a promise which you need to wait for

@chinalwb
Copy link
Author

@cx5168 Thanks very much! It takes time for the server to generate tokens would this means, the token finally needs to be generated at fcm server? If so that will make sense, my phone is not able to access to fcm server (but my emulator is able to do that and there is no problem to the emulator).

Thanks again.

@chinalwb
Copy link
Author

@Ehesp Thank you! Per @cx5168 's comment, the token is generated at server-side, so at first I need to check the network on my phone to make sure it is able to connect to FCM server.

Thanks again.

@chinalwb
Copy link
Author

I'll come back to close this thread after I am done with the network problem and double checked.

@gavin-gmlab
Copy link

I'm also seeing this problem the 1st time I install the app on the actual device. I will need to kill the app then relaunch to get the token successfully. Not great for user experience though. How can we make this more reliable?

@cx5168
Copy link

cx5168 commented Sep 12, 2018

@cx5168 Thanks very much! It takes time for the server to generate tokens would this means, the token finally needs to be generated at fcm server? If so that will make sense, my phone is not able to access to fcm server (but my emulator is able to do that and there is no problem to the emulator).
Thanks again.

Mobile phones must be able to connect to servers that provide firebase services.
The simulator can not provide deviceid to generate token, so it needs to be tested with real machine.

@chinalwb
Copy link
Author

@cx5168 Got it, thanks!

BTW, just FYI, my emulator does provide me the FCM token.

@Ehesp Ehesp closed this as completed Sep 13, 2018
@jperezr13
Copy link

Hello, in Android 8.0 is not returning the token, there are some solution for this.

@chinalwb
Copy link
Author

Sometimes I get token = null as well, maybe this issue should be reopen

@efstathiosntonas
Copy link
Contributor

Any news in this? Still getting null, tried all methods above

@efstathiosntonas
Copy link
Contributor

According to docs, getToken() is deprecated. Other than that, docs state:

Returns the automatically generated token for the default Firebase project.
This generates an Instance ID if it does not exist yet, which starts periodically sending information to the Firebase backend (see getId()).
Returns
the master token or null if the token is not yet available

@efstathiosntonas
Copy link
Contributor

efstathiosntonas commented Dec 2, 2018

Ok folks, here's the deal:

In RNFirebaseMessaging.java replace getToken method with:

  @ReactMethod
  public void getToken(Promise promise) {
    try {
      String senderId = FirebaseApp.getInstance().getOptions().getGcmSenderId();
      String token = FirebaseInstanceId
              .getInstance()
              .getToken(senderId, "FCM");
      Log.d(TAG, "Firebase token: " + token);
      promise.resolve(token);
    } catch (Throwable e) {
       e.printStackTrace();
       promise.reject(null,e.getMessage());
    }
  }

don't forget to import FirebaseApp import com.google.firebase.FirebaseApp;

Tested on emulator, not on real device.

@HasanAlyazidi
Copy link

Mr. @efstathiosntonas please bump the package version, so we can update RNFirebaseMessaging.java from npm/yarn.

@faisalpathan
Copy link

faisalpathan commented Dec 19, 2018

@efstathiosntonas , it is showing this error , please can anyone help , i am using

react-native-firebase:4.3.8
react-naive: 0.55.4

Error: INVALID_SENDER
    at createErrorFromErrorData (NativeModules.js:121)
    at NativeModules.js:78
    at MessageQueue.__invokeCallback (MessageQueue.js:398)
    at MessageQueue.js:137
    at MessageQueue.__guardSafe (MessageQueue.js:314)
    at MessageQueue.invokeCallbackAndReturnFlushedQueue (MessageQueue.js:136)
    at debuggerWorker.js:70

@efstathiosntonas
Copy link
Contributor

@faisalpathan have you added google services json and plist from firebase in your project? It seems that firebase is not initiating thus you dont have sender id.

@faisalpathan
Copy link

faisalpathan commented Dec 19, 2018

@efstathiosntonas , google-services.json is already present in android/app folder of the application and also the notification permission is also granted

i have just replaced getToken method with above mentioned code , is it correct ?

@efstathiosntonas
Copy link
Contributor

efstathiosntonas commented Dec 20, 2018

@faisalpathan @cx5168 this has nothing to do with this modification, there is something wrong with your setup/configuration. The change I've made is according to docs so there's nothing wrong.

For example, to get a token that can be used to send messages to an application via FirebaseMessaging, set authorizedEntity to the sender ID, and set scope to "FCM".

@faisalpathan
Copy link

@efstathiosntonas , please can you share your configuration and which version of react-native-firebase you are using ?

@cx5168
Copy link

cx5168 commented Dec 20, 2018

@efstathiosntonas You're right. I've tried several times and I can get token normally. Thank you very much.

@faisalpathan
Copy link

@cx5168 can you share your configuration as well ?

@cx5168
Copy link

cx5168 commented Dec 20, 2018

Environment:
OS: Windows 10
Node: 8.11.3
Yarn: 1.12.3
npm: 5.6.0
Watchman: Not Found
Xcode: N/A
Android Studio: Not Found

Packages: (wanted => installed)
react: 16.2.0 => 16.2.0
react-native: 0.53.3 => 0.53.3

react-native-firebase: 4.3.8

android/build.gradle:
classpath 'com.android.tools.build:gradle:3.1.3'
classpath 'com.google.gms:google-services:4.0.1'

android/app/build.gradle
implementation "com.google.android.gms:play-services-base:15.0.1"
implementation "com.google.firebase:firebase-core:16.0.3"
implementation "com.google.firebase:firebase-messaging:17.3.0"

apply plugin: 'com.google.gms.google-services'
com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true

android/app/google.services.json

source:
const res = Firebase.messaging().requestPermission();
Firebase.messaging().getToken().then(async (token) => {console.log(token);});

@faisalpathan
Copy link

faisalpathan commented Dec 20, 2018

@cx5168 , thank you so much for the configuration , Really Appreciated. Still getting the same error as

 Error: INVALID_SENDER
    at createErrorFromErrorData (NativeModules.js:121)
    at NativeModules.js:78
    at MessageQueue.__invokeCallback (MessageQueue.js:398)
    at MessageQueue.js:137
    at MessageQueue.__guardSafe (MessageQueue.js:314)
    at MessageQueue.invokeCallbackAndReturnFlushedQueue (MessageQueue.js:136)
    at debuggerWorker.js:70 

any solution anyone can help with ?

@cx5168
Copy link

cx5168 commented Dec 20, 2018

@faisalpathan
It looks like an error caused by an invalid registration. I think your google-services.json configuration is not working.

@caobo171
Copy link

caobo171 commented Apr 1, 2020

I checked the native code , maybe your issue is like me, I resolved by follow this issue , turn on/off push notification capability
https://github.com/firebase/quickstart-ios/issues/111

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Service: Messaging FCM only - ( messaging() ) - do not use for Notifications
Projects
None yet
9 participants