Geen omschrijving

DingTalkHelper.cs 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. 
  2. using Newtonsoft.Json;
  3. using Newtonsoft.Json.Linq;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Collections.Specialized;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Net.Http;
  11. using System.Net.Http.Headers;
  12. using System.Text;
  13. namespace CallCenter.Utility
  14. {
  15. public class DingTalkHelper
  16. {
  17. /// <summary>
  18. /// 获取AccessToken
  19. /// </summary>
  20. /// <returns></returns>
  21. public static string GetAccessToken()
  22. {
  23. var accesstoken = RedisHelper1.StringGet("DingTalkToken")?.ToString() ?? "";
  24. if (string.IsNullOrEmpty(accesstoken))
  25. {
  26. string result = HttpMethods.HttpGet(string.Format("https://oapi.dingtalk.com/gettoken?appkey={0}&appsecret={1}",
  27. Configs.GetValue("DingTalk_AppKey"), Configs.GetValue("DingTalk_AppSecret")));
  28. var resultobj = result.ToJObject();
  29. if (resultobj["errcode"].ToString() == "0")
  30. {
  31. accesstoken = resultobj["access_token"].ToString();
  32. string cachetime = Configs.GetValue("DingTalk_TokenCacheTime");
  33. RedisHelper1.StringSet("DingTalkToken", accesstoken, new TimeSpan(0, 0, int.Parse(cachetime)));
  34. }
  35. }
  36. return accesstoken;
  37. }
  38. /// <summary>
  39. /// 根据手机号获取用户id
  40. /// </summary>
  41. /// <param name="mobile">手机号</param>
  42. /// <returns></returns>
  43. public static string GetUserIdByMobile(string mobile)
  44. {
  45. string userid = string.Empty;
  46. var param = new
  47. {
  48. mobile = mobile
  49. };
  50. var strresult = HttpMethods.HttpPost(string.Format("https://oapi.dingtalk.com/topapi/v2/user/getbymobile?access_token={0}", GetAccessToken()), param.ToJson(), "application/json");
  51. if (!string.IsNullOrEmpty(strresult))
  52. {
  53. var resultobj = strresult.ToJObject();
  54. if (resultobj["errcode"].ToString() != "0")
  55. {
  56. LogFactory.GetLogger("DINGDING ").Error(strresult);
  57. //userid = resultobj["errmsg"].ToString();
  58. }
  59. else
  60. {
  61. var robj = resultobj["result"].ToString().ToJObject();
  62. userid = robj["userid"].ToString();
  63. }
  64. }
  65. return userid;
  66. }
  67. /// <summary>
  68. /// 发送模板消息
  69. /// </summary>
  70. /// <param name="userids">多个用户逗号隔开</param>
  71. /// <param name="deptids">多个部门逗号隔开</param>
  72. /// <param name="msgjson">模板参数json</param>
  73. /// <param name="templateid">模板ID</param>
  74. /// <returns></returns>
  75. public static string SendMessageByTemplate(string userids, string deptids, string msgjson, string templateid)
  76. {
  77. string result = string.Empty;
  78. var param = new
  79. {
  80. agent_id = Configs.GetValue("DingTalk_AgentId"),
  81. template_id = templateid,
  82. //data = "{\"name\":\"淘宝6\",\"name2\":\"http://www.taobao.com\"}",
  83. data = msgjson,
  84. //userid_list = "213,234,123",
  85. userid_list = userids,
  86. //dept_id_list = "421,897,262"
  87. dept_id_list = deptids
  88. };
  89. var strresult = HttpMethods.HttpPost(string.Format("https://oapi.dingtalk.com/topapi/message/corpconversation/sendbytemplate?access_token={0}", GetAccessToken()), param.ToJson(), "application/json");
  90. if (!string.IsNullOrEmpty(strresult))
  91. {
  92. var resultobj = strresult.ToJObject();
  93. if (resultobj["errcode"].ToString() != "0")
  94. {
  95. LogFactory.GetLogger("DINGDING ").Error(strresult);
  96. result = resultobj["errmsg"].ToString();
  97. }
  98. }
  99. return result;
  100. }
  101. /// <summary>
  102. /// 发送工作通知
  103. /// </summary>
  104. /// <param name="userids">多个用户逗号隔开</param>
  105. /// <param name="deptids">多个部门逗号隔开</param>
  106. /// <param name="msgjson">内容json</param>
  107. /// <param name="isall">是否全部群发</param>
  108. /// <returns></returns>
  109. public static string SendMessage(string userids, string deptids, string msgjson, bool isall = false)
  110. {
  111. string result = string.Empty;
  112. var param = new JObject();
  113. param["agent_id"] = Configs.GetValue("DingTalk_AgentId");
  114. if (!string.IsNullOrEmpty(userids))
  115. {
  116. param["userid_list"] = userids;
  117. }
  118. if (!string.IsNullOrEmpty(deptids))
  119. {
  120. param["dept_id_list"] = deptids;
  121. }
  122. param["to_all_user"] = isall;
  123. param["msg"] = msgjson.ToJObject();
  124. //var param=new
  125. //{
  126. // agent_id = ConfigHelper.GetValue("DingTalk_AgentId"),
  127. // //userid_list = "213,234,123",
  128. // userid_list = userids,
  129. // //dept_id_list = "421,897,262"
  130. // dept_id_list = deptids,
  131. // to_all_user = isall,
  132. // //msg = new {
  133. // // msgtype="text",
  134. // // text = new {content="内容" }
  135. // //},
  136. // //msg = new
  137. // //{
  138. // // msgtype = "markdown",
  139. // // markdown = new { text = "内容",title="标题" }
  140. // //},
  141. // msg
  142. //};
  143. var strresult = HttpMethods.HttpPost(string.Format("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token={0}", GetAccessToken()), param.ToJson(), "application/json");
  144. if (!string.IsNullOrEmpty(strresult))
  145. {
  146. var resultobj = strresult.ToJObject();
  147. if (resultobj["errcode"].ToString() != "0")
  148. {
  149. LogFactory.GetLogger("DINGDING ").Error(strresult);
  150. result = resultobj["errmsg"].ToString();
  151. }
  152. else
  153. {
  154. result = resultobj["task_id"].ToString();
  155. }
  156. }
  157. return result;
  158. }
  159. /// <summary>
  160. /// 发送工作通知-文本
  161. /// </summary>
  162. /// <param name="userids">多个用户逗号隔开</param>
  163. /// <param name="deptids">多个部门逗号隔开</param>
  164. /// <param name="content">文本内容</param>
  165. /// <returns></returns>
  166. public static string SendMessageText(string userids, string deptids, string content)
  167. {
  168. var msg = new
  169. {
  170. msgtype = "text",
  171. text = new { content }
  172. };
  173. string result = SendMessage(userids, deptids, msg.ToJson());
  174. return result;
  175. }
  176. /// <summary>
  177. /// 发送链接工作通知-文本
  178. /// </summary>
  179. /// <param name="userids">多个用户逗号隔开</param>
  180. /// <param name="deptids">多个部门逗号隔开</param>
  181. /// <param name="content">文本内容</param>
  182. /// <returns></returns>
  183. public static string SendUrlText(string userids, string deptids, string content, string url, string title, string pc_message_url, string picurl = "@lALPDeC286_fT0rNAePNAnM")
  184. {
  185. var msg = new
  186. {
  187. msgtype = "oa",
  188. oa = new
  189. {
  190. message_url = url,
  191. pc_message_url,
  192. head = new { bgcolor = "FFBBBBBB", text = title },
  193. body = new { title, content = content }
  194. }
  195. };
  196. string result = SendMessage(userids, deptids, msg.ToJson());
  197. return result;
  198. }
  199. /// <summary>
  200. /// 获取工作通知结果
  201. /// <returns></returns>
  202. public static int GetMessage(string task_id)
  203. {
  204. int result = 0;
  205. var param = new JObject();
  206. param["agent_id"] = Configs.GetValue("DingTalk_AgentId");
  207. if (!string.IsNullOrEmpty(task_id))
  208. {
  209. param["task_id"] = task_id;
  210. }
  211. var strresult = HttpMethods.HttpPost(string.Format("https://oapi.dingtalk.com/topapi/message/corpconversation/getsendresult?access_token={0}", GetAccessToken()), param.ToJson(), "application/json");
  212. if (!string.IsNullOrEmpty(strresult))
  213. {
  214. var resultobj = strresult.ToJObject();
  215. if (resultobj["errcode"].ToString() != "0")
  216. {
  217. LogFactory.GetLogger("DINGDING ").Error(strresult);
  218. result = 0;
  219. }
  220. else
  221. {
  222. send_result jo = JsonConvert.DeserializeObject<send_result>(resultobj["send_result"].ToString());
  223. if (jo != null)
  224. {
  225. if (jo.read_user_id_list != null && jo.read_user_id_list.Count > 0)
  226. result = 1;
  227. else if (jo.unread_user_id_list != null && jo.unread_user_id_list.Count > 0)
  228. result = 2;
  229. }
  230. }
  231. }
  232. return result;
  233. }
  234. /// <summary>
  235. /// 通过免登码获取用户信息
  236. /// <returns></returns>
  237. public static string GetUserInfo(string code)
  238. {
  239. string result = "";
  240. var param = new JObject();
  241. if (!string.IsNullOrEmpty(code))
  242. {
  243. param["code"] = code;
  244. }
  245. var strresult = HttpMethods.HttpPost(string.Format("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo?access_token={0}", GetAccessToken()), param.ToJson(), "application/json");
  246. if (!string.IsNullOrEmpty(strresult))
  247. {
  248. JObject jo = (JObject)JsonConvert.DeserializeObject(strresult);
  249. if (jo["errcode"].ToString() != "0")
  250. {
  251. LogFactory.GetLogger("DINGDING ").Error(strresult);
  252. result = "err";
  253. }
  254. else
  255. {
  256. var message = jo["result"].ToString();
  257. var messages = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(message);
  258. result = messages["userid"].ToString();
  259. }
  260. }
  261. return result;
  262. }
  263. /// <summary>
  264. /// 上传附件
  265. /// <returns></returns>
  266. public static string Upload(string media)
  267. {
  268. string result = "";
  269. using (var client = new HttpClient())
  270. {
  271. using (var content = new MultipartFormDataContent())
  272. {
  273. NameValueCollection fileCollection = new NameValueCollection();
  274. fileCollection.Add("media", media);
  275. //处理文件内容
  276. string[] fileKeys = fileCollection.AllKeys;
  277. foreach (string key in fileKeys)
  278. {
  279. byte[] bmpBytes = File.ReadAllBytes(fileCollection[key]);
  280. var fileContent = new ByteArrayContent(bmpBytes);//填充文件字节
  281. fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
  282. {
  283. Name = key,
  284. FileName = Path.GetFileName(fileCollection[key])
  285. };
  286. content.Add(fileContent);
  287. }
  288. var Postresult = client.PostAsync(string.Format("https://oapi.dingtalk.com/media/upload?access_token={0}&type=image", GetAccessToken()), content).Result;//post请求
  289. string strresult = Postresult.Content.ReadAsStringAsync().Result;
  290. if (!string.IsNullOrEmpty(strresult))
  291. {
  292. JObject jo = (JObject)JsonConvert.DeserializeObject(strresult);
  293. if (jo["errcode"].ToString() != "0")
  294. {
  295. LogFactory.GetLogger("DINGDING ").Error(strresult);
  296. result = "err";
  297. }
  298. else
  299. {
  300. result = jo["media_id"].ToString();
  301. }
  302. }
  303. }
  304. }
  305. return result;
  306. }
  307. /// <summary>
  308. /// 查询用户详情
  309. /// <returns></returns>
  310. public static string GetUser(string userid)
  311. {
  312. string result = "";
  313. var param = new JObject();
  314. if (!string.IsNullOrEmpty(userid))
  315. {
  316. param["userid"] = userid;
  317. param["language"] = "zh_CN";
  318. }
  319. var strresult = HttpMethods.HttpPost(string.Format("https://oapi.dingtalk.com/topapi/v2/user/get?access_token={0}", GetAccessToken()), param.ToJson(), "application/json");
  320. if (!string.IsNullOrEmpty(strresult))
  321. {
  322. JObject jo = (JObject)JsonConvert.DeserializeObject(strresult);
  323. if (jo["errcode"].ToString() != "0")
  324. {
  325. LogFactory.GetLogger("DINGDING ").Error(strresult);
  326. result = "err";
  327. }
  328. else
  329. {
  330. var message = jo["result"].ToString();
  331. var messages = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(message);
  332. result = messages["mobile"].ToString();
  333. }
  334. }
  335. return result;
  336. }
  337. public class send_result
  338. {
  339. public List<string> read_user_id_list { set; get; }
  340. public List<string> unread_user_id_list { set; get; }
  341. }
  342. /// <summary>
  343. ///
  344. /// </summary>
  345. /// <param name="userid"></param>
  346. /// <returns></returns>
  347. public static string GetUserInfoByUserId(string userid)
  348. {
  349. //WebClient web = new WebClient();
  350. //web.Encoding = Encoding.UTF8;
  351. //string strresult = web.DownloadString(string.Format("https://oapi.dingtalk.com/user/get?access_token={0}&userid={1}", GetAccessToken(), userid));
  352. //JObject jo = (JObject)JsonConvert.DeserializeObject(strresult);
  353. //return jo.ToJson();
  354. string url = string.Format("https://oapi.dingtalk.com/user/get?access_token={0}&userid={1}", GetAccessToken(), userid);
  355. var strresult = HttpMethods.HttpGet(url);
  356. return strresult;
  357. }
  358. //给某个部门的所有的人发消息
  359. /// <summary>
  360. /// 获取部门列表 参数传1 是根节点的子部门
  361. /// https://open.dingtalk.com/document/orgapp-server/obtain-the-department-list-v2
  362. /// </summary>
  363. /// <returns></returns>
  364. public static string GetDeptlist()
  365. {
  366. WebClient web = new WebClient();
  367. web.Encoding = Encoding.UTF8;
  368. string strresult = web.DownloadString(string.Format("https://oapi.dingtalk.com/topapi/v2/department/listsub?access_token={0}&dept_id={1}", GetAccessToken(), 1));
  369. JObject jo = (JObject)JsonConvert.DeserializeObject(strresult);
  370. return jo.ToJson();
  371. }
  372. /// <summary>
  373. /// 获取部门所有的userid
  374. /// </summary>
  375. /// <param name="deptid">Get https://oapi.dingtalk.com/user/getDeptMember </param>
  376. /// <returns></returns>
  377. public static string GetUserIdsByDeptId(double deptid)
  378. {
  379. WebClient web = new WebClient();
  380. web.Encoding = Encoding.UTF8;
  381. string strresult = web.DownloadString(string.Format("https://oapi.dingtalk.com/user/getDeptMember?access_token={0}&deptId={1}", GetAccessToken(), deptid));
  382. JObject jo = (JObject)JsonConvert.DeserializeObject(strresult);
  383. if (jo != null && jo["userIds"] != null)
  384. {
  385. return jo["userIds"].ToString();
  386. }
  387. //JsonConvert.SerializeObject();
  388. //TreeModel model= JsonConvert.DeserializeObject<TreeModel>(strresult);
  389. return "";
  390. }
  391. }
  392. }