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 : 23384  
 
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

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…

What is Google My Business and how does it help my local business?

Google My Business is increasingly present in the digital marketing strategies of companies, and this Google tool provides us with various options to better position our business in the search…

There are 470,000 WhatsApp groups indexed on Google and Facebook says it's not his fault

Want to find new WhatsApp groups? Google it. Reporter Jordan Wildon has discovered hundreds of thousands of private groups through the search engine thanks to public invitation links. Not all were…

How to prevent people from adding spam events and appointments in Google Calendar

Let's explain how to prevent people from adding spam to your Google Calendar by adding events and appointments without your approval. This is a practice that has been used for…

Google Search hacks to Use Google More Efficiently

Modern folks have grown up with having all the world's data at their fingertips with super mobile phones glued to our palms. Or it's what we've always believed. Sometimes the…

RCS: Everything you need to know about the successor to the SMS

What is RCS? What is it for? Discover everything about this system that Google has been promoting for some time and the future it could have. Messaging in the handset market…