微信官方提供的信息还要手写内部转发,太麻烦了。本着省事的原则,找到了开源wxjava来进行一些小程序获取授权和手机号的操作
- 引入jar
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>3.6.0</version>
</dependency>
- 配置SpringBean,
WechatConfig
/**
* 微信小程序配置类
*/
@SpringBootConfiguration
public class WechatConfig {
@Value("${wechat.appid}")
private String appId;
@Value("${wechat.secret}")
private String secret;
@Bean
public WxMaConfig wxMaConfig() {
WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
config.setAppid(appId);
config.setSecret(secret);
config.setMsgDataFormat("JSON");
return config;
}
@Bean
public WxMaService wxMaService(WxMaConfig maConfig) {
WxMaService service = new WxMaServiceImpl();
service.setWxMaConfig(maConfig);
return service;
}
}
- 实体
WechatLogin
,如果不使用可以忽略
@Data
public class WechatLogin {
@ApiModelProperty("用户登录凭证")
private String code;
@ApiModelProperty("原始数据字符串")
private String signature;
@ApiModelProperty("校验用户信息字符串")
private String rawData;
@ApiModelProperty("手机号加密用户数据")
private String phoneEncryptedData;
@ApiModelProperty("手机号加密算法的初始向量")
private String phoneIv;
@ApiModelProperty("基本信息加密用户数据")
private String basicEncryptedData;
@ApiModelProperty("基本信息加密算法的初始向量")
private String basicIv;
@ApiModelProperty("图片地址")
private String avatarUrl;
}
- 一些基本操作
/**
* 获取用户登录Session
*/
public WxMaJscode2SessionResult getWechatSession(WechatLogin wechatLogin) {
WxMaJscode2SessionResult session = null;
try {
// 获取微信用户session
session = wxMaService.getUserService().getSessionInfo(wechatLogin.getCode());
if (null == session) {
throw new RuntimeException("登录异常");
}
} catch (WxErrorException e) {
throw new RuntimeException("获取微信用户Session异常");
}
return session;
}
/**
* 解密微信用户信息
*/
public WxMaUserInfo getWxMaUserInfo(WxMaJscode2SessionResult wxMaJscode2SessionResult, WechatLogin wechatLogin) {
WxMaUserInfo wxUserInfo = wxMaService.getUserService().getUserInfo(wxMaJscode2SessionResult.getSessionKey(),
wechatLogin.getBasicEncryptedData(), wechatLogin.getBasicIv());
if (null == wxUserInfo) {
throw new RuntimeException("获取用户信息异常");
}
return wxUserInfo;
}
/**
* 解密手机号码信息
*/
public WxMaPhoneNumberInfo getWxMaPhoneNumberInfo(WxMaJscode2SessionResult wxMaJscode2SessionResult, WechatLogin wechatLogin) {
WxMaPhoneNumberInfo wxMaPhoneNumberInfo = wxMaService.getUserService().getPhoneNoInfo(wxMaJscode2SessionResult.getSessionKey(),wechatLogin.getPhoneEncryptedData(), wechatLogin.getPhoneIv());
if (Objects.isNull(wxMaPhoneNumberInfo) || StringUtils.isBlank(wxMaPhoneNumberInfo.getPhoneNumber())) {
throw new RuntimeException("解密手机号码信息错误");
}
return wxMaPhoneNumberInfo;
}