最近对接开发微信小程序,需要获取用户的openid使用支付,所以记下这篇通用小程序授权笔记。
这里使用到开源工具
此致 致敬 大佬
maven引入如下
<!-- https://mvnrepository.com/artifact/com.github.binarywang/weixin-java-miniapp -->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>4.3.3.B</version>
</dependency>
准备参数,application配置文件需配置参数
wx:
miniapp:
appid: 微信官方申请的appid
secret: 微信官方申请的秘钥
msgDataFormat: JSON #数据可以,默认json就ok
编写WxMaProperties.java文件获取配置文件中的字段
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Data
@ConfigurationProperties(prefix = "wx.miniapp")
public class WxMaProperties {
/**
* 设置微信小程序的appid
*/
private String appid;
/**
* 设置微信小程序的Secret
*/
private String secret;
/**
* 消息格式,XML或者JSON
*/
private String msgDataFormat;
}
创建配置类WxMaConfiguration配置初始化配置
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties(WxMaProperties.class)
public class WxMaConfiguration {
@Bean
public WxMaService wxMaService(WxMaProperties properties) {
WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
config.setAppid(properties.getAppid());
config.setSecret(properties.getSecret());
config.setMsgDataFormat(properties.getMsgDataFormat());
WxMaService service = new WxMaServiceImpl();
service.setWxMaConfig(config);
return service;
}
}
controller编写授权代码
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Api(tags = "微信模块")
@RestController
@RequestMapping("/wx/auth")
@RequiredArgsConstructor
public class WxController extends BaseController {
private final WxMaService wxService;
@ApiOperation("微信登陆")
@GetMapping(value = "/getWxInfo", produces = "application/json")
@SneakyThrows(WxErrorException.class)
public WxMaJscode2SessionResult getWxInfo(@ApiParam("小程序CODE") String code){
WxMaJscode2SessionResult wx = wxService.jsCode2SessionInfo(code);
logger.info("请求微信授权完成=>{}",wx);
return wx;
}
}
非常简单,俩行代码直接搞定授权。
觉得有用的话记得给个赞,谢谢各位大佬了。