无法将通知从php脚本发送到android应用

时间:2019-04-06 07:34:45

标签: php android firebase

我正在按照下面的JSON结构将推送通知从PHP脚本发送到android应用,但无法实现。我正在使用POSTMAN,并且收到状态码200,但未收到通知。

我遵循的JSON结构:

https://firebase.google.com/docs/cloud-messaging/concept-options

reshape()

PHP脚本

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification":{
      "title":"Portugal vs. Denmark",
      "body":"great match!"
    }
  }
}

2 个答案:

答案 0 :(得分:0)

在下面使用此代码。将该类导入其他任何PHP文件中,只需传递fcm令牌和消息即可。

<?php 
class Firebase {
public function send($registration_ids, $message) {
    $fields = array(
        'registration_ids' => $registration_ids,
        'data' => $message,
    );
    return $this->sendPushNotification($fields);
}

/*
* This function will make the actuall curl request to firebase server
* and then the message is sent 
*/
private function sendPushNotification($fields) {

    //importing the constant files
    require_once 'Config.php';

    //firebase server url to send the curl request
    $url = 'https://fcm.googleapis.com/fcm/send';

    //building headers for the request
    $headers = array(
        'Authorization: key=' . FIREBASE_API_KEY,
        'Content-Type: application/json'
    );

    //Initializing curl to open a connection
    $ch = curl_init();

    //Setting the curl url
    curl_setopt($ch, CURLOPT_URL, $url);

    //setting the method as post
    curl_setopt($ch, CURLOPT_POST, true);

    //adding headers 
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    //disabling ssl support
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    //adding the fields in json format 
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

    //finally executing the curl request 
    $result = curl_exec($ch);
    if ($result === FALSE) {
        die('Curl failed: ' . curl_error($ch));
    }

    //Now close the connection
    curl_close($ch);

    //and return the result 
    return $result;
  }
}

答案 1 :(得分:0)

实际上,我的$ notifyArray变量存在问题,因为我需要传递以下链接中定义的预定义参数:

https://firebase.google.com/docs/cloud-messaging/http-server-ref

$notify=array('to'=>$token,'notification'=>
                             array('title'=>"Title",body'=>"Subtitle"));