使用FCM和php推送通知

时间:2017-10-10 06:41:48

标签: php android firebase-cloud-messaging react-native-android

我正在尝试使用fcm和php作为服务器从我的本机应用程序发送推送通知。以下是我的代码响应以接收来自服务器的通知。

pushNotification.js

import React, { Component } from "react";

import FCM from "react-native-fcm";

export default class PushNotification extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {

    // this method generate fcm token.
    FCM.requestPermissions();
    FCM.getFCMToken().then(token => {
      console.log("TOKEN (getFCMToken)", token);
    });

    // This method get all notification from server side.
    FCM.getInitialNotification().then(notif => {
      console.log("INITIAL NOTIFICATION", notif)
    });

    // This method give received notifications to mobile to display.
    this.notificationUnsubscribe = FCM.on("notification", notif => {
      console.log("a", notif);
      if (notif && notif.local_notification) {
        return;
      }
      this.sendRemote(notif);
    });

    // this method call when FCM token is update(FCM token update any time so will get updated token from this method)
    this.refreshUnsubscribe = FCM.on("refreshToken", token => {
      console.log("TOKEN (refreshUnsubscribe)", token);
      this.props.onChangeToken(token);
    });
  }

  // This method display the notification on mobile screen.
  sendRemote(notif) {
    console.log('send');
    FCM.presentLocalNotification({
      title: notif.title,
      body: notif.body,
      priority: "high",
      click_action: notif.click_action,
      show_in_foreground: true,
      local: true
    });
  }

  componentWillUnmount() {
    this.refreshUnsubscribe();
    this.notificationUnsubscribe();
  }
  render() {
    return null;
  }
}

我的php脚本如下。我正在尝试通过获取每个用户的设备令牌来发送通知。

notification.php

<?php
include 'db.php';
$check_json = file_get_contents('php://input');
$obj= json_decode($check_json);
$uid =$obj->{'uuid'};
$fcm =$obj->{'fcm'}
$to =$fcm;
$data = array(
    'title'=>"Testmessage",
    'message'=>"You have a new request");

function send_message($to,$data){

    $server_key= 
'*******'; 
    $target= $to;
    $headers = array(
        'Content-Type:application/json',
         'Authorization:key=' .$server_key
        );
        $ch = curl_init();
            $message = array(
           'fcm' => $to,
           'priority' => 'high',
           'data' => $data
                    );
         curl_setopt_array($ch, array(
           CURLOPT_URL => 'https://fcm.googleapis.com/fcm/send',
           CURLOPT_HTTPHEADER => $headers,
           CURLOPT_POST => true,
           CURLOPT_RETURNTRANSFER => true,
           CURLOPT_POSTFIELDS => json_encode($message)
                               ));
      $response = curl_exec($ch);        
}
 curl_close($ch);
   //echo  $response;
   return $response;
?>

我正在真实设备和模拟器上测试它。想要从真实设备向模拟器发送推送通知(可能吗?)。但是没有工作。任何人都可以帮助我。我是新手做出反应,所以请..

1 个答案:

答案 0 :(得分:1)

可以将推送通知从物理设备发送到仿真器,但仿真器应该在FCM中注册

public function sendMessageThroughFCM($arr) {
    //Google Firebase messaging FCM-API url
    $url = 'https://fcm.googleapis.com/fcm/send';
    $fields = (array) $arr;
    define("GOOGLE_API_KEY","XXXXXXXXXXXXXXXXXXXXX");
    $headers = array(
        'Authorization: key=' . GOOGLE_API_KEY,
        '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;
}

构建数组以发送通知

$arr = array(
            'registration_ids' => $androidTokens,
            'notification' => array( 'title' => $notificationTitle, 'body' => $notificationBody),
            'data' => array( 'title' => $notificationTitle, 'body' => $notificationBody)
        );

将FCM令牌列表推送到您需要发送通知的设备

array_push($androidTokens,$token['Fcm_registration_token']);

如果未生成FCM令牌,请刷新

String refreshedToken = FirebaseInstanceId.getInstance().getToken();

通过API调用将refreshedToken更新为服务器。