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 : 34395  
 
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 AND DEVELOPMENT.

 
 
 

Related Posts

Google Play Games on PC: Transforming Your Gaming Experience

Do you want to play your favorite Android games directly on your computer? If your answer is yes, you've come to the right place! In today's guide, I will explain…

Are you being floCed by Google?

No panic! Don't be alarmed, because it may sound worse than it is. But since Google doesn't seem to have any intention of communicating it properly, it's up to the…

Parental controls on Android: how to make mobiles and tablets child-friendly

Despite all the good things about them, mobile devices can expose your children to content that they're better off not seeing. The good news is that your Android phone or…

Interesting and Helpful Google Search Features You’ll Want to Start Using

Google – THE search engine for many internet users. It has been with us since its launch back in 1998 and thanks to its simplicity of use and genius algorithms,…

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…

Clicky