bthe0
bthe0

Reputation: 1434

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?

Upvotes: 6

Views: 8689

Answers (1)

Alexi Akl
Alexi Akl

Reputation: 1942

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;

Upvotes: 9

Related Questions