2012-06-13 105 views
0

我在嘗試使用此代碼設置C2DM推送消息的應用服務器部分 - https://github.com/lytsing/c2dm-phpPHP-C2DM應用服務器實現

我已經完成了應用程序的一面,並註冊了Google的電子郵件地址 - 每次運行代碼時(在裝有php/cURL的服務器上),我都會收到錯誤「get auth token error」。這讓我瘋狂,因爲我不知道從哪裏開始解決問題。

我已經在代碼更改的唯一線 - 在s2dm.php文件 -

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

,我將我的電子郵件/密碼進入post.php中的文件 -

$result = $c2dm->getAuthToken("[email protected]", "password"); 

任何建議都會很棒! 乾杯 保羅

回答

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..."); 

僅供參考!每次發送通知時都不需要調用get_auth_id(),您也可以調用一次並將auth_id存儲在配置文件的某處。

+0

嗨周杰倫 - 多數民衆贊成在此非常感謝 - 這完全取代了以前的解決方案呢? – Dancer

+0

通常的做法是將其與受保護的表單配合以提交消息? – Dancer

+0

是的保羅,這將取代你的解決方案。但我認爲這會滿足您的需求是否正確? – jaym