When I am using GCM for push notification , I got an error return as: field "data" must be a JSON array. When user create the new post then notification will be send to all Registered devices. Any one have some idea of how to solve it? Thank you.
当我使用GCM进行推送通知时,我得到一个错误返回:字段“data”必须是一个JSON数组。当用户创建新的post时,通知将发送到所有注册的设备。有人知道怎么解它吗?谢谢你!
function Notification($post) {
global $wpdb;
$pub_post = get_post($post_ID);
$post_title=$pub_post->post_title;
$totalrecord = $this->get_allrecord();
$message = "Your New post, " .$post_title." has been published";
if (count($totalrecord) > 0) {
//$display_row = null;
foreach ($totalrecord as $row) {
$a = $row->token;
$this->sendPushNotification($a, $message);
}
}
}
function get_allrecord(){
global $wpdb;
$results =$wpdb->get_results('SELECT token FROM wp_push_tokens ', OBJECT);
return $results;
}
function sendPushNotification($registration_ids, $message) {
$apiKey = "xxxxxxxxxxxxxxxxxxxxxxx";
$headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $apiKey);
$fields = array(
'register' =>$registration_ids,
'data' =>$message );
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send");
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, wp_json_encode($fields));
// Execute post
$result = curl_exec($ch);
if($result === false)
die('Curl failed ' . curl_error());
// Close connection
curl_close($ch);
return $result;
}
}
1 个解决方案
#1
1
Your content type is "application/json"
, which means the "data"
field must be a JSON of the form :
您的内容类型是“application/json”,这意味着“data”字段必须是表单的json:
"data": {
"message": "your message"
}
Note that the "message"
key in this example is custom. You can use whatever keys you wish, and your app will have to search for those keys when it receives the message.
注意,本例中的“message”键是自定义的。你可以使用你想要的任何键,当你的应用收到消息时,你必须搜索这些键。
I don't know PHP, but something like this may work :
我不知道PHP,但是类似这样的东西可能有用:
$fields = array(
'registration_ids' =>$registration_ids,
'data' => array('message' => $message));
#1
1
Your content type is "application/json"
, which means the "data"
field must be a JSON of the form :
您的内容类型是“application/json”,这意味着“data”字段必须是表单的json:
"data": {
"message": "your message"
}
Note that the "message"
key in this example is custom. You can use whatever keys you wish, and your app will have to search for those keys when it receives the message.
注意,本例中的“message”键是自定义的。你可以使用你想要的任何键,当你的应用收到消息时,你必须搜索这些键。
I don't know PHP, but something like this may work :
我不知道PHP,但是类似这样的东西可能有用:
$fields = array(
'registration_ids' =>$registration_ids,
'data' => array('message' => $message));