GCM服务器端PHP - 未经授权的401错误

时间:2014-05-20 16:01:15

标签: android push-notification google-api google-cloud-messaging

我设置了谷歌开发者控制台,支持 Google Cloud Messaging for Android

在凭证方面,我创建了在引用中键入0.0.0.0的浏览器API密钥。实际上我创建了两种类型的键,因为我在不同的教程中找到了不同的指示。

browser-key picture

server-key picture

我用这个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"}]}

但我获得(使用两个键)未经授权的401错误

感谢您的帮助。

2 个答案:

答案 0 :(得分:7)

不要输入0.0.0.0作为允许的引荐来源或允许的IP,也不要输入任何内容。这应该有用。

答案 1 :(得分:0)

不要在IP地址字段中输入任何内容。它就像一个魅力。 还要确保您在服务器端使用服务器密钥和正确的发件人ID android客户端。