Skip to content

Instantly share code, notes, and snippets.

@cleardemon
Created December 9, 2021 11:18
Show Gist options
  • Save cleardemon/4bdf27494f789cbcdf10e07f9a1c37ef to your computer and use it in GitHub Desktop.
Save cleardemon/4bdf27494f789cbcdf10e07f9a1c37ef to your computer and use it in GitHub Desktop.
How to send a push notification from C# console to Firebase
/* Requires these packages to be included in the project (or whatever latest versions are available):
<PackageReference Include="FirebaseAdmin" Version="2.2.0" />
<PackageReference Include="System.Text.Json" Version="6.0.0" />
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using FirebaseAdmin;
using FirebaseAdmin.Messaging;
using Google.Apis.Auth.OAuth2;
namespace FirebasePushTest
{
class Program
{
static void Main(string[] args)
{
var configFilename = args.Length == 1 ? args[0] : "test-config.json";
// parse json file containing configuration (not secrets)
var config = JsonSerializer.Deserialize<TestConfiguration>(File.OpenRead(configFilename));
if(config is null)
{
Fail("Couldn't parse config.");
return;
}
// create firebase app, parse services json for secrets
// you need to set the GOOGLE_APPLICATION_CREDENTIALS environment variable to point to the
// location of the JSON file on your computer for this to work (it must be a full path).
// if you don't have a JSON file, you need to get the private key from here:
// https://console.firebase.google.com/u/0/project/api-XXXXXXXX-XXXXXXX/settings/serviceaccounts/adminsdk
// and click "Generate new private key"... check with anyone on your team first if one has been created!
FirebaseApp.Create(new AppOptions { Credential = GoogleCredential.GetApplicationDefault() });
// send notification
Console.WriteLine("Sending notification...");
SendNotification(config).Wait();
void Fail(string msg)
{
Console.WriteLine($"ERROR: {msg}");
Environment.Exit(1);
}
}
static async Task SendNotification(TestConfiguration configuration)
{
// this is how you send metadata in a push notification via Firebase
// it is represented as a key/value string pair...
// on Android, this will appear in the intent Extras (e.g. intent.GetStringExtra("go"))
// on iOS, this will appear in the UserInfo NSDictionary in UNNotificationContent
// in this example, we use this metadata to tell the app about a deep/shallow link to navigate to
var data = new Dictionary<string, string>();
if(!string.IsNullOrEmpty(configuration.DeepLink))
{
data.Add("go", configuration.DeepLink);
}
// multicast so it can be sent to more than one device
var message = new MulticastMessage
{
Tokens = configuration.Tokens,
Notification = new Notification
{
Title = configuration.Title,
Body = configuration.Body
},
Data = data
};
var response = await FirebaseMessaging.DefaultInstance.SendMulticastAsync(message);
Console.WriteLine("Notification sent.");
Console.WriteLine($"Success count: {response.SuccessCount}, failures: {response.FailureCount}");
}
}
// this matches the test-config.json file, deserialised from JSON
class TestConfiguration
{
[JsonPropertyName("tokens")]
public List<string> Tokens { get; set; }
[JsonPropertyName("title")]
public string Title { get; set; }
[JsonPropertyName("body")]
public string Body { get; set; }
[JsonPropertyName("deepLink")]
public string DeepLink { get; set; }
}
}
{
"tokens": [
// you can include one or more tokens here. dump it to console/logs in your app when Firebase tells you.
// on Android, this would be via the OnCompleteListener in FirebaseMessaging.Instance.GetToken().
"<YOUR DEVICE TOKEN HERE>",
"<YOUR DEVICE TOKEN HERE>",
"<YOUR DEVICE TOKEN HERE>"
],
"title": "Test message",
"body": "This is a test message",
"deepLink": "/a/route/to/go/to?param=abc&param2=123"
}
@Nedunchezhian
Copy link

Please add apns code for ios device

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment