使用 php 将带有 fcm 令牌的远程通知发送到 ios 设备

send remote notification with fcm token to ios device using php

我是一名 React Native 开发人员,负责制作 ios 应用程序。

我正在努力使用 fcm 实现获取远程通知。

我们的后端开发人员使用 php,他也是 android 开发人员。

所以他为fcm开发api的方式优化为android.

这是代码。

function sendFCM($notif_array, $id) {
    $API_KEY = "API key";
    $url = 'https://fcm.googleapis.com/fcm/send';

    $keys = array_keys($notif_array);
    $fields = array (
            'registration_ids' => array (
                    $id
            ),
            // 'data' => array (
            //         "message" => $message,
            //         "type" => $notif_type
            // )
            'content_available'=>true,
            'priority'=>'high',
            'data' => $notif_array,
            'notification'=>array(
              "body"=>$notif_content
            )
    );
    $fields = json_encode ( $fields );

    $headers = array (
            'Authorization: key=' . $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_POSTFIELDS, $fields );

    $result = curl_exec ( $ch );
    echo $result;
    curl_close ( $ch );
}

我已经在 firebase 控制台上注册了 APNs 密钥并对其进行了测试。效果不错。

我正在从 firebase 获取测试云消息。

如你所知,react-native-firebase 上有几个与通知相关的函数

firebase.notifications().onNotification(notif => console.log(notif))
firebase.notifications().onNotificationDisplayed(notif => console.log(notif))
...
...
firebase.messaging().onMessage(message => console.log(message))

但是现在只有 onMessage 函数在工作。

我猜 fcm 服务器只提供数据而不是通知。

如果有熟悉php的人,可以看看这个php代码是否正确?

谢谢!

在您的 sendFCM 方法中,未定义变量 $notif_content。另外,我知道 data 被注释掉了,但是没有注释,变量 $notif_type 也不会被定义。

我知道让 FCM 与 iOS 一起工作可能会有点痛苦,之前我遇到过无效证书的问题,尽管我希望 Firebase 更有弹性,因为我没有不得不使用它几年。