Firebase Cloud Messaging: Push Notification On Flutter Using PHP

Link Copied To Clipboard !

FCM using PHP and Flutter Flutter

Firebase Cloud Messaging also abbreviated as FCM is a cross-platform messaging and notification service provided by Google. FCM is also known formerly know as Google Cloud Messaging or GCM. It provides cross platform messaging and notification services to Android, IOS and Web platforms. The service cost is free as of this date(2021).

FCM lets to send push notifications, schedule notifications to application users manually using firebase console or by implementing some code to make api request. In this article, we will learn how to implement FCM in flutter application and send notifications from the admin panel using PHP code. Note that we will not be doing whole stuffs to make flutter application or admin panel rather we will write some core code required to achieve FCM working on the app.

Alright, lets divide the whole process two parts. First we will see how we can integrate FCM into flutter application.

How to integrate Firebase Push Notification using FCM in flutter ?

  1. Create Firebase Project
    Using any Firebase services requires a Firebase project. If you haven’t created one for your project, create one at Firebase Console .
  2. Add firebase_messaging package
    Add the flutter package provided by google flutter team for integrating firebase messaging service. Add this line firebase_messaging in the dependencies section of pubspec.yaml file and execute flutter pub get .
  3. Complete Android specific configurations
    In this article, we are giving an example which sets up flutter FCM to work on android devices. For IOS, you will have to follow the official guide on configuring this. Now, before adding some codes, make sure you create an android app on your firebase project. You can do that by selecting your project on firebase console. Once you do that, it generates a file called google-services.json. Download that file and move it to yourproject/android/app/ .

    Add the line classpath 'com.google.gms:google-services:4.3.4' to dependencies section of your project level gradle file i.e. yourproject/android/build.gradle .

    Now, go to your app level gradle file i.e. yourproject/android/app/build.gradle and add apply plugin: 'com.google.gms.google-services' at the end of the file. In the dependencies section of same file, add the following lines :
    implementation platform('com.google.firebase:firebase-bom:26.1.0')
    implementation 'com.google.firebase:firebase-analytics-ktx'
    implementation 'com.google.android.gms:play-services-basement:17.5.0'
    implementation 'com.google.firebase:firebase-messaging-ktx:17.3.4'
    You might have to make some changes on version numbers. It’s a working setup for my case.

    If you want to open the app when the user taps on a notification, add the following intent filter inside of the activity element of your AndroidManifest.xml.

    <intent-filter>
    <action android.name=”FLUTTER_NOTIFICATION_CLICK” />
    <category android.name=”android.intent.category.DEFAULT” />
    </intent-filter>


    We are all set in android configuration side. Now we add some code in flutter side so that we receive notifications when sent.

Go the the file which first loads up in your app when run like splash.dart (you might have different start up file). Initialize the firebase messaging by putting final FirebaseMessaging _firebaseMessaging = FirebaseMessaging(); just inside class.
Add following functions inside your class.

_getToken() {
    _firebaseMessaging.getToken().then((value) => print('Device token $value'));
  }

  _configureFirebaseListeners() {
    _firebaseMessaging.subscribeToTopic('all');
    
    _firebaseMessaging.configure(onMessage: (message) async {
      print('onMessage ${json.encode(message)}');
    }, onResume: (message) async {
      print('onResume $message');
    }, onLaunch: (message) async {
      print('onLaunch $message');
    });
  }

Call these functions inside initState() . So the function looks something like this:

@override
  void initState() {
    super.initState();
    _configureFirebaseListeners();
    _getToken();
  }

When the notification is received, the behavior depends upon the state of app whether it is running in background or foreground or not running at all.

When app is running in foreground, the notification will not be shown by default. The listener function onMessage(message) in invoked and what we want our app to do when this event fires is totally up to us. We can show a dialog message or we can even show a notification by ourselves.

When app is running in background, the notification will be shown as system notification automatically. Tapping on notification will bring the app in foreground. The event onResume(message) will be invoked upon receive.

When app is not running at all, the notification will be shown as a system notification automatically and tapping on it will start the app.

We are done on the flutter side unless there exists some errors or typos. I am assuming you are capable of figuring them out and solving them. Once our of errors, run the app.

Sending Push Notification Via Firebase Console

After completing the implementation process explained above, go to Firebase Console, find Cloud Messaging and click on it. Then you will find an option to send notification, click on it, if you need device token, check your flutter console because we have printed that out. Follow instructions and send the notification.

Notice that, you will see a notification only when you are in background because we have not done anything for the foreground event (onMessage). You can see the console log though.

Sending Push Notification Using FCM And PHP

It can be done basically by executing a HTTP request. You can do that via terminal, shell, or any type of curl. Talking about PHP, we can use php-curl for that purpose. Before writing code, make sure you have php-curl of your php version installed. If not, check the php version by php --version and install curl by sudo apt install php7.4-curl (7.4 is an example, replace that with your php version). Then put the following code in a file where you have to perform notification send operation.

$url = 'https://fcm.googleapis.com/fcm/send';
$api_key = 'YOUR_FCM_SERVER_KEY_HERE';
$fields = array(
      'notification' => array(
          'title' => 'Test Title',
           'body' => 'This is just a test for FCM.'
       ),
       "to" => "/topics/all" //users are subscribed to topic all at startup
);
$headers = array(
     'Content-Type:application/json',
      'Authorization:key=' . $api_key
);
$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);
curl_close($ch);
if ($result === FALSE) {
     die(curl_error($ch));
}

echo 'Notification Sent !';

If everything is correct, you should now have a working Push Notification implemented on both server side as well as on application(flutter-android) side.

CHEERS – KEEP CODING !


You May Also Like