


C# WeChat public platform development access_token acquisition, storage and update
Jan 17, 2017 am 10:46 AM1. What is access_token?
access_token is the globally unique ticket of the public account. The public account needs to use access_token when calling each interface. Under normal circumstances, the access_token is valid for 7200 seconds. Repeated acquisition will cause the last access_token to become invalid. Since the number of API calls to obtain access_token is very limited, it is recommended that developers store and update access_token globally. Frequent refresh of access_token will limit API calls and affect their own business.
2. Problems to be solved
1. How to obtain access_token.
2. Since the validity period of access_token is 7200 seconds, that is, 2 hours, and repeated acquisition will cause the last access_token to become invalid, the number of api calls to obtain access_token is very limited, so it is necessary to solve how to globally store and update access_token. .
3. Ideas
1. Store access_token in the database.
2. When will the access_token be updated? Update when access_token expires, so how to determine whether access_token has expired? Use the current access_token to request the WeChat interface to obtain the custom menu. If the returned errcode is 42001, it means that the access_token has expired. At this time, obtain the access_token again.
Database design (table name SWX_Config):
4. Code:
1. Http request code (HttpRequestUtil class):
#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()程序才開始向目標(biāo)網(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. Auxiliary method (Tools class):
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. Determine whether access_token has expired (WXApi class):
#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. Request the WeChat interface to obtain access_token (WXApi Class):
#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. Global storage and update access_token (AdminUtil class):
#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
The above is the entire content of this article. I hope it will be helpful to everyone in the development of WeChat public platform.
For more articles related to the acquisition, storage and update of access_token in C# WeChat public platform development, please pay attention to the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)
