我们经常在微信公众号开发的时候,会遇到获取token的问题,虽然官方提供了api接口,但是作为资深开发者,我们可以使用第三方的工具,快速解决获取token以及校验token是否有效,下面我就给大家说一下如何使用
引入jar包
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>3.7.0</version>
</dependency>
这里我们使用的是 [(gitee.com/binary/weix…)] 大家可以访问地址去看官方的文档
配置微信公众号工具类
/**
* 微信配置
* @author admin
*
*/
@Configuration
public class WxConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Bean
public JedisPool redisPoolFactory() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(200);
return new JedisPool(jedisPoolConfig, host, port, 0, null, 1);
}
@Bean
public WxMpService wxMpService(){
WxMpService wxMpService = new WxMpServiceImpl();
WxMpRedisConfigImpl config =new WxMpRedisConfigImpl(redisPoolFactory());
config.setAppId("xxxxxxxx"); // 设置微信公众号的appid
config.setSecret("xxxxxxxx"); // 设置微信公众号的app corpSecret
config.setToken("xxxx"); // 设置微信公众号的token
config.setAesKey("xxxxxxxxxxxxxxxxxxxxxxxxxxxx"); // 设置微信公众号的EncodingAESKey
wxMpService.setWxMpConfigStorage(config);
return wxMpService;
}
}
获取token
public String getAccessToken() {
try {
return wxMpService.getAccessToken();
} catch (WxErrorException e) {
e.printStackTrace();
}
return "";
}
有的同学就会问了,accesstoken获取到了,不需要存放吗,其实有心的会看到了,其实这个工具类已经将token存入到了redis中。所以我们获取的时候,工具类会先去redis里查找。查找到后看一下是否过期,如果过期了,会再重新获取,在存到redis中。我们可以去源码中看一下
大家看到上面的截图就知道了,所以推荐大家使用 班纳睿的加这个微信jar包,官方还提供了很多的版本