Send Push Notification to Users Using Firebase Messaging Service in PHP

Today I will show you how to send unlimited free push notifications to your clients using Firebase Cloud Messaging (FCM) in your PHP web application. Push Notifications are clickable messages that come from a website. They are used to show notifications outside the web page context even if the user is not browsing the page he subscribed to. You can examples of push notification in many famous blogs, Facebook and youtube.

What is FCM?

The FCM or Firebase Messaging Service is the new version of GCM (Google Cloud Messaging). It inherits the reliable and scalable GCM infrastructure, plus new features. Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost. Using FCM, you can notify a client app that new email or other data is available to sync.

Browser Support

Chrome: 50+

Firefox: 44+

Opera Mobile: 37+

Note: Sending messages to the Notifications Console is not supported.

Working

The Involves mainly two

Get FCM Token From User Show Notification To User

Before We Start

We need to make a firebase project by visiting following link. The procedures are fairly simple and straight forward so I am skipping it.

Let's Start Coding

1) Get FCM Token From User

Get the web setup codes from firebase console by visiting Authentication tab. The codes for index.html file is given below

<script src="https://www.gstatic.com/firebasejs/3.7.2/firebase.js"></script> <script> // Initialize Firebase var config = { apiKey: "your api key", authDomain: "your auth domain", databaseURL: "your database url", storageBucket: "your storage bucket", messagingSenderId: "your messaging id" }; firebase.initializeApp(config); const messaging = firebase.messaging(); messaging.requestPermission() .then(function() { console.log('Notification permission granted.'); return messaging.getToken(); }) .then(function(token) { console.log(token); // Display user token }) .catch(function(err) { // Happen if user deney permission console.log('Unable to get permission to notify.', err); }); messaging.onMessage(function(payload){ console.log('onMessage',payload); }) </script>

You can get the client token by opening the console. The onMessage function is used because we don't need to send notification if the user is on your web page.

In real world application, you need to send the token to your server via Ajax Post like below and store it in a table for future use.

$.ajax({ type:'POST', url:'/storetoken', data:{token : token, _token: "<?php echo csrf_token(); ?>"}, success:function(data){ $("#msg").html(data); } });

Note You need to create firebase-messaging-sw.js file and put it in your www or htdocs folder before you execute the index.html file. The codes for it is given below.

importScripts('https://www.gstatic.com/firebasejs/3.7.1/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/3.7.1/firebase-messaging.js'); // Initialize Firebase var config = { apiKey: "your api key", authDomain: "your auth domain", databaseURL: "your database url", storageBucket: "your storage bucket", messagingSenderId: "your messaging id" }; firebase.initializeApp(config); const messaging = firebase.messaging();

Note: You also need to save your icon in www or htdocs folder.

2) Send Notification To User

Again two optional methods

a) By using curl in command line

If you are using windows you can download curl for 64 bit from following the link. After downloading it unzip it and copy the contents inside bin folder to a newly created curl folder inside your c drive and add that folder to windows path.

If you are using Linux a simple apt-get install curl command is enough to install curl.

Now we need to post user id information and notification information in JSON to https://fcm.googleapis.com/fcm/send along with authentication key in the header.

You can get authentication key or API_ACCESS_KEY by visiting project setting could messaging section in firebase console.

The code for curl command line is given below

curl -X POST --header "Authorization: key=AAAA-----FE6F" \ --Header "Content-Type: application/json" \ https://fcm.googleapis.com/fcm/send \ -d "{\"to\":\"cNf2Sx----9\",\"notification\":{\"title\" : \"Shareurcodes.com\",\"body\":\"A Code Sharing Blog!\",\"icon\": \"icon.png\",\"click_action\": \"http://shareurcodes.com\"}}"

The sample output image is given below

b) By calling curl by using PHP scripts (Recommended and easy method)

The code for curl.php file is given below

<?php // Server key from Firebase Console define( 'API_ACCESS_KEY', 'AAAA----FE6F' ); $data = array("to" => "cNf2---6Vs9", "notification" => array( "title" => "Shareurcodes.com", "body" => "A Code Sharing Blog!","icon" => "icon.png", "click_action" => "http://shareurcodes.com")); $data_string = json_encode($data); echo "The Json Data : ".$data_string; $headers = array ( 'Authorization: key=' . API_ACCESS_KEY, 'Content-Type: application/json' ); $ch = curl_init(); curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' ); curl_setopt( $ch,CURLOPT_POST, true ); curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers ); curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch,CURLOPT_POSTFIELDS, $data_string); $result = curl_exec($ch); curl_close ($ch); echo "<p> </p>"; echo "The Result : ".$result;

Note you need to execute curl.php file using another browser ie not from the browser that is used to get the user token. You can see notification only if you are browsing another website.

Now what?

Note: The FCM SDK is supported only in pages served over HTTPS. This is due to its use of service workers, which are available only on HTTPS sites.

If you are making real world application then the first step is buying SSL certificate to your server.

Store user token information in your server. Send the message by calling a cul function one by one for each user. The modify it according to your need. The above code gives basic core snippets. Comment below if you have any suggestions or doubts.

DEMO

You can demo this application by visiting following link.