1

I'm sending push notifications using FCM to Android with MySSQL and PHP. This is my code:

<?php 
    function send_notification ($tokens, $message)
    {
        $url = 'https://fcm.googleapis.com/fcm/send';
        $fields = array(
             'registration_ids' => $tokens,
             'data' => $message
            );
        $headers = array(
            'Authorization:key = YOUR_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;
    }

    $conn = mysqli_connect("localhost","root","","fcm");
    $sql = " Select Token From users";
    $result = mysqli_query($conn,$sql);
    $tokens = array();
    if(mysqli_num_rows($result) > 0 ){
        while ($row = mysqli_fetch_assoc($result)) {
            $tokens[] = $row["Token"];
        }
    }
    mysqli_close($conn);
    $message = array("message" => " FCM PUSH NOTIFICATION TEST MESSAGE");
    $message_status = send_notification($tokens, $message);
    echo $message_status;
 ?>

But I tried sending notifications on iOS(Swift) devices and it does not work. I get the token (FIRInstanceID.instanceID().token()) and try to send a notification from send.php (above code) and not worked.

I send individual/group/topic notification from Firebase Console and worked perfectly. Why doesn't it work from file.php?

help?!

FireUser
  • 173
  • 1
  • 3
  • 13

1 Answers1

3

To send iOS through FCM, you need to define notification key in your payload. It is explained in docs please take a look at there. https://firebase.google.com/docs/cloud-messaging/ios/send-multiple

Here is an example request

{
  "condition": "'all' in topics",
  "priority" : "high",
  "notification" : {
    "body" : "This is a Firebase Cloud Messaging Topic Message!",
    "title" : "FCM Message Title",
  }
}

In the example above I'm sending to the topic named all. You should create topic and subscribe your users to related topics. You need to make necessary changes in your $fields variable.