Send Push Notification to Users Using Firebase Messaging Service in Php

Send Push Notification to Users Using Firebase Messaging Service in PHP
by Janeth Kent Date: 14-05-2018 google push messaging


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

  1. Get FCM Token From User
  2. 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\"}}"

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>&nbsp;</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. 

 
by Janeth Kent Date: 14-05-2018 google push messaging hits : 25004  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN END DEVELOPMENT.

 
 
 

Related Posts

Google Maps updates and now shows gas prices at gas stations

Any help, no matter how small, that can make our daily life easier is welcome; for example, Google Maps has allowed us to move from one corner to another is…

Cumulative Layout Shift, what is and How to optimize CLS

Cumulative Layout Shift, one of the new Core Web Vitals metrics,  is the first metric that focuses on user experience beyond performance. Unexpected movement of web page content is a major…

The best free tools for linkbuilding

Linkbuilding is one of the main factors in improving the SEO positioning of a page. Having a profile of inbound links from pages with great authority can mean the difference…

SEO: How to find and remove artificial links

At Ma-no we are aware of the importance of a good linkbuilding strategy in order to achieve success with a website. Links are key to placing a website among the top…

Google everywhere: anatomy of a massive giant

The alarm clock is going off. A hand floats over the bedside table groping for the source of the sound: probably a cell phone and maybe one of the more than…

What's the Difference between Google TV and Android TV?

At the end of September, Google launched the renewal of its classic dongle. The new Google Chromecast didn't arrive alone, but added two very important innovations compared to the devices…

How to prevent your neighbor from hacking your Chromecast

Google Chromecast was born as a device to add Smart TV features to those that were not yet Smart TV, and with WiFi connectivity as one of the key features…

How to share your location using Plus codes on Google Maps for Android

Do you know what plus codes or plus codes on Google Maps are and what they are for? We tell you how they work and how to get them from anywhere. You…

The new features coming to the Google search engine in autumn 2020

Google has included important improvements in its search engine, applying Artificial Intelligence, to make it easier for users to find what they are looking for. It has also announced new…

How to change the arrow icon on Google Maps to a 3D car

When you follow a navigation route on Google Maps, your position is represented by an arrow except on specific occasions such as anniversaries. However, it is possible to change the…

SEO in Google News: How to appear in Google News

Google News is a tool, from Google, that spreads current, reliable and truthful content from different websites or portals dedicated exclusively to news. The sites that appear in Google News…

Google Dorks: How to find interesting data and search like hacker

Go the words Google and Hacking together? Well if you thought that we will learn how to use hack Google, you might be wrong. But we can Use Google search engine…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration