Search code examples
phpreact-nativereact-native-firebase

send remote notification with fcm token to ios device using php


I'm a react native developer to make ios application.

I'm struggling with implementing getting remote notification using fcm.

Our backend developer uses php and also he is a android developer.

So the way he developed api for fcm is optimized to android.

Here's the code.

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 );
}

I've already registered APNs key on firebase console and tested it. It's working well.

I'm getting test cloud message from firebase well.

As you know, there's several function on react-native-firebase related to notification

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

but only onMessage function is working right now.

I guess fcm server is giving only data well not notification.

If there are someone who are familiar with php, could you check this php code if it's correct or not?

Thanks!


Solution

  • In your sendFCM method, the variable $notif_content isn't defined. Additionally, I know data is commented out, but uncommented, the variable $notif_type wouldn't be defined either.

    I know getting FCM working with iOS can be a bit of a pain, previously I've had issues with invalid certificates, although I'd expect Firebase is a bit more resilient as I haven't had to use it for a couple of years.