微信发送模板消息
自己封装个类库,用于微信开发
/// <summary> /// 公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。 /// access_token的存储至少要保留512个字符空间。access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。 /// </summary> public class Access_token { public Access_token() { // //TODO:用于验证Access_token是否过期实体 // } /// <summary> /// 获取到的凭证 /// </summary> public string access_token { get; set; } /// <summary> /// 凭证有效时间,单位:秒 /// </summary> public string expires_in { get; set; } }
/// <summary> /// 微信主要处理类 /// </summary> public static class Main { /// <summary> /// 获取AccessToken 为null表示获取失败 /// </summary> /// <param name="AppId">第三方用户唯一凭证</param> /// <param name="AppSecret">第三方用户唯一凭证密钥,即appsecret</param> /// <returns>Access_token</returns> public static Access_token GetAccessToken(string AppId, string AppSecret) { //grant_type 获取access_token填写client_credential //appid 第三方用户唯一凭证 //secret 第三方用户唯一凭证密钥,即appsecret string strUrl = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", AppId, AppSecret);//微信获取Accesstoken接口地址 Access_token res = new Access_token(); //正常情况下,微信会返回下述JSON数据包给公众号: //{ "access_token":"ACCESS_TOKEN","expires_in":7200} //access_token 获取到的凭证 //expires_in 凭证有效时间,单位:秒 //错误时微信会返回错误码等信息 //{"errcode":40013,"errmsg":"invalid appid"} string retString = WebRequestExt.GetData(strUrl); if (retString.IndexOf("7200") > 0)//Accesstoken有效时间2小时 { //Newtonsoft.Json 反序列化 res = JsonConvert.DeserializeObject<Access_token>(retString); } else { res = null; } return res; } /// <summary> /// 发送模板消息(每次只能发一条,目前每日上限10万次) /// </summary> /// <param name="access_token"></param> /// <param name="TemplateId">模板消息ID</param> /// <param name="Receiver_OpenID">接收者openid</param> /// <param name="MsgUrl">消息跳转地址</param> /// <param name="SenderName">发送人姓名</param> /// <param name="Title">发送标题</param> /// <param name="Content">发送内容</param> /// <returns>返回发送结果</returns> public static string TemplateMsg_Send(string access_token, string strJson) { string result = string.Empty;//消息发送结果 try { //发送模板消息的微信接口地址 string PostUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token; #region 发送给微信服务器的模板消息格式 //string strJson = "{" + // "\"touser\":\"" + Receiver_OpenID + "\"," + // "\"template_id\":\"" + TemplateId + "\"," + // "\"url\":\"" + MsgUrl + "\"," + // "\"topcolor\":\"#FF0000\"," + // "\"data\":{" + // "\"first\":{" + // "\"value\":\"" + SenderName + "给你发来最新消息!\"," + // "\"color\":\"#173177\"" + // "}," + // "\"keyword1\":{" + // "\"value\":\"" + FormatClear(Title) + "\"," + // "\"color\":\"#173177\"" + // "}," + // "\"keyword2\":{" + // "\"value\":\"" + DateTime.Now + "\"," + // "\"color\":\"#173177\"" + // "}," + // "\"keyword3\":{" + // "\"value\":\"" + FormatClear(Content) + "\"," + // "\"color\":\"#173177\"" + // "}," + // "\"remark\":{" + // "\"value\":\"\"," + // "\"color\":\"#173177\"" + // "}" + // "}" + // "}"; #endregion //在调用模板消息接口后,会返回JSON数据包。正常时的返回JSON数据包示例: //{"errcode":0,"errmsg":"ok","msgid":200228332} result = WebRequestExt.PostData(strJson, PostUrl); } catch (Exception ex) { result = ex.Message; } return result; } }
使用的大概逻辑:
Model层新建类Access_token
public class Access_token { /// <summary> /// 获取到的凭证 /// </summary> public string access_token { get; set; } /// <summary> /// 凭证有效截止时间 /// </summary> public DateTime ValidTime { get; set; } }
结合redis或其他数据库使用
public Model.Access_token GetAccess_token_redis() { //从redis中取Access_token Model.Access_token mod_Access_token = DFS.BLL.SERedisHelper.HashGet<Model.Access_token>("Access_token", "Access_token"); if (mod_Access_token == null) {//redis中没有 Set_Access_token_redis(mod_Access_token); } else {//redis中存在 判断是否过期 if (mod_Access_token.ValidTime < DateTime.Now)//已过期 { Set_Access_token_redis(mod_Access_token); } }//else return mod_Access_token; } /// <summary> /// 从微信接口取Access_token 存储到redis中 /// </summary> /// <param name="mod_Access_token"></param> private void Set_Access_token_redis(Access_token mod_Access_token) { //从微信接口取Access_token Model.wxConfig mod_wxConfig = GetwxConfigModel_redis(); WeChat.Access_token Access_token = WeChat.Main.GetAccessToken(mod_wxConfig.AppId, mod_wxConfig.AppSecret); if (Access_token.expires_in == "7200") {//拿到正确Access_token mod_Access_token.access_token = Access_token.access_token; mod_Access_token.ValidTime = DateTime.Now.AddSeconds(7200); //存储到redis中 BLL.SERedisHelper.HashSet("Access_token", "Access_token", mod_Access_token); } } /// <summary> /// 获取微信配置 先从redis里面取 不存在从数据库中取 /// </summary> /// <returns></returns> public Model.wxConfig GetwxConfigModel_redis() { //从redis中取 Model.wxConfig cfg = SERedisHelper.HashGet<Model.wxConfig>("wxConfig", "wxConfig"); if (cfg == null) { cfg = new wxConfig(); //从数据库中取 List<Model.WeChatSysConfig> lst = GetModelList("ID between 600 and 604"); foreach (Model.WeChatSysConfig item in lst) { switch (item.ItemName) { case "AppId"://微信唯一标识 cfg.AppId = item.ItemValue; break; case "AppSecret"://微信密钥 cfg.AppSecret = item.ItemValue; break; case "Token"://微信配置标码(自定义) cfg.Token = item.ItemValue; break; case "ServerName"://部署的服务器域名 cfg.ServerName = item.ItemValue; break; case "Templateid"://发送模版消息ID cfg.Templateid = item.ItemValue; break; default: break; } } //存储到redis 默认永不过期 SERedisHelper.HashSet("wxConfig", "wxConfig",cfg); } return cfg; }