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

四、代碼:
1、Http請求代碼(HttpRequestUtil類):
#region 請求Url,不發(fā)送數(shù)據(jù)
/// <summary>
/// 請求Url,不發(fā)送數(shù)據(jù)
/// </summary>
public static string RequestUrl(string url)
{
return RequestUrl(url, "POST");
}
#endregion
#region 請求Url,不發(fā)送數(shù)據(jù)
/// <summary>
/// 請求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ā)送請求并獲取相應(yīng)回應(yīng)數(shù)據(jù)
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才開始向目標網(wǎng)頁發(fā)送Post請求
Stream responseStream = response.GetResponseStream();
StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
//返回結(jié)果網(wǎng)頁(html)代碼
string content = sr.ReadToEnd();
return content;
}
#endregion
2、輔助方法(Tools類):
namespace SWX.Utils
{
/// <summary>
/// 工具類
/// </summary>
public class Tools
{
#region 獲取Json字符串某節(jié)點的值
/// <summary>
/// 獲取Json字符串某節(jié)點的值
/// </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)
{
//先截逗號,若是最后一個,截“}”號,取最小值
int end = jsonStr.IndexOf(',', index);
if (end == -1)
{
end = jsonStr.IndexOf('}', index);
}
result = jsonStr.Substring(index, end - index);
result = result.Trim(new char[] { '"', ' ', '\'' }); //過濾引號或空格
}
}
return result;
}
#endregion
}
}
3、判斷access_token是否過期(WXApi類):
#region 驗證Token是否過期
/// <summary>
/// 驗證Token是否過期
/// </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、請求微信接口,獲取access_token(WXApi類):
#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、全局存儲與更新access_token(AdminUtil類):
#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)) //尚未保存過access_token
{
access_token = WXApi.GetToken(user.AppID, user.AppSecret);
}
else
{
if (WXApi.TokenExpired(user.access_token)) //access_token過期
{
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
精彩專題分享:ASP.NET微信開發(fā)教程匯總,歡迎大家學(xué)習(xí)。
以上就是本文的全部內(nèi)容,希望對大家進行微信公眾平臺開發(fā)有所幫助。
相關(guān)文章
基于WPF實現(xiàn)帶蒙版的MessageBox消息提示框
這篇文章主要介紹了如何利用WPF實現(xiàn)帶蒙版的MessageBox消息提示框,文中的示例代碼講解詳細,對我們學(xué)習(xí)或工作有一定幫助,需要的可以參考一下2022-08-08
C# 如何設(shè)置label(標簽)控件的背景顏色為透明
這篇文章主要介紹了C# 如何設(shè)置label(標簽)控件的背景顏色為透明,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下2020-10-10
C#關(guān)于Task.Yeild()函數(shù)的討論
這篇文章主要介紹了C#中關(guān)于Task.Yeild()函數(shù)的相關(guān)資料,文中講解非常細致,幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-07-07

