access_token是公眾號的全局唯一票據,公眾號調用各接口時都需使用access_token。正常情況下access_token有效期為7200秒(兩個小時),微信獲取access_token接口每日限制調用2000次。
(一)access_token的作用
access_token由公眾號的AppID和AppSecret組成,所以具有識別公眾號的作用。
(二)access_token的特點
access_token存儲至少要保留512個字符空間。access_token的有效期目前為2個小時,重復獲取將導致上次獲取的access_token失效。
(三)access_token的存儲調用策略
access_token在后期應用開發中應采取的策略,如圖所示,將access_token存儲到中控服務器,所有需要用到該參數的程序都應訪問中控服務器獲取access_token,中控服務器判斷當前access_token是否有效並刷新即可。
(四)接口調用請求說明
http請求方式: GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
(五)獲取access_token
1 /// <summary> 2 /// GET方式請求URL,並返回AccessTokenResult類 3 /// </summary> 4 public static AccessTokenResult GetJson<AccessTokenResult>(string url) 5 { 6 string returnText = HttpGet(url); 7 8 JavaScriptSerializer js = new JavaScriptSerializer(); 9 10 AccessTokenResult result = js.Deserialize<AccessTokenResult>(returnText); 11 12 return result; 13 }
1 /// <summary> 2 /// 獲取憑證接口 3 /// </summary> 4 private static AccessTokenResult GetToken(string appid, string secret, string grant_type = "client_credential") 5 { 6 var url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", grant_type, appid, secret); 7 8 return HttpService.GetJson<AccessTokenResult>(url); 9 }
1 //token緩存鍵值對 2 private static Dictionary<string, ComponentAccessTokenResult> tokenCache = new Dictionary<string, ComponentAccessTokenResult>(); 3 4/// <summary> 5/// 獲取緩存令牌 6/// </summary> 7public static string GetAccessToken(string appid, string secret) 8{ 9 //token緩存 10 ComponentAccessTokenResult result = null; 11 //判斷緩存是否存在鍵:appid,就將緩存中的token賦給result 12 if (tokenCache.ContainsKey(appid)) 13 { 14 result = tokenCache[appid]; 15 } 16 //不存在則獲取token 17 if (result == null) 18 { 19 AccessTokenResult token = GetToken(appid, secret); 20 21 result = new ComponentAccessTokenResult() { 23 //access_token 24 component_access_token = token.access_token, 25 //生成access_token的時間 26 dt = System.DateTime.Now, 27 }; 28 tokenCache.Add(appid, result); 29 } 30 //判斷是否在有效期內,過期重新獲取token 31 else if (System.DateTime.Compare(result.dt.AddSeconds(7200), System.DateTime.Now) < 0) 32 { 33 AccessTokenResult token = GetToken(appid, secret); 34 result.component_access_token = token.access_token; 35 result.dt = System.DateTime.Now; 36 tokenCache[appid] = result; 37 } 38 return result.component_access_token; 39}