2

我现在正在构建自己的 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;
4

3 回答 3

2

与 curl 一起使用 key'd 数组的示例。这几乎是我工作的确切代码(为了清楚起见,做了一些小改动)。

$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。

希望有帮助。

于 2011-02-08T00:14:54.990 回答
1

尝试在此处注册您的应用程序。我有同样的问题。

于 2012-06-03T20:10:41.973 回答
0

我不完全确定这里发生了什么,但是我从我的应用程序服务器中注意到了一些可以正常工作的不同之处。

在您对 CURLOPT_HTTPHEADER 的 curl_setopt 调用中,内容长度和大小之间没有空格。这应该不会造成问题,但我之前曾看到网络服务器因此类愚蠢的事情而变得情绪化。

此外, CURLOPT_POSTFIELDS 是一个字符串,而我将我的作为键数组发送。

除此之外,我看起来和我的工作代码一样。

于 2011-02-07T00:57:49.137 回答