自己封裝個類庫,用於微信開發 使用的大概邏輯: Model層新建類Access_token 結合redis或其他資料庫使用 ...
自己封裝個類庫,用於微信開發
/// <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; }