Android的FCM通知

时间:2016-08-26 18:42:24

标签: php android firebase firebase-cloud-messaging

我正在尝试使用PHP脚本发送FCM通知,在数据库插入事件中,我尝试从FCM控制台发送,它使用主题选项工作正常,知道我已将应用实例注册到某个主题“exptopic”使用MainActivity.java OnCreate类中的以下代码:

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"}]}

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

根据this documentationto字段应为/topics/exptopic

答案 1 :(得分: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);