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 circumstances, the validity period of the access_token is 7200 seconds. Repeated access_token acquisition will invalidate the previous 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. problem 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, therefore, we need to solve how to store and update access_token globally. 3. Train of Thought 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. Iv. Code: 1. Http Request Code (HttpRequestUtil class): copy the Code # region request Url, do not send data /// <summary> // request Url, do not send data // </summary> public static string RequestUrl (string url) {return RequestUrl (url, "POST") ;}# endregion # region request Url, do not send data /// <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 ;}# endregion copy code 2. Auxiliary method (Tools class): Copy code 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;} # e Ndregion} copy code 3. Determine whether the access_token has expired (WXApi class ): copy the Code # 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;} # endregion copy Code 4. Request interface, get access_token (WXApi class ): copy the Code # region to 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") ;}# endregion copy Code 5. Global storage and update access_token (AdminUtil class ): copy the Code # region to 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;} # endregion