我正在使用Appengine并通过测试脚本来通过GCM发送消息,但它会导致401 Unauthorized错误。
按照我的脚本
$url = 'https://android.googleapis.com/gcm/send';
$serverApiKey = "AIzaSyCKPMazvtdyhqhH7IdIqdHjqUtLNlHnsgA"; // API KEY SERVER
$reg = "APA91bEmal_3NpDSV5vuIysMjF8GYxO70_2Nmzx78VCSLmGpX_oX73TqfHczzjP_PgUmwYcdGz0yPGAajRLb1eP7wfzqtoADMzL1-DoCLYH9kz2dKknwcd7fZFSg_qM6Cgk_gphIRWD2FbcJZ83-ymnF1UhF40j32vYzD7WCDZnq_0-87R5Dbmk"; // registration id
$headers = array(
'Content-Type:application/json',
'Authorization:key=' . $serverApiKey
);
$data = array(
'registration_ids' => array($reg),
'data' => array(
'message' => 'Hello, World!'
));
print (json_encode($data) . "\n\n");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$response = curl_exec($ch);
curl_close($ch);
print ($response);
如果我在我的本地机器上进行相同的测试,它可以工作,但是在appengine不起作用
http://s3.postimg.org/ndzcfujoj/local_machine_1.png
http://s17.postimg.org/f48alja3z/local_machine_2.png
...在appengine不起作用
{"registration_ids":["APA91bEmal_3NpDSV5vuIysMjF8GYxO70_2Nmzx78VCSLmGpX_oX73TqfHczzjP_PgUmwYcdGz0yPGAajRLb1eP7wfzqtoADMzL1-DoCLYH9kz2dKknwcd7fZFSg_qM6Cgk_gphIRWD2FbcJZ83-ymnF1UhF40j32vYzD7WCDZnq_0-87R5Dbmk"],"data":{"message":"Hello, World!"}}
Unauthorized
Error 401
遵循API设置
Key for server applications
API key
AIzaSyCKPMazvtdyhqhH7IdIqdHjqUtLNlHnsgA
IPs
Any IP allowed
Activation date
Mar 12, 2015, 2:40:00 AM
有人可以帮助我吗?
答案 0 :(得分:0)
尝试使用浏览器密钥。 服务器密钥从公共IP地址工作。 你也应该将你的IP地址列入白名单。
答案 1 :(得分:0)
我不知道cURL不起作用的原因。我用另一种方式做了它并且它起作用了
$regId = "myid";
$message = "Hello World!";
$registrationIds = array($regId);
$msg = array( 'message' => $message, 'title' => 'notification center', 'tickerText' => $message, 'vibrate' => 1, 'sound' => 1, );
$fields = array(
'registration_ids' => $registrationIds,
'data' => $msg
);
$fields = json_encode($fields);
$arrContextOptions=array(
"http" => array(
"method" => "POST",
"header" =>
'Authorization: key = MyApiKey'. "\r\n" .
'Content-Type: application/json'. "\r\n",
"content" => $fields,
),
"ssl"=>array(
"allow_self_signed"=>true,
"verify_peer"=>false,
),
);
$arrContextOptions = stream_context_create($arrContextOptions);
$result = file_get_contents('https://android.googleapis.com/gcm/send', false, $arrContextOptions);
echo $result;