using CommonUtil; using CommonUtil.Web; using System; using System.Collections.Generic; using System.Text; namespace Operater.Common { public class SmsGzhHelperHandle { public static GzhToken _gzhToken; /// /// 获取公众号acess_token /// /// public static GetAccessTokenResponse GetGzhAccessToken() { string gzhAppid = ConfigUtil.GetValue("gzhappid"); string gzhSecret= ConfigUtil.GetValue("gzhsecret"); string getUrl = $" https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={gzhAppid}&secret={gzhSecret}"; string resStr = new WebUtil().DoGet(getUrl, null); LogUtil.Info($"[获取access_token]返回:{resStr}", "接口请求日志"); if (resStr.IsNullOrEmpty()) { return null; } GetAccessTokenResponse response = JSONUtil.JsonToObject(resStr); return response; } /// /// 获取公众号token /// /// public static string GetGzhToken() { if (_gzhToken.IsNull() || _gzhToken.ExpressTime < DateTime.Now) { if (_gzhToken.IsNull()) { _gzhToken = new GzhToken(); } var token = GetGzhAccessToken(); _gzhToken.AccessToken = token.access_token; _gzhToken.ExpressTime = DateTime.Now.AddSeconds(token.expires_in); } return _gzhToken.AccessToken; } /// /// 发送公众号模板消息 /// /// public static SendTemplateMsgResponse SendTemplateMsg(SendTemplateMsgRequest request, string access_token) { string url = $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}"; Dictionary dic = new Dictionary(); dic.Add("touser", request.touser); dic.Add("template_id", request.template_id); dic.Add("data", request.data); string resStr = new WebUtil().DoPostWithJson(url, dic, null); LogUtil.Info($"[发模板消息]请求:{JSONUtil.ObjectToJson(dic)},返回:{resStr}", "发送模板消息日志"); SendTemplateMsgResponse res = JSONUtil.JsonToObject(resStr); return res; } } public class SendTemplateMsgRequest { public string touser { get; set; } public string template_id { get; set; } public object data { get; set; } } public class SendTemplateMsgResponse : WxKfBaseResponse { public string msgid { get; set; } } public class GzhToken { public string AccessToken { get; set; } public DateTime ExpressTime { get; set; } } public class WxKfBaseResponse { public int errcode { get; set; } public string errmsg { get; set; } } public class GetAccessTokenResponse : WxKfBaseResponse { public string access_token { get; set; } public long expires_in { get; set; } } }