Sending Notification Message with Firebase with JavaScript and .Net client

Sending Notification Message with Firebase with JavaScript and ASP.Net client

Introduction to Firebase

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost. 

FCM server has two components for sending and receiving messages which are:
  • The trusted environment (app server)
  • FCM servers
It is the job of the app server to send the message to the FCM server which then sends the message to the client device.

The trusted environment can be an app server for sending messages; you can also use the Admin SDK or HTTP and XMPP APIs. The work of the server is to forward the message to the FCM server which then sends to the client.

Find out more about how it works here: https://firebase.google.com/docs/cloud-messaging/ 
In this tutorial, I will show you how to use firebase using JavaScript client to send token and notification messages to the FCM Legacy server.

Setting up Firebase Cloud Messaging Client App with JavaScript

The FCM JavaScript API lets you receive notification messages in web apps running in browsers that provide service worker support. This includes the following browsers. Check out https://firebase.google.com/docs/cloud-messaging/js/client for more info.




To get a boilerplate code from FCM console, navigate to the developer section and click on the WEB SETUP link above, you will get a boilerplate code to configure your FCM client.
Open the index.html page and you get a notification message that is asking for your permission, click “Allow” refresh the page and the token would be displayed in the browser console then. Copy the token and save it somewhere on your computer.

Note: I am currently using visual studio code live server instead of creating a node-js app server.

Fork/clone the source code on Git: https://github.com/cizu64/FirebaseClientNotification

Sending Message

To send a message, login to the firebase console and create a new project which is available on https://console.firebase.google.com/

Now you make your request to the Legacy protocol endpoint to create a message.
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=[Server key]
Note: To access this endpoint, you need to be authorized with the server key. If you try to access it with postman without the server, it will throw an error.

The endpoint must contain two request headers for the message to be sent successfully.
  •         Content-type: application/json
  •          Authorization: Key = <server key>

The server key can be found in the firebase project settings section under the tab cloud messaging in the firebase console.


The notification message is displayed in the console and if the browser is minimized or you open another page, it would show the notification toast.

ASP.Net client with FCM

I will show you how to send a notification from a .net client with the token that has been generated. It is good practice for the client to generate the token and send it to the server. For example, if we are building Android app that enables users to invite their friends to like their page, it would be better to use the FCM android library to generate the device token for the particular device and send the token to the backend server which would be stored in the database.

using System;
using System.IO;
using System.Net.Http.Headers;
using System.Net.Http;
using Newtonsoft.Json;

namespace FirebaseApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new HttpClient
            {
                BaseAddress = new Uri("https://fcm.googleapis.com/fcm/send"),
            };
            var val = "key=AIzaSyChJbkL7bTecnWYtRwb_5lqqqvCW6bnHSQ";
           
            client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", val);
            var fs = File.Open("body.txt", FileMode.Open); //read request body from file
            var sr = new StreamReader(fs).ReadToEnd();
            HttpContent sc = new StringContent(sr);
            string src = sc.ReadAsStringAsync().Result;


            var parseJson = JsonConvert.DeserializeObject(src); //Deserialize json into .net object using newtonsoft lib

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var response = client.PostAsJsonAsync(client.BaseAddress.ToString(), parseJson).Result;
            Console.WriteLine(response.Content);
            Console.ReadLine();
        }
    }
}

when you run the app, you should see the toast at the bottom

Comments

Popular posts from this blog

Solved: Jwt Authentication in Asp.Net Web Api And Mvc

Using SignalR with Unity