拒绝造轮子 - 微信API开发工具包
在开发中, 有时候需要对接微信相关的API, 虽然不复杂, 但是写起来还是有点耗费时间的, 现在有一个优秀的开源工具包, 它封装了微信支付、开放平台、公众号、企业号、企业微信、小程序等API, 我们只需要引入该依赖, 就能轻松调用微信相关API, 能节省不少时间.
该项目Gitee和Github地址:
https://gitee.com/binary/weixin-java-tools
https://github.com/Wechat-Group/WxJava
该项目说明文档:
https://github.com/Wechat-Group/WxJava/wiki/%E5%85%AC%E4%BC%97%E5%8F%B7%E5%BC%80%E5%8F%91%E6%96%87%E6%A1%A3
1.使用Maven引入依赖
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>(不同模块参考下文)</artifactId>
<version>4.3.0</version>
</dependency>
微信小程序:weixin-java-miniapp
微信支付:weixin-java-pay
微信开放平台:weixin-java-open
公众号:(包括订阅号和服务号):weixin-java-mp
企业号/企业微信:weixin-java-cp
2.增加一个配置类
package com.ruoyi.auth.form;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WxConfiguration {
@Bean
public WxMaConfig wxMaConfig(){
WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
// 设置微信小程序的AppId
config.setAppId("...");
// 设置微信小程序的Secret
config.setSecret("...");
return config;
}
@Bean
public WxMaService wxMaService(WxMaConfig wxMaConfig){
WxMaService wxService = new WxMaServiceImpl();
wxService.setWxMaConfig(wxMaConfig);
return wxService;
}
}
注意, 上面配置类中的 WxMaConfig 、WxMaDefaultConfigImpl 、WxMaService 、WxMaServiceImpl 是微信小程序工具模块相关类, 如果使用其他模块, 需要换成相应的类. 这里只是一个使用流程示例.
3.在程序中愉快地使用WxMaService的相关接口.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WxMaController {
@Autowired
private WxMaService wxMaService;
public void test(){
String accessToken = wxMaService.getAccessToken();
}
}