Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCM return error: field data must be a json array

When I using GCM, I got an error return as: field "data" must be a JSON array. Any one have some idea of how to solve it? Thank you. There is first part of my code, parts of code are omitted:

<?php

$gcm_regid = array();
$gcm_data = array();  
while ($row = mysql_fetch_array($result)) {
array_push($gcm_regid, $single_gcm_regid );
array_push($gcm_data , $notificationMessage);
}

?>

Here are the second part:

<?php

$url    = 'https://android.googleapis.com/gcm/send';

$apiKey = '******************************';
$registrationIDs = $gcm_regid;

$data = $gcm_data;

$fields = array('registration_ids' => $registrationIDs,
            'data' => $data);

//http header
$headers = array('Authorization: key=' . $apiKey,
             'Content-Type: application/json');

//curl connection
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
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);

echo $result;
?>
like image 709
Darren Liu Avatar asked Sep 28 '22 04:09

Darren Liu


1 Answers

Change from line 5 of your code

$message = $gcm_data;

$fields = array(
    'registration_ids' => $registrationIDs,
     'data' => array("message" =>$message)
);
like image 84
S raj Avatar answered Oct 03 '22 02:10

S raj