C # public platform development-access_token acquisition, storage, and update,
1. What is access_token?
Access_token is the globally unique ticket of the public account. access_token is required when the Public Account calls each interface. Under normal circumstancesAccess_token is valid for 7200 seconds, Duplicate access will invalidate the last 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. Refreshing access_token frequently will restrict api calls and affect their own services.
Ii. Problems to be Solved
1. How to obtain access_token.
2. Because the validity period of access_token is 7200 seconds, that is, 2 hours, and repeated access_token acquisition will invalidate the last access_token. The number of api calls to get access_token is very limited.How to store and update access_token globally.
Iii. Ideas
1. Store access_token in the database.
2. When will access_token be updated? When the access_token expires, how can I determine whether the access_token is invalid? Use the current access_token request interface to obtain the custom menu. If the returned errcode is 42001, it indicates that the access_token has expired and then the access_token is retrieved again.
4. Code:
1. Http Request Code (HttpRequestUtil class ):
# Region request Url, no data is sent /// <summary> /// request Url, no data is sent /// </summary> public static string RequestUrl (string url) {return RequestUrl (url, "POST") ;}# endregion # region request Url, no data is sent /// <summary> /// request Url, do not send data /// </summary> public static string RequestUrl (string url, string method) {// set the 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 obtain the response data HttpWebResponse response = request. getResponse () as HttpWebResponse; // wait until request. the GetResponse () program starts to send the Post request Stream responseStream = response to the target webpage. getResponseStream (); StreamReader sr = new StreamReader (responseStream, Encoding. UTF8); // returned result webpage (html) code string content = sr. readToEnd (); return content ;}# endregionView Code
2. Auxiliary methods (Tools class ):
Namespace SWX. utils {// <summary> /// tool class // </summary> public class Tools {# region obtains the value of a node in the Json string /// <summary> // /obtain the value of a node in the Json string // </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) {// cut the comma first. If it is the last one, cut the "}" and 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 }}View Code
3. Determine whether the access_token expires (WXApi class ):
# Region verify that the Token has expired /// <summary> // verify that the Token has expired /// </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;} # endregionView Code
4. Request interface, get access_token (WXApi class ):
# Region get Token // <summary> // get 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 ");} # endregionView Code
5. Globally store and update access_token (AdminUtil class ):
# Region get access_token // <summary> // get 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 has not been saved. getToken (user. appID, user. appSecret);} else {if (WXApi. tokenExpired (user. access_token) // access_token expired {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;} # endregionView Code
C # the source code for public platform development is displayed on the left of my blog homepage.