WeChatHelper.cs 17 KB

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