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


GCM PHP : Field "data" must be a JSON array

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

Field "data" must be a JSON array: [{"sound":1,"vibrate":1,"message":"Push Notification Message","title":"Push Notification Title"}]

尝试使用 GCM 时出错。我的注册 ID、发件人 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;
}
?>

替换该行

$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);

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

希望它能有所帮助。