Friday 23 March 2018

Send Push Notification to Users Using Firebase Messaging Service in PHP

Send Push Notification to Users Browser Using Firebase Messaging Service in PHP   To Day I am Explain about how to send Push notifications using Firebase Cloud Messaging (FCM) in web application FCM service is free of charge with some limitations. The size is limited to 2KB or 4KB depending on the type of data, and the message will be kept for default duration of 4 weeks before it gets deleted.
Browser Support:
Chrome: 50+
Firefox: 44+
Opera Mobile: 37+


Step 1) First we need to create firebase project from Here
Go to Fibrebase Click On "Add Project" to create a new project. Give your project a name, and choose the country/region that reflects your currency and revenue reporting. follow the Screen shots.


Step 2) Getting FCM token from user Browser
Create index.html file for geting User FCM Browser token, go to fibrebase console and click on Add Firebase to your web app and copy the snnipet of code, paste the code in index.html file


<title>KC Firebase Messaging Demo</title>
<body>
   <div id="token"></div>
   <div id="msg"></div>
   <div id="notofication"></div>
   <div id="error"></div>
   <script src="https://www.gstatic.com/firebasejs/4.12.0/firebase.js"></script>
   <script>
       MsgElem = document.getElementById("msg");
       TokenElem = document.getElementById("token");
       NotisElem = document.getElementById("notofication");
       ErrElem = document.getElementById("error");
         // Initialize Firebase
         var config = {
           apiKey: "",
           authDomain: "",
           databaseURL: "",
           projectId: "",
           storageBucket: "",
           messagingSenderId: ""
         };
         firebase.initializeApp(config);
       const messaging = firebase.messaging();
       messaging
           .requestPermission()
           .then(function () {
               MsgElem.innerHTML = "Notification permission granted."
               console.log("Notification permission granted.");
               // get the token in the form of promise
               return messaging.getToken()
           })
           .then(function(token) {
               TokenElem.innerHTML = "token is : " + token
           })
           .catch(function (err) {
               ErrElem.innerHTML =  ErrElem.innerHTML + "; " + err
               console.log("Unable to get permission to notify.", err);
           });
       messaging.onMessage(function(payload) {
           console.log("Message received. ", payload);
           NotisElem.innerHTML = NotisElem.innerHTML + JSON.stringify(payload)
       });
   </script>
   <body>
</html>

step 3) We need to create firebase-messaging-sw.js file and put it in your www or htdocs folder before you execute the index.html file.
importScripts('https://www.gstatic.com/firebasejs/4.12.0/firebase-app.js');
 importScripts('https://www.gstatic.com/firebasejs/4.12.0/firebase-messaging.js');
 // Initialize Firebase
   var config = {
     apiKey: "your api key",
     authDomain: "your auth domain",
     databaseURL: "your database url",
      projectId: "your project id",
     storageBucket: "your storage bucket",
     messagingSenderId: "your messaging id"
   };
   firebase.initializeApp(config);
   
   const messaging = firebase.messaging();

Step 4) Execute index.html and getting Token
open browser and type localhost/kc_fcm_demo/ you will get the request prompt like the following screenshot.
After the user grant the permission for us to send the notification, we can get an FCM registration token that can be used to send push messages to this user.

Step 5) Sending Push Message using curl
crate send_push_message.php file replace your "API_ACCESS_KEY" from ""Legacy server key Go to fibre console click on Gear icon -> project settings->cloud messigning ->Legacy server key Paste User token at "to" parameter we alredy getting user browser token in step 4.
 define( 'API_ACCESS_KEY', 'Legacy server key');//Go to fibre console click on Gear icon -> project settings->cloud messigning ->Legacy server key
   $message=array( "title" =>; "Srinu Chilukuri",
                "body" => "Test Message",
                "icon" => "Koala.jpg",
                 "click_action" => "https://knowledgecornor.blogspot.in/"
           );
   $data = array("to" => "Paste Here User Token we alredy getting token in step 4",
                 notification" =>$message ); 
   $data_string = json_encode($data);
   $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 "The Result is: ".$result;
?>
We will see the following response after successfully executing of send_push_message.php
{"multicast_id":4751625963323170363,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1521798166275771%e609af1cf9fd7ecd"}]}
When your app is in the foreground, i.e. the user is currently viewing the web page, you can receive and notification directly on the page. For this example, we display the whole notification payload like in below
{"collapse_key":"do_not_collapse","from":"604921974894","notification":{"title":"Srinu Chilukuri","body":"Test message from knowledgecorner","icon":"kc_logo.jpg","click_action":"https://knowledgecornor.blogspot.in/"}}
if your app is in the background, the message received will trigger a display notification in the browser like the screenshot below. You can specify what action to perform if the user clicks on the notification.


Thank You
Sorce: FCM

No comments:

Post a Comment