当我使用GCM时,我得到一个错误返回:字段“data”必须是JSON数组。任何人都知道如何解决它?谢谢。 我的代码的第一部分,部分代码被省略:
<?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);
}
?>
以下是第二部分:
<?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;
?>
答案 0 :(得分:4)
从代码的第5行更改
$message = $gcm_data;
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array("message" =>$message)
);
答案 1 :(得分:0)
在$fields
对象上使用json_encode返回JSON表示。
查看已接受的答案here,了解它是如何使用的。