Google GCM服务器返回未经授权的错误401

Sus*_*ola 30 php android json google-cloud-messaging

我正在使用GCM服务从服务器推送信息.如果我使用浏览器密钥,则显示成功的表格:{"multicast_id":4849013215736515938,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0: 1348742583011905%2adac3a0f9fd7ecd"}]} 但我没有在设备上收到任何通知.如果我使用服务器密钥,它会显示Unauthorized Error 401.我的代码如下所示:

$apiKey = "xxxxx";
$registrationIDs = array("xxxxxxxx");
$message = "testing Process";
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
        'registration_ids'  => $registrationIDs,
        'data'              => array("message"=>$message),
        );
$headers = array( 
        'Authorization: key=' . $apiKey,
        'Content-Type: application/json'
        );
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($fields) );

$result = curl_exec($ch);
if(curl_errno($ch)){ echo 'Curl error: ' . curl_error($ch); }
curl_close($ch);
echo $result;
Run Code Online (Sandbox Code Playgroud)

请帮我解决这个问题.提前致谢.

Jos*_*Jos 31

你是否将服务器的IP列入白名单?默认情况下,浏览器密钥不需要这样做,但它适用于服务器密钥.

你可以在这里查看:

https://code.google.com/apis/console/#project:[您的项目编号]:访问权限

  • 谢谢大家.由于浏览器密钥和API密钥,我遇到了问题.现在它与Server API密钥配合使用. (3认同)
  • Google稍微更新了控制台,您将根据我的回答中的链接重定向.您可以在那里看到"编辑允许的IP"按钮.我已经输入了"允许任何IP",这取决于我的安全密钥的保密性. (2认同)

Dan*_*anO 19

另一个答案已经建议将IP地址列入白名单,这似乎很明显.为我修复的是将我的IPv6地址列入白名单.那是关键!我希望这有助于其他人.

  • 如果您使用curl进行调试,并将IPv4地址列入白名单而不是IPv6地址,则可以将"-4"传递给curl以使其使用IPv4进行连接. (5认同)

小智 14

我在这个帖子中尝试了一切,但仍然没有运气.

所以,我检查启用的API(API和验证- >的API,启用的API),并意识到,我已经启用了Google Cloud Messaging for Chrome没有Google Cloud Messaging for Android.一旦我启用后者,它立即起作用.

仔细检查您是否启用了正确的API!