Envoi push à Android par C # à l’aide de FCM (Firebase Cloud Messaging)

J’utilise ce code pour envoyer un message de notification par C # avec GCM, en utilisant Winforms, Webforms, peu importe. Maintenant, je souhaite envoyer à FCM (Firebase Cloud Messaging). Devrais-je mettre à jour mon code? :

public class AndroidGCMPushNotification { public AndroidGCMPushNotification() { // // TODO: Add constructor logic here // } public ssortingng SendNotification(ssortingng deviceId, ssortingng message) { ssortingng SERVER_API_KEY = "server api key"; var SENDER_ID = "application number"; var value = message; WebRequest tRequest; tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send"); tRequest.Method = "post"; tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8"; tRequest.Headers.Add(ssortingng.Format("Authorization: key={0}", SERVER_API_KEY)); tRequest.Headers.Add(ssortingng.Format("Sender: id={0}", SENDER_ID)); ssortingng postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToSsortingng() + "&registration_id=" + deviceId + ""; Console.WriteLine(postData); Byte[] byteArray = Encoding.UTF8.GetBytes(postData); tRequest.ContentLength = byteArray.Length; Stream dataStream = tRequest.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); WebResponse tResponse = tRequest.GetResponse(); dataStream = tResponse.GetResponseStream(); StreamReader tReader = new StreamReader(dataStream); Ssortingng sResponseFromServer = tReader.ReadToEnd(); tReader.Close(); dataStream.Close(); tResponse.Close(); return sResponseFromServer; } } 

mais le GCM a été changé en FCM. Est-ce que c’est le même code pour envoyer la notification? Où puis-je trouver le SERVER_API_KEY? Est-ce la même solution?

    Firebase cloud messaging with c #: fonctionne sur toutes les plateformes .net (asp.net, .netmvc, .netcore)

      WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send"); tRequest.Method = "post"; //serverKey - Key from Firebase cloud messaging server tRequest.Headers.Add(ssortingng.Format("Authorization: key={0}", "AIXXXXXX....")); //Sender Id - From firebase project setting tRequest.Headers.Add(ssortingng.Format("Sender: id={0}", "XXXXX..")); tRequest.ContentType = "application/json"; var payload = new { to = "e8EHtMwqsZY:APA91bFUktufXdsDLdXXXXXX..........XXXXXXXXXXXXXX", priority = "high", content_available = true, notification = new { body = "Test", title = "Test", badge = 1 }, }; ssortingng postbody = JsonConvert.SerializeObject(payload).ToSsortingng(); Byte[] byteArray = Encoding.UTF8.GetBytes(postbody); tRequest.ContentLength = byteArray.Length; using (Stream dataStream = tRequest.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); using (WebResponse tResponse = tRequest.GetResponse()) { using (Stream dataStreamResponse = tResponse.GetResponseStream()) { if (dataStreamResponse != null) using (StreamReader tReader = new StreamReader(dataStreamResponse)) { Ssortingng sResponseFromServer = tReader.ReadToEnd(); //result.Response = sResponseFromServer; } } } }`` 

    Voici une autre approche permettant d’écrire Notification Service dans l’API ASP.Net REST.

     public async Task NotifyAsync(ssortingng to, ssortingng title, ssortingng body) { try { // Get the server key from FCM console var serverKey = ssortingng.Format("key={0}", "Your server key - use app config"); // Get the sender id from FCM console var senderId = ssortingng.Format("id={0}", "Your sender id - use app config"); var data = new { to, // Recipient device token notification = new { title, body } }; // 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 SsortingngContent(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 _logger.LogError($"Error sending notification. Status Code: {result.StatusCode}"); } } } } catch (Exception ex) { _logger.LogError($"Exception thrown in Notify Service: {ex}"); } return false; } 

    Références:

     using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System.Net.Http; using System.Text; using System.Threading.Tasks; 

    J’ai posté cette réponse car cette question était la plupart du temps consultée et ce code côté serveur a été écrit dans VS 2015 en C # pour envoyer une notification push à un seul périphérique en fonction de l’identifiant du périphérique ou d’un sujet souscrit à l’application Android Xamarin.

     public class FCMPushNotification { public FCMPushNotification() { // TODO: Add constructor logic here } public bool Successful { get; set; } public ssortingng Response { get; set; } public Exception Error { get; set; } public FCMPushNotification SendNotification(ssortingng _title, ssortingng _message, ssortingng _topic) { FCMPushNotification result = new FCMPushNotification(); try { result.Successful = true; result.Error = null; // var value = message; var requestUri = "https://fcm.googleapis.com/fcm/send"; WebRequest webRequest = WebRequest.Create(requestUri); webRequest.Method = "POST"; webRequest.Headers.Add(ssortingng.Format("Authorization: key={0}", YOUR_FCM_SERVER_API_KEY)); webRequest.Headers.Add(ssortingng.Format("Sender: id={0}", YOUR_FCM_SENDER_ID)); webRequest.ContentType = "application/json"; var data = new { // to = YOUR_FCM_DEVICE_ID, // Uncoment this if you want to test for single device to="/topics/"+_topic, // this is for topic notification=new { title=_title, body=_message, //icon="myicon" } }; var serializer = new JavaScriptSerializer(); var json = serializer.Serialize(data); Byte[] byteArray = Encoding.UTF8.GetBytes(json); webRequest.ContentLength = byteArray.Length; using (Stream dataStream = webRequest.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); using (WebResponse webResponse = webRequest.GetResponse()) { using (Stream dataStreamResponse = webResponse.GetResponseStream()) { using (StreamReader tReader = new StreamReader(dataStreamResponse)) { Ssortingng sResponseFromServer = tReader.ReadToEnd(); result.Response = sResponseFromServer; } } } } } catch(Exception ex) { result.Successful = false; result.Response = null; result.Error = ex; } return result; } } 

    et ses utilisations

     // start sending push notification to apps FCMPushNotification fcmPush = new FCMPushNotification(); fcmPush.SendNotification("your notificatin title", "Your body message","news"); // end push notification 

    Oui, vous devez mettre à jour votre code pour utiliser l’interface de messagerie Firebase. Il y a un projet GitHub pour cela ici .

     using Stimulsoft.Base.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Web; namespace _WEBAPP { public class FireBasePush { private ssortingng FireBase_URL = "https://fcm.googleapis.com/fcm/send"; private ssortingng key_server; public FireBasePush(Ssortingng Key_Server) { this.key_server = Key_Server; } public dynamic SendPush(PushMessage message) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(FireBase_URL); request.Method = "POST"; request.Headers.Add("Authorization", "key=" + this.key_server); request.ContentType = "application/json"; ssortingng json = JsonConvert.SerializeObject(message); //json = json.Replace("content_available", "content-available"); byte[] byteArray = Encoding.UTF8.GetBytes(json); request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); HttpWebResponse respuesta = (HttpWebResponse)request.GetResponse(); if (respuesta.StatusCode == HttpStatusCode.Accepted || respuesta.StatusCode == HttpStatusCode.OK || respuesta.StatusCode == HttpStatusCode.Created) { StreamReader read = new StreamReader(respuesta.GetResponseStream()); Ssortingng result = read.ReadToEnd(); read.Close(); respuesta.Close(); dynamic stuff = JsonConvert.DeserializeObject(result); return stuff; } else { throw new Exception("Ocurrio un error al obtener la respuesta del servidor: " + respuesta.StatusCode); } } } public class PushMessage { private ssortingng _to; private PushMessageData _notification; private dynamic _data; private dynamic _click_action; public dynamic data { get { return _data; } set { _data = value; } } public ssortingng to { get { return _to; } set { _to = value; } } public PushMessageData notification { get { return _notification; } set { _notification = value; } } public dynamic click_action { get { return _click_action; } set { _click_action = value; } } } public class PushMessageData { private ssortingng _title; private ssortingng _text; private ssortingng _sound = "default"; //private dynamic _content_available; private ssortingng _click_action; public ssortingng sound { get { return _sound; } set { _sound = value; } } public ssortingng title { get { return _title; } set { _title = value; } } public ssortingng text { get { return _text; } set { _text = value; } } public ssortingng click_action { get { return _click_action; } set { _click_action = value; } } } } 

    Basé sur le code de Teste .. Je peux confirmer les travaux suivants. Je ne peux pas dire s’il s’agit ou non d’un “bon” code, mais il fonctionne certainement et pourrait vous permettre de reprendre vos activités rapidement si vous vous retrouviez avec des problèmes de serveur GCM à FCM!

     public AndroidFCMPushNotificationStatus SendNotification(ssortingng serverApiKey, ssortingng senderId, ssortingng deviceId, ssortingng message) { AndroidFCMPushNotificationStatus result = new AndroidFCMPushNotificationStatus(); try { result.Successful = false; result.Error = null; var value = message; WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send"); tRequest.Method = "post"; tRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8"; tRequest.Headers.Add(ssortingng.Format("Authorization: key={0}", serverApiKey)); tRequest.Headers.Add(ssortingng.Format("Sender: id={0}", senderId)); ssortingng postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToSsortingng() + "&registration_id=" + deviceId + ""; Byte[] byteArray = Encoding.UTF8.GetBytes(postData); tRequest.ContentLength = byteArray.Length; using (Stream dataStream = tRequest.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); using (WebResponse tResponse = tRequest.GetResponse()) { using (Stream dataStreamResponse = tResponse.GetResponseStream()) { using (StreamReader tReader = new StreamReader(dataStreamResponse)) { Ssortingng sResponseFromServer = tReader.ReadToEnd(); result.Response = sResponseFromServer; } } } } } catch (Exception ex) { result.Successful = false; result.Response = null; result.Error = ex; } return result; } public class AndroidFCMPushNotificationStatus { public bool Successful { get; set; } public ssortingng Response { get; set; } public Exception Error { get; set; } } 

    Vous devez modifier l’URL de https://android.googleapis.com/gcm/send vers https://fcm.googleapis.com/fcm/send et modifier votre bibliothèque d’applications. ce didacticiel peut vous aider à https://firebase.google.com/docs/cloud-messaging/server#implementing-http-connection-server-protocol

    Essayez d’envoyer un object JSON. Remplacez ceci:

     tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8"; ssortingng postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToSsortingng() + "&registration_id=" + deviceId + ""; Console.WriteLine(postData); Byte[] byteArray = Encoding.UTF8.GetBytes(postData); 

    Pour ça:

     tRequest.ContentType = "application/json"; var data = new { to = deviceId, notification = new { body = "This is the message", title = "This is the title", icon = "myicon" } }; var serializer = new JavaScriptSerializer(); var json = serializer.Serialize(data); Byte[] byteArray = Encoding.UTF8.GetBytes(json); 

    Voici le code pour la demande de nuage firebase côté serveur de C # / Asp.net.
    Veuillez noter que votre côté client devrait avoir le même sujet.
    par exemple

     FirebaseMessaging.getInstance().subscribeToTopic("news"); public Ssortingng SendNotificationFromFirebaseCloud() { var result = "-1"; var webAddr = "https://fcm.googleapis.com/fcm/send"; var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr); httpWebRequest.ContentType = "application/json"; httpWebRequest.Headers.Add("Authorization:key=" + YOUR_FIREBASE_SERVER_KEY); httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { ssortingng json = "{\"to\": \"/topics/news\",\"data\": {\"message\": \"This is a Firebase Cloud Messaging Topic Message!\",}}"; streamWriter.Write(json); streamWriter.Flush(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { result = streamReader.ReadToEnd(); } return result; } 
      public SendNotice(int deviceType, ssortingng deviceToken, ssortingng message, int badge, int status, ssortingng sound) { AndroidFCMPushNotificationStatus result = new AndroidFCMPushNotificationStatus(); try { result.Successful = false; result.Error = null; var value = message; WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send"); tRequest.Method = "post"; tRequest.ContentType = "application/json"; var serializer = new JavaScriptSerializer(); var json = ""; tRequest.Headers.Add(ssortingng.Format("Authorization: key={0}", "AA******")); tRequest.Headers.Add(ssortingng.Format("Sender: id={0}", "11********")); if (DeviceType == 2) { var body = new { to = deviceToken, data = new { custom_notification = new { title = "Notification", body = message, sound = "default", priority = "high", show_in_foreground = true, targetScreen = notificationType,//"detail", }, }, priority = 10 }; json = serializer.Serialize(body); } else { var body = new { to = deviceToken, content_available = true, notification = new { title = "Notification", body = message, sound = "default", show_in_foreground = true, }, data = new { targetScreen = notificationType, id = 0, }, priority = 10 }; json = serializer.Serialize(body); } Byte[] byteArray = Encoding.UTF8.GetBytes(json); tRequest.ContentLength = byteArray.Length; using (Stream dataStream = tRequest.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); using (WebResponse tResponse = tRequest.GetResponse()) { using (Stream dataStreamResponse = tResponse.GetResponseStream()) { using (StreamReader tReader = new StreamReader(dataStreamResponse)) { Ssortingng sResponseFromServer = tReader.ReadToEnd(); result.Response = sResponseFromServer; } } } } } catch (Exception ex) { result.Successful = false; result.Response = null; result.Error = ex; } } 

    Vous pouvez utiliser cette bibliothèque, ce qui rend transparente l’envoi de notifications push à l’aide du service Firebase à partir d’un téléchargement en backend C # ici