目錄
* 前言 <https://www.cnblogs.com/AprilBlank/p/11447390.html#前言>
* 企業(yè)微信 <https://www.cnblogs.com/AprilBlank/p/11447390.html#企業(yè)微信>
* 開始 <https://www.cnblogs.com/AprilBlank/p/11447390.html#開始>
* 測試 <https://www.cnblogs.com/AprilBlank/p/11447390.html#測試>
* 小結(jié) <https://www.cnblogs.com/AprilBlank/p/11447390.html#小結(jié)>
@
前言
這幾天忙活著別的東西,耽誤了很長時間,從文件操作完了之后就在考慮著下一步鼓搗點兒啥,因為最開始的業(yè)務(wù)開發(fā)就是企業(yè)微信相關(guān)的,這剛好來做個內(nèi)部應(yīng)用的小例子玩玩。
企業(yè)微信
前身是企業(yè)號,當時微信主推的還是公眾號與服務(wù)號,后續(xù)戰(zhàn)略考慮到企業(yè)的OA了(當然還是跟某個搶市場),企業(yè)號應(yīng)該是在16年還是具體啥時候出的,剛出的時候也是問題不斷一直在修復(fù)更新,最近這兩年基本上沒咋關(guān)注企業(yè)微信了,也都是偶爾上去看看有沒有新東西啊什么的,不過不得不說,在這幾年的成長中已經(jīng)修復(fù)逐漸成為一個不錯的產(chǎn)品了(大廠的效率還是有的),相對于公眾號的開發(fā),為什么我選這個作為例子呢,因為企業(yè)微信我可以通過個人來使用(注冊的早,現(xiàn)在不清楚注冊流程,主要看是否需要企業(yè)認證),個人開發(fā)者在不論啥時候啥平臺都或多或少有些不友好(當然,認證了說明你是個好人,為了信息安全,都懂)。
開始
注冊企業(yè)微信的流程我就不多說了,直接說注冊完成之后,我們來看下這個界面,標注的就是我們需要的關(guān)鍵參數(shù)。
記好這個東西之后,我們轉(zhuǎn)到應(yīng)用管理。
這個創(chuàng)建就是你添張圖片打個名字而已,不多說,創(chuàng)建完成之后我們來看下圖的標記。
記好這兩個參數(shù),OK,下來我們就來看API <https://work.weixin.qq.com/api/doc#90000/90003/90487>
吧,這里我只是介紹下消息推送。
微信等相關(guān)的第三方開發(fā)大致流程都類似,如下:
* 注冊賬號(這不廢話么)
* 賬號認證(為了權(quán)限,當然企業(yè)微信內(nèi)部應(yīng)用不需要)
* 服務(wù)域名確定好
* AppID、Secret等等的配置(為了accesstoken)
* 幾乎所有的接口都是先獲取accesstoken,相當于你在微信的登錄
* 根據(jù)接口文檔來傳參啊獲取回調(diào)啊獲取事件等等
* 根據(jù)返回值來看看錯誤信息
我這里不做服務(wù)端,只是寫個示例,需要服務(wù)端什么的開發(fā)之類的可以給我聯(lián)系,互相學(xué)習(xí)。
首先,在我們的Util新建一個類QyThirdUtil(名字感覺起的好沒水平,玩游戲止于起名字,別人都10級了,我還在想名字),先把我們需要的配置信息搞了。
private static string _CorpID = string.Empty; private static string _Secret =
string.Empty; private static string _AgentID = string.Empty; /// <summary> ///
企業(yè)微信id /// </summary> public static string CorpID { get { if
(string.IsNullOrEmpty(_CorpID)) { _CorpID =
AprilConfig.Configuration["QyThird:CorpID"]; } return _CorpID; } } ///
<summary> /// 企業(yè)微信應(yīng)用秘鑰 /// </summary> public static string Secret { get { if
(string.IsNullOrEmpty(_Secret)) { _Secret =
AprilConfig.Configuration["QyThird:Secret"]; } return _Secret; } } ///
<summary> /// 企業(yè)微信應(yīng)用id /// </summary> public static string AgentID { get { if
(string.IsNullOrEmpty(_Secret)) { _AgentID =
AprilConfig.Configuration["QyThird:AgentID"]; } return _AgentID; } }
然后我們來劃分下方法,我們需要獲取accesstoken,需要執(zhí)行發(fā)送消息的方法。
/// <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; }
這里用到了兩個地方,一個是微信端回調(diào)的對象實例QyAccessToken,需要的朋友可以在源碼里cv,我這里就不貼出來了。
另一個是HttpClient的簡單封裝請求方法RequestUtil
,看了有些博客說HttpClient的生命周期之類的,有推薦直接實例化一個私有靜態(tài)的,也有做工廠模式創(chuàng)建的,沒細究,這塊兒要多注意下。
public class RequestUtil { /// <summary> /// 發(fā)起POST同步請求 /// </summary> ///
<param name="url">請求地址</param> /// <param name="postData">請求數(shù)據(jù)</param> ///
<param name="contentType">數(shù)據(jù)類型</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> /// 發(fā)起POST異步請求
/// </summary> /// <param name="url">請求地址</param> /// <param
name="postData">請求數(shù)據(jù)</param> /// <param name="contentType">數(shù)據(jù)類型</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> /// 發(fā)起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> ///
發(fā)起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();
} } }
然后我們來寫個發(fā)送消息的方法SendMessage,這里我只寫了下普通文本推送。
/// <summary> /// 消息推送 /// </summary> /// <param name="content">文本內(nèi)容</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) { //沒有發(fā)送范圍 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($"獲取到發(fā)送消息請求:{data.ToString()}"); string res =
RequestUtil.HttpPost(url, data.ToString(), "application/json");
LogUtil.Debug($"獲取到發(fā)送消息回調(diào):{res}"); return false; }
簡單說下消息推送,第一個就是你的推送類型,是普通文本還是啥(文檔都有,我這凈扯淡),然后就是你的范圍,再然后就是你的推送內(nèi)容了,當然根據(jù)不同的推送類型你的內(nèi)容參數(shù)也不同,需要進一步封裝的朋友可以去看下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); //… }
小結(jié)
寫到這里基本上都結(jié)束了,為什么我特意拿出來企業(yè)微信的內(nèi)部應(yīng)用來寫這篇呢,其實是做下這個消息推送,以后的自己的工程就可以寫個這個然后做異常警告之類的東西,這樣想想這篇就不是廢話了,編程的奇淫技巧(咳咳,樂趣,樂趣)就在于此,代碼自己敲,東西自己組,全在于你自己怎么玩了。
熱門工具 換一換