2016-08-26 127 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按钮。如果它回答了您的问题,请点击复选标记以接受它。这样别人就知道你已经(充分)帮助了。 –