Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用PHP实现flatterfirebase消息传递_Php_Firebase_Flutter - Fatal编程技术网

用PHP实现flatterfirebase消息传递

用PHP实现flatterfirebase消息传递,php,firebase,flutter,Php,Firebase,Flutter,我已使用FCM注册令牌从Firebase控制台成功发送推送通知。这是我的dart文件: class PushNotificationsManager { PushNotificationsManager._(); factory PushNotificationsManager() => _instance; static final PushNotificationsManager _instance = PushNotificationsManager._();

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

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;
    }
  }
}
类PushNotificationsManager{
PushNotificationsManager.uz();
factory PushNotificationsManager()=>\u实例;
静态最终PushNotificationsManager_实例=PushNotificationsManager.z();
最终FirebaseMessaging_FirebaseMessaging=FirebaseMessaging();
bool _initialized=false;
Future init()异步{
如果(!\u已初始化){
//对于iOS,请先请求权限。
_firebaseMessaging.requestNotificationPermissions();
_firebaseMessaging.configure();
//出于测试目的,打印Firebase消息传递令牌
String token=wait_firebaseMessaging.getToken();
打印(“FirebaseMessaging令牌:$token”);
_初始化=真;
}
}
}
现在我想使用PHP发送推送通知。我找到了。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;
    }
}
?>
push.php

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

尝试将代码配置为


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);
如果这有帮助的话

您需要在_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");
    }           
);
\u firebaseMessaging.configure
(
onMessage:(映射消息)异步
{
打印(“onMessage:$message”);
},
onLaunch:(映射消息)异步//在应用程序终止时调用
{
打印(“onLaunch:$message”);
},
onResume:(映射消息)异步
{
打印(“onResume:$message”);
}           
);

使用此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);
?>

我们需要在main.dart或其他任何地方配置它吗。另外,如果我在不同的页面上,那么通知是否在onMessage事件期间可见,或者是否需要在任何地方定义它?