我现在正在构建自己的 C2DM 应用程序。我首先从一个小型 Android 应用程序开始测试推送功能。如果我只是在我的 shell 中使用正确的设置调用 curl 命令,它就可以工作。
现在对于服务器部分,我想使用 PHP,但似乎我做错了什么,因为当我尝试向客户端发送消息时总是收到 401 错误消息。首先,代码由两部分组成。第一个 curl 请求请求服务器令牌。这行得通,我得到了来自谷歌的真实回应,带有一个工作令牌!
第二个 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;