GCM PHP:字段“data”必须是JSON数组

时间:2016-03-12 17:35:00

标签: php android cordova google-cloud-messaging phonegap-pushplugin

我知道这里有几个帖子谈论我的问题,但没有一个对我有用。它是提到的不完整的解决方案或保留原样。 我的查询:  我正在

Field "data" must be a JSON array: [{"sound":1,"vibrate":1,"message":"Push Notification Message","title":"Push Notification Title"}]
尝试使用GCM时出现

错误。我的regID,发件人ID和服务器密钥看起来很好。 可能知道如何解决这个问题。

PHP代码:

<?php
$to="";
if($_GET['id']){
$to = $_GET['id'];
}
$title="Push Notification Title";
$message="Push Notification Message";
sendPush($to,$title,$message);

function sendPush($to,$title,$message)
{
// API access key from Google API's Console
// replace API
define( 'API_ACCESS_KEY', 'API_HIDDEN');
$registrationIds = array($to);

$msg = array
(
'message' => $message,
'title' => $title,
'vibrate' => 1,
'sound' => 1

// you can also add images, additionalData
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => array($msg),

);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
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 );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );

echo $result;

}
?>

1 个答案:

答案 0 :(得分:1)

替换

$message="Push Notification Message";

通过

$message=array( 'response' =>  json_encode("Push Notification Message"));
  

GCM需要JSONArray格式的响应数据。

或使用以下方法

function sendGoogleCloudMessage( $data, $ids ) {
    $apiKey = 'YOUR_KEY';
    $url = 'https://android.googleapis.com/gcm/send';
    $post = array(
                    'registration_ids'  => $ids,
                    'data'              => $data,
                    );
    $headers = array( 
                        'Authorization: key=' . $apiKey,
                        'Content-Type: application/json'
                    );
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
    curl_setopt( $ch, CURLOPT_POST, true );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $post ) );
    $result = curl_exec( $ch );
    if ( curl_errno( $ch ) ) {
        $result = $result . 'GCM error: ' . curl_error( $ch );
    }
    curl_close( $ch );
    return $result;
}

并使用

调用它
$response = array();
$response["title"] = "title";
$response["message"] = "Notification message.";
$data = array( 'response' =>  json_encode($response));
$result = sendGoogleCloudMessage($data, $ids);

它正在我的应用程序中工作。

希望它会有所帮助。