27

I am getting weird issue of sending push notification to Android using FCM.

Goal :- Having error while sending push notification

Below is the scenario I do have function for sending push notification to Android

 public static function SendMultipleNotificationAndroid($groups)
    {
        //your api key SERVER API KEY
        $apiKey = Yii::$app->params['android_api_key'];
        $url = 'https://fcm.googleapis.com/fcm/send';    
        $headers = array(
            'Authorization:key=' . $apiKey,
            'Content-Type: application/json'
        );
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        foreach($groups as $resG){
            $users  = $resG['users'];                        
            $msg    =   $resG['message'];
            $type    =   $resG['notification_type'];
            $notification_data    =   $resG['notification_data'];

            $deviceTokens = [];
            foreach($users as $resUser){
                $deviceTokens[] = $resUser['device_token'];
                //Add  Friend badge count +1
                Common::AddRemoveBadgeCount($resUser['user_id']);
            }
            if(!empty($deviceTokens)){
                $fields = array(
                    'registration_ids' => $deviceTokens,
                    'priority'     => 'high', 
                    'collapse_key' => $resG['notification_type'],   
                    'time_to_live' => 2419200,     
                    "click_action" =>"NotificationListingActivity",     
                    'data'         => [                  
                        "title"             => "ProjectName",
                        "body"              => $resG['message'],
                        "action_tag"        => $resG['notification_type'],
                        "message"           => $resG['message'],
                        'notification_type' => $type,
                        'notification_data' => $notification_data,
                        'sound'             => 'default',
                    ]
                );
                //Print result 
                p($ch,0);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
                curl_exec($ch);
            }            
        }
        curl_close($ch);
    }

So the issue is when I send single notification it works fine but when I send multiple notification I got error every time

<pre>Resource id #5</pre>{"multicast_id":4818908994630396118,"success":1,"failure":1,"canonical_ids":0,"results":[{"error":"NotRegistered"},{"message_id":"0:1487136045570022%c3bae3c6002e9358"}]}

<pre>Resource id #5</pre>{"multicast_id":5218359780835228544,"success":1,"failure":1,"canonical_ids":0,"results":[{"error":"NotRegistered"},{"message_id":"0:1487136046618669%c3bae3c6002e9358"}]}

As we debug the code we do have device token in our database no firewall which stops sending push notifications.

Every time I call above function I get

"error":"NotRegistered"
double-beep
  • 5,031
  • 17
  • 33
  • 41
Shashank Shah
  • 2,077
  • 4
  • 22
  • 46

18 Answers18

23

According to the doc its because the mobile device testing does not have your app installed anymore

If it is NotRegistered, you should remove the registration ID from your server database because the application was uninstalled from the device, or the client app isn't configured to receive messages.

Sahan Maldeniya
  • 1,028
  • 1
  • 14
  • 21
  • 2
    No it was not the case!! I have sent multiple notification there! some of the notification were sent successfully and some having NotRegistered error. In both cases application was installed in the device. – Shashank Shah Dec 04 '18 at 06:17
  • 1
    "some of the notification were sent successfully and some having NotRegistered error." -> Having same issue @ShashankShah, Can you share something if you got work around? – Nandam Mahesh Nov 14 '20 at 12:50
  • After search 4 fours i make sure this is the correct answer. – Dorbagna Feb 07 '23 at 13:42
21

Don't know much about php, but recently I have faced the same issue in another project and I have resolved this way :

Refere this first : Where can I find the API KEY for Firebase Cloud Messaging?

and get updated API key as shown in below snapshotenter image description here

Community
  • 1
  • 1
Maddy
  • 4,525
  • 4
  • 33
  • 53
  • 1
    @maddy this did not worked for me. I've changed the server key when making the request but still i'm getting the same error. – AIon Mar 01 '18 at 11:10
  • @AIon, send a test notification from firebase console, if it is working then the problem might be from your side. – Maddy Mar 01 '18 at 11:12
10

This is a client-side (device) issue, not service-side. Multiple scenarios can cause this:

  • If the client app unregisters with GCM.
  • If the client app is automatically unregistered, which can happen if the user uninstalls the application. For example, on iOS, if the APNS Feedback Service reported the APNS token as invalid.
  • If the registration token expires (for example, Google might decide to refresh registration tokens, or the APNS token has expired for iOS devices).
  • If the client app is updated but the new version is not configured to receive messages.

See https://developers.google.com/cloud-messaging/http-server-ref

On app startup I check to see if the token I have stored locally matches the new token. If not then I refresh the token on my servers. I also do this in FirebaseInstanceIDService::onTokenRefresh.

Dan
  • 473
  • 3
  • 7
7

The thing is firebase generates a unique device-ID for your target device when the app is run for the first time, and it will be used as the identity of the device.

If the user uninstalls the app or clears the data of the app then in that case on reinstalling or reopening the app the device-ID will differ. This will result in the ID not be identified by firebase to send the notification. This will result in the error Not Registered

tobias47n9e
  • 2,233
  • 3
  • 28
  • 54
Mahesh Jamdade
  • 17,235
  • 8
  • 110
  • 131
3

I got this error when i uninstalled and reinstalled my application.

What i think is, when we reinstall application, we cant get a new fcm token every time we install.

So, we must first delete the previous instance id and then create new fcm token. Please see the code below..

Just adding the uncommented line resolved my issue..

See first comment for this solution for code :)

_firebaseRegister() { 
    // _firebaseMessaging.deleteInstanceID(); 
    _firebaseMessaging.getToken().then((token) => fcmtoken = token); 
}

Hope this works for you! :)

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
2

In my case, the problem was on the recipient side, not the sender. If you're sending a message to someone who has not run the app for awhile, then their device token is stale. All they need to do is restart the app.

In your case, did you ensure that when you sent multiple notifications all the devices you messaged were up and running and that the app refreshes the token on startup by calling FirebaseMessaging.getInstance().getToken()?

FractalBob
  • 3,225
  • 4
  • 29
  • 40
1

While searching for the "NotRegistered" issue, we found the following ...

At device end, the generation of device notification token was done by following code once, when user first time starts the app after installation.

RegToken = FirebaseInstanceId.getInstance().getToken(senderId, "FCM");  // Old code

We were using other class derived from "FirebaseMessagingService" to create / receive notifications. But the following method was missing in that class.

// New code
@Override
public void onNewToken(String token) {
    Log.d(TAG, "Refreshed token: " + token);

    // If you want to send messages to this application instance or
    // manage this apps subscriptions on the server side, send the
    // Instance ID token to your app server.
    sendRegistrationToServer(token);
 }

We found that, the above method was called by FCM system in device on every start of App. ( The App was not Uninstalled, still the method was giving different token every time. ) So we called our method 'sendRegistrationToServer(token);' to submit the token to our server along with the 'DeviceId' and other identification data. When we sent notification from php server on this token, it returned 'sent' instead of "NotRegistered".

SHS
  • 1,414
  • 4
  • 26
  • 43
  • I agree with your way you are doing. But i have one question, what if some user not open app for while and that between device token is changed.? What should we have to do ? – Nils Jun 17 '21 at 09:03
  • @Nils the token changes only when app is opened ( every start of app ). So if app is not opened, token is not going to change. You may try at your end, and confirm here. – SHS Jun 18 '21 at 14:38
  • that's great for me. In my case when user install app i got notification for 3-5 days. And If user not use app for 4-5 days. I did not get any push notification. Any idea what went i wrong ? – Nils Jun 21 '21 at 10:13
1

I have a 100 percent solution i had fix recently this issue this error, occurring because you are sending this notification on a device which does does not contain your firebase setup api key For example when you registered user that time user registered from different firebase setup so your android token was different and your sending request to other firebase setup for which didn't create android token whom you trying to send notification(message) so you would have to make sure your user android token generating from same firebase project of which project you are using firebase api key

msk
  • 46
  • 4
1

This error appeared in an Android application when sending request to https://fcm.googleapis.com/fcm/send:

...
"results": [
    {
        "error": "NotRegistered"
    }
]

While the application was working well for some time, and push notifications were delivered, then (probably after reauthorization in the app or reauthorization in Play Market) that error started to show.

If I changed push token (added "1", for instance), then I got another error:

"results": [
    {
        "error": "InvalidRegistration"
    }
]

So, Firebase knew about the push token, but didn't deliver a notification.

I uninstalled the Android application and installed again.

CoolMind
  • 26,736
  • 15
  • 188
  • 224
1

My problem was different then all of the above. The Firebase message that we we're trying exceeded the maximum size of 4Kb. Very small chance this triggers an "NotRegistered". But the problem was that I took this log of a moment the app was probably not installed. So also check the size of the Firebase message.

jobbert
  • 3,297
  • 27
  • 43
1

In our case, this issue appears on iOS when we override a production installation of the app using Xcode "Run" (replaces production app with the debug version in-place).

The app still receives the same registration token, but doesn't accept messages (NotRegistered is returned from the FCM).

We've found out that uninstalling the app from the device, and performing a clean install fixes this issue.

Martin Janeček
  • 560
  • 4
  • 20
1

In my case, updating the FCM token for the device worked!

M.AQIB
  • 359
  • 5
  • 11
1

For iOS, I ran into the same issue. We were only saving the token on didRegisterForRemoteNotificationsWithDeviceToken. As mentioned above, you can lose reference to the token for a variety of reasons.

To fix the "NotRegistered" error, I added the following to App Delegate:

extension AppDelegate: MessagingDelegate {
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Firebase registration token: \(String(describing: fcmToken))")

        //Notification setup. Token will be available anywhere
        let dataDict: [String: String] = ["token": fcmToken ]
        NotificationCenter.default.post(
            name: Notification.Name("FCMToken"),
            object: nil,
            userInfo: dataDict
        )

        // Send token to application server.
        if Auth.auth().currentUser?.uid != nil {
            guard let userUid = Auth.auth().currentUser?.uid else { return }
            let dataBaseRef = Database.database().reference()
            let value: [String : Any] = ["pushToken" : fcmToken]
            
            dataBaseRef.child("Your database path here").updateChildValues(value, withCompletionBlock: { (error, ref) in
                
                if error != nil {
                    print("Error with storing/updating user token", error?.localizedDescription as Any)
                }
            })
        }
    }
}

didReceiveRegistrationToken is called anytime the token is updated.

1

In my case, two cloned emulators are the reason. I think cloned emulators have same device ID, so firebase think they are same device. So when one device get a push message, the push token may be removed and return not NotRegistered. If you are in the similar situation, try to remove the emulator and create new one.

hoi
  • 2,168
  • 20
  • 22
1

A possible solution can be update user push token. When the client app is updated (new version), old push token is changed.

1

I got this error after setting firebase and using app for some time.

I updated google-service.json file (look for new file in the user's personal account firebase) and reinstall app. It helps me.

Andres
  • 51
  • 1
  • 6
1

After uninstalling the app in my device, the error occurred. That was because my code wasn't set up to regenerate a new fcm device token. The firebase documentation for this API recommends to call the method at app start and update your backend (or wherever you're using the tokens). I fixed it with the snippet below:

import {Platform} from 'react-native';
import messaging from '@react-native-firebase/messaging';

 useEffect(() => {
    requestPermission();
    messaging()
      .getToken()
      .then(async token => {
        console.log('_token=>>>', token);

        if (token) {
          setDeviceToken(token);
          // update user realtime fdb with device token and userIdToken
          const _authDriverIdRef = firebase
            .database()
            .ref(`users/${user.uid}`);
          _authDriverIdRef.update({
            fcmDeviceToken: deviceToken,
            userIdToken: await user?.getIdToken(true),
          });
        }
      });
  });

  const requestPermission = async () => {
    return Platform.OS === 'ios' && (await messaging().requestPermission());
  };
Okpo
  • 375
  • 4
  • 9
0

See if you have uninstalled the app and your device token is modified. Update the device token, and your error will be gone