Sunday 3 February 2019

Firebase FCM Push & subscribe Notification Topics Using Firebase Cloud Messaging Using .NET

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

Steps to get server key / SenderID
  1. To get the keys, log in to Firebase account.
  2. Select the project from the list.
  3. Click on "Setting" gear icon and click "Project Settings". 
  1. //Create the web request with fire base API  
  2. WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");  
  3. tRequest.Method = "post";  
  4. //serverKey - Key from Firebase cloud messaging server  
  5. tRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));  
  6. //Sender Id - From firebase project setting  
  7. tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));  
  8. tRequest.ContentType = "application/json";  
  9. var payload = new {  
  10.     to = deviceId,  
  11.         priority = "high",  
  12.         content_available = true,  
  13.         notification = new {  
  14.             body = txtmsg,  
  15.                 title = txttitle.Replace(":"""),  
  16.                 sound = "sound.caf",  
  17.                 badge = badgeCounter  
  18.         },  
  19. };  
  20. var serializer = new JavaScriptSerializer();  
  21. Byte[] byteArray = Encoding.UTF8.GetBytes(payload);  
  22. tRequest.ContentLength = byteArray.Length;  
  23. using(Stream dataStream = tRequest.GetRequestStream()) {  
  24.     dataStream.Write(byteArray, 0, byteArray.Length);  
  25.     using(WebResponse tResponse = tRequest.GetResponse()) {  
  26.         using(Stream dataStreamResponse = tResponse.GetResponseStream()) {  
  27.             if (dataStreamResponse != null) using(StreamReader tReader = new StreamReader(dataStreamResponse)) {  
  28.                 String sResponseFromServer = tReader.ReadToEnd();  
  29.                 result.Response = sResponseFromServer;  
  30.             }  
  31.         }  
  32.     }  
  33. }  

Subscribe Topics FCM :

The FCM JavaScript API lets you receive notification messages in web apps running in browsers.


Retrieve a messaging object
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
// Add the public key generated from the console here.
messaging.usePublicVapidKey("XXXdd");


Request permission to receive notifications

messaging.requestPermission().then(function() {
  console.log('Notification permission granted.');
  // TODO(developer): Retrieve an Instance ID token for use with FCM.
  // ...
}).catch(function(err) {
  console.log('Unable to get permission to notify.', err);
});

Access the registration token
The messaging service requires a firebase-messaging-sw.js file. Unless you already have a firebase-messaging-sw.js file, create an empty file with that name and place it in the root of your domain before retrieving a token.

// Get Instance ID token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
messaging.getToken().then(function(currentToken) {
  if (currentToken) {
    sendTokenToServer(currentToken);
    updateUIForPushEnabled(currentToken);
  } else {
    // Show permission request.
    console.log('No Instance ID token available. Request permission to generate one.');
    // Show permission UI.
    updateUIForPushPermissionRequired();
    setTokenSentToServer(false);
  }
}).catch(function(err) {
  console.log('An error occurred while retrieving token. ', err);
  showToken('Error retrieving Instance ID token. ', err);
  setTokenSentToServer(false);
});



Receive Messaging :
When your app is in the foreground (the user is currently viewing your web page), you can receive data and notification payloads directly in the page.
//   `messaging.setBackgroundMessageHandler` handler.
messaging.onMessage(function(payload) {
  console.log('Message received. ', payload);
  // ...
});

firebase-messaging-sw.js
// Note that you can only use Firebase Messaging here, other Firebase libraries
// are not available in the service worker.
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
  'messagingSenderId': 'YOUR-SENDER-ID'
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();