详解微信开发之access_token之坑
作者:slanf 时间:2022-09-04 16:49:30
首先不得不提到access_token的分类,一是普通access_token,二是网页授权access_token。其中前者是用于调用微信提供的各种借口,作为开发者的调用凭证,一般有效期为7200S,获取次数受限;另一种是第三方网页若需要使用用户微信账户登录,需要获取该access_token从而来获取用户微信账户信息。这个一定得区分开。
另外获取用户微信账户信息也有两种情况,一是普通的获取用户信息,它只需要调用微信用户信息接口即可获取,因而使用到的是第一种普通access_token,另一种就是上面提到的网页授权时获取用户信息。一旦二者概念混淆,则会报出invalid access_token错误。
对于第一种普通access_token,需要注意到的是,它是全局性的,就是一旦获取到了新的access_token,原有的access_token就会失效,而无法调用相关接口。而这种特性,导致的情况是,多个不同进程相互独立获取access_token时,会直接影响到其他进程调用相关微信接口,这种异常通常对应着 access_token失效异常。
为了解决这种情况,必须独立启动一个线程定时去获取access_token,并由该线程向所有其他线程提供该access_token,从而避免access_token获取混乱导致的失效问题。我实现该想法的方式是采用timer定时器,定时刷新获取access_token,并将其存入到指定property文件中,其他线程通过读取该文件中的access_token值,来调用相关接口。
@Controller
@RequestMapping(value = "/timer")
public class AcessTokenTimer {
private static final String APPID = "*************";
private static final String APPSECRET = "*********";
private Timer timer = new Timer(true);
@PostConstruct
public void setToken(){
if(null == timer){
timer = new Timer(true);
}
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try {
SystemUtil.setString("token.properties","access_token", UrlGETUtil.GET("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APPID+"&secret="+APPSECRET).getString("access_token"));
}catch (Exception e){
e.printStackTrace();
}
}
},0,3600*1000);
}
}
在定时器任务中获取和写入access_token值。该类基于SpringMVC框架,此处用到了@PostConstruct标签,它的作用是,在Spring框架初始化完成之后,及执行对应方法体,直白地说就是开机自启。
access_token失效和刷新
目前想到的比较理想的解决方案就是:服务器发现功能异常时,刷新access_token并更新redis,然后再次调用接口。
来源:https://blog.csdn.net/u013248535/article/details/52613632
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android如何动态调整应用字体大小详解
![](https://img.aspxhome.com/file/2023/5/120175_0s.gif)
java 用itext设置pdf纸张大小操作
Java Stream流零基础教程
android studio3.0.1无法启动Gradle守护进程的解决方法
![](https://img.aspxhome.com/file/2023/0/92600_0s.png)
Spring FreeMarker整合Struts2过程详解
![](https://img.aspxhome.com/file/2023/9/62169_0s.jpg)
Java中的collection集合类型总结
![](https://img.aspxhome.com/file/2023/4/122954_0s.jpg)
Mybatis一对一延迟加载实现过程解析
java实现二分法的完整代码
java String校招面试题过程详解
![](https://img.aspxhome.com/file/2023/1/95461_0s.png)
C#通过流写入一行数据到文件的方法
c++中的malloc底层实现代码
![](https://img.aspxhome.com/file/2023/3/105183_0s.jpg)
idea快速搭建spring cloud注册中心与注册的方法
![](https://img.aspxhome.com/file/2023/5/84775_0s.png)
一文看懂JAVA设计模式之工厂模式
![](https://img.aspxhome.com/file/2023/8/60338_0s.png)
Mybatis之#{}与${}的区别使用详解
Java实现五子棋网络版
![](https://img.aspxhome.com/file/2023/2/63382_0s.png)
Java编程计算兔子生兔子的问题
获取Java线程转储的常用方法(推荐)
![](https://img.aspxhome.com/file/2023/8/61248_0s.png)
SpringMVC整合mybatis实例代码
输出的文本实现对齐的方法(超简单)
![](https://img.aspxhome.com/file/2023/1/66581_0s.jpg)