首页 > 解决方案 > 使用 firebase 和 php 反应原生后台通知

问题描述

我是本机反应的新手,并创建了一个应用程序,该应用程序显示存储在 mysql 数据库中并使用 php 转换为 json 的事件列表。然后将事件列表显示在 react native flatlist 中。

每次将事件添加到平面列表时,我都希望收到背景通知。在做了一些研究之后,我发现发送后台通知的最佳方式是使用 firebase。我能够设置后台通知,然后从 firebase 控制台发送。

这是我的代码。

const getFcmToken = async () => {
  const fcmToken = await messaging().getToken();
  if (fcmToken) {
      console.log("Your Firebase Token is:", fcmToken);
  } else {
      console.log("Failed", "No Token Recived");
  }
};

export default class App extends React.Component {
  requestUserPermission = async () => {
    const authStatus = await messaging().requestPermission();
    const enabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL;
      if (enabled) {
        getFcmToken();
        console.log('Authorization status:', authStatus);
      }
    };

    async componentDidMount() {
      await this.requestUserPermission();
      fetch('http://ad9e61f2797a.ngrok.io/Notifications.php');
      
       // Register background handler
       messaging().setBackgroundMessageHandler(async (remoteMessage) => {
       console.log('Messaage handled in the background!', remoteMessage);
  });

      // When app is in the background and clicked
      messaging().onNotificationOpenedApp(async (remoteMessage) => {
        console.log('Notification caused app to open from background state:', remoteMessage.notification);
      });

      // when app is in closed and clicked
      messaging()
        .getInitialNotification()
        .then(remoteMessage => {
          if (remoteMessage) {
            console.log('Notifivation caused app to open from closed state:', remoteMessage.notification);
        }    
    });
};
)

我希望我的通知无需使用 firebase cconsole 即可发送。我已经创建了 php 服务器代码来尝试执行此操作,但我似乎无法显示通知。

这是我的php代码

<?php
$url = "https://fcm.googleapis.com/fcm/send";
$token = "xxxxxxxx";
$serverKey = 'xxxxxxxxx';
$title = "Title";
$body = "Body of the message";
$notification = array('title' => $title, 'text' => $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);
// Send the request
$response = curl_exec($ch);
// Close request
if ($response === FALSE) {
    die('FCM Send Error: ' , curl_errno($ch));
}
curl_close($ch);

?>

我正在尝试在我的 iPhone 上运行我的应用程序。

标签: phpreact-nativefirebase-cloud-messagingreact-native-iosreact-native-firebase

解决方案


推荐阅读