Saturday, October 12, 2019

Send Push Notification using C#

Here is the way by which we can send push notification to mobile device. Below are some steps to perform before sending notification to device.

(1) Google Firebase provides way by which we can send push notification through that. In this case we have valid google account 
(2) From your Firebase account, create project for the android/ios application
(3) Once your application is installed on your device it will register your device for that project to receive notification
(4) When your device is ready with application created on firebase and device id is registered then it is ready to receive push notifications for that application
(5) In step - (4), when your device is registered with device id, this device id to be shared or stored at some repository so that whenever we want to send notification we can pull that device id and send notification with below c# code

var result = "-1";
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://fcm.googleapis.com/fcm/send");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", "server key"));
httpWebRequest.Headers.Add(string.Format("Sender: id={0}", "Test Sender"));
httpWebRequest.Method = "POST";

var payload = new
{
to = "device token",
priority = "high",
        content_available = true,
notification = new
        {
        body = "body of notification",
        title = "notification title"
        },
};

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = JsonConvert.SerializeObject(payload);
        streamWriter.Write(json);
        streamWriter.Flush();
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}

No comments:

Post a Comment