剑轩

.net 微信开发获取access_token,使用缓存处理token过期

电脑版发表于:2019/6/11 8:26


获取access_token很简单,使用httpclient发起一个请求就可以了,我们使用redis做一下缓存处理

  public static string GetToken()
        {
            RedisClient redis = new RedisClient();

            //从缓存中获取access_token
            string gtoken = redis.Get<string>("access_token");
            if (!string.IsNullOrEmpty(gtoken)) 
            {
                return gtoken;
            }

            HttpClient client = new HttpClient();
            //根据账户信息获取token
            string token = client.GetStringAsync("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appid&secret=secret").Result;
            DTO_Accesstoken acess_token = JsonConvert.DeserializeObject<DTO_Accesstoken>(token);

            //当token过期的时候就请求一次,放入缓存      
            redis.Set<string>("access_token", acess_token.access_token, TimeSpan.FromSeconds(acess_token.expires_in - 20));

            return acess_token.access_token;
        }


关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢