C # basic methods for obtaining tokens using wx,
# 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 var request = WebRequest. create (url) as HttpWebRequest; var cookieContainer = new CookieContainer (); request. cookieContainer = co OkieContainer; request. allowAutoRedirect = true; request. method = method; request. contentType = "text/html"; request. headers. add ("charset", "UTF-8"); // send the request and obtain the response data var 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 (); var sr = new StreamReader (responseStream, Encoding. UTF8); // returned result webpage (html) code string content = Sr. readToEnd (); return content ;} # endregion # region obtain 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 "}" number 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 [] {'"','', '\ "'}); // filter quotation marks or spaces} return result ;} # endregion # region verify that the Token has expired /// <summary> // verify that the Token has expired /// </summary> public static bool TokenExpired (string access_token) {string jsonStr = RequestUrl (string. format (" https://api.weixin.qq.com/cgi-bin/menu/get?access_token= {0} ", access_token); if (GetJsonValue (jsonStr," errcode ") =" 42001 ") {return true;} return false ;} # endregion # region get Token /// <summary> /// get Token /// </summary> public static string GetToken (string appid, string secret) {string strJson = RequestUrl (string. format (" https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid= {0} & secret = {1} ", appid, secret); return GetJsonValue (strJson," access_token ");} # endregion // obtain Openidpublic static string GetOpenId (string appid, string secret, string code) {string strJson = RequestUrl (string. format (" https://api.weixin.qq.com/sns/jscode2session?appid= {0} & secret = {1} & js_code = {2} & grant_type = authorization_code ", appid, secret, code); // LogUtil. writeLog (strJson); return GetJsonValue (strJson, "openid ");}