【问题标题】:Flutter Firebase Messaging with PHP使用 PHP 进行 Flutter Firebase 消息传递
【发布时间】:2022-04-11 21:37:15
【问题描述】:

我已使用 FCM 注册令牌从 Firebase 控制台成功发送推送通知。这是我的飞镖文件:

class PushNotificationsManager {

  PushNotificationsManager._();

  factory PushNotificationsManager() => _instance;

  static final PushNotificationsManager _instance = PushNotificationsManager._();

  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
  bool _initialized = false;

  Future<void> init() async {
    if (!_initialized) {
      // For iOS request permission first.
      _firebaseMessaging.requestNotificationPermissions();
      _firebaseMessaging.configure();

      // For testing purposes print the Firebase Messaging token
      String token = await _firebaseMessaging.getToken();
      print("FirebaseMessaging token: $token");

      _initialized = true;
    }
  }
}

现在我想使用 PHP 发送推送通知。我找到了this tutorial。 PHP代码如下:

push.php
<?php

/**
 * @author Ravi Tamada
 * @link URL Tutorial link
 */
class Push {

    // push message title
    private $title;
    private $message;
    private $image;
    // push message payload
    private $data;
    // flag indicating whether to show the push
    // notification or not
    // this flag will be useful when perform some opertation
    // in background when push is recevied
    private $is_background;

    function __construct() {

    }

    public function setTitle($title) {
        $this->title = $title;
    }

    public function setMessage($message) {
        $this->message = $message;
    }

    public function setImage($imageUrl) {
        $this->image = $imageUrl;
    }

    public function setPayload($data) {
        $this->data = $data;
    }

    public function setIsBackground($is_background) {
        $this->is_background = $is_background;
    }

    public function getPush() {
        $res = array();
        $res['data']['title'] = $this->title;
        $res['data']['is_background'] = $this->is_background;
        $res['data']['message'] = $this->message;
        $res['data']['image'] = $this->image;
        $res['data']['payload'] = $this->data;
        $res['data']['timestamp'] = date('Y-m-d G:i:s');
        return $res;
    }

}

firebase.php
<?php

/**
 * @author Ravi Tamada
 * @link URL Tutorial link
 */
class Firebase {

    // sending push message to single user by firebase reg id
    public function send($to, $message) {
        $fields = array(
            'to' => $to,
            'data' => $message,
        );
        return $this->sendPushNotification($fields);
    }

    // Sending message to a topic by topic name
    public function sendToTopic($to, $message) {
        $fields = array(
            'to' => '/topics/' . $to,
            'data' => $message,
        );
        return $this->sendPushNotification($fields);
    }

    // sending push message to multiple users by firebase registration ids
    public function sendMultiple($registration_ids, $message) {
        $fields = array(
            'to' => $registration_ids,
            'data' => $message,
        );

        return $this->sendPushNotification($fields);
    }

    // function makes curl request to firebase servers
    private function sendPushNotification($fields) {

        require_once __DIR__ . '/config.php';

        // Set POST variables
        $url = 'https://fcm.googleapis.com/fcm/send';

        $headers = array(
            'Authorization: key=' . FIREBASE_API_KEY,
            'Content-Type: application/json'
        );
        // Open connection
        $ch = curl_init();

        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }

        // Close connection
        curl_close($ch);

        return $result;
    }
}
?>

网络控制台显示返回成功消息,但我的设备没有收到通知。出了什么问题?

【问题讨论】:

    标签: php firebase flutter


    【解决方案1】:

    使用此 PHP 代码解决的问题

    <?php
        $url = "https://fcm.googleapis.com/fcm/send";
        $token = "firebase token";
        $serverKey = 'Server key';
        $title = "Title";
        $body = "Body";
        $notification = array('title' =>$title , 'body' => $body, 'sound' => 'default', 'badge' => '1');
        $arrayToSend = array('to' => $token, 'notification' => $notification,'priority'=>'high');
        $json = json_encode($arrayToSend);
        $headers = array();
        $headers[] = 'Content-Type: application/json';
        $headers[] = 'Authorization: key='. $serverKey;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
        //Send the request
        $response = curl_exec($ch);
        //Close request
        if ($response === FALSE) {
        die('FCM Send Error: ' . curl_error($ch));
        }
        curl_close($ch);
    ?>
    

    【讨论】:

      【解决方案2】:

      尝试将您的代码配置为

      
      protected function sendPushNotification($fields = array())
      {
          define( 'API_ACCESS_KEY', 'AAAA4-.....' );
      
      
          $headers = array
          (
              'Authorization: key=' . API_ACCESS_KEY,
              'Content-Type: application/json'
          );
          $ch = curl_init();
          curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
          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( $fields ) );
          $result = curl_exec($ch );
          curl_close( $ch );
          return $result;
      }
      

      并像这样使用它:

          $msg = array
      (
      'body'  => 'your message',
      'title'     => "your app name",
      'vibrate'   => 1,
      'sound'     => 1,
      );
      $fields = array
      (
      'to'  => '/topics/your topic name', // or 'to'=> 'phone token'
      'notification'=> $msg
      );
      $this->sendPushNotification($fields);
      

      【讨论】:

        【解决方案3】:

        如果这有帮助,

        您需要在 _firebaseMessaging.configure(); 下添加通知的处理程序;

        你有没有在任何地方这样做过 -

        _firebaseMessaging.configure
        (
            onMessage: (Map<String, dynamic> message) async
            {
                print("onMessage: $message");               
            },
            onLaunch: (Map<String, dynamic> message) async // Called when app is terminated
            {
                print("onLaunch: $message");
            },
            onResume: (Map<String, dynamic> message) async
            {
                print("onResume: $message");
            }           
        );
        

        【讨论】:

        • 我们是否需要在 main.dart 或其他任何地方配置它。另外,如果我在不同的页面,那么通知会在 onMessage 事件期间可见还是需要在任何地方定义它?
        猜你喜欢
        • 2020-07-09
        • 2021-07-22
        • 2021-02-19
        • 1970-01-01
        • 2018-09-07
        • 2021-09-04
        • 2023-03-23
        • 2021-07-21
        • 2021-06-12
        相关资源
        最近更新 更多