獲取 AccessToken 官方文檔
https://work.weixin.qq.com/api/doc/90000/90135/91039
Controller層
[HttpGet] public string Get(bool refresh = false) { try { string accessToken = JsSdkProcess.GetCurrentAccessToken(refresh); return accessToken; } catch (Exception ex) { return ex.Message; } }
注意事項:
開發者需要緩存access_token,用於后續接口的調用(注意:不能頻繁調用gettoken接口,否則會受到頻率攔截)。當access_token失效或過期時,需要重新獲取。
緩存
public class JsSdkProcess { /// <summary> /// 全局驗證器緩存容器 /// </summary> private static MemoryCacheClient MemoryCache = new MemoryCacheClient(); /// <summary> /// 獲取普通access_token並進行緩存 /// </summary> /// <returns></returns> public static string GetCurrentAccessToken(bool refresh = false) { try { //需要強制刷新 if (refresh) { var accessToken = AccessTokenService.GetAccessToken(); if (!accessToken.StartsWith("Exception:")) { MemoryCache.Set("GetCurrentAccessToken()", accessToken, DateTime.Now.AddSeconds(7200)); } return accessToken; } //不需要強制刷新 else { var accessToken = MemoryCache.Get<string>("GetCurrentAccessToken()"); if (string.IsNullOrWhiteSpace(accessToken)) { accessToken = AccessTokenService.GetAccessToken(); if (!accessToken.StartsWith("Exception:")) { MemoryCache.Set("GetCurrentAccessToken()", accessToken, DateTime.Now.AddSeconds(7200)); } } return accessToken; } } catch (Exception ex) { return ex.Message; } } }
Service層
public static string GetAccessToken() { try { string wxUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}"; wxUrl = wxUrl.Fmt(corpid, corpsecret); var json = wxUrl.GetStringFromUrl(); var data = json.FromJson<Dictionary<string, string>>(); if (data["errcode"] == "0") { return data["access_token"]; } return "NotAccessToken:" + data.ToJsv(); } catch (System.Exception ex) { return "Exception:" + ex.ToString(); } }