Skip to content

Instantly share code, notes, and snippets.

@graco911
Created May 25, 2018 19:10
Show Gist options
  • Save graco911/aeffa3bd2bb81f4446f3ffc2ff15da20 to your computer and use it in GitHub Desktop.
Save graco911/aeffa3bd2bb81f4446f3ffc2ff15da20 to your computer and use it in GitHub Desktop.
FirebaseSendNotification
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Services
{
public partial class Firebase
{
public static async Task<bool> SendNotification(NotificationData not)
{
try
{
// Get the server key from FCM console
var serverKey = string.Format("key={0}", serverkey);
// Get the sender id from FCM console
var senderId = string.Format("id={0}", "ID");
var data = new
{
to = not.To, // Recipient device token
notification = new { title = not.Title, body = not.Body, sound = "default" },
priority = "high"
};
// Using Newtonsoft.Json
var jsonBody = JsonConvert.SerializeObject(data);
using (var httpRequest = new HttpRequestMessage(HttpMethod.Post, "https://fcm.googleapis.com/fcm/send"))
{
httpRequest.Headers.TryAddWithoutValidation("Authorization", serverKey);
//httpRequest.Headers.TryAddWithoutValidation("Sender", senderId);
httpRequest.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient())
{
var result = await httpClient.SendAsync(httpRequest);
if (result.IsSuccessStatusCode)
{
return true;
}
else
{
// Use result.StatusCode to handle failure
// Your custom error handler here
Console.WriteLine($"Error sending notification. Status Code: {result.StatusCode}");
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception thrown in Notify Service: {ex}");
}
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment