![](/img/trans.png)
[英]Sending notifications to Google Cloud Messaging with php gives me Unauthorized Error 401
[英]Error in sending request Google Cloud Messaging in PHP
我正在嘗試使用Google Clouding Messaging API與Android App集成。 對於后端,我正在使用Laravel 5.2。 我在Google API中生成了3個api密鑰。 這些是服務器API密鑰,Android API密鑰和瀏覽器API密鑰。 我正在參考本教程 。
這是我從服務器到GCM服務器的推送請求:
private function sendNotification($registatoin_ids,$message)
{
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key='.GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE)
{
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
function register(Request $request)
{
$name = $request->name;
$email = $request->email;
$gcm_regid = $request->reg_ids;
$registatoin_ids = array($gcm_regid);
$message = array("product" => "shirt");
$result = $this->sendNotification($registatoin_ids,$message);
echo $result;
}
我叫寄存器功能。 email
, name
和reg_ids
是模擬值。 我只是分別傳遞了myemail
, myname
和random string。 寄存器功能是控制器的動作。 對於GOOGLE_API_KEY
,我傳遞了服務器api密鑰。 但是當我請求時,它給了我以下錯誤。
{"multicast_id":5065519232839143946,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
我的推送請求正確嗎? 我可以將任何唯一值傳遞給reg_ids
。 此外,我的GOOGLE_API_KEY
應該是Android,服務器還是瀏覽器密鑰?
您收到的錯誤是401 HTTP狀態代碼 ,這意味着用於發送消息的發件人帳戶無法通過身份驗證。 以下是可能的原因:
授權標頭丟失或HTTP請求中的語法無效。
無效的項目編號作為密鑰發送。
密鑰有效,但禁用了GCM服務。
請求源自未在服務器密鑰IP中列入白名單的服務器。
API密鑰無效。
檢查您在Authentication標頭中發送的令牌是否是與您的項目關聯的正確API密鑰。 有關詳細信息,請參見檢查API密鑰的有效性 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.