Search code examples
phpfirebaseionic-frameworkionic2cordova-plugin-fcm

ionic - firebase notification using PHP not working


I want to push notification to my Ionic 2 app using firebase. I can push notification directly using firebase console, but I want to send it via php file.

when I send I get a response from PHP as: {"message_id":5718309985299480645}

And there is no notification in the phone.

I have placed this.fcm.subscribeToTopic('all') in the app.component.ts constructor.

I dont know what I am doing wrong..

this.fcm.subscribeToTopic('all') is the only code related to fcm in my app.

MY PHP CODE:

<?php 

   $data = array('title'=>'FCM Push Notifications');
   $target = '/topics/mytopic';


   //FCM API end-point
   $url = 'https://fcm.googleapis.com/fcm/send';
   //api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
   $server_key = 'my_server_key_from_firebase';

   $fields = array();
   $fields['data'] = $data;
   if(is_array($target)){
   $fields['registration_ids'] = $target;
   }else{
   $fields['to'] = $target;
   }

   //header with content_type api key
   $headers = array(
   'Content-Type:application/json',
   'Authorization:key='.$server_key
   );
   //CURL request to route notification to FCM connection server (provided by Google)           
   $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('Oops! FCM Send Error: ' . curl_error($ch));
   }
   curl_close($ch);
   echo $result;

?>

I EVEN TRIED PUSHBOTS BUT COULD NOT GET NOTFICATIONS ON THE DEVICE WITH PHP


Solution

  • I solved the problem by looking at fcm docs.

    I changed the PHP file to:

       $data = array('title'=>'Title of the notification', 'body'=>$msg, 'sound'=>'default');
       $target = '/topics/notetoall';
    
       $url = 'https://fcm.googleapis.com/fcm/send';
    
       $server_key = 'my_server_api_key_from_firebase';
    
       $fields = array();
       $fields['notification'] = $data; // <-- this is what I changed from $fields['body']
       if(is_array($target)){
       $fields['registration_ids'] = $target;
       }else{
       $fields['to'] = $target;
       }