我正在开发一个应用程序,我必须在其中集成 GCM 功能。收件人的 device_id 存储在 MySQL 数据库中,然后通过 CURL 检索并发送到 Google GCM API url。问题是我这样做时收到错误消息:
Recipients_Id field is not a JSON Array.
php代码是:
//get the recipients gcm_ids
if (isset($_POST["deviceid"]) && isset($_POST["message"]) && isset($_POST["recipient_id"])) {
require_once __DIR__ . '/db_connect.php';
include_once './GCM.php';
$gcm = new GCM();
// connecting to db
$db = new DB_CONNECT();
$device_id=$_POST['deviceid'];
$recipient_id=$_POST['recipient_id'];
$get_details=mysql_query("select id,name from gcm_users where gcm_regid='$device_id' ");
$row_details=mysql_fetch_array($get_details);
$user_name=$row_details["name"];
$user_id=$row_details["id"];
$recipients_gcm_ids=mysql_query("SELECT gcm_regid from gcm_users where id='$recipient_id'");
$rec_gcm1=array();
while($row = mysql_fetch_assoc($recipients_gcm_ids))
{array_push($rec_gcm1,$row);}
$recipients_gcm=array();
$recipients_gcm=json_encode($rec_gcm1);
$message = array("price" => $message1);
$result = $gcm->send_notification($recipients_gcm, $message);
//The class that sends the message to the Google API url
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($Recipients_Id, $message) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'Recipients_Id' => $Recipients_Id,
'data' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo "Result Is:".$result;
}
我知道这个问题与这行代码有关:
$result = $gcm->send_notification($recipients_gcm, $message);
但是,除了使用“json_encode”函数之外,我还不知道我将使用什么方法在 PHP 中创建 JSON 数组。也许还有另一种方法可以规避:
"Not a JSON Array" error ?
顺便说一下 print_r($recipients_gcm) 的输出是:
[{"gcm_regid": "ABCDEFGH12y63i4455u65y4i4p4yu4t3i3zzttyuuiioo"}]