故如虹,知恩;故如月,知明
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术

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

6123人阅读 2019/6/11 8:26 总访问:3904188 评论:0 收藏:0 手机
分类: 微信


获取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;
        }


欢迎加群讨论技术,群:677373950(满了,可以加,但通过不了),2群:656732739

评价