/// <summary> /// 获取微信API访问凭证。仅在需要时调用微信API接口,即:若凭证尚在有效期内,则直接取回上一次得到的凭证。 /// </summary> /// <param name="appId"></param> /// <param name="appSecret"></param> /// <param name="forceRenew">强制立即取新。这将废弃并替换旧的,而不管是否旧的令牌是否过期。</param> /// <returns>微信API访问凭证</returns> public string GetToken(string appId, string appSecret, bool forceRenew = false) { //bool forceRenew = false; if (forceRenew) { //立即过期 _AccessTokenBags.SetExpired(appId); } else { forceRenew = _AccessTokenBags.IsExpired(appId); } //forceRenew = CheckTokenExpire(); if (forceRenew) { lock (_lockApiCalling) { //再次检查,通常在等待上一锁释放期间,过期状态已经发生改变。若已改变,则不应再调用API去刷新Token! if (_AccessTokenBags.IsExpired(appId)) { AccessTokenJson json = AccessTokenApi.GetTokenAsync(appId, appSecret).Result; if (json != null && !string.IsNullOrEmpty(json.access_token)) { _AccessTokenBags.Store(appId, new AccessTokenBag() { AccessTokenJson = json, AppId = appId, AppSecret = appSecret, CreateTime = DateTime.Now }); } } } } return(_AccessTokenBags.GetToken(appId)); }
public string GetToken(bool forceRenew) { var appId = _options.AppId; var appSecret = _options.AppSecret; var cacheKey = GenerateCacheKey(appId); if (!forceRenew) { if (_cache.TryGetValue(cacheKey, out string accessToken)) { return accessToken; } } else { _cache.Remove(cacheKey); } try { var json = AccessTokenApi.GetTokenAsync(appId, appSecret).Result; if (json == null || string.IsNullOrWhiteSpace(json.access_token) || json.expires_in < 1 || json.expires_in > 7200) { throw WeixinAccessTokenError.UnknownResponse(); } else { var newAccessToken = json.access_token; _cache.Set(cacheKey, newAccessToken, TimeSpan.FromSeconds(json.expires_in)); return newAccessToken; } } catch (Exception ex) { throw WeixinAccessTokenError.GenericError(ex); } }