FCM Server ,C#推播
廢話不多說付上程式碼
public static void SendPushNotification()
{
try
{
//伺服器
string applicationID = "FCM伺服器金鑰";
string senderId = "FCM寄件者 ID";
//string deviceId = "手機的TOKEN";
string deviceId = "/topics/Test";
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;
}
}
在這邊要說明一下 deviceID 就是字面上的意思,裝置的ID也就是裝置的TOKEN,你必須先去上一篇製作一個APP,放入你要推播的手機內,
便會alert該手機的TOKEN 這樣可以達到單人的推播
如果要多人以上
就要使用string deviceid = "/Topics/Test" 這個
但前提你要先將你的APP中加上
即可