How do I send a server side Push Notification on Firebase Http V1 for Android
Here I am using the FirebaseAdmin Nuget package
Create a NotificationPayload class
public class NotificationPayload
{
public string Title { get; set; }
public string Body { get; set; }
public Dictionary<string, string> CustomFields { get; set; }
}
Now you can create the method "SendAndroidPushNotificationAsync" that is going to send the Push Notification:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using FirebaseAdmin.Messaging;
using FirebaseAdmin;
using Google.Apis.Auth.OAuth2;
using System.IO;
public async Task SendAndroidPushNotificationAsync(string deviceId, NotificationPayload notificationPayload)
{
var customFields = new Dictionary<string, string>();
if (notificationPayload.CustomFields != null && notificationPayload.CustomFields.Count > 0)
{
foreach (var field in notificationPayload.CustomFields)
{
customFields.Add(field.Key.ToString(), field.Value);
}
}
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "firebase-adminsdk.json")),
});
var notificationMessage = new FirebaseAdmin.Messaging.Message()
{
Data = customFields,
Notification = new FirebaseAdmin.Messaging.Notification
{
Title = notificationPayload.Title,
Body = notificationPayload.Body
},
Android = new FirebaseAdmin.Messaging.AndroidConfig()
{
Priority = Priority.Normal,
TimeToLive = TimeSpan.FromHours(1),
},
Token = deviceId
};
var result = await FirebaseMessaging.DefaultInstance.SendAsync(notificationMessage);
Console.WriteLine(result);
}
The "firebase-adminsdk.json" is the private key json file that you need to generate from your Firebase Project and store in your Application's root folder.
Now you can call this method "SendAndroidPushNotificationAsync" from whichever project that you want to sent the Push Notification. You will need an App to which you want to send the Notification and the deviceId/channelId to which the Notification need to be sent.
If we are getting a result like "//projects/myapp/messages/2492588335721724324" we should be good