Example Analysis of access_token acquisition, Storage and Update developed by C# Wechat Public platform
This article mainly introduces the example analysis of access_token acquisition, storage and update developed by C# Wechat public platform. The article is very detailed and has certain reference value. Interested friends must finish reading it!
What is access_token?
Access_token is the global unique ticket of the official account, which needs to use access_token when calling each interface. Under normal circumstances, the access_token is valid for 7200 seconds. Repeated acquisition will invalidate the last acquired access_token. 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 result in limited api calls and affect their business.
II. 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 invalidate the last acquired access_token, the number of api calls to obtain access_token is very limited, so it is necessary to solve how to store and update access_token globally.
Third, train of thought
1. Store access_token in the database.
2. When will access_token be updated? When access_token is updated when it fails, how can you tell if access_token has failed? Use the current API Wechat to request access_token to get a custom menu. If the returned errcode is 42001, the access_token is invalid, and then get the access_token again.
Database design (table name SWX_Config):
IV. Code:
1. Http request code (HttpRequestUtil class):
# region request Url, do not send data / request Url, do not send data / public static string RequestUrl (string url) {return RequestUrl (url, "POST");} # endregion # region request Url, do not send data / request Url, do not send data / public static string RequestUrl (string url, string method) {/ / set parameter 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"); / / send the request and get the corresponding response data HttpWebResponse response = request.GetResponse () as HttpWebResponse; / / until the request.GetResponse () program starts sending the Post request Stream responseStream = response.GetResponseStream (); StreamReader sr = new StreamReader (responseStream, Encoding.UTF8) / / return the result web page (html) code string content = sr.ReadToEnd (); return content;} # endregion
2. Auxiliary methods (Tools class):
Namespace SWX.Utils {/ utility class / public class Tools {# region get the value of a node in the Json string / 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) {/ / comma first, if the last one, truncate the "}" sign, take the minimum value int end = jsonStr.IndexOf (',', index); if (end = =-1) {end = jsonStr.IndexOf ('}', index);} result = jsonStr.Substring (index, end-index) Result = result.Trim (new char [] {'",'','\'}); / / filter quotation marks or spaces}} return result;} # endregion}}
3. Determine whether access_token is out of date (WXApi class):
# region verify whether the Token expires / verify whether the Token expires / 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 API Wechat to obtain access_token (WXApi class):
# region get Token/// get Token/// 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 get access_token/// get access_token/// public static string GetAccessToken (PageBase page) {string access_token = string.Empty; UserInfo user = GetLoginUser (page); if (user! = null) {if (string.IsNullOrWhiteSpace (user.access_token)) / / has not yet saved access_token {access_token = WXApi.GetToken (user.AppID, user.AppSecret) } else {if (WXApi.TokenExpired (user.access_token)) / / access_token expires {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 above are all the contents of this article entitled "sample Analysis of access_token acquisition, Storage and Update developed by C# Wechat Public platform". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!