使用FCM(Firebase Cloud Messaging)通过C#发送推送至Android
我正在使用此代码通过C#发送通知消息与GCM,使用Winforms,Webforms,无论如何。 现在我想发送到FCM(Firebase云消息传递)。 我应该更新我的代码吗? :
public class AndroidGCMPushNotification { public AndroidGCMPushNotification() { // // TODO: Add constructor logic here // } public string SendNotification(string deviceId, string message) { string 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(string.Format("Authorization: key={0}", SERVER_API_KEY)); tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID)); string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "®istration_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); String sResponseFromServer = tReader.ReadToEnd(); tReader.Close(); dataStream.Close(); tResponse.Close(); return sResponseFromServer; } }
但GCM更改为FCM。 这是相同的代码发送通知? 我在哪里可以findSERVER_API_KEY? 是一样的解决scheme?
这里是服务器端的firebase到android和IOS的代码:
public static void SendPushNotification() { try { string applicationID = "AIz..........Fep0"; string senderId = "30............8"; string deviceId = "ch_G60NPga4:APA9............T_LH8up40Ghi-J"; WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send"); tRequest.Method = "post"; tRequest.ContentType = "application/json"; var data = new { to = deviceId, notification = new { body = "Osama", title = "AlBaami", sound = "Enabled" } }; var serializer = new JavaScriptSerializer(); var json = serializer.Serialize(data); Byte[] byteArray = Encoding.UTF8.GetBytes(json); tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID)); tRequest.Headers.Add(string.Format("Sender: id={0}", senderId)); 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)) { String sResponseFromServer = tReader.ReadToEnd(); string str = sResponseFromServer; } } } } } catch (Exception ex) { string str = ex.Message; } }
基于Teste的代码..我可以确认以下的作品。 我不能说这是否是“好”的代码,但是它确实有效,如果你最终发现GCM到FCM服务器的问题,它可以让你快速备份和运行!
public AndroidFCMPushNotificationStatus SendNotification(string serverApiKey, string senderId, string deviceId, string 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(string.Format("Authorization: key={0}", serverApiKey)); tRequest.Headers.Add(string.Format("Sender: id={0}", senderId)); string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "®istration_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)) { String 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 string Response { get; set; } public Exception Error { get; set; } }
我已经发布了这个答案,因为这个问题最常被看到,而这个服务器端代码是在C#中用VS 2015编写的,用于发送推送通知,无论是基于设备ID还是订阅主题的单个设备到Xamarin Android应用程序
public class FCMPushNotification { public FCMPushNotification() { // TODO: Add constructor logic here } public bool Successful { get; set; } public string Response { get; set; } public Exception Error { get; set; } public FCMPushNotification SendNotification(string _title, string _message, string _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(string.Format("Authorization: key={0}", YOUR_FCM_SERVER_API_KEY)); webRequest.Headers.Add(string.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)) { String sResponseFromServer = tReader.ReadToEnd(); result.Response = sResponseFromServer; } } } } } catch(Exception ex) { result.Successful = false; result.Response = null; result.Error = ex; } return result; } }
及其用途
// start sending push notification to apps FCMPushNotification fcmPush = new FCMPushNotification(); fcmPush.SendNotification("your notificatin title", "Your body message","news"); // end push notification
您需要从https://android.googleapis.com/gcm/send更改url到https://fcm.googleapis.com/fcm/send,然后更改您的应用程序库。; 本教程可以帮助您https://firebase.google.com/docs/cloud-messaging/server#implementing-http-connection-server-protocol
尝试发送一个json对象。 replace这个:
tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8"; string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "®istration_id=" + deviceId + ""; Console.WriteLine(postData); Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
为了这:
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);
以下是来自C#/ Asp.net的服务器端Firebase云请求的代码。
请注意,您的客户端应该有相同的主题。
例如
FirebaseMessaging.getInstance().subscribeToTopic("news"); public String 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())) { string 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; }
是的,您应该更新代码以使用Firebase消息传递界面。 这里有一个GitHub项目。
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 string FireBase_URL = "https://fcm.googleapis.com/fcm/send"; private string key_server; public FireBasePush(String 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"; string 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()); String 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 string _to; private PushMessageData _notification; private dynamic _data; private dynamic _click_action; public dynamic data { get { return _data; } set { _data = value; } } public string 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 string _title; private string _text; private string _sound = "default"; //private dynamic _content_available; private string _click_action; public string sound { get { return _sound; } set { _sound = value; } } public string title { get { return _title; } set { _title = value; } } public string text { get { return _text; } set { _text = value; } } public string click_action { get { return _click_action; } set { _click_action = value; } } } }