net core WebApi——嘗試企業微信來開發企業內部應用
- 2019 年 10 月 3 日
- 筆記
前言
這幾天忙活着別的東西,耽誤了很長時間,從文件操作完了之後就在考慮着下一步鼓搗點兒啥,因為最開始的業務開發就是企業微信相關的,這剛好來做個內部應用的小例子玩玩。
企業微信
前身是企業號,當時微信主推的還是公眾號與服務號,後續戰略考慮到企業的OA了(當然還是跟某個搶市場),企業號應該是在16年還是具體啥時候出的,剛出的時候也是問題不斷一直在修復更新,最近這兩年基本上沒咋關注企業微信了,也都是偶爾上去看看有沒有新東西啊什麼的,不過不得不說,在這幾年的成長中已經修復逐漸成為一個不錯的產品了(大廠的效率還是有的),相對於公眾號的開發,為什麼我選這個作為例子呢,因為企業微信我可以通過個人來使用(註冊的早,現在不清楚註冊流程,主要看是否需要企業認證),個人開發者在不論啥時候啥平台都或多或少有些不友好(當然,認證了說明你是個好人,為了信息安全,都懂)。
開始
註冊企業微信的流程我就不多說了,直接說註冊完成之後,我們來看下這個界面,標註的就是我們需要的關鍵參數。
記好這個東西之後,我們轉到應用管理。
這個創建就是你添張圖片打個名字而已,不多說,創建完成之後我們來看下圖的標記。
記好這兩個參數,OK,下來我們就來看API吧,這裡我只是介紹下消息推送。
微信等相關的第三方開發大致流程都類似,如下:
- 註冊賬號(這不廢話么)
- 賬號認證(為了權限,當然企業微信內部應用不需要)
- 服務域名確定好
- AppID、Secret等等的配置(為了accesstoken)
- 幾乎所有的接口都是先獲取accesstoken,相當於你在微信的登錄
- 根據接口文檔來傳參啊獲取回調啊獲取事件等等
- 根據返回值來看看錯誤信息
我這裡不做服務端,只是寫個示例,需要服務端什麼的開發之類的可以給我聯繫,互相學習。
首先,在我們的Util新建一個類QyThirdUtil(名字感覺起的好沒水平,玩遊戲止於起名字,別人都10級了,我還在想名字),先把我們需要的配置信息搞了。
private static string _CorpID = string.Empty; private static string _Secret = string.Empty; private static string _AgentID = string.Empty; /// <summary> /// 企業微信id /// </summary> public static string CorpID { get { if (string.IsNullOrEmpty(_CorpID)) { _CorpID = AprilConfig.Configuration["QyThird:CorpID"]; } return _CorpID; } } /// <summary> /// 企業微信應用秘鑰 /// </summary> public static string Secret { get { if (string.IsNullOrEmpty(_Secret)) { _Secret = AprilConfig.Configuration["QyThird:Secret"]; } return _Secret; } } /// <summary> /// 企業微信應用id /// </summary> public static string AgentID { get { if (string.IsNullOrEmpty(_Secret)) { _AgentID = AprilConfig.Configuration["QyThird:AgentID"]; } return _AgentID; } }
然後我們來劃分下方法,我們需要獲取accesstoken,需要執行發送消息的方法。
/// <summary> /// 獲取AccessToken /// </summary> /// <returns></returns> public static string GetAccessToken() { QyAccessToken accessToken = null; bool isGet = false; if (CacheUtil.Exists("QyAccessToken")) { accessToken = CacheUtil.Get<QyAccessToken>("QyAccessToken"); if (accessToken.Expire_Time >= DateTime.Now.AddMinutes(1)) { isGet = true; } } if (!isGet) { string url = $"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={CorpID}&corpsecret={Secret}"; //請求獲取 string res = RequestUtil.HttpGet(url); accessToken = JsonConvert.DeserializeObject<QyAccessToken>(res); if (accessToken != null && accessToken.ErrCode == 0) { accessToken.Expire_Time = DateTime.Now.AddSeconds(accessToken.Expires_In); CacheUtil.Set("QyAccessToken", accessToken, new TimeSpan(2, 0, 0)); } else { LogUtil.Error($"獲取accesstoken失敗——{accessToken.ErrCode},{accessToken.ErrMsg}"); } } return accessToken.Access_Token; }
這裡用到了兩個地方,一個是微信端回調的對象實例QyAccessToken,需要的朋友可以在源碼里cv,我這裡就不貼出來了。
另一個是HttpClient的簡單封裝請求方法RequestUtil,看了有些博客說HttpClient的生命周期之類的,有推薦直接實例化一個私有靜態的,也有做工廠模式創建的,沒細究,這塊兒要多注意下。
public class RequestUtil { /// <summary> /// 發起POST同步請求 /// </summary> /// <param name="url">請求地址</param> /// <param name="postData">請求數據</param> /// <param name="contentType">數據類型</param> /// <param name="timeOut">超時時間</param> /// <returns></returns> public static string HttpPost(string url, string postData = null, string contentType = null, int timeOut = 30) { if (string.IsNullOrEmpty(postData)) { postData = ""; } using (HttpClient client = new HttpClient()) { client.Timeout = new TimeSpan(0, 0, timeOut); using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8)) { if (contentType != null) httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType); HttpResponseMessage response = client.PostAsync(url, httpContent).Result; return response.Content.ReadAsStringAsync().Result; } } } /// <summary> /// 發起POST異步請求 /// </summary> /// <param name="url">請求地址</param> /// <param name="postData">請求數據</param> /// <param name="contentType">數據類型</param> /// <param name="timeOut">超時時間</param> /// <returns></returns> public static async Task<string> HttpPostAsync(string url, string postData = null, string contentType = null, int timeOut = 30) { if (string.IsNullOrEmpty(postData)) { postData = ""; } using (HttpClient client = new HttpClient()) { client.Timeout = new TimeSpan(0, 0, timeOut); using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8)) { if (contentType != null) httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType); HttpResponseMessage response = await client.PostAsync(url, httpContent); return await response.Content.ReadAsStringAsync(); } } } /// <summary> /// 發起GET同步請求 /// </summary> /// <param name="url">請求地址</param> /// <returns></returns> public static string HttpGet(string url) { using (HttpClient client = new HttpClient()) { return client.GetStringAsync(url).Result; } } /// <summary> /// 發起GET異步請求 /// </summary> /// <param name="url">請求地址</param> /// <returns></returns> public static async Task<string> HttpGetAsync(string url) { using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(url); return await response.Content.ReadAsStringAsync(); } } }
然後我們來寫個發送消息的方法SendMessage,這裡我只寫了下普通文本推送。
/// <summary> /// 消息推送 /// </summary> /// <param name="content">文本內容</param> /// <param name="range">推送範圍</param> /// <param name="messageType">消息類型</param> /// <returns></returns> public static bool SendMessage(string content, MessageRange range, AprilEnums.MessageType messageType) { bool isSend = false; if (string.IsNullOrEmpty(content) || content.Length > 2048 || range==null) { return false; } string accessToken = GetAccessToken(); if (string.IsNullOrEmpty(accessToken)) { return false; } string url = $"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={accessToken}"; StringBuilder data = new StringBuilder(); bool isVaildRange = false; if (range.IsAll) { data.Append($""touser":"@all""); isVaildRange = true; } else { if (range.Users != null && range.Users.Count > 0) { data.AppendFormat(""touser" : {0}", GetRangeValue(range.Users)); isVaildRange = true; } if (range.Tags != null && range.Tags.Count > 0) { if (data.Length > 0) { data.Append(","); } data.AppendFormat(""totag" : {0}", GetRangeValue(range.Tags)); isVaildRange = true; } if (range.Departments != null && range.Departments.Count > 0) { if (data.Length > 0) { data.Append(","); } data.AppendFormat(""totag" : {0}", GetRangeValue(range.Departments)); isVaildRange = true; } } if (!isVaildRange) { //沒有發送範圍 return false; } data.AppendFormat(","msgtype":"{0}"", GetMessageType(messageType)); data.AppendFormat(","agentid":"{0}"", AgentID); data.Append(","text": {"); data.AppendFormat(""content":"{0}"", content); data.Insert(0, "{"); data.Append("}}"); LogUtil.Debug($"獲取到發送消息請求:{data.ToString()}"); string res = RequestUtil.HttpPost(url, data.ToString(), "application/json"); LogUtil.Debug($"獲取到發送消息回調:{res}"); return false; }
簡單說下消息推送,第一個就是你的推送類型,是普通文本還是啥(文檔都有,我這凈扯淡),然後就是你的範圍,再然後就是你的推送內容了,當然根據不同的推送類型你的內容參數也不同,需要進一步封裝的朋友可以去看下API。
測試
我們在控制器中(不再說Values了)加上消息推送的測試,這裡的範圍可以在你自己的通訊錄中查看。
[HttpGet] public ActionResult<IEnumerable<string>> Get() { //… MessageRange range = new MessageRange(); range.Users = new List<string>(); range.Users.Add("10001"); QyThridUtil.SendMessage("我就是來測試", range, AprilEnums.MessageType.Text); //… }
小結
寫到這裡基本上都結束了,為什麼我特意拿出來企業微信的內部應用來寫這篇呢,其實是做下這個消息推送,以後的自己的工程就可以寫個這個然後做異常警告之類的東西,這樣想想這篇就不是廢話了,編程的奇淫技巧(咳咳,樂趣,樂趣)就在於此,代碼自己敲,東西自己組,全在於你自己怎麼玩了。