Laurent
Laurent

Reputation: 1563

Firebase Cloud Message (FCM) : trying to send message to device from PHP (error: InvalidRegistration)

I'm trying to send push messages from PHP but I'm getting the following error message:

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

I suppose there is a mismatch with the browser ID but I don't know which one I'm supposed to use.

When I register the push notification through JS, I receive the following payload on my PHP server:

{"endpoint":"https://fcm.googleapis.com/fcm/send/XXX:YYY","expirationTime":null,"keys":{"p256dh":"ZZZ","auth":"AAA"}}

To send the message in PHP, I have used the following code (found on stackexchange):

function sendnotification($to, $title, $message, $img = "", $datapayload = "")
{
    $msg = urlencode($message);
    $data = array(
        'title'=>$title,
        'sound' => "default",
        'msg'=>$msg,
        'data'=>$datapayload,
        'body'=>$message,
        'color' => "#79bc64"
        );

    if($img)
        {
            $data["image"] = $img;
            $data["style"] = "picture";
            $data["picture"] = $img;
        }
        
    $fields = array(
        'to'=>$to,
        'notification'=>$data,
        'data'=>$datapayload,
        "priority" => "high",
        );
        
    $headers = array(
        'Authorization: key=MYSERVERKEY',
        'Content-Type: application/json'
        );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
    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, json_encode($fields));
    $result = curl_exec($ch);
    curl_close( $ch );
    return $result;

I think I'm using the right server key, when I don't, I get a different error message.

For $to, I'm wondering what I should use. I thought I had to use XXX:YYY after the endpoint but it's not working (XXX is very short, YYY is very long). I have also tried ZZZ and AAA but it doesn't help either.

My questions:

What kind of ID should I be using to send the message to one specific browser ?

What should I do to send a notification to all registered browser?

Thanks!

Upvotes: 1

Views: 949

Answers (1)

Gaurang
Gaurang

Reputation: 147

Well you have to make sure store the token of your user browser, which you can only get when they allow on request prompt e.g.

enter image description here

On user Allow the request it generate the token which look like as below

enter image description here

This token you can use for send the message to specific browser.

So in your code where as your $to = it should be the device token.

i.e. "to": "<DEVICE_REGISTRATION_TOKEN>"

Upvotes: 1

Related Questions