web-dev-qa-db-ja.com

FCM(Firebase Cloud Messaging)を使用してC#でAndroidにプッシュを送信します

このコードを使用して、C#でGCMを使用して、Winforms、Webformsなどを使用して通知メッセージを送信します。次に、FCM(Firebase Cloud Messaging)に送信します。コードを更新する必要がありますか? :

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() + "&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);

        String sResponseFromServer = tReader.ReadToEnd();


        tReader.Close();
        dataStream.Close();
        tResponse.Close();
        return sResponseFromServer;
    }
}

しかし、GCMはFCMに変更されました。通知を送信するのと同じコードですか? SERVER_API_KEYはどこにありますか?同じ解決策ですか?

38
Teste

c#を使用したfirebaseクラウドメッセージング:すべての.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(string.Format("Authorization: key={0}", "AIXXXXXX...."));
        //Sender Id - From firebase project setting  
        tRequest.Headers.Add(string.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
            },
        };

        string postbody = JsonConvert.SerializeObject(payload).ToString();
        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))
                        {
                            String sResponseFromServer = tReader.ReadToEnd();
                            //result.Response = sResponseFromServer;
                        }
                }
            }
        }
62
Osama Hassan

ASP.Net REST AP​​I内に通知サービスを記述する別のアプローチを次に示します。

public async Task<bool> NotifyAsync(string to, string title, string body)
{
    try
    {
        // Get the server key from FCM console
        var serverKey = string.Format("key={0}", "Your server key - use app config");

        // Get the sender id from FCM console
        var senderId = string.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 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
                    _logger.LogError($"Error sending notification. Status Code: {result.StatusCode}");
                }
            }
        }
    }
    catch (Exception ex)
    {
        _logger.LogError($"Exception thrown in Notify Service: {ex}");
    }

    return false;
}

参照:

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

この質問が最も多く見られ、このサーバー側コードはVS 2015でC#で書かれており、デバイス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
10
Ishwor Khanal

はい、Firebase Messagingインターフェイスを使用するようにコードを更新する必要があります。そのためのGitHubプロジェクトがあります here

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;
            }
        }
    }
}
5
checkmate711

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() + "&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))
                    {
                        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;
    }
}
4
Steven Elliott

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;
}
3
Aditya varale

JSONオブジェクトを送信してみてください。これを置き換えます:

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() + "&registration_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);
3

URLを https://Android.googleapis.com/gcm/send から https://fcm.googleapis.com/fcm/send に変更し、アプリを変更する必要がありますライブラリも。このチュートリアルはあなたを助けることができます https://firebase.google.com/docs/cloud-messaging/server#implementing-http-connection-server-protocol

3
Gustavo Rozolin

私はこのコードを書いて、それは私のために働いています。

public static string ExcutePushNotification(string title, string msg, string fcmToken, object data) 
{

        var serverKey = "AAAA*******************";
        var senderId = "3333333333333";


        var result = "-1";

        var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://fcm.googleapis.com/fcm/send");
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
        httpWebRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
        httpWebRequest.Method = "POST";


        var payload = new
        {
            notification = new
            {
                title = title,
                body = msg,
                sound = "default"
            },

            data = new
            {
                info = data
            },
            to = fcmToken,
            priority = "high",
            content_available = true,

        };


        var serializer = new JavaScriptSerializer();

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = serializer.Serialize(payload);
            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            result = streamReader.ReadToEnd();
        }
        return result;
}

私はこのアプローチを使用していますが、うまく機能しています:

 public class PushNotification
 {
     private static readonly ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        // firebase
     private static Uri FireBasePushNotificationsURL = new Uri("https://fcm.googleapis.com/fcm/send");
     private static string ServerKey = ConfigurationManager.AppSettings["FIREBASESERVERKEY"];

     public static async Task<bool> SendPushNotification(List<SendNotificationModel> notificationData)
     {
         try
         {
             bool sent = false;         
             foreach (var data in notificationData)
             {
                 var messageInformation = new Message()
                 {
                     notification = new Notification()
                     {
                         title = data.Title,
                         text = data.Message,
                         ClickAction = "FCM_PLUGIN_ACTIVITY"
                      },
                      data = data.data,
                      priority="high",
                      to =data.DeviceId
                 };
                 string jsonMessage = JsonConvert.SerializeObject(messageInformation);

                 //Create request to Firebase API
                 var request = new HttpRequestMessage(HttpMethod.Post, FireBasePushNotificationsURL);

                 request.Headers.TryAddWithoutValidation("Authorization", "key=" + ServerKey);
                 request.Content = new StringContent(jsonMessage, Encoding.UTF8, "application/json");

                 HttpResponseMessage result;
                 using (var client = new HttpClient())
                 {
                     result = await client.SendAsync(request);
                     sent =  result.IsSuccessStatusCode;
                 }             
             }

                return sent;
         }
         catch(Exception ex)
         {
             Logger.Error(ex);
             return false;
          }
    }
 }
1
Divya Agrawal
 public  SendNotice(int deviceType, string deviceToken, string message, int badge, int status, string 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(string.Format("Authorization: key={0}", "AA******"));
            tRequest.Headers.Add(string.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))
                        {
                            String sResponseFromServer = tReader.ReadToEnd();
                            result.Response = sResponseFromServer;
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            result.Successful = false;
            result.Response = null;
            result.Error = ex;
        }
}
1
Dinesh.net

このライブラリを使用して、C#バックエンドダウンロードからFirebase Serviceを使用してプッシュ通知をシームレスに送信できます here

1
Frank Odoom