Skip to content

Instantly share code, notes, and snippets.

@NeuroWhAI
Created June 25, 2020 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NeuroWhAI/b916a27db59d311960fecb6c92751c67 to your computer and use it in GitHub Desktop.
Save NeuroWhAI/b916a27db59d311960fecb6c92751c67 to your computer and use it in GitHub Desktop.
Send a message to the FCM.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net;
using System.IO;
using Google.Apis.Auth.OAuth2;
using Newtonsoft.Json;
namespace FirebaseCSTest
{
class Program
{
static void Main(string[] args)
{
string jsonFile = "service-key.json";
ServiceAccountCredential credential;
string token;
using (var stream = new FileStream(jsonFile, FileMode.Open))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(Enumerable.Repeat("https://www.googleapis.com/auth/firebase.messaging", 1))
.UnderlyingCredential as ServiceAccountCredential;
}
token = credential.GetAccessTokenForRequestAsync().GetAwaiter().GetResult();
Console.WriteLine("Token: {0}", token);
string msg = JsonConvert.SerializeObject(new
{
message = new
{
topic = "news",
notification = new
{
body = "This is test. 테스트 알림입니다.\n123abc.",
title = "Test Alarm",
},
},
});
var msgBytes = Encoding.UTF8.GetBytes(msg);
string endpoint = "https://fcm.googleapis.com/v1/projects/<my-project-id>/messages:send";
var request = WebRequest.Create(endpoint);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = msgBytes.Length;
request.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {token}");
using (var stream = request.GetRequestStream())
{
stream.Write(msgBytes, 0, msgBytes.Length);
}
using (var res = request.GetResponse())
{
Console.WriteLine(((HttpWebResponse)res).StatusDescription);
using (var stream = new StreamReader(res.GetResponseStream()))
{
Console.WriteLine(stream.ReadToEnd());
}
}
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment