0

我正在尝试使用此代码 - https://github.com/lytsing/c2dm-php设置 C2DM 推送消息的应用程序服务器部分。

我已经完成了应用程序方面的工作,并在 Google 注册了一个电子邮件地址 - 每次我运行代码(在安装了 php/cURL 的服务器上)我都会收到错误“获取身份验证令牌错误”。它让我发疯,因为我不知道从哪里开始解决问题。

我在代码中更改的唯一行是 - 在 s2dm.php 文件中 -

  'source'        => 'com.phonegap.chillimusicapp', 

我将我的电子邮件/密码添加到 post.php 文件中 -

  $result = $c2dm->getAuthToken("email@googlemail.com", "password");

任何建议都会很棒!干杯保罗

4

1 回答 1

1

尝试使用下面的示例代码,它工作正常。

<?php
define("C2DM_ACCOUNT_EMAIL","[C2DM_EMAIL]");
define("C2DM_ACCOUNT_PASSWORD","[C2DM_PASSWORD]");
define("C2DM_CLIENT_LOGIN_URL","https://www.google.com/accounts/ClientLogin");
define("C2DM_MSG_SEND_URL","https://android.apis.google.com/c2dm/send");

function sendPushNotification($device_reg_id,$msg){

    $auth_id=get_auth_id(); // To get Auth ID

    $post_fields=array(
        'collapse_key=ck_1',
        'registration_id='. trim($device_reg_id),
        'data.payload='. trim($msg),
    );

    $data_str=implode('&', $post_fields);

    $headers = array(
    'Authorization: GoogleLogin auth='.trim($auth_id),
    'Content-Type: application/x-www-form-urlencoded',
    'Content-Length: '.trim(strlen($data_str)),
    'Connection: close'
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,C2DM_MSG_SEND_URL);
    curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_str);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $server_output = curl_exec ($ch);
    curl_close ($ch);
//  print_r($server_output);
}

function get_auth_id(){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,C2DM_CLIENT_LOGIN_URL);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "Email=".C2DM_ACCOUNT_EMAIL."&Passwd=".C2DM_ACCOUNT_PASSWORD."&accountType=GOOGLE&source=Google-cURL-Example&service=ac2dm");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $server_output = curl_exec ($ch);
    curl_close ($ch);
//  print_r($server_output);
    $parts=explode("Auth=",$server_output);
    $auth_id=$parts[1];
//  echo $auth_id;
    return $auth_id;
}

$reg_id = "[DEVICE_REG_ID]";
sendPushNotification($reg_id,"Hello World...!! Jay is testing C2DM...");

FYI! No need to call get_auth_id() every time you send notification, You can call once and store auth_id somewhere in config file also.

于 2012-06-13T12:03:52.567 回答