2015-12-12 86 views
0

我是相當新的PHP語法,我知道如何接收http post請求,並且也在PHP中獲取請求,但我不知道如何正確發送一個http post請求在php中沒有窗體,使用數據下面。 (我明白我可以使用Ajax,但我想學習如何使用PHP腳本)。如何使用php發送此GCM下游消息(HTTP POST REQUEST)?

https://gcm-http.googleapis.com/gcm/send 
Content-Type:application/json 
Authorization:key=I_PUT_THIS_AS_A_SAMPLE 

{ 
    "data": { 
     "score": "5x1", 
     "time": "15:10" 
    }, 
    "to": "SAMPLE_SAMPLE" 
} 
+0

爲GCM的PHP'下游message'點擊這裏:http://www.androidbegin.com/tutorial/android-google-cloud-messaging-gcm-tutorial/搜索'創建一個簡單的PHP服務器與GCM進行通信.'下,它包含'gcm_engine.php',這是php腳本 – bjiang

回答

0

此代碼爲Android。

請嘗試下面的例子。您可以將此代碼粘貼到http://phpfiddle.org/。嘗試瞭解邏輯流程是如何工作的,並通過添加您想要發送的消息(代表分數和時間)來處理代碼。當我執行推送通知時,我發現了這段代碼。爲了使下面的代碼正常工作,您需要授權密鑰以及設備註冊令牌。祝你好運!

<?php 


// API access key from Google API's Console 
define('API_ACCESS_KEY', 'Axxxxxxxxxxxxxxxxxx'); 


$registrationIds = array("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); 

// prep the bundle 
$msg = array 
(
    'message'  => 'here is a message. message', 
    'title'   => 'This is a title. title', 
    'subtitle'  => 'This is a subtitle. subtitle', 
    'tickerText' => 'Ticker text here...Ticker text here...Ticker text  here', 
    'vibrate' => 1, 
    'sound'  => 1 
); 

$fields = array 
(
    'registration_ids' => $registrationIds, 
    'data'    => $msg 
); 

$headers = array 
(
    'Authorization: key=' . API_ACCESS_KEY, 
    'Content-Type: application/json' 
); 

$ch = curl_init(); 
curl_setopt($ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send'); 
curl_setopt($ch,CURLOPT_POST, true); 
curl_setopt($ch,CURLOPT_HTTPHEADER, $headers); 
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch,CURLOPT_POSTFIELDS, json_encode($fields)); 
$result = curl_exec($ch); 
curl_close($ch); 

echo $result; 
?>