using com.sun.org.apache.bcel.@internal.generic; using com.sun.xml.@internal.xsom; using Elight.Utility; using Elight.Utility.Code; using Elight.Utility.Extensions; using java.lang.annotation; using Microsoft.IdentityModel.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Runtime.Caching; using static java.security.cert.CertPathValidatorException; namespace _24Hour { public class WechatMessagerClient { private readonly HttpClient httpCliet; // 实例化MemoryCache对象 MemoryCache cache = MemoryCache.Default; private readonly IConfiguration _configuration; /// /// 小程序AppID /// private string appid = "wx48108a0c98a3dab0"; /// /// 小程序AppID /// private string secret = "wx48108a0c98a3dab0"; /// /// 微信公众号AppID /// private string Gzhappid = "wx48108a0c98a3dab0"; /// /// 微信公众号密码 /// private string Gzhsecret = "wx48108a0c98a3dab0"; /// /// 微信公众号模板Id /// private string GzhtemplateId = "wx48108a0c98a3dab0"; /// /// 小程序secretID /// private string secid = "e752e4fba67526eca21313a18c96a58f"; private string TemplateIdSuccess { get; set; } = ""; private string TemplateIdFail { get; set; } = ""; private readonly ILogger logger; public WechatMessagerClient(HttpClient _httpCliet, IConfiguration configuration, ILogger _logger) { this.httpCliet = _httpCliet; this.logger = _logger; httpCliet.DefaultRequestHeaders.Add("Accept", "application/json"); httpCliet.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample"); httpCliet.DefaultRequestHeaders.ConnectionClose = true; _configuration = configuration; appid = $"{configuration.GetSection("Wechat:appid").Value}"; secret = $"{configuration.GetSection("Wechat:secret").Value}"; secid = $"{configuration.GetSection("Wechat:secid").Value}"; Gzhappid = $"{configuration.GetSection("WechatGzh:appid").Value}"; Gzhsecret = $"{configuration.GetSection("WechatGzh:secret").Value}"; GzhtemplateId = $"{configuration.GetSection("WechatGzh:templateId").Value}"; TemplateIdSuccess = $"{configuration.GetSection("Wechat:templateIdSuccess").Value}"; TemplateIdFail = $"{configuration.GetSection("Wechat:templateIdFail").Value}"; } //小程序获取openId public async Task GetOpenId(string code) { var ret = new Result(); var reponse = await httpCliet.GetAsync($"/sns/jscode2session?appid={appid}&secret={secid}&js_code={code}&grant_type=authorization_code"); var opendata = await reponse.EnsureSuccessStatusCode().Content.ReadAsStringAsync(); var data = JsonConvert.DeserializeAnonymousType(opendata, new { openid = default(string), session_key = default(string), unionid = default(string), errcode = default(int), errmsg = default(string), }); if (data.errcode == 0) { ret.IsSucceed = true; ret.result = data.openid; } else { ret.IsSucceed = false; ret.Message = data.errmsg; } return ret; } /// /// 微信公众号获取openId /// /// /// public async Task GetGzhOpenId(string code) { var ret = new Result(); var reponse = HttpHelper.Get($" https://api.weixin.qq.com/sns/oauth2/access_token?appid={Gzhappid}&secret={Gzhsecret}&code={code}&grant_type=authorization_code"); var opendata = reponse; var data = JsonConvert.DeserializeAnonymousType(opendata, new { openid = default(string), session_key = default(string), unionid = default(string), errcode = default(int), errmsg = default(string), }); if (data.errcode == 0) { ret.IsSucceed = true; ret.result = data.openid; } else { ret.IsSucceed = false; ret.Message = data.errmsg; } return ret; } /// /// 律师预约微信消息提醒,成功 /// /// public bool wxts(string? useropenId, string? name, string? unit, DateTime? datetime, string? matter, string? attention) { try { var token = ""; // 获取缓存 token = cache.Get("token")?.ToString(); if (string.IsNullOrEmpty(token)) { string geturl = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}"; var re1 = HttpHelper.Get(geturl); if (re1.Jsonstr("errcode") == null) { token = re1.Jsonstr("access_token"); // 移除缓存 cache.Remove("token"); // 添加缓存 cache.Add("token", token, new CacheItemPolicy { AbsoluteExpiration = DateTime.Now.AddMinutes(120) }); } } string url = $"https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=";//发送地址 try { object msg = null; string posturl = $"{url}{token}";//发送地址 var thing4 = matter; var thing5 = attention; if (!string.IsNullOrEmpty(matter) && matter.Length > 20) thing4 = matter.Substring(0, 17) + "..."; if (!string.IsNullOrEmpty(attention) && attention.Length > 20) thing5 = attention.Substring(0, 17) + "..."; msg = new { touser = useropenId, //兼容北关区模板id,那边的配置文件没有模板id的字段 template_id = string.IsNullOrEmpty(TemplateIdSuccess) ? "XgrMTq1gwDfMJI6vN0jsSEv3xGy7v3amh0JMWj4SnAY" : TemplateIdSuccess, page = "pages/selfService/reception/reception", miniprogram_state = $"{_configuration.GetSection("Wechat:miniprogram_state").Value}", lang = "zh_CN", data = new { //name1 = new { value = $"{name}"},// thing2 = new { value = $"{unit}" },// date3 = new { value = $"{datetime:yyyy年MM月dd日 HH:mm}" },// thing4 = new { value = $"{thing4}" },// thing5 = new { value = $"{thing5}", color = "#173177" },// }, }; logger.LogInformation($"发送审核成功通知 参数{msg.ConvertToJsonStr()} url {url}"); var re = HttpHelper.Post(posturl, msg); logger.LogInformation($"发送审核成功通知 结果:{re}"); if (re.Jsonstr("errcode") == "0") return true; return false; } catch (Exception ex) { } return true; } catch (Exception ex) { } return false; } /// /// 律师预约微信消息提醒,失败 /// /// public bool sbwxts(string? useropenId, string? name, string? unit, DateTime? datetime, string? matter, string? reason) { try { var token = ""; // 获取缓存 var tokenss = cache.Get("token"); if (string.IsNullOrEmpty(token)) { string geturl = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}"; var re1 = HttpHelper.Get(geturl); if (re1.Jsonstr("errcode") == null) { token = re1.Jsonstr("access_token"); // 移除缓存 cache.Remove("token"); // 添加缓存 cache.Add("token", token, new CacheItemPolicy { AbsoluteExpiration = DateTime.Now.AddMinutes(120) }); } } string url = $"https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=";//发送地址 try { object msg = null; string posturl = $"{url}{token}";//发送地址 var thing4 = matter; if (!string.IsNullOrEmpty(matter) && matter.Length > 20) thing4 = matter.Substring(0, 17) + "..."; var thing5 = reason; if (!string.IsNullOrEmpty(reason) && reason.Length > 20) thing5 = reason.Substring(0, 17) + "..."; msg = new { touser = useropenId, //兼容北关区模板id,那边的配置文件没有模板id的字段 template_id = string.IsNullOrEmpty(TemplateIdFail) ? "bfA-t5EN4pkQzAOS17SRPRKvmMteaJt0kw3YKIcovIQ" : TemplateIdFail, page = "pages/selfService/reception/reception", miniprogram_state = $"{_configuration.GetSection("Wechat:miniprogram_state").Value}", lang = "zh_CN", data = new { //thing1 = new { value = $"{name}" },//访问人 thing2 = new { value = $"{unit}" },//访问单位 time3 = new { value = $"{datetime:yyyy年MM月dd日 HH:mm}" },//预约时间 thing4 = new { value = $"{thing4}" },//事由 thing5 = new { value = $"{thing5}" },//事由 }, }; logger.LogInformation($"发送审核成功通知 参数{msg.ConvertToJsonStr()} url {url}"); var re = HttpHelper.Post(posturl, msg); logger.LogInformation($"发送审核通知 结果:{re}"); if (re.Jsonstr("errcode") == "0") return true; return false; } catch (Exception ex) { } return true; } catch (Exception ex) { } return false; } /// /// 微信公众号消息提醒,推送检察官 /// /// public string gzhwxts(string? useropenId, string? name,string? phone, string? matter, string? attention) { try { var token = ""; // 获取缓存 token = cache.Get("gzhtoken")?.ToString(); if (string.IsNullOrEmpty(token)) { string geturl = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={Gzhappid}&secret={Gzhsecret}"; var re1 = HttpHelper.Get(geturl); if (re1.Jsonstr("errcode") == null) { token = re1.Jsonstr("access_token"); // 移除缓存 cache.Remove("gzhtoken"); // 添加缓存 cache.Add("gzhtoken", token, new CacheItemPolicy { AbsoluteExpiration = DateTime.Now.AddMinutes(120) }); } } string url = $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";//发送地址 try { object msg = null; string posturl = $"{url}{token}";//发送地址 var thing4 = matter; var thing5 = attention; if (!string.IsNullOrEmpty(matter) && matter.Length > 20) thing4 = matter.Substring(0, 17) + "..."; if (!string.IsNullOrEmpty(attention) && attention.Length > 20) thing5 = attention.Substring(0, 17) + "..."; msg = new { touser = useropenId, template_id = GzhtemplateId, //miniprogram =new{ // appid= appid, // pagepath= "pages/selfService/reception/reception" //}, //miniprogram_state = $"{_configuration.GetSection("Wechat:miniprogram_state").Value}", //lang = "zh_CN", data = new { //name1 = new { value = $"{name}"},// thing1 = new { value = $"{name}" },// phone_number4 = new { value = $"{phone}" },// thing5 = new { value = $"{thing4}" },// }, }; var re = HttpHelper.Post(posturl, msg); if (re.Jsonstr("errcode") == "0") return "成功"; return $"失败:{re}"; } catch (Exception ex) { return $"{ex.Message}"; } return "成功"; } catch (Exception ex) { return $"{ex.Message}"; } return "失败"; } } }