Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Firebase Cloud Messaging on Web server

I have a server running a website. I need this server to be able to administer (only downstream) notifications to three separate device groups, Android, iOS, and a client-side web app.

I am trying to use firebase cloud messaging. With FCM, I plan on using the http protocol to send json messages.

Aside from this, I am pretty confused about where to go. I know that GCM tutorials should pretty much be exactly the same as FCM tutorials, but I am having trouble finding a tutorial to figure out what I need to be doing, as each tutorial seems to mix up the server and client side applications together, which is confusing me.

I have been through

https://firebase.google.com/docs/cloud-messaging/server#choose

pretty thoroughly but it seems to gloss over some requisite knowledge that I don't have yet. Can anyone suggest a good starting place on how to implement FCM in the manner I am looking for? I am overall very new to web dev, less than 2 months, (using node, mongo, and scss) and feel a bit overwhelmed on how to get started on FCM.

I appreciate any feedback you guys can offer.

like image 234
Liquidmetal Avatar asked Feb 23 '26 21:02

Liquidmetal


1 Answers

as you have written that you are planning to get notifications on all three platforms that are android, iOS, and a client-side web app. You can use firebase to get real time notification or desired data that's good but you have to keep this in your mind that each one has a little different process to achieve this compared to each other. Very first you have to choose any of one and start the implementation. Let's start from the begin...

A common process for using firebase into your application to create a project at https://console.firebase.google.com/ .

After creating project you will be able to see the firebase key that will be used in your application. You can see this at https://console.firebase.google.com/project/project-[your_project_number]/overview.

I hope you have done this already but don't forget to give permission to Database and Storage at https://console.firebase.google.com/project/project-[your_project_number]/database/rules and https://console.firebase.google.com/project/project-[your_project_number]/storage/rules.

For database just leave this...

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

For storage just leave this...

service firebase.storage {
  match /b/project-[your_project_number].appspot.com/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}

It will define that you can use it publicly no need to of any verifaction at firebase end. If you want to add any kind of verification you can go through https://console.firebase.google.com/project/project-[your_project_number]/authentication/providers .

Now start with the SERVER to WEB APPLICATION notification. First of all I want to let you know FCM (firebase cloud messaging) can be implemented with Android, iOS and web(specified Google Chrome) only. So for using it on all browser we have to implement the firebase database. At js side. You have to put something like, what you have seen in Overview.

<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase.js"></script>
<script>
  // Initialize Firebase
  var config = {
    apiKey: "your_api_key",
    authDomain: "project-[your_project_number].firebaseapp.com",
    databaseURL: "https://project-[your_project_number].firebaseio.com",
    storageBucket: "project-[your_project_number].appspot.com",
  };
  firebase.initializeApp(config);
</script>

On server side for triggering an event or notification you can use CURL. As you have mentioned that you are using Node.js so this https://firebase.google.com/docs/server/setup#add_firebase_to_your_app can help you. I have achieved it by applying CURL at server side on PHP with CodeIgniter. I am attaching the code below. You can see the CURL example here https://firebase.google.com/docs/database/rest/save-data#section-put

<?php 
if (!defined('BASEPATH')) exit('No direct script access allowed');

//PHP CURL FOR NOTIFICATION
function booking_notification($notif_arr, $notif_type)
{
    //GET CI 
    $CI =& get_instance();

    $url = 'put_your_firebase_database_url_here';
    $key = 'put_firebase_key';
    $notif_arr = {'Key':'values'};//THIS IS THE DATA WHAT YOU WILL NEED TO SHOW ON FRONT END TO NOTIFY
    $notif_type = 'notification'; //THIS IS THE NAME JSON WHICH WILL BE CREATED IF NOT EXIST AT FIREBASE DATABASE
    $headers = array(
       'Authorization: key=' . $key,
       'Content-Type: application/json'
   );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url."/".$notif_type.".json");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

   // Disabling SSL Certificate support temporarly
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

   curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($notif_arr));

   // Execute post
   $result = curl_exec($ch);

   if ($result === FALSE) {
       die('Curl failed: ' . curl_error($ch));
       // Close connection
       curl_close($ch);

       return FALSE;
   }
   else
   {
       // Close connection
       curl_close($ch);
       return TRUE;
   }
}

Now let's see how we can get the notification when it will be fired from server side.

JAVASCRIPT

var fireBaseJSONref = firebase.database().ref().child("notification"); //BY THIS YOU CAN GET THE JSON OF FIREBASE DATABASE
fireBaseJSONref.on('child_added', function(snapshot) {
        if (!ignoreItems) {
            console.log(snapshot.val());//THIS WILL PRINT THE DATA WHAT YOU HAVE TRIGGERD FROM SERVER
        }
});
/* WHEN FIRST TIME ANY DATA SENT TO DATABASE OF FIREBASE AFTER PAGE LOAD */


fireBaseJSONref.once('value', function(snapshot) {ignoreItems = false}); //THIS WILL HELP YOU TO NOT TO CALL FOR PREVIOUSLY ADDED ITEM IN FIREBASE DATABASE. WHEN NEW DATA WILL BE ONLY THEN IT WILL CALL.

This will help you and figure out where you were confusing. Let me know if this will work for you, I will improve it for android and iOS also.

like image 120
Pritish Joshi Avatar answered Feb 26 '26 01:02

Pritish Joshi