Firebase push notifications using a .NET Backend

At Kaizen Softworks we are currently working on a site that uses Angular 2, .NET and Azure as main technologies. In addition to this project, our client was needing a mobile application that was going to use the same database as the web-app due to the fact that they share information, so we needed a way to send notifications from the backend with hidden information to the mobile app, these messages were going to be carrying all the information needed on each action the notification was going to trigger. After a proof of concept we decided to work with Firebase as an intermediate between the backend and all our applications.

Firebase logo

What is Firebase?

Firebase works as a backend as a service which means it has a group of APIs that let’s you create a backend without too much coding skills. Firebase offers as part of the benefits easy integration with different platforms such as iOS, Android, Unity and C++. Free plans, premium plans and many functionalities are among them too. Some of them are Auth, Storage, Real-time database, Crash reports and many others including Firebase Cloud Messaging (FCM), the one that we need to send Push notifications.

Firebase Cloud Messaging

FCM gives us many advantages, here is the list of the most important:

  • It’s Free!! Unlimited use :)
  • Easy integration with many platforms
  • Well documented
  • 95% of all notifications delay 250ms since the notification is sent until it is received on the platform (by Google)
  • Target your audience: Send messages to a single device, a specific platform or a group of devices
  • Send messages from Firebase Console or hit the Firebase API

The FCM flow:
FCM flow diagram

Setting up client-side

Now that the Firebase introduction is finished, it’s coding and configuring time.

First of all, we need a Firebase Console project. With our Google account we have to go to the Firebase dashboard and press on Add project, then select the name you want for you project, the region and then click on “Create project”.

Ok, you’re done, you have your project created so now you are able to use all Firebase functionalities!

You have to register each platform you want Firebase configured to. During this tutorial I am going to configure an Android project. On the app-registration modal, you have to complete the package name depending on the name of your app. In my case, I am using a Firebase initial project, a project configured with all you need to start using any of the Firebase functionalities so the name of the app is already defined as “com.google.firebase.quickstart.fcm”. You can find the projects at the documentation samples section.

After pressing on “Register app”, you need to download and add google-services.json to your project. Firebase is going to provide you in case you don’t have them, if you have them you have to add FCM dependencies. Remember it is mandatory if you want Firebase working on your app.

Cloud Messaging menu Well done, your client side is ready, if you want more information about client side configuration you can get it on the documentation guide for Android or for iOS or other platforms you will find on the side panel of the Cloud Messaging documentation page.

For each app-installation, Firebase is going to create a token that identifies it, so in case of sending a notification to that specific app-installation, you will need that token. To learn about getting this token, please read “Access the device registration token” part on the setting up section of the platform you want to configure Firebase to.

Sending our first notification

We can send push notifications without having the backend configured, we can use the Firebase console, to do that we have to go to our Firebase project, select Notifications in the side panel and press on the button “Send your first message” to see the next panel:
Configuration panel

Fields you have to fill to send your first notification:

  • Message text: Main message of the notification.
  • Target: Devices that you want to send this notification. These can be:
  • “User segment” if you want to send it to a group of users in a specific condition, for example all Android app-installations with app-purchases.
  • “Topic” if you want to send it to a group of users defined by you, you can read more about this in the documentation.
  • “Single device” if you want to send it to a specific FCM Token. After completing those fields, just press on “SEND MESSAGE”, a popup is going to open with all important information about the notification you are going to send, press “SEND” and you’re done!

After completing those fields, just press on “SEND MESSAGE”, a popup is going to open with all important information about the notification you are going to send, press “SEND” and you’re done!
Push notification received

Preparing your .NET backend

For this example, I am going to use a backend developed in .NET, a console project that I specifficaly developed for a .NET Meetup in Uruguay.

To hit Firebase API we need some information from Firebase, we need the API url (https://fcm.googleapis.com/fcm/send) and a unique key that identifies our Firebase project for security reasons. To get this server-key, we have to do the following:

  • Access to “Project settings” as it’s showed on the image
  • Select “Cloud Messaging” tab
  • The server-key is on the section “Project credentials” Project settings

Time to code the backend

In addition to the API-Url and the server-key, we are going to need a method with some parameters to hit Firebase API. For that, I created a static class called “PushNotificationLogic.cs” with this method:
Code method

These parameters are:

  • deviceTokens: An array of strings, each string represents a FCM token provided by Firebase on each app-installation. This is going to be the list of app-installations that the notification is going to send.
  • title: It’s the bold section of a notification.
  • body: It represents “Message text” field of the Firebase SDK, this is the message you want to send to the users.
  • data: These is a dynamic object, it can be whatever you want because this object is going to be used as additional information you want to send to the app, it’s like hidden information. For example an action you want to execute when the user presses on the notification or an id of some product.

For the method, I am going to suppose that all parameters are correct without bad values (you can add all the validations you want). The first thing we have to do is to create an object with all the data we need to send to the API, I created two classes for that:

public class Message  
{
  public string[] registration_ids { get; set; }
  public Notification notification { get; set; }
  public object data { get; set; }
}
public class Notification  
{
  public string title { get; set; }
  public string text { get; set; }
}

Then, just create a new object of type “Message” and serialize it as I did it here:

var messageInformation = new Message()  
{
  notification = new Notification()
  {
    title = title,
    text = body
  },
  data = data,
  registration_ids = deviceTokens
};
//Object to JSON STRUCTURE => using Newtonsoft.Json;
string jsonMessage = JsonConvert.SerializeObject(messageInformation);  

Now we just need a request to Firebase API and we’re done. The request has to be as a “Post” Method to the Firebase API-Url, we have to add a Header which is “Authorization” and use a value like: “key={YourServerKey}”. Then we add the content (jsonMessage) and you are ready to hit the api.

Here it is the code you need to do the last part:

// Create request to Firebase API
var request = new HttpRequestMessage(HttpMethod.Post, FireBasePushNotificationsURL);  
request.Headers.TryAddWithoutValidation(“Authorization”, “key=” + ServerKey);  
request.Content = new StringContent(jsonMessage, Encoding.UTF8, “application/json”);  
HttpResponseMessage result;  
using (var client = new HttpClient())  
{
  result = await client.SendAsync(request);
}

I hope I was clear and precise. You can reach out to me with doubts, recommendations, improvements or any type of constructive critics. You can find me on LinkedIn and twitter.

In addition, you can check the code on my github repo so you can download it and use it as you want.

Thank you for reading!

Nicolas Bonora

Nicolas Bonora

I was born in July 1st in a small country called Uruguay :), Tech lover, developer, speaker, and also .NET Meetup’s Organizer.

Read More