我设置google开发者控制台启用 google Cloud Messaging for Android。
在凭据端,我创建了浏览器API密钥,在引用中键入0.0.0.0。实际上我创建了这两种类型的键,因为我在不同的教程中发现了不同的指示。
browser-key图片
服务器密钥的照片
我用这个PHP脚本
测试这个键<?
/**
* The following function will send a GCM notification using curl.
*
* @param $apiKey [string] The Browser API key string for your GCM account
* @param $registrationIdsArray [array] An array of registration ids to send this notification to
* @param $messageData [array] An named array of data to send as the notification payload
*/
function sendNotification( $apiKey, $registrationIdsArray, $messageData )
{
$headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $apiKey);
$data = array(
'data' => $messageData,
'registration_ids' => $registrationIdsArray
);
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send" );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data) );
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
?>
<?
// Message to send
$message = "the test message";
$tickerText = "ticker text message";
$contentTitle = "content title";
$contentText = "content body";
$registrationId = '372CBFD0C4BFE728';
$apiKey = "AIzaSyDeNN1XJBFGE_lJ_35VMUmx5cUbRCUGkjo";
$response = sendNotification(
$apiKey,
array($registrationId),
array('message' => $message, 'tickerText' => $tickerText, 'contentTitle' => $contentTitle, "contentText" => $contentText) );
echo $response;
?>
我期望得到类似的东西
{"multicast_id":6782339717028231855,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
但我获得(与两个密钥)Unauthorized 401 Error。
谢谢你的帮助
不要将0.0.0.0
输入为允许的引用或允许的ip,而是不输入任何内容。应该可以了
不要在IP地址栏中输入任何内容。这招很管用。另外,请确保您在服务器端使用的是Server键和正确的sender id android client。