
搞事情
- 小程序wxml文件中增加授權(quán)標(biāo)簽
# 授權(quán)按鈕,綁定用戶點(diǎn)擊后的方法 getPhoneNumber()
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">{{quickLoginTitle}}</button>
- 在小程序js文件中增加getPhoneNumber方法
getPhoneNumber: function (e) {
// 參數(shù)e是綁定的授權(quán)方法自動(dòng)傳入過來的, 主要是為了拿到vi和encryptedData值從后臺(tái)換取用戶聯(lián)系方式
if ("getPhoneNumber:ok" != e.detail.errMsg){
wx.showToast({
icon:'none',
title: '快捷登陸失敗'
})
return;
}
var iv = e.detail.iv;
var encryptedData = e.detail.encryptedData;
// this.data.wxCode, 定義wxCode變量,并在onShow()方法中調(diào)用小程序login方法獲取code值賦予this.data.wxCode
var code = this.data.wxCode;
var _this = this;
//調(diào)用后臺(tái)接口獲取用戶手機(jī)號碼
api.sendPost({
url: api.decode_phone,
params:{
encrypted: encryptedData,
iv:iv,
code:code
},
success:function(data){
// 獲取到的手機(jī)號碼
var phone = data.phone;
},
fail:function(msg){
})
}
- 在后臺(tái)增加接口
@RequestMapping(value = "decode/wxapp/phone", method = RequestMethod.POST)
@Override
public Result<JSONObject> decodeWxAppPhone(
@RequestParam(value = "encrypted") String encrypted,
@RequestParam(value = "iv") String iv,
@RequestParam(value = "code") String code) {
return Result.success(userService.decodeWxAppPhone(encrypted, iv, code));
}
- userService.decodeWxAppPhone 內(nèi)部實(shí)現(xiàn)邏輯
// 定義微信解密獲取手機(jī)號碼的接口地址,固定的
String wxAppHost = "https://api.weixin.qq.com";
String wxAppPath = "/sns/jscode2session"
String wxAppId = "自己的appid"
String wxAppSecret = "自己的wxAppSecret"
public JSONObject decodeWxAppPhone(String encrypted, String iv, String code) {
String path =
wxAppPath
+ "?appid="
+ wxAppId
+ "&secret="
+ wxAppSecret
+ "&js_code="
+ code
+ "&grant_type=authorization_code";
try {
// 向微信服務(wù)器發(fā)送get請求獲取加密了的內(nèi)容
HttpResponse response = HttpUtils.doGet(wxAppHost, path, "GET", null, null);
String jsonStr = EntityUtils.toString(response.getEntity());
JSONObject jsonObject = JSON.parseObject(jsonStr);
String sessionkey = jsonObject.getString("session_key");
// 解密
byte[] encrypData = Base64Utils.decodeFromString(encrypted);
byte[] ivData = Base64Utils.decodeFromString(iv);
byte[] sessionKey = Base64Utils.decodeFromString(sessionkey);
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(sessionKey, "AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
String resultString = new String(cipher.doFinal(encrypData), "UTF-8");
JSONObject object = JSONObject.parseObject(resultString);
// 拿到手機(jī)號碼
String phone = object.getString("phoneNumber");
// 返回手機(jī)號碼
JSONObject returnObject = new JSONObject();
returnObject.put("phone", phone);
return returnObject;
} catch (Exception e) {
log.error("微信小程序手機(jī)號碼解密異常,信息如下:", e);
}
}