微信Access Token預設快取是2小時,但是需要特別強調,微信服務號和微信企業號快取並不相同。
(1)微信公眾號號:每次Http請求Access Token 系統會返回不同的Token,並附帶超時時間,預設是2小時。
(2)微信企業號:每次請求Access Token,預設有效期為2個小時,在這2個小時內獲取的Access Token是一樣的。
對於微信公眾號,我們通過txt儲存每次獲取的Access Token。換句話說,當快取後,再次獲取Access時,直接從txt裡獲取。程式碼如下:
private static string wxml = HttpContext.Current.Server.MapPath("~/app_data/access_token.txt"); public static string GetAccessToken() { string json = ""; DateTime dt = DateTime.Now; if (!System.IO.File.Exists(wxml)) {
//txt不存在,建立 json = GetTokenFromURL(); } else { json = System.IO.File.ReadAllText(wxml); } //獲取最後txt寫入的時間 dt = System.IO.File.GetLastWriteTime(wxml); DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AccessToken)); var mStream = new MemoryStream(Encoding.Default.GetBytes(json)); AccessToken token = (AccessToken)serializer.ReadObject(mStream); //_expires_in預設為 7200秒,也就是2小時,也就是access_token2小時即失效。為了保證可靠性,系統讓access_tokey 1.5小時失效。 int minRefreshTimeSpan = 1800 - int.Parse(token.expires_in); // -5400秒 if (minRefreshTimeSpan > 0) { minRefreshTimeSpan = -1800; } if (dt < DateTime.Now.AddSeconds(minRefreshTimeSpan)) { GetTokenFromURL(); json = System.IO.File.ReadAllText(wxml); serializer = new DataContractJsonSerializer(typeof(AccessToken)); mStream = new MemoryStream(Encoding.Default.GetBytes(json)); token = (AccessToken)serializer.ReadObject(mStream); } return token.access_token; } private static string GetTokenFromURL() { string appid = AppID; string secret = AppSecret; string strUrl = Access_Token_URL; string json = HttpUtility.SendGetHttpRequest(strUrl); System.IO.File.WriteAllText(wxml, json); return json; }
(2)對於企業微信AccessToken,可以使用單列模式儲存
private static DateTime _lastGetTimeOfAccessToken = DateTime.Now.AddSeconds(-7201); private static string _AccessToken=""; public static string GetAccessToken() { if (_lastGetTimeOfAccessToken < DateTime.Now ) { var rsEntity = new { access_token = "", expires_in = 0, errcode = 0, errmsg = "" }; string json = GetTokenFromURL(); DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AccessToken)); var mStream = new MemoryStream(Encoding.Default.GetBytes(json)); AccessToken token = (AccessToken)serializer.ReadObject(mStream); _lastGetTimeOfAccessToken = DateTime.Now.AddSeconds( int.Parse(token.expires_in) - 1); _AccessToken = token.access_token; } return _AccessToken; }