Capacitor push notification and FCM generate different tokens, crashes android

Viewed 1309

Ionic 5 app with Capacitor push notification and FCM plugins.

import { FCM } from '@capacitor-community/fcm';

import {
  ActionPerformed,
  PushNotificationSchema,
  PushNotifications,
  Token,
} from '@capacitor/push-notifications';

Why do they both generate different tokens??

For Capacitor/PushNotifications, the following generates a token

PushNotifications.addListener('registration',
        async (token: Token) => {
          console.log('token: ' + token.value);
        }
      ).catch(e=>{alert('reqPerm'+e)});

While for FCM, the following generates a different token

FCM.getToken()
      .then(async (r) => {
         console.log(`token saved ${r.token}`)
        })
      .catch((err) => console.warn('error saving token', err));

The FCM token works on iOS (iPhone receives notifications), but registering it on Android, it says something about invalid token registered. So I had to use the token from PushNotifications.addListener for Android, but when it receives a notification, the app crashes.

I made sure that the google-services.json file is in the android/apps folder.

What gives?? Any suggestions?

1 Answers

Yes, in new update FCM is returning JWT token. There is a workaround for it same as iOS. you need to register for it before you get token.

getToken() {
    PushNotifications.requestPermissions().then(async (permission) => {
        if (permission.receive == "granted") {
            // Register with Apple / Google to receive push via APNS/FCM
            if (Capacitor.getPlatform() == 'ios') {
                await PushNotifications.register();
                PushNotifications.addListener('registration', (token: Token) => {
                    FCM.getToken().then((result) => {
                        console.log(result.token); // This is token for IOS
                    }).catch((err) => console.log('i am Error', err));
                })
            } else if (Capacitor.getPlatform() == 'android') {
                await PushNotifications.register()
                PushNotifications.addListener('registration', async ({ value }) => {
                    let androidToken = value; // this is token for Android use this token
                });
            }
        } else {
            // No permission for push granted
            alert('No Permission for Notifications!')
        }
    });

}
Related