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 }
时间: 2024-10-17 00:18:22