微信官方提供的信息還要手寫內(nèi)部轉(zhuǎn)發(fā)奕锌,太麻煩了钩蚊。本著省事的原則烹困,找到了開源wxjava來進(jìn)行一些小程序獲取授權(quán)和手機(jī)號(hào)的操作
- 引入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;
}
}
- 實(shí)體
WechatLogin
,如果不使用可以忽略
@Data
public class WechatLogin {
@ApiModelProperty("用戶登錄憑證")
private String code;
@ApiModelProperty("原始數(shù)據(jù)字符串")
private String signature;
@ApiModelProperty("校驗(yàn)用戶信息字符串")
private String rawData;
@ApiModelProperty("手機(jī)號(hào)加密用戶數(shù)據(jù)")
private String phoneEncryptedData;
@ApiModelProperty("手機(jī)號(hào)加密算法的初始向量")
private String phoneIv;
@ApiModelProperty("基本信息加密用戶數(shù)據(jù)")
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;
}
/**
* 解密手機(jī)號(hào)碼信息
*/
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("解密手機(jī)號(hào)碼信息錯(cuò)誤");
}
return wxMaPhoneNumberInfo;
}