一、什么是access_token?
access_token是公眾號(hào)的全局唯一票據(jù),公眾號(hào)調(diào)用各接口時(shí)都需使用access_token。正常情況下access_token有效期為7200秒,重復(fù)獲取將導(dǎo)致上次獲取的access_token失效。由于獲取access_token的api調(diào)用次數(shù)非常有限,建議開(kāi)發(fā)者全局存儲(chǔ)與更新access_token,頻繁刷新access_token會(huì)導(dǎo)致api調(diào)用受限,影響自身業(yè)務(wù)。
二、要解決的問(wèn)題
1、如何獲取access_token。
2、由于access_token的有效期為7200秒,即2小時(shí),并且重復(fù)獲取將導(dǎo)致上次獲取的access_token失效,獲取access_token的api調(diào)用次數(shù)非常有限,所以要解決如何全局存儲(chǔ)與更新access_token。
三、思路
1、將access_token存儲(chǔ)在數(shù)據(jù)庫(kù)中。
2、何時(shí)更新access_token呢?當(dāng)access_token失效的時(shí)候更新,那么怎么判斷access_token有沒(méi)有失效呢?使用當(dāng)前的access_token請(qǐng)求微信接口,獲取自定義菜單,如果返回的errcode為42001,則說(shuō)明access_token已經(jīng)失效,這時(shí)再重新獲取access_token。
數(shù)據(jù)庫(kù)設(shè)計(jì)(表名SWX_Config):

四、代碼:
1、Http請(qǐng)求代碼(HttpRequestUtil類(lèi)):
#region 請(qǐng)求Url,不發(fā)送數(shù)據(jù)/// <summary>/// 請(qǐng)求Url,不發(fā)送數(shù)據(jù)/// </summary>public static string RequestUrl(string url){ return RequestUrl(url, "POST");}#endregion#region 請(qǐng)求Url,不發(fā)送數(shù)據(jù)/// <summary>/// 請(qǐng)求Url,不發(fā)送數(shù)據(jù)/// </summary>public static string RequestUrl(string url, string method){ // 設(shè)置參數(shù) HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = method; request.ContentType = "text/html"; request.Headers.Add("charset", "utf-8"); //發(fā)送請(qǐng)求并獲取相應(yīng)回應(yīng)數(shù)據(jù) HttpWebResponse response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才開(kāi)始向目標(biāo)網(wǎng)頁(yè)發(fā)送Post請(qǐng)求 Stream responseStream = response.GetResponseStream(); StreamReader sr = new StreamReader(responseStream, Encoding.UTF8); //返回結(jié)果網(wǎng)頁(yè)(html)代碼 string content = sr.ReadToEnd(); return content;}#endregion 2、輔助方法(Tools類(lèi)):
namespace SWX.Utils{ /// <summary> /// 工具類(lèi) /// </summary> public class Tools { #region 獲取Json字符串某節(jié)點(diǎn)的值 /// <summary> /// 獲取Json字符串某節(jié)點(diǎn)的值 /// </summary> public static string GetJsonValue(string jsonStr, string key) { string result = string.Empty; if (!string.IsNullOrEmpty(jsonStr)) { key = "/"" + key.Trim('"') + "/""; int index = jsonStr.IndexOf(key) + key.Length + 1; if (index > key.Length + 1) { //先截逗號(hào),若是最后一個(gè),截“}”號(hào),取最小值 int end = jsonStr.IndexOf(',', index); if (end == -1) { end = jsonStr.IndexOf('}', index); } result = jsonStr.Substring(index, end - index); result = result.Trim(new char[] { '"', ' ', '/'' }); //過(guò)濾引號(hào)或空格 } } return result; } #endregion }} 3、判斷access_token是否過(guò)期(WXApi類(lèi)):
#region 驗(yàn)證Token是否過(guò)期/// <summary>/// 驗(yàn)證Token是否過(guò)期/// </summary>public static bool TokenExpired(string access_token){ string jsonStr = HttpRequestUtil.RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}", access_token)); if (Tools.GetJsonValue(jsonStr, "errcode") == "42001") { return true; } return false;}#endregion 4、請(qǐng)求微信接口,獲取access_token(WXApi類(lèi)):
#region 獲取Token/// <summary>/// 獲取Token/// </summary>public static string GetToken(string appid, string secret){ string strJson = HttpRequestUtil.RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret)); return Tools.GetJsonValue(strJson, "access_token");}#endregion 5、全局存儲(chǔ)與更新access_token(AdminUtil類(lèi)):
#region 獲取access_token/// <summary>/// 獲取access_token/// </summary>public static string GetAccessToken(PageBase page){ string access_token = string.Empty; UserInfo user = GetLoginUser(page); if (user != null) { if (string.IsNullOrWhiteSpace(user.access_token)) //尚未保存過(guò)access_token { access_token = WXApi.GetToken(user.AppID, user.AppSecret); } else { if (WXApi.TokenExpired(user.access_token)) //access_token過(guò)期 { access_token = WXApi.GetToken(user.AppID, user.AppSecret); } else { return user.access_token; } } MSSQLHelper.ExecuteSql(string.Format("update SWX_Config set access_token='{0}' where UserName='{1}'", access_token, user.UserName)); } return access_token;}#endregion 以上就是本文的全部?jī)?nèi)容,希望對(duì)大家進(jìn)行微信公眾平臺(tái)開(kāi)發(fā)有所幫助。



















