WeChat development-access token expiration failure solution,-accesstoken

Source: Internet
Author: User
Tags sha1 hash

Development-access token expiration failure solution,-accesstoken

Development-access token expiration failure Solution

Cause: All developers know the importance of access_token, but he has his own life cycle. The official explanation is: "The validity period is 7200 seconds" and 2000 calls are made every day. If the traffic is high, it will be over. No way, long GE will not help us solve the problem, we have to solve it by ourselves, and cannot wait to die.

The solution is simple: Create public access token data and do not re-create access_token within the validity period.

Solution:
1. Class Library: directly reads the json data in the access token data file within the validity period, expires, and gets and creates a new access token data file.
2. Data File: stores valid access token data, including access_token.json and jsapi_ticket.json.

The core code is as follows:

 

Index: wxjsSDK. cs
========================================================== ======================================
--- WxjsSDK. cs (revision 0)
++ WxjsSDK. cs (revision 1)
@-1,209 + @@
+ Using System;
+ Using System. Collections. Generic;
+ Using System. Web;
+ Using System. IO;
+ Using System. Security. Cryptography;
+ Using System. Runtime. Serialization. Json;
+ Using System. Runtime. Serialization;
+ Using System. Net;
+ Using System. Runtime. Serialization. Formatters. Binary;
+ Using System. Text;
+
+ Namespace JR. Common
+ {
+ Public class wxjsSDK
+ {
+ Private string appId;
+ Private string appSecret;
+
+
+ Public wxjsSDK (string appId, string appSecret)
+ {
+ This. appId = appId;
+ This. appSecret = appSecret;
+}
+
+
+
+ // Get the data packet and return to the usage page
+ Public System. Collections. Hashtable getSignPackage ()
+ {
+ String jsapiTicket = getJsApiTicket ();
+ String url = HttpContext. Current. Request. Url. ToString (); // "http: // $ _ SERVER [HTTP_HOST] $ _ SERVER [REQUEST_URI]";
+ String timestamp = Convert. ToString (ConvertDateTimeInt (DateTime. Now ));
+ String nonceStr = createNonceStr ();
+ // Here, the parameter order should be sorted in ascending order by the key value ASCII code
+ String rawstring = "jsapi_ticket =" + jsapiTicket + "& noncestr =" + nonceStr + "& timestamp =" + timestamp + "& url =" + url + "";
+ String signature = SHA1_Hash (rawstring );
+ Var signPackage = new System. Collections. Hashtable ();
+ SignPackage. Add ("appId", appId );
+ SignPackage. Add ("nonceStr", nonceStr );
+ SignPackage. Add ("timestamp", timestamp );
+ SignPackage. Add ("url", url );
+ SignPackage. Add ("signature", signature );
+ SignPackage. Add ("rawString", rawstring );
+ Return signPackage;
+}
+
+
+ // Create a random string
+ Private string createNonceStr ()
+ {
+ Int length = 16;
+ String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
+ String str = "";
+ Var rad = new Random ();
+ For (int I = 0; I <length; I ++)
+ {
+ Str + = chars. Substring (rad. Next (0, chars. Length-1), 1 );
+}
+ Return str;
+}
+
+
+ // Get ticket. If the time in the file times out, get it again.
+ Private string getJsApiTicket ()
+ {
+ String ticket = "";
+ // Jsapi_ticket should be stored and updated globally. The following code is used as an example to write data to a file.
+ String path = HttpContext. Current. Server. MapPath (@ "/log/jssdk/jsapi_ticket.json ");
+ If (! File. Exists (path ))
+ {
+ File. Create (path). Close ();
+}
+ StreamReader sr = new StreamReader (path, System. Text. Encoding. Default );
+ String filecontent = sr. ReadToEnd ();
+ CommonJsonModel jsonModel = null;
+ If (! String. IsNullOrEmpty (filecontent ))
+ {
+ JsonModel = new CommonJsonModel (filecontent );
+}
+ Sr. Close ();
+ Sr. Dispose ();
+ If (jsonModel = null | int. Parse (jsonModel. GetValue ("expires_in") <ConvertDateTimeInt (DateTime. Now ))
+ {
+ String accessToken = getAccessToken ();
+ String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket? Type = jsapi & access_token = "+ accessToken;
+ JsonModel = new CommonJsonModel (httpGet (url ));
+ Ticket = jsonModel. GetValue ("ticket ");
+ If (ticket! = "")
+ {
+ String json = "{\" ticket \ ": \" "+ ticket +" \ ", \" expires_in \ ":" + (ConvertDateTimeInt (DateTime. now) + 7000) + "}";
+ StreamWriterMetod (json, path );
+}
+}
+ Else
+ {
+ Ticket = jsonModel. GetValue ("ticket ");
+}
+ Return ticket;
+}
+
+
+ // Obtain the accesstoken. If the time in the file times out, obtain the accesstoken again.
+ Private string getAccessToken ()
+ {
+ // Access_token should be stored and updated globally. The following code is used as an example to write data to a file.
+ String access_token = "";
+ String path = HttpContext. Current. Server. MapPath (@ "/log/jssdk/access_token.json ");
+ If (! File. Exists (path ))
+ {
+ File. Create (path). Close ();
+}
+ StreamReader sr = new StreamReader (path, System. Text. Encoding. Default );
+ String filecontent = sr. ReadToEnd ();
+ CommonJsonModel jsonModel = null;
+ If (! String. IsNullOrEmpty (filecontent ))
+ {
+ JsonModel = new CommonJsonModel (filecontent );
+}
+ Sr. Close ();
+ Sr. Dispose ();
+ If (jsonModel = null | int. Parse (jsonModel. GetValue ("expires_in") <ConvertDateTimeInt (DateTime. Now ))
+ {
+ String url = "https://api.weixin.qq.com/cgi-bin/token? Grant_type = client_credential & appid = "+ appId +
+ "& Secret =" + appSecret + "";
+ JsonModel = new CommonJsonModel (httpGet (url ));
+ Access_token = jsonModel. GetValue ("access_token ");
+ If (access_token! = "")
+ {
+ String json = "{\" access_token \ ": \" "+ access_token +" \ ", \" expires_in \ ":" + (ConvertDateTimeInt (DateTime. now) + 7000) + "}";
+ StreamWriterMetod (json, path );
+}
+}
+ Else
+ {
+ Access_token = jsonModel. GetValue ("access_token ");
+}
+ Return access_token;
+}
+
+
+ // Initiate an http ball and return the value
+ Private string httpGet (string url)
+ {
+ Try
+ {
+ Var MyWebClient = new WebClient ();
+ MyWebClient. Credentials = CredentialCache. DefaultCredentials; // gets or sets the network Credentials used to authenticate requests to Internet resources.
+ Byte [] pageData = MyWebClient. DownloadData (url); // download data from a specified website
+ String pageHtml = System. Text. Encoding. Default. GetString (pageData); // if you use GB2312 to retrieve the website page, use this sentence.
+ // String pageHtml = Encoding. UTF8.GetString (pageData); // if you get a website page using a UTF-8, use this sentence
+ Return pageHtml;
+}
+ Catch (WebException webEx)
+ {
+ Console. WriteLine (webEx. Message. ToString ());
+ Return null;
+}
+}
+
+
+ // SHA1 hash Encryption Algorithm
+ Private string SHA1_Hash (string str_sha1_in)
+ {
+ SHA1 sha1 = new SHA1CryptoServiceProvider ();
+ Byte [] bytes_sha1_in = System. Text. UTF8Encoding. Default. GetBytes (str_sha1_in );
+ Byte [] bytes_sha1_out = sha1.ComputeHash (bytes_sha1_in );
+ String str_sha1_out = BitConverter. ToString (bytes_sha1_out );
+ Str_sha1_out = str_sha1_out.Replace ("-", ""). ToLower ();
+ Return str_sha1_out;
+}
+
+
+ /// <Summary>
+ /// Method for writing StreamWriter to a file
+ /// </Summary>
+ Private void StreamWriterMetod (string str, string patch)
+ {
+ FileStream stream = new FileStream (patch, FileMode. OpenOrCreate, FileAccess. Write, FileShare. Delete | FileShare. ReadWrite );
+ StreamWriter writer = new StreamWriter (stream );
+ Writer. WriteLine (str );
+ Stream. Flush ();
+ Writer. Close ();
+ Stream. Close ();
+ Stream. Dispose ();
+ Writer. Dispose ();
+}
+
+
+
+
+ /// <Summary>
+ /// Convert the c # DateTime time format to the Unix timestamp format
+ /// </Summary>
+ /// <Param name = "time"> time </param>
+ /// <Returns> double </returns>
+ Private int ConvertDateTimeInt (System. DateTime time)
+ {
+ Int intResult = 0;
+ System. DateTime startTime = TimeZone. CurrentTimeZone. ToLocalTime (new System. DateTime (1970, 1, 1 ));
+ IntResult = Convert. ToInt32 (time-startTime). TotalSeconds );
+ Return intResult;
+}
+
+
+}
+
+
+}

 

 

Access_token.json
{"Access_token": "token", "expire_time": 1428599121}


Access_token.json
{"Jsapi_ticket": "success", "expire_time": 1428599122}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.