public TokenCacheModel GetToken() { TokenCacheModel cache = TokenCache.ContainsKey(AgentId) ? TokenCache[AgentId] : null; if (cache != null && DateTime.Now < cache.ExpiresAt) { return(cache); } using (var webClient = new WebClient()) { var address = $"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={CorpId}&corpsecret={AgentSecret}"; var json = webClient.DownloadString(address); var result = JsonConvert.DeserializeObject <TokenResultModel>(json); if (result.ErrCode != 0) { throw new Exception(result.ErrMsg); } var accessToken = result.AccessToken; var expiresAt = DateTime.Now.AddSeconds(result.ExpiresIn); cache = new TokenCacheModel { AccessToken = accessToken, ExpiresAt = expiresAt }; TokenCache[AgentId] = cache; return(cache); } }
/// <summary> /// 核对缓存中是否存在token以及token的有效性 /// </summary> /// <param name="cachename">缓存名称</param> private string CheckCacheToken() { TokenCacheModel token = TokenCache.GetCacheToken(CacheName); if (token != null) { if (TimeHelper.GetTimeSecond() >= (token.TokenClaim.Exp - 60)) { return(null); } else { return(token.TokenStr); } } return(null); }