發表於 程式分享

C#傳送FCM Notification Topics

1.FCMNotificationManager.cs


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;

   public class FCMNotificationManager
    {
        private NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
        public FCMNotificationManager()
        {
        }

        public string SendNotification(string message, string title, long id)
        {
            string SERVER_API_KEY = "[請填入]";
            var SENDER_ID = "[請填入]";

            WebRequest tRequest;
            tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
            tRequest.Method = "post";
            tRequest.ContentType = "application/json";
            tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));
            tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));

            string deviceId = "/topics/marketing";
            var data = new
            {
                to = deviceId,
                notification = new
                {
                    body = message,
                    title = title,
                    sound = "Enabled"

                }
            };
            var serializer = new JavaScriptSerializer();
            var json = serializer.Serialize(data);
            logger.Info("json: " + json);
            Byte[] byteArray = Encoding.UTF8.GetBytes(json);
            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;
        }
    }

2.呼叫方式


FCMNotificationManager fcmNotificationMgr = new FCMNotificationManager();
string sResponseFromServer = fcmNotificationMgr.SendNotification("測試訊息...", "測試標題", 1);

3.SERVER_API_KEY 及 SENDER_ID
SERVER_API_KEY: 請填伺服器金鑰
SENDER_ID: 請填寄件者 ID
1

C#傳送FCM Notification Topics 有 “ 1 則迴響 ”

發表留言