第一步.
调用wx.login 获取code
uni.login({
provider: 'weixin',
success(res) {
if (res.errMsg === 'login:ok') {
return resolve({access_token, code: res.code})
} else {
return reject()
}
}
})
第二步.
根据code去获取session_key
get请求?https://api.weixin.qq.com/sns/jscode2session
/**
* @author
*/
@Data
@Component
@ConfigurationProperties(prefix = "wx.config")
public class WxMaProperties {
/**
* 设置微信小程序的appid
*/
private String appid;
/**
* 设置微信小程序的Secret
*/
private String secret;
/**
* 设置微信小程序消息服务器配置的token
*/
private String token;
/**
* 设置微信小程序消息服务器配置的EncodingAESKey
*/
private String aesKey;
/**
* 消息格式,XML或者JSON
*/
private String msgDataFormat;
}
/**
* 微信小程序获取OPENID
*/
String WX_AUTHORIZATION_CODE_URL = "https://api.weixin.qq.com/sns/jscode2session" +
"?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
public R getOpenId(String code){
String url = String.format(SecurityConstants.WX_AUTHORIZATION_CODE_URL
, wxMaProperties.getAppid(), wxMaProperties.getSecret(), code);
String result = restTemplate.getForObject(url, String.class);
//log.info("微信响应报文:{}", result);
ObjectMapper objectMapper = new ObjectMapper();
OpenIdDto openIdDto;
try {
openIdDto = objectMapper.readValue(result, OpenIdDto.class);
}catch (Exception e){
e.printStackTrace();
return new R(-1,"解析微信结果出错");
}
return new R(openIdDto);
}
@Data
public class OpenIdDto {
private String openid;
private String session_key;
}
第三步,
将接口返回的session_key.?
<button class="cu-btn" open-type="getPhoneNumber" @getphonenumber="getPhone" >获取微信授权</button>
wx接口的iv,?encryptedData,? 放进工具类解密
methods: {
getPhone(e) {
console.log(e.detail.errMsg)
console.log(e.detail.iv)
console.log(e.detail.encryptedData)
}
}
手机号, 用户信息都已经测试过,可以使用
解密方法如下
public class DecodeUtil {
/**
* 解密工具直接放进去即可
*/
public static String decryptS5(String encryptedData, String sessionKey, String ivParameter) {
try {
Base64.Decoder decoder = Base64.getDecoder();
byte[] raw = decoder.decode(sessionKey);
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
IvParameterSpec iv = new IvParameterSpec(decoder.decode(ivParameter));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] myendicod = decoder.decode(encryptedData);
byte[] original = cipher.doFinal(myendicod);
return new String(original, "utf-8");
} catch (Exception ex) {
return null;
}
}
}
?
|