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

4
我设置了谷歌开发者控制台并启用了Google Cloud Messaging for Android
在凭证方面,我创建了浏览器API密钥,并在引用中输入了0.0.0.0。实际上,我创建了两种类型的密钥,因为我在不同的教程中找到了不同的指示。 浏览器密钥图片 服务器密钥图片 我使用这个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 错误
谢谢您的帮助。

感谢您指出这个问题:curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 没有这个设置,我会收到未经授权的401错误。 - laplasz
2个回答

7

不要输入 0.0.0.0 作为允许引荐者或允许的IP地址,什么也不要输入。这样应该可以解决问题。


我也遇到了同样的错误。你是如何解决的?我正在本地测试中,出现了未经授权的401错误。你能帮忙吗? - Bora

0

不要在IP地址字段中输入任何内容。它能够完美运行。 同时确保在服务器端使用服务器密钥和在Android客户端使用正确的发送者ID。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接