Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase FCM error JSON_PARSING_ERROR: Unexpected token END OF FILE at position

I am trying to send notifications through firebase's fcm service using php. Here is what I got so far:

$ch      = curl_init();
$payload = [
    'to'   => '/topics/'.ANDROID_TOPIC,
    'notification' => [
        'message' => 1
    ]
];
$headers = [
    'Content-Type: application/json',
    'Content-length: '.sizeof(json_encode($payload)),
    'Authorization: key='.FIREBASE_KEY
];

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($payload));

$result = curl_exec($ch );
curl_close($ch);

return $result;

However, I am getting Unexpected token END OF FILE at position 2 response from firebase.

What do you think is the reason this is happening?

like image 523
bthe0 Avatar asked Aug 01 '17 08:08

bthe0


People also ask

What is FCM server?

Firebase Cloud Messaging (FCM), formerly called Google Cloud Messaging (GCM), is a free cloud service from Google that allows app developers to send notifications and messages to users across a variety of platforms, including Android, iOS and web applications.

What protocol does FCM use?

FCM (Firebase Cloud Messaging) uses HTTP and XMPP Server Protocol serving JSON and Plain Text both. FCM Server Protocols Currently FCM provides these raw server protocols: FCM HTTP v1 API.


1 Answers

Remove Content-length line:

$header = array();
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: key=' . FIREBASE_KEY;

$payload = [
  'to' => 'verybigpushtoken',
  'notification' => [
    'title' => "Portugal VS Germany",
    'body' => "1 to 2"
  ]
];

$crl = curl_init();
curl_setopt($crl, CURLOPT_HTTPHEADER, $header);
curl_setopt($crl, CURLOPT_POST,true);
    curl_setopt($crl, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($crl, CURLOPT_POSTFIELDS, json_encode( $payload ) );

curl_setopt($crl, CURLOPT_RETURNTRANSFER, true );
// curl_setopt($crl, CURLOPT_SSL_VERIFYHOST, false); should be off on production
// curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, false); shoule be off on production

$rest = curl_exec($crl);
if ($rest === false) {
    return curl_error($crl)
}
curl_close($crl);
return $rest;
like image 101
Alexi Akl Avatar answered Nov 15 '22 07:11

Alexi Akl