WeChatHelper.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. using log4net;
  2. using Newtonsoft.Json;
  3. using Newtonsoft.Json.Linq;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Http;
  9. using System.Net.Http.Headers;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. using System.Xml.Linq;
  13. namespace Ropin.Inspection.Common.Helper
  14. {
  15. public class WeChatHelper
  16. {
  17. private readonly IHttpClientFactory _httpClientFactory;
  18. private static readonly ILog log = LogManager.GetLogger(typeof(WeChatHelper));
  19. public WeChatHelper(IHttpClientFactory httpClientFactory)
  20. {
  21. _httpClientFactory = httpClientFactory;
  22. }
  23. public async Task<string> GetToken()
  24. {
  25. string token = null;
  26. string url = string.Format(WXConstModel.WeChatTokenUrlTemplate, WXConstModel.GZHAppId, WXConstModel.GZHSecret);
  27. using (var client = _httpClientFactory.CreateClient())
  28. {
  29. var request = new HttpRequestMessage(HttpMethod.Get, url);
  30. request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  31. try
  32. {
  33. var response = await client.SendAsync(request);
  34. response.EnsureSuccessStatusCode(); // 确保响应状态码为成功
  35. if (response.IsSuccessStatusCode)
  36. {
  37. var strReturn = await response.Content.ReadAsStringAsync();
  38. TencentAccessToken tencentToken = JsonConvert.DeserializeObject<TencentAccessToken>(strReturn);
  39. if (tencentToken != null && !string.IsNullOrEmpty(tencentToken.access_token))
  40. {
  41. token = tencentToken.access_token;
  42. }
  43. }
  44. }
  45. catch (HttpRequestException ex)
  46. {
  47. log.Info($"微信获取token异常【{ex.Message}】");
  48. }
  49. catch (JsonException ex)
  50. {
  51. log.Info($"解析微信Token响应异常【{ex.Message}】");
  52. }
  53. catch (Exception ex)
  54. {
  55. log.Info($"获取微信Token时发生未知异常【{ex.Message}】");
  56. }
  57. }
  58. return token;
  59. }
  60. /// <summary>
  61. /// 推送消息-小程序
  62. /// </summary>
  63. /// <returns></returns>
  64. public async void PushMessageToUser(List<string> openIds, object msg, string templateId = null)
  65. {
  66. try
  67. {
  68. string url = string.Format(WXConstModel.WeChatTokenUrlTemplate, WXConstModel.XCXAppId, WXConstModel.XCXSecret);
  69. using (var client = _httpClientFactory.CreateClient())
  70. {
  71. var requestt = new HttpRequestMessage(HttpMethod.Get, url);
  72. requestt.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  73. var response = await client.SendAsync(requestt);
  74. if (response.IsSuccessStatusCode)
  75. {
  76. var strReturn = await response.Content.ReadAsStringAsync();
  77. TencentAccessToken tencentToken = JsonConvert.DeserializeObject<TencentAccessToken>(strReturn);
  78. if (tencentToken != null && tencentToken.access_token != null)
  79. {
  80. if (openIds.Any())
  81. {
  82. foreach (var id in openIds)
  83. {
  84. await SubscribeMessageToUser(id, tencentToken.access_token, null, msg, templateId);
  85. }
  86. }
  87. }
  88. else
  89. {
  90. }
  91. }
  92. }
  93. }
  94. catch (Exception ex)
  95. {
  96. log.Info($"微信推送消息结果异常【用戶openid={openIds},msg={msg},templateId={templateId}】");
  97. }
  98. }
  99. /// <summary>
  100. /// 小程序
  101. /// </summary>
  102. /// <param name="openid"></param>
  103. /// <param name="accessToken"></param>
  104. /// <param name="title"></param>
  105. /// <param name="content"></param>
  106. /// <param name="templateId"></param>
  107. /// <returns></returns>
  108. public async Task<string> SubscribeMessageToUser(string openid, string accessToken, string title = null, object content = null, string templateId = null)
  109. {
  110. string strReturn = string.Empty;
  111. try
  112. {
  113. string _url = string.Format("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={0}", accessToken);
  114. //json参数
  115. string postData = Newtonsoft.Json.JsonConvert.SerializeObject(new
  116. {
  117. touser = openid,//用戶openid
  118. template_id = templateId ?? WXConstModel.TemplateId,
  119. page = WXConstModel.XCXLoginPage,
  120. data = content
  121. });
  122. using (var client = _httpClientFactory.CreateClient())
  123. {
  124. var requestt = new HttpRequestMessage(HttpMethod.Post, _url);
  125. requestt.Content = new StringContent(postData);
  126. requestt.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  127. var response = await client.SendAsync(requestt);
  128. if (response.IsSuccessStatusCode)
  129. {
  130. Console.WriteLine(response.IsSuccessStatusCode);
  131. strReturn = await response.Content.ReadAsStringAsync();
  132. log.Info($"微信发送消息结果返回【用戶openid={openid},strReturn={strReturn}】");
  133. }
  134. }
  135. }
  136. catch (Exception ex)
  137. {
  138. log.Info($"微信发送消息结果异常【用戶openid={openid},ex={ex.Message}】");
  139. }
  140. return strReturn;
  141. }
  142. /// <summary>
  143. /// 小程序-发送消息
  144. /// </summary>
  145. /// <param name="openid"></param>
  146. /// <param name="accessToken"></param>
  147. /// <param name="title"></param>
  148. /// <param name="content"></param>
  149. /// <returns></returns>
  150. public string SubMessageToUser(string openid, string accessToken, string title = null, object content = null)
  151. {
  152. string strReturn = string.Empty;
  153. try
  154. {
  155. string _url = string.Format("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={0}", accessToken);
  156. //json参数
  157. string postData = Newtonsoft.Json.JsonConvert.SerializeObject(new
  158. {
  159. touser = openid,//用戶openid
  160. template_id = WXConstModel.TemplateId,
  161. page = WXConstModel.XCXLoginPage,
  162. data = content
  163. });
  164. using (var client = _httpClientFactory.CreateClient())
  165. {
  166. var requestt = new HttpRequestMessage(HttpMethod.Post, _url);
  167. requestt.Content = new StringContent(postData);
  168. requestt.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  169. var response = client.Send(requestt);
  170. if (response.IsSuccessStatusCode)
  171. {
  172. Console.WriteLine(response.IsSuccessStatusCode);
  173. strReturn = "";
  174. }
  175. }
  176. }
  177. catch (Exception ex)
  178. {
  179. }
  180. return strReturn;
  181. }
  182. public async Task<bool> PushGZHMessageToUser(List<string> openIds, string templateId, string url, object data, string miniProgramAppId, string miniProgramPagePath)
  183. {
  184. bool result=false;
  185. string token = await GetToken();
  186. if (string.IsNullOrEmpty(token))
  187. {
  188. log.Info("获取微信Token失败,无法发送模板消息");
  189. }
  190. else
  191. {
  192. if (openIds.Any())
  193. {
  194. foreach (var id in openIds)
  195. {
  196. bool bol= await SendTemplateMessageAsync(id, templateId, url, data, miniProgramAppId, miniProgramPagePath,token);
  197. if (bol)
  198. {
  199. result = true;
  200. }
  201. else
  202. {
  203. log.Info($"PushGZHMessageToUser【{id}】发送消息失败");
  204. }
  205. }
  206. }
  207. }
  208. return result;
  209. }
  210. /// <summary>
  211. /// 推送微信订阅消息
  212. /// </summary>
  213. /// <param name="openId">接收人openid</param>
  214. /// <param name="templateId">模板id</param>
  215. /// <param name="url">跳转url</param>
  216. /// <param name="data">模板数据</param>
  217. /// <param name="miniProgramAppId">小程序appid</param>
  218. /// <param name="miniProgramPagePath">跳转小程序路径</param>
  219. /// <param name="token">token</param>
  220. /// <returns></returns>
  221. public async Task<bool> SendTemplateMessageAsync(string openId, string templateId, string url, object data, string miniProgramAppId, string miniProgramPagePath,string token)
  222. {
  223. bool result=false;
  224. string messageUrl = string.Format(WXConstModel.WeChatTemplateMessageUrl, token);
  225. var message = new
  226. {
  227. touser = openId,
  228. template_id = templateId ?? WXConstModel.GZHTemplateId,
  229. url,
  230. miniprogram = new
  231. {
  232. appid = miniProgramAppId,
  233. pagepath = miniProgramPagePath
  234. },
  235. data
  236. };
  237. using (var client = _httpClientFactory.CreateClient())
  238. {
  239. var sss = JsonConvert.SerializeObject(message);
  240. var request = new HttpRequestMessage(HttpMethod.Post, messageUrl)
  241. {
  242. Content = new StringContent(JsonConvert.SerializeObject(message), System.Text.Encoding.UTF8, "application/json")
  243. };
  244. try
  245. {
  246. var response = await client.SendAsync(request);
  247. response.EnsureSuccessStatusCode(); // 确保响应状态码为成功
  248. if (response.IsSuccessStatusCode)
  249. {
  250. var strReturn = await response.Content.ReadAsStringAsync();
  251. log.Info($"发送微信模板消息返回数据【strReturn={strReturn}】");
  252. var responseMessage = JsonConvert.DeserializeObject<WXResult>(strReturn);
  253. if (responseMessage != null && responseMessage.errcode == 0)
  254. {
  255. result = true;
  256. }
  257. else
  258. {
  259. log.Info($"发送微信模板消息失败,错误码: {responseMessage?.errcode}, 错误信息: {responseMessage?.errmsg}");
  260. }
  261. }
  262. }
  263. catch (HttpRequestException ex)
  264. {
  265. log.Info($"发送微信模板消息异常【{ex.Message}】");
  266. }
  267. catch (JsonException ex)
  268. {
  269. log.Info($"解析微信模板消息响应异常【{ex.Message}】");
  270. }
  271. catch (Exception ex)
  272. {
  273. log.Info($"发送微信模板消息时发生未知异常【{ex.Message}】");
  274. }
  275. }
  276. return result;
  277. }
  278. /// <summary>
  279. /// 获取微信AccessToken
  280. /// </summary>
  281. /// <param name="code"></param>
  282. /// <returns></returns>
  283. public async Task<string> GetOpenIdByCodeAsync(string code)
  284. {
  285. string url = string.Format(WXConstModel.WeChatAccessTokenUrlTemplate, WXConstModel.GZHAppId, WXConstModel.GZHSecret, code);
  286. using (var client = _httpClientFactory.CreateClient())
  287. {
  288. var request = new HttpRequestMessage(HttpMethod.Get, url);
  289. request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  290. try
  291. {
  292. var response = await client.SendAsync(request);
  293. response.EnsureSuccessStatusCode(); // 确保响应状态码为成功
  294. var strReturn = await response.Content.ReadAsStringAsync();
  295. var accessTokenResponse = JsonConvert.DeserializeObject<WeChatAccessTokenResponse>(strReturn);
  296. if (accessTokenResponse != null && !string.IsNullOrEmpty(accessTokenResponse.openid))
  297. {
  298. return accessTokenResponse.openid;
  299. }
  300. else
  301. {
  302. throw new Exception("获取微信AccessToken失败");
  303. }
  304. }
  305. catch (HttpRequestException ex)
  306. {
  307. log.Info($"请求微信AccessToken异常【{ex.Message}】");
  308. throw new Exception("获取微信AccessToken失败");
  309. }
  310. catch (JsonException ex)
  311. {
  312. log.Info($"解析微信AccessToken响应异常【{ex.Message}】");
  313. throw new Exception("获取微信AccessToken失败");
  314. }
  315. catch (Exception ex)
  316. {
  317. log.Info($"获取微信AccessToken时发生未知异常【{ex.Message}】");
  318. throw new Exception("获取微信AccessToken失败");
  319. }
  320. }
  321. return null;
  322. }
  323. }
  324. /// <summary>
  325. /// 腾讯Token
  326. /// </summary>
  327. public class TencentAccessToken
  328. {
  329. public string access_token { get; set; }
  330. public int expires_in { get; set; }
  331. }
  332. /// <summary>
  333. /// 调用微信接口返回结果
  334. /// </summary>
  335. class WXResult
  336. {
  337. public int errcode { get; set; }
  338. public string errmsg { get; set; }
  339. }
  340. public class WeChatAccessTokenResponse
  341. {
  342. public string access_token { get; set; }
  343. public int expires_in { get; set; }
  344. public string refresh_token { get; set; }
  345. public string openid { get; set; }
  346. public string scope { get; set; }
  347. public int errcode { get; set; }
  348. public string errmsg { get; set; }
  349. }
  350. public static class WXConstModel
  351. {
  352. public const string XCXLoginPage = "pages/login/login";
  353. /// <summary>
  354. /// 手表健康告警提醒-模板ID-长期订阅模板
  355. /// </summary>
  356. public const string WatchHealthAlarm_TemplateId = "xVR2kPGC3lCaXqYlEmmlcPdgA8KFstXEC4eC8LWSz0I";
  357. /// <summary>
  358. /// 模板ID-短期期订阅模板
  359. /// </summary>
  360. public const string TemplateId = "Q4a7suW57aOxTCAo5b-X-kC4DpMvcJXWQqXNqkUeWTg";
  361. /// <summary>
  362. /// 小程序-AppId
  363. /// </summary>
  364. public const string XCXAppId = "wx40250567e9c14ae6";
  365. /// <summary>
  366. /// 小程序-Secret
  367. /// </summary>
  368. public const string XCXSecret = "8c1117595f359f4ebc60650ed27e835a";
  369. /// <summary>
  370. /// 公众号-AppId//AI:"wx5e59258499b53581";
  371. /// </summary>
  372. public const string GZHAppId = "wx0fddd2b0603913e0";
  373. /// <summary>
  374. /// 公众号-Secret// AI:"60c43e714f143b31f5528a28fbc19c9d";
  375. /// </summary>
  376. public const string GZHSecret = "4e4b16dcf7286261bb60df3fe28395f3";
  377. /// <summary>
  378. /// 公众号模板 【设备编号{character_string2.DATA};设备名称{ thing1.DATA};关闭状态{ thing3.DATA};关闭时间{time4.DATA}】
  379. /// //AI:"KfPCaPhJkUVi3em1baZu1HmsN9qRi-AbOSTo_I3GSfQ";
  380. /// </summary>
  381. public const string GZHTemplateId = "_wP22WQxAlfYGfS8zlnHTl_-KgKS8j_FP5HDeqfsPtU";
  382. /// <summary>
  383. /// 公众号模板-设备报警【设备名称;设备编号;报警内容;报警时间】
  384. /// </summary>
  385. public const string GZHDevAlarmTemplateId = "7eGjzIBAyysTOLfcn-oqkpOCEL_My5ItXHkd_DdniGw";
  386. /// <summary>
  387. /// 微信登录
  388. /// </summary>
  389. public const string WeChatTokenUrlTemplate = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
  390. /// <summary>
  391. /// 公众号模板发送url
  392. /// </summary>
  393. public const string WeChatTemplateMessageUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}";
  394. /// <summary>
  395. /// 三方登录
  396. /// </summary>
  397. public const string WeChatAccessTokenUrlTemplate = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code";
  398. }
  399. }