2016-08-26 128 views
1

我想發送FCM通知使用PHP腳本,數據庫插入事件,我試圖從FCM控制檯發送,它使用主題選項正常工作,知道我註冊了應用程序實例某些主題「exptopic」 使用下面的代碼在MainActivity.java的OnCreate類:FCM通知爲Android

FirebaseMessaging.getInstance().subscribeToTopic("exptopic"); 

現在PHP腳本如下:

function sendMessage($data,$target){ 
    //FCM api URL 
    $url = 'https://fcm.googleapis.com/fcm/send'; 

    //api_key available in Firebase console -> project settings -> cloud messaging -> server key 

    $server_key = "API_KEY";//my api key 

    $fields = array(); 
    $fields['data'] = array('message'=>$data); 
    $fields['to'] = $target; 

    $headers = array('content-type:application/json', 
      'Authorization:key='.$server_key); 

    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_POST, true); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); 
    $result = curl_exec($ch); 

    if($result === FALSE){ 
     die('FCM Send error: '.curl_error($ch)); 
     echo 'notification not sent'; 
    } 
    curl_close($ch); 
    echo $result; 
    return $result; 
} 

顯然$target = "exptopic",當我運行snedMessage函數,它返回以下結果:

{"multicast_id":6779996340041741184,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]} 

任何人都可以幫忙嗎?

+0

MySQL的似乎不相關這一問題,標籤去除。 – tadman

回答

0

您錯過了數據中的priority字段。試試這個:

$fields["priority"] = "high" //This is required 

編輯:

我有這身成功

。也許試試這個:

<?php 

// Get cURL resource 
$ch = curl_init(); 

// Set url 
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send'); 

// Set method 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); 

// Set options 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

// Set headers 
curl_setopt($ch, CURLOPT_HTTPHEADER, [ 
    "Authorization: key=API_KEY", 
    "Content-Type: application/json", 
] 
); 
// Create body 
$json_array = [ 
     "notification" => [ 
      "title" => "TEST", 
      "sound" => "default", 
      "body" => $data 
     ], 
     "to" => $target, 
     "priority" => "high" 
    ]; 
$body = json_encode($json_array); 

// Set body 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $body); 

// Send the request & save response to $resp 
$resp = curl_exec($ch); 

if(!$resp) { 
    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch)); 
} else { 
    echo "Response HTTP Status Code : " . curl_getinfo($ch,  CURLINFO_HTTP_CODE); 
    echo "\nResponse HTTP Body : " . $resp; 
} 

// Close request to clear up some resources 
curl_close($ch); 
+0

謝謝您的回覆,但它返回了同樣的錯誤,我不認爲這是問題 –

+0

檢查更新。祝你好運。 –

+0

非常感謝你 –

1

基於this documentation,在to場應該是/topics/exptopic

+0

非常感謝你,那就是它 –

+1

如果這個答案是有用的,點擊左邊的upvote按鈕。如果它回答了您的問題,請點擊複選標記以接受它。這樣別人就知道你已經(充分)幫助了。 –