Chrome Notification Using Firebase In PHP

Before starting we should know about the Chrome Notification and Google Firebase Cloud Messaging Service (FCM), for what purpose we are using it and how it works.

1. Push Notification

A push notification is a message sent to your device by a web app or a website. Notification can be delivered to your device, mobile or desktop even when the user is not on your website.

The browser which supports web notifications is Chrome, Firefox, Edge and Safari. Notifications are used to attract the user engagement by providing them different types of offers.

2. Firebase Cloud Messaging (FCM)

Firebase Cloud Messaging (FCM) is a messaging service provided by a Google at free of cost. FCM is used as a cross-platform cloud solution for messages and notifications for web applications, android applications and iOS apllications.

3. Steps To Create a Push Notification

Before getting started you should know that the push notification only works in the HTTPS sites due to its use of service workers, which only run on a secure origin. But you can test it in the localhost.

Step 1 : Create an Account In Google Firebase
  1. Go to Google Firebase and create an account by using your email id.
  2. Click the Add Project button and create your project by filling the fields.
  3. After the project has been created successfully go to the Setting pane and open cloud messaging tab and scroll to the Web configuration section and click Generate Key Pair.
  4. Now go to the General tab and scroll to the Your apps section and click the button with sign </> to get all of your credentials.
Step 2 : Configure Web credentials in your app
  1. Create four files in your directory name as manifest.json, firebase-messaging-sw.js, app.js and index.php.

Important: Do not change the name of firebase-messaging-sw.js because it is used by firebase as a service worker file.

manifest.json

{"gcm_sender_id": "103953800507"}

Important: Just copy the gcm_sender_id as given above, do not change its value.

Replace all the credential fields in app.js and firebase-messaging-sw.js with your credentials provided by firebase cloud messaging service.

app.js

var config = {
    apiKey: "<YOUR API KEY>", //Replace this
    authDomain: "<YOUR AUTH DOMAIN>", //Replace this
    databaseURL: "<YOUR DATABASE URL>", //Replace this
    projectId: "<YOUR PROJECT ID>", //Replace this
    storageBucket: "<YOUR STORAGE BUCKET>", //Replace this
    messagingSenderId: "<YOUR MESSAGING SENDER ID>" //Replace this
  };
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);
})
.catch(function(err) {
  console.log('Unable to get permission to notify.', err);
})

//Show the notification when the user is surfing the page 

messaging.onMessage(function(payload) {
    const notificationTitle = payload.notification.title;
    const notificationOptions = {
        body: payload.notification.body,
        icon: payload.notification.icon,        
    };

    if (!("Notification" in window)) {
        console.log("This browser does not support system notifications");
    }
    // Let's check whether notification permissions have already been granted
    else if (Notification.permission === "granted") {
        // If it's okay let's create a notification
        var notification = new Notification(notificationTitle,notificationOptions);
        notification.onclick = function(event) {
            event.preventDefault(); // prevent the browser from focusing the Notification's tab
            window.open(payload.notification.click_action , '_blank');
            notification.close();
        }
    }
});

firebase-messaging-sw.js

importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
var config = {
    apiKey: "<YOUR API KEY>", //Replace this
    authDomain: "<YOUR AUTH DOMAIN>", //Replace this
    databaseURL: "<YOUR DATABASE URL>", //Replace this
    projectId: "<YOUR PROJECT ID>", //Replace this
    storageBucket: "<YOUR STORAGE BUCKET>", //Replace this
    messagingSenderId: "<YOUR MESSAGING SENDER ID>" //Replace this
  };
  firebase.initializeApp(config);
  
  const messaging = firebase.messaging();

index.php

<html>
<head>
	<script src="https://www.gstatic.com/firebasejs/5.8.4/firebase.js"></script>
	<script src="/app.js"></script>
	<link rel="manifest" href="/manifest.json">
</head>
<body>
	<div id="token"><div>
</body>
</html>

Now just run index.php in your browser and allow permission for notification. After allowing for the notification you will get the unique token in your console, just store this token in your database for sending a notification to the users.

Step 3 : Send your Message

You can send message to the client by using HTTP POST method by requesting header as Authorization and Content-Type. Here I will show how to send notification using PHP CURL, for that we have to create one file send.php or you can directly use in PHP console.

Now just copy the token which is shown in your browser index.php and replace with the field <CLIENT TOKEN> in your send.php file.

Now go to your firebase console Project Setting and open a tab Cloud Messaging . In Project Credentials section your authorization key is located just copy that and replace with the field <YOUR AUTHORIZATION KEY> in your send.php file.

Authorization Key

Note: Do not use your api key instead of authorization key because both are not same.

send.php

<head>
	<script src="https://www.gstatic.com/firebasejs/5.8.4/firebase.js"></script>
	<script src="/app.js"></script>
	<link rel="manifest" href="/manifest.json">
</head>
<?php
$notification = array("notification"=>array(
"title"=>"Hello World",
"body"=>"Welcome Friends",
"icon"=>"/icon.png",
"click_action"=>"https://www.example.com",
),
"to"=>"<CLIENT TOKEN>"
);
$notification_json=json_encode($notification);
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $notification_json);
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = 'Authorization: key=<YOUR AUTHORIZATION KEY>';
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
echo $result."<br>";
?>

After successfully mentioning your token and authorization key in your send.php file, run this file in your browser, if nothing goes wrong you will get a response like shown in below.

{"multicast_id":7303881325315809310,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1551369816729708%e609af1cf9fd7ecd"}]}

If the success message appears you will see the notification in the bottom right corner in your chrome browser. The image in the bottom is an example of chrome notification.

Notification

Leave a Reply

Your email address will not be published. Required fields are marked *