0

I'm going to develop a react-native app which uses Firebase Push Notification , when I send push notification from Firebase Console it's working on both background and foreground of the app , but when I send notification from my server using PHP(WordPress) it just sends notification while the app is in foreground and not in background, but the notification message result show success. Here I'm gonna provide some of codes

Mobile side:

        import React, { Component } from "react";

    import { Platform, AsyncStorage } from 'react-native';

    import FCM, { FCMEvent, RemoteNotificationResult, WillPresentNotificationResult, NotificationType } from "react-native-fcm";

    export default class PushNotificationController extends
      Component {
      constructor(props) {
        super(props);
        console.ignoredYellowBox = ['Setting a timer'];

        this.state = {
          firebase_token :'',
        }
      }
      saveFirebaseToken() {
        console.log("------------- as "+this.state.firebase_token+" ---------- ");
        AsyncStorage.setItem('firebase_token', this.state.firebase_token);
      }
      componentDidMount() {
        FCM.requestPermissions();

        FCM.getFCMToken().then(token => {
          console.log(token+' on getFCMToken');

          this.setState({

            firebase_token: token,
          })
          this.saveFirebaseToken()
        });

        FCM.getInitialNotification().then(notif => {
          console.log("INITIAL NOTIFICATION", notif)
        });

        this.notificationListner = FCM.on    (FCMEvent.Notification, notif => {
          console.log("Notification", notif);
          if (notif.local_notification) {
            return;
          }
          if (notif.opened_from_tray) {
            return;
          }

          if (Platform.OS === 'ios') {
            //optional
            //iOS requires developers to call completionHandler to end notification process. If you do not call it your background remote notifications could be throttled, to read more about it see the above documentation link.
            //This library handles it for you automatically with default behavior (for remote notification, finish with NoData; for WillPresent, finish depend on "show_in_foreground"). However if you want to return different result, follow the following code to override
            //notif._notificationType is available for iOS platfrom
            switch (notif._notificationType) {
              case NotificationType.Remote:
                notif.finish(RemoteNotificationResult.NewData) //other types available: RemoteNotificationResult.NewData, RemoteNotificationResult.ResultFailed
                break;
              case NotificationType.NotificationResponse:
                notif.finish();
                break;
              case NotificationType.WillPresent:
                notif.finish(WillPresentNotificationResult.All) //other types available: WillPresentNotificationResult.None
                break;
            }
          }
          this.showLocalNotification(notif);
        });

        this.refreshTokenListener = FCM.on(FCMEvent.RefreshToken, token => {
          console.log("TOKEN (refreshUnsubscribe)", token);
        });
      }

      showLocalNotification(notif) {
        FCM.presentLocalNotification({
          title: notif.title,
          body: notif.body,
          priority: "high",
          click_action: notif.click_action,
          show_in_foreground: true,
          local: true
        });
      }

      componentWillUnmount() {
        this.notificationListner.remove();
        this.refreshTokenListener.remove();
      }
      render() {
        return null;
      }
    }

Added codes in manifest:

    <receiver android:name="com.evollu.react.fcm.FIRLocalMessagingPublisher"/>
     <receiver android:enabled="true" android:exported="true"  android:name="com.evollu.react.fcm.FIRSystemBootEventReceiver">
         <intent-filter>
             <action android:name="android.intent.action.BOOT_COMPLETED"/>
            <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
             <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
             <category android:name="android.intent.category.DEFAULT" />
         </intent-filter>
     </receiver>
       <service android:name="com.evollu.react.fcm.MessagingService" android:enabled="true" android:exported="true">
    <intent-filter>
      <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
  </service>

  <service android:name="com.evollu.react.fcm.InstanceIdService" android:exported="false">
    <intent-filter>
      <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
    </intent-filter>
 </service>

And Here is the server codes:

        function send_notification($tokens, $message)
    {


        $url = 'https://fcm.googleapis.com/fcm/send';
        $fields = array(
             'registration_ids' => $tokens,
             'data' => $message
            );
        $headers = array(
            'Authorization:key = My_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;
    }
ReyAnthonyRenacia
  • 17,219
  • 5
  • 37
  • 56
Naser Nikzad
  • 713
  • 12
  • 27

2 Answers2

0

Hopefully I could figure out to solve this with a friend of mine and the help of the bottom link.

Solution: I need to re-format the data I was sending to Firbase server, the payload issues which are used for custom data sending along with notification was involved here.

function send_notification($tokens, $message)
  {


      $url = 'https://fcm.googleapis.com/fcm/send';


      $msg = array
             (
                'body'      => $data,
                'title'     => "New Job",
                'sound'     => 'default',
                'vibrate'   => 1,
                'largeIcon' => 'large_icon',
                'smallIcon' => 'small_icon'

            );

            $dat = array
            (
                'job_id'     => "90",
                'emp_id'     => "9000",
                'cand_id'     => "1010001"
            );

            $fields = array
            (
                'registration_ids'  => array($tokens),
                'notification'      => $msg,
                'data'       => $dat
            );

      $headers = array(
          'Authorization:key = My_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;
  }

Also the credit goes to @HarikumarAlangode for his useful answer.

Make a custom data for parameter on firebase to call on push notification

Naser Nikzad
  • 713
  • 12
  • 27
0

Notification Payload Object

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification":{
      "title":"Portugal vs. Denmark",
      "body":"great match!"
    },
    "data" : {
      "Nick" : "Mario",
      "Room" : "PortugalVSDenmark"
    }
  }
}

For more info: https://firebase.google.com/docs/cloud-messaging/concept-options

Vinit Bhavsar
  • 226
  • 3
  • 13