phpfirebasecurlfirebase-notifications

"error":"InvalidRegistration" while sending notification from PHP


Trying the mentioned code with registeration_ids and to parameter and both are not working. Help me to solve the same. Every time it is giving this error of multi cast id and InvalidRegistration. Getting this error: {"multicast_id":8367359766XXXXXXXXX,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

function send_notification () {
    $fcmUrl = 'https://fcm.googleapis.com/fcm/send';
    $args = func_get_args();
    $response = ["status" => 0, "message" => "Notification couldn't be sent"];

    $title = "Hey test notification";
    $body = "";
    $apiKey = "QWERTYHHVCFVBVBN";//Server key under the Project settings
    $tokenArr = ["XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX","YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY"];
    $refId = 123;
    $msgNotification = [
        "title" => $title,
        "body" => $body
    ];
    $extraNotificationData = [
        "refId" => $refId,
        "title" => $title
    ];

    $fcmNotification = [
        "registration_ids" => $tokenArr,
        "notification" => $msgNotification,
        "data" => $extraNotificationData
    ];
    $headers = [
        "Authorization: key=" . $apiKey,
        "Content-Type: application/json"
    ];
    
    $encodedData = json_encode($fcmNotification);
    // echo "<pre>";print_r($fcmNotification);exit;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$fcmUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $encodedData);
    $result = curl_exec($ch);
    if ($result === FALSE) {
        die("Curl failed: " . curl_error($ch));
    }
    print_r($result);exit;
    curl_close($ch);
    $response = ["status" => 1, "message" => "Notification sent to users", "payload" => $result];

    return $response;
}

Solution

  • Invalid Registrations usually have one of the following reasons:

    In all cases, except the last one, you can remove the registration token from your server and stop sending notifications to it.

    The $fcmUrl = 'https://fcm.googleapis.com/fcm/send'; shows that you're using the legacy FCM API to send your messages. Please note that, unless you're relying on device group notifications, Google recommends migrating to the newer HTTP v1 API.