phpfirebasefirebase-cloud-messaging

Sending data with push notification to Android with PHP


According to this docs, there is the field data which I'm trying to use:

$fields = [
    'message' => [
        'token' => $deviceToken,
        'notification' => [
            'title' => $notifTitle,
            'body' => $notifDesc
        ],
        'data' => $data
    ]
]; 

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/v1/projects/bla/messages: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) . '<br><br>';
print($result);

This is what $data contains:

array(11) {
  ["title"]=>
  string(21) "Antwort auf Kommentar"
  ["msg"]=>
  string(29) "Cornholio hat dir geantwortet"
  ["image"]=>
  string(12) "30321555.jpg"
  ["notifType"]=>
  string(5) "reply"
  ["channelID"]=>
  string(21) "channel_reply_comment"
  ["memeID"]=>
  int(20202)
  ["memeTitle"]=>
  string(10) "meme title"
  ["meme"]=>
  string(19) "TrlNO38.mp4"
  ["size"]=>
  string(7) "460|818"
  ["commentCount"]=>
  int(7)
  ["mentioned"]=>
  int(1)
}

And I get this error:

{ "error": { "code": 400, "message": "Invalid value at 'message.data[5].value' (TYPE_STRING), 20202\nInvalid value at 'message.data[9].value' (TYPE_STRING), 7\nInvalid value at 'message.data[10].value' (TYPE_STRING), 1", "status": "INVALID_ARGUMENT", "details": [ { "@type": "type.googleapis.com/google.rpc.BadRequest", "fieldViolations": [ { "field": "message.data[5].value", "description": "Invalid value at 'message.data[5].value' (TYPE_STRING), 20202" }, { "field": "message.data[9].value", "description": "Invalid value at 'message.data[9].value' (TYPE_STRING), 7" }, { "field": "message.data[10].value", "description": "Invalid value at 'message.data[10].value' (TYPE_STRING), 1" } ] } ] } }

I was able to send data like this with the old API, but how to do this with the current one?


Solution

  • Solution:

    To resolve issues with sending data in Firebase Cloud Messaging, you need to convert all values in the data key to strings. This avoids “Invalid value” errors when sending the data. Here’s how to do it:

    before $fields add this to convert you all data in string :

    foreach ($data as $key => $value) {
        $data[$key] = (string) $value;
    }