spring boot整合第三方微信开发工具 weixin-java-miniapp 实现小程序微信登录
有时候项目需要用到微信登录或获取用户的手机号码,weixin-java-miniapp是一个好用的第三方工具,不用我们自己写httpcline调用。
导入jar包
<dependency> <groupId>com.github.binarywang</groupId> <artifactId>weixin-java-miniapp</artifactId> <version>4.1.0</version> </dependency>
添加一个resource.properties文件,写上小程序的appid和secret
wx.miniapp.appid: xxxxxxxxxxxx wx.miniapp.secret: xxxxxxxxxxxxxxxxxxxxxxxxxx wx.miniapp.msgDataFormat: JSON
添加两个配置文件
WxMaProperties.java
@ConfigurationProperties(prefix = "wx.miniapp") public class WxMaProperties { /** * 设置微信小程序的appid */ private String appid; /** * 设置微信小程序的Secret */ private String secret; /** * 消息格式,XML或者JSON */ private String msgDataFormat; public String getAppid() { return appid; } public void setAppid(String appid) { this.appid = appid; } public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } public String getMsgDataFormat() { return msgDataFormat; } public void setMsgDataFormat(String msgDataFormat) { this.msgDataFormat = msgDataFormat; }
WxMaConfiguration.java
@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; } }
如何使用
@Autowired private WxMaService wxMaService; @ApiOperation("获取微信授权信息") @ApiImplicitParam(name = "code",value = "前端授权登录后传来的code", required = true,paramType = "query") @RequestMapping(value = "/wechatSession", method = RequestMethod.POST) @ResponseBody public ResponseResult wechatSession(@RequestParam String code) { //获取openId、unionid、session_key WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code); } @ApiOperation("小程序手机号登录") @ApiImplicitParams({ @ApiImplicitParam(name = "sessionKey", value = "sessionKey", paramType = "query", dataType = "string", required = true), @ApiImplicitParam(name = "encryptedData", value = "加密串", paramType = "query", dataType = "string", required = true), @ApiImplicitParam(name = "iv", value = "偏移量", paramType = "query", dataType = "string", required = true) }) @RequestMapping(value = "/wechatLogin", method = RequestMethod.POST) @ResponseBody public ResponseResult wechatLogin(HttpServletRequest request, @RequestParam @NotBlank(message = "sessionKey不能为空") String sessionKey, @RequestParam @NotBlank(message = "加密串不能为空") String encryptedData, @RequestParam @NotBlank(message = "偏移串不能为空") String iv) { WxMaPhoneNumberInfo phoneInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv); return phoneInfo.getPurePhoneNumber(); }