首页 > 解决方案 > 无法从 php 脚本向 android 应用程序发送通知

问题描述

我遵循以下 JSON 结构将 PHP 脚本的推送通知发送到 android 应用程序,但无法实现。我正在使用 POSTMAN 并获得 200 的状态代码,但未收到通知。

我遵循的 JSON 结构:

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

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

PHP 脚本

<?php
    $API_KEY="AAAAoyz8W_Q:APA91bFIJxTqoBnQo218QIIXi7uCmHFRP604RTC......";
    $url = "https://fcm.googleapis.com/fcm/send";
    $headers = array(
            'Authorization:key='.$API_KEY,
            'Content-Type:application/json'
    );

    $token="2tJfPjKZQ6UTVG....";
    $notify=array("message"=>
                        array('token' =>$token,
                              'notification'=>array('title'=>"Title",
                              'body'=>"Body")));

    $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_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($notify));

    $result = curl_exec($ch);
    if ($result === FALSE) {
        die('Curl failed: ' . curl_error($ch));
    }else{
        echo $ch;
    }
    curl_close ( $ch );

?> 

标签: phpandroidfirebase

解决方案


使用下面的代码。在任何其他 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;
  }
}

推荐阅读