无法使用php触发firebase云消息传递

时间:2017-05-25 12:53:35

标签: php android firebase firebase-cloud-messaging

我需要做的是,我将从我的Android应用程序触发此脚本,设备所有者将收到通知。

这是我的代码:

<?php
  $db_name = "testdb";
  $mysql_username = "root";
  $mysql_password = "";
  $server_name = "localhost";

  function send_notification ($tokens , $message)
  {
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
                'registration_ids' => $tokens,
                'data' => $message
                );
$headers = array(
                'Authorization:key = AIzaSyBAYIZohaZPXBEGqktPh8YEfMlmuYnuCOk',
                'Content-Type: application/json'
                );
$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('Curl.failed: '.curl_error($ch));
}
curl_close($ch);
return $result;
  }

$conn = mysqli_connect    
                  ($server_name,$mysql_username,$mysql_password,$db_name);
$sql = "select `token` from `user_token`;";
$result = mysqli_query($conn,$sql);
$token = array();
if(mysqli_num_rows($result) > 0){
    while($row = mysqli_fetch_assoc($result)){
        $token[] = $row["token"];
    }
}
mysqli_close($conn);
$message = array('message' => "FCM MESSAGE");
$message_status = send_notification($token , $message);
echo $message_status;


   ?>

我已经阅读了很多博客,stackoverflows但没有积极的结果。

提前谢谢。

1 个答案:

答案 0 :(得分:0)

您的PHP代码运行正常。实际上,您只在data对象中发送$fields字段。请再次检查控制台是否有FCM数据。因此,您必须手动构建Notification对象。

但是,如果您想要通知面板的默认通知,请修改您的$fileds对象,如下所示并运行。

$notificationObj = array(
                'title' => 'FCM',
                'body' => 'MESSAGE'
);
$fields = array(
                'registration_ids' => $tokens,
                'data' => $message,
                'notification' => $notificationObj 
                );