IDingDingService.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. using DingTalk.Api;
  2. using DingTalk.Api.Request;
  3. using DingTalk.Api.Response;
  4. using Microsoft.Extensions.Caching.Distributed;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using XYY.Data.Standard;
  11. using XYY.Service.Standard.DingDing.Dto;
  12. using static DingTalk.Api.Response.OapiV2UserGetResponse;
  13. namespace XYY.Service.Standard.DingDing
  14. {
  15. public interface IDingDingService
  16. {
  17. Task<long> GetDingDingUserDepIdAsUserId(string userId);
  18. Task<string> GetDingDingUserIdAsPhone(string phone);
  19. Task<DingDingUserInfo> GetDingDingUserInfo(int xyyUserId);
  20. Task<string> GetTokenAsCache();
  21. Task<string> SendMessage(string userId, dynamic root);
  22. /// <summary>
  23. /// 根据钉钉Id获取用户信息
  24. /// </summary>
  25. /// <param name="uid"></param>
  26. /// <returns></returns>
  27. Task<UserGetResponseDomain> GetUserInfo(string uid);
  28. }
  29. public class DingDingService : IDingDingService
  30. {
  31. private const string UserCacheKey = "UserKey";
  32. private const string DingDingTokenCacheKey = "DingDingToken";
  33. IDistributedCache _cache;
  34. IUserInfoRepository _userInfoRepository;
  35. public DingDingService(IDistributedCache cache, IUserInfoRepository userInfoRepository)
  36. {
  37. _cache = cache;
  38. _userInfoRepository = userInfoRepository;
  39. }
  40. public async Task<long> GetDingDingUserDepIdAsUserId(string userId)
  41. {
  42. string token = await GetTokenAsCache();
  43. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
  44. OapiV2UserGetRequest req = new OapiV2UserGetRequest();
  45. req.Userid = userId;
  46. OapiV2UserGetResponse rsp = client.Execute(req, token);
  47. return rsp.Result.DeptIdList[0];
  48. }
  49. public async Task<string> GetDingDingUserIdAsPhone(string phone)
  50. {
  51. string token = await GetTokenAsCache();
  52. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
  53. OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
  54. req.Mobile = phone;
  55. OapiV2UserGetbymobileResponse rsp = client.Execute(req, token);
  56. if (rsp.IsError || !string.IsNullOrWhiteSpace(rsp.ErrMsg) || (!string.IsNullOrWhiteSpace(rsp.Errmsg)&&rsp.Errmsg!="ok"))
  57. {
  58. string msg = rsp.Errmsg;
  59. if(string.IsNullOrWhiteSpace(msg))
  60. {
  61. msg = rsp.ErrMsg;
  62. }
  63. throw new Exception("获取钉钉用户信息失败:" + msg + $"({phone})");
  64. }
  65. return rsp.Result.Userid;
  66. }
  67. /// <summary>
  68. /// 获取钉钉,缓存过期时间为两小时
  69. /// </summary>
  70. /// <returns></returns>
  71. public async Task<string> GetTokenAsCache()
  72. {
  73. string token = await _cache.GetStringAsync(DingDingTokenCacheKey);
  74. if (string.IsNullOrEmpty(token))
  75. {
  76. token = GetToken();
  77. await _cache.SetAsync(DingDingTokenCacheKey, Encoding.UTF8.GetBytes(token), new DistributedCacheEntryOptions
  78. {
  79. AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(2)
  80. });
  81. }
  82. return token;
  83. //return await Task.Run(() => { return "385ca6aea2a931f28f35ff34b1431469"; });
  84. }
  85. private static string GetToken()
  86. {
  87. IDingTalkClient tokenClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  88. OapiGettokenRequest oapiGettokenRequest = new OapiGettokenRequest();
  89. oapiGettokenRequest.Appkey = "dingxucfxjsjiuzhlcg8";
  90. oapiGettokenRequest.SetHttpMethod("get");
  91. oapiGettokenRequest.Appsecret = "g5D4S6OEsGklJSED3-F7i4_BaAr3Wy0Z-rC41FV1d-8doF-9JwCgh5DaR4Mz68qf";
  92. OapiGettokenResponse rsp = tokenClient.Execute(oapiGettokenRequest);
  93. TokenResult tokenResult = Newtonsoft.Json.JsonConvert.DeserializeObject<TokenResult>(rsp.Body);
  94. string token;
  95. if (tokenResult.errmsg != "ok")
  96. throw new Exception("获取授权失败");
  97. else
  98. token = tokenResult.access_token;
  99. return token;
  100. }
  101. /// <summary>
  102. /// 根据钉钉Id获取用户信息
  103. /// </summary>
  104. /// <param name="uid"></param>
  105. /// <returns></returns>
  106. public async Task<UserGetResponseDomain> GetUserInfo(string uid)
  107. {
  108. string token = await GetTokenAsCache();
  109. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
  110. OapiV2UserGetRequest req = new OapiV2UserGetRequest();
  111. req.Userid = uid;
  112. OapiV2UserGetResponse rsp = client.Execute(req, token);
  113. return rsp.Result;
  114. }
  115. public async Task<string> SendMessage(string userId, dynamic root)
  116. {
  117. string token = await GetTokenAsCache();
  118. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
  119. OapiMessageCorpconversationAsyncsendV2Request messageCorpconversationAsyncsendV2Request = new OapiMessageCorpconversationAsyncsendV2Request();
  120. messageCorpconversationAsyncsendV2Request.AgentId = 1362321125L;
  121. messageCorpconversationAsyncsendV2Request.UseridList = userId;
  122. messageCorpconversationAsyncsendV2Request.Msg = Newtonsoft.Json.JsonConvert.SerializeObject(root);
  123. var response = client.Execute(messageCorpconversationAsyncsendV2Request, token);
  124. return response.Errmsg;
  125. }
  126. /// <summary>
  127. /// 通过缓存查找钉钉用户信息
  128. /// </summary>
  129. /// <param name="xyyUserId">系统用户Id</param>
  130. /// <returns></returns>
  131. public async Task<DingDingUserInfo> GetDingDingUserInfo(int xyyUserId)
  132. {
  133. var key = UserCacheKey + "#" + xyyUserId;
  134. var userStr = await _cache.GetStringAsync(key);
  135. if (string.IsNullOrEmpty(userStr))
  136. {
  137. var info = await _userInfoRepository.GetAsync(xyyUserId);
  138. if (info == null)
  139. throw new Exception("找不到当前用户的行运易帐户信息");
  140. if (string.IsNullOrEmpty(info.Phone))
  141. throw new Exception("当前用户未设置电话信息");
  142. //钉钉获取用户Id
  143. if (string.IsNullOrWhiteSpace(info.Phone))
  144. return null;
  145. string ddUserId = await GetDingDingUserIdAsPhone(info.Phone);
  146. long ddDepId = await GetDingDingUserDepIdAsUserId(ddUserId);
  147. var user = new DingDingUserInfo
  148. {
  149. UserId = ddUserId,
  150. DepId = ddDepId
  151. };
  152. userStr = Newtonsoft.Json.JsonConvert.SerializeObject(user);
  153. await _cache.SetStringAsync(key, userStr);
  154. }
  155. return Newtonsoft.Json.JsonConvert.DeserializeObject<DingDingUserInfo>(userStr);
  156. }
  157. }
  158. }