按钮HTML
<button type='warn'
open-type="getPhoneNumber"
@getphonenumber="getPhoneNumber"
class="mini-btn">授权登录</button>
WXBizDataCrypt.js
var crypto = require('crypto');
var jiemi = function (appId, sessionKey,encryptedData, iv) {
// base64 decode
var sessionKey = new Buffer(sessionKey, 'base64')
encryptedData = new Buffer(encryptedData, 'base64')
iv = new Buffer(iv, 'base64')
try {
// 解密
var decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv)
// 设置自动 padding 为 true,删除填充补位
decipher.setAutoPadding(true)
var decoded = decipher.update(encryptedData, 'binary', 'utf8')
decoded += decipher.final('utf8')
decoded = JSON.parse(decoded)
} catch (err) {
console.log(err);
}
return decoded
};
module.exports = {
jiemi:jiemi
}
Js方法
var WXBizDataCrypt = require('../../common/WXBizDataCrypt.js');
export default {
data() {
return {
wxCode:""
}
},
onLoad() {
var _self = this;
wx.login({
success (res) {
if (res.code) {
_self.wxCode = res.code;
}
}
});
},
methods: {
getPhoneNumber:function(e){
if (e.detail.errMsg != 'getPhoneNumber:fail user deny') { //允许授权
var encryptedData = e.detail.encryptedData;
var iv = e.detail.iv;
console.log("encryptedData-> "+encryptedData);
console.log("iv-> "+iv);
$.Post({t:"wx_xcx_login",code:this.wxCode},function(res){
console.log(res);
var res2 = res.res;
var resObj = JSON.parse(res2);
var appId = res.appid;
var sessionKey = resObj.session_key;
var openId = resObj.openid;
var unionid = resObj.unionid;
console.log("appId-> "+appId);
console.log("sessionKey-> "+sessionKey);
console.log("openId-> "+openId);
console.log("unionid-> "+unionid);
var data = WXBizDataCrypt.jiemi(appId, sessionKey,encryptedData, iv);
console.log('------------------->');
console.log('解密后 data: ', data);
});
}else{
console.log("fail user deny");
}
}
}
}
后端:wx_xcx_login
if("wx_xcx_login".equals(t)){
String code = $.get("code");
String appid = "wx13马赛克ff9";
String appsecret = "55ca98f马赛克马赛克b91370ce4";
if(!$.empty(code)){
String result = $.httpGet("https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+appsecret+"&js_code="+code+"&grant_type=authorization_code");
if(!$.empty(result)){
Map info = $.gson.fromJson(result,Map.class);
String openid = (String)info.get("openid");
if(!$.empty(openid)){
$.json("status",1).json("appid",appid).json("openId",openid).json("res",result).out();
}
}
}
}
感谢您的支持,写的文章如对您有所帮助,开源不易,请您打赏,谢谢啦~