tnblog
首页
视频
资源
登录

微信公众号Access_token获取(二)

4103人阅读 2019/12/11 19:35 总访问:38143 评论:0 收藏:0 手机
分类: 微信公众号

接口调用请求说明(可参考《微信各公众号Access_token获取(一)》)

https请求方式: GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

一、创建MVC空白项目,结构如下


二、打开工具中--NuGet包管理器--程序包管理控制台(选择的默认项目为:NET58.AccessToken.Tools),执行

    1)、安装Redis插件命令:Install-Package ServiceStack.Redis

    2)、安装Json反序列化插件命令:Install-Package Newtonsoft.Json -Version 12.0.1


三、于类库AccessTokenTools类中实现方法

public class AccessTokenTools

    {

        public static string GetToken()

        {

            RedisClient redisClient = new RedisClient();

            //先从缓存获取

            string token = redisClient.Get<string>("token");

            if (token != null)

                return token;


            //缓存中没有token就从外网获取

            HttpClient httpClient = new HttpClient();


            string result = httpClient.GetAsync("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx12c33b41dd3dec1f&secret=1a25eda57598e74014b803899a60c15c")

.Result.Content.ReadAsStringAsync().Result;


            AccessTokenDTO accessTokenDTO = JsonConvert.DeserializeObject<AccessTokenDTO>(result);


            //把token写入缓存

            //设置token过期时间和缓存过期时间同步(缓存过期快一丢丢)

            redisClient.Set<string>("token", accessTokenDTO.access_token,TimeSpan.FromSeconds(accessTokenDTO.expires_in-120));


            return accessTokenDTO.access_token;

        }

    }


四、Home控制器中执行GetToken()方法

     public ActionResult Index()

        {

            string token = AccessTokenTools.GetToken();


            return View();

        }


备注:AccessTokenDTO类

 public class AccessTokenDTO

    {

        public string access_token { get; set; }

        public int expires_in { get; set; }

    }


    

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