1. 程式人生 > 其它 >c# 服務端接入個推指定物件訊息推送

c# 服務端接入個推指定物件訊息推送

個推訊息推送主要步驟:1.獲取鑑權token 2.傳送推送訊息

1.獲取鑑權token(會過期,需要間隔時間獲取一次):
tokenUrl = "https://restapi.getui.com/v2/" + appId + "/auth";
        private string GetToken()
        {
            long nowTime ;    //當前的時間戳 毫秒級   
            string sign = appKey + nowTime + masterSecret;
            string sha256Sign = SHA256EncryptString(sign);  //
用sha256加密 string postParam = "{\"sign\":\"" + sha256Sign + "\",\"timestamp\":\"" + nowTime + "\",\"appkey\":\""+ appKey + "\"}"; //json格式的post引數 appkey masterSecret appid 申請應用後會有 return HttpRequestPost(tokenUrl, postParam); } private string HttpRequestPost(string
Url, string Param) { string result = string.Empty; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Timeout = Timeout; request.ContentType = "application/json;charset=utf-8"; request.ReadWriteTimeout
= Timeout; request.Proxy = null; request.ServicePoint.Expect100Continue = false; request.KeepAlive = false; request.ServicePoint.ConnectionLimit = 1000; //物件最大連線數 request.Method = "POST"; byte[] data = Encoding.UTF8.GetBytes(Param); using (Stream requestStream = request.GetRequestStream()) { using (StreamWriter swrite = new StreamWriter(requestStream)) { swrite.Write(data); } } HttpWebResponse wbResponse = (HttpWebResponse)request.GetResponse(); using (Stream responseStream = wbResponse.GetResponseStream()) { using (StreamReader sread = new StreamReader(responseStream)) { result = sread.ReadToEnd(); } } } catch (Exception ex) { Console.WriteLine("GeTuiMsgTask.HttpRequestPost post failed url={0} ex={1}", Url, ex); } return result; } private string SHA256EncryptString(string data) { byte[] bytes = Encoding.UTF8.GetBytes(data); byte[] hash = SHA256Managed.Create().ComputeHash(bytes); StringBuilder builder = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { builder.Append(hash[i].ToString("x2")); } return builder.ToString(); } 2. 傳送推送訊息:必要引數 string cid 客戶端給過來的clientid(目標使用者) string requestId 請求唯一標識號,10-32位之間;如果request_id重複,會導致訊息丟失 string title, 推送訊息標題 string content 推送內容

pushUrl = "https://restapi.getui.com/v2/" + appId + "/push/single/cid"; 推送url
    
private void SendMsgNotification(object o) { MsgTaskItem item = (MsgTaskItem)o; string postParam = "{\"request_id\":\"" + item.RequestId + "\",\"audience\":{\"cid\":[\"" + item.Cid + "\"]}," + "\"push_message\":{\"notification\":{\"title\":\"" + item.Title + "\",\"body\":\"" + item.Content + "\",\"click_type\":\"none\",\"url\":\"\"}}}"; string result = HttpRequestPost(pushUrl, postParam); //返回結果成功也是json格式字串 } 更具體的檢視官方文件:https://docs.getui.com/getui/server/rest_v2/push/
線上http介面測試網站:https://www.sojson.com/http/test.html