//小程序固定了获取手机号的方式 必须要用户主动触发
<button bindgetphonenumber='getPhoneNumber' open-type='getPhoneNumber'> </button>
//判断授权
getPhoneNumber(e){
var that = this;
if(e.detail.errMsg == 'getPhoneNumber:ok'){
wx.login({
success (res) {
if (res.code) {
let param={'designEffectId':that.data.designEffectId,'code':res.code,'encryptedData':e.detail.encryptedData,'iv':e.detail.iv}
//此处请求后台
} else {
console.log('获取失败!')
}
}
})
}else{
console.log("拒绝授权,无法查看")
}
}
//后台的处理方法
public void getUserMobile(HttpServletRequest request,HttpServletResponse response) {
String encryptedData = request.getParameter("encryptedData");
String iv = request.getParameter("iv");
String code = request.getParameter("code");
//利用code可获取openid和sessionKey
//获取的urlhttps://api.weixin.qq.com/sns/jscode2session?appid=你的appid&secret=你的AppSecret&js_code=接受到的code&grant_type=authorization_code";
String openid = ""//;
String sessionKey = ""
* 解析式需要的操作
* 1.下载bcprov-jdkxx-xxx.jar
2.将bcprov-jdkxx-xxx.jar放入$JAVA_HOME/jre/lib/ext下
3.打开$JAVA_HOME/jre/lib/security下的java.security文件,在末尾加上
security.provider.x=org.bouncycastle.jce.provider.BouncyCastleProvider
*/
JSONObject json = new JSONObject();
if(!StringUtil.isEmpty(encryptedData) && !StringUtil.isEmpty(sessionKey) && !StringUtil.isEmpty(iv)) {
String mobileStr = WechatDecryptDataUtil.wxDecrypt(encryptedData, sessionKey, iv);
//mobileStr的数据{"phoneNumber":"152********","purePhoneNumber":"152********","countryCode":"86","watermark":{"timestamp":1605842111,"appid":""}}
} try {
Writer out = response.getWriter();
out.write(json.toString());
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}