C# v3微信 access token 過時處理的問題

 1         //記錄access token 申請時的時間
 2         private static DateTime GetAccessToken_Time;  
3 /// <summary> 4 /// 過時時間爲7200秒 5 /// </summary> 6 private static int Expires_Period = 7200;

       private static string mAccessToken;
7 /// <summary> 8 /// 獲取access token 9 /// </summary> 10 /// <returns></returns> 11 private static string GetAccessToken() 12 { 13 if (string.IsNullOrEmpty(mAccessToken) || HasExpired()) 14 { 15 string Url = "https://api.weixin.qq.com/cgi-bin/token"; 16 string RequestPara = "grant_type=client_credential&appid=" + APPID + "&secret=" + APPSECRET; 17 string result = WebRequestHelper.GetData(RequestPara, Url); 18 if (!result.Equals("")) 19 { 20 GetAccessToken_Time = DateTime.Now; 21 accesstoken token = JsonFormat.Deserialize<accesstoken>(result); 22 Expires_Period = Convert.ToInt32(token.expires_in); 23 return token.access_token; 24 } 25 else 26 { 27 GetAccessToken_Time = DateTime.MinValue; 28 } 29 } 30 return null; 31 } 32 33 /// <summary> 34 /// 判斷Access_token是否過時 35 /// </summary> 36 /// <returns>bool</returns> 37 private static bool HasExpired() 38 { 39 if (GetAccessToken_Time != null) 40 { 41 //過時時間,容許有必定的偏差,一分鐘。獲取時間消耗 42 if (DateTime.Now > GetAccessToken_Time.AddSeconds(Expires_Period).AddSeconds(-60)) 43 { 44 return true; 45 } 46 } 47 return false; 48 }
相關文章
相關標籤/搜索