我现在正在构建自己的 C2DM 应用程序。我首先从一个小型 Android 应用程序开始测试推送功能。如果我只是在 shell 中使用正确的设置调用curl 命令,它就可以工作。
现在,对于服务器部分,我想使用 PHP,但似乎我做错了什么,因为当我尝试向客户端发送消息时,我总是收到 401 错误消息。首先,代码由两部分组成。第一个curl请求请求服务器 token 。这有效我从谷歌得到了一个带有工作 token 的真实响应!
第二个curl请求以401错误消息结束。你知道我做错了什么吗?
$post_params = array ( "Email" => $MY_GOOGLE_ACC, "Passwd" => $MY_GOOGLE_PWD, "accountType"=>"GOOGLE", "source=" . $MY_GOOGLE_SRC, "service=ac2dm" );
$first = true;
$data_msg = "";
foreach ($post_params as $key => $value) {
if ($first)
$first = false;
else
$data_msg .= "&";
$data_msg .= urlencode($key) ."=". urlencode($value);
}
$x = curl_init("https://www.google.com/accounts/ClientLogin");
curl_setopt($x, CURLOPT_HEADER, 1);
curl_setopt($x, CURLOPT_POST, 1);
curl_setopt($x, CURLOPT_POSTFIELDS, $data_msg);
curl_setopt($x, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($x);
curl_close($x);
$response = $data;
$authKey = trim(substr($response, 4+strpos($response, "SID=")));
echo $authKey;
$collapse_key = 'something';
$post_params = array ( "registration_id" => $DEVICE_TOKEN, "collapse_key" => $collapse_key, "data.payload"=>"cakephp" );
$first = true;
$data_msg = "";
foreach ($post_params as $key => $value) {
if ($first)
$first = false;
else
$data_msg .= "&";
$data_msg .= urlencode($key) ."=". urlencode($value);
}
$size=strlen($data_msg);
$x = curl_init("https://android.apis.google.com/c2dm/send");
curl_setopt($x, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded', 'Content-Length:'. $size, 'Authorization: GoogleLogin auth=' . $authKey));
curl_setopt($x, CURLOPT_HEADER, 1);
curl_setopt($x, CURLOPT_POST, 1);
curl_setopt($x, CURLOPT_POSTFIELDS, $data_msg);
curl_setopt($x, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($x);
curl_close($x);
$response = $data;
最佳答案
与curl 一起使用的键数组示例。这几乎是我正在使用的代码(为了清晰起见做了一些细微的更改)。
$headers = array('Authorization: GoogleLogin auth=' . $authcode);
$data = array(
'registration_id' => $device_registration_id,
'collapse_key' => 'ck_' . $device_id,
'data.arg' => 'arrrrghhh'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://android.apis.google.com/c2dm/send");
if($headers) curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
$authcode 是 ClientLogin 返回的 SID。 $device_registration_id 是我们执行 C2DM_REGISTER 时手机上的客户端应用程序向我们提供的注册 ID。
希望有帮助。
关于php - C2DM 服务器出现 PHP 401 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4915985/