页面button
<button class="bottom2" type="default" open-type="getPhoneNumber" @getphonenumber="clos_">允许</button>
js代码处理
clos_ (e) {
console.log('请求1111', e.detail);
var a = ''
//#ifdef H5
if (this.state.tel) {
a = '?tel=' + this.state.tel
}
this.$refs.popup.close()
uni.navigateTo({
url: '/pages/My/Bindingsj/index' + a
})
// #endif
// #ifdef MP-WEIXIN
if (this.state.tel) {
a = '?tel=' + this.state.tel
}
if (e.detail.errMsg == 'getPhoneNumber:fail user deny') { //用户点击拒绝
uni.navigateTo({
url: '/pages/My/Bindingsj/index',
})
} else { //允许授权执行跳转
if (e.detail.code) {
getwxphone({//后端接口,传参code后端解析手机号
code: e.detail.code,
bsCode: wx.getStorageSync("bsCode"),
}).then(ress => {
if (ress.code == 200) {
// 是否绑定手机
savemicrotempphone({
bsGuid: wx.getStorageSync("bsGuid"),
tmpGuid: wx.getStorageSync("tmpGuid"),
phone: ress.data
}).then(result => {
if (result.code == 200) {
this.querygetWxUser()//执行代码片段,可自行编写
}
})
}
})
} else {
//重点,部分手机获取不到code,后端无法解析出手机号,前端自行解析。
const accountInfo = uni.getAccountInfoSync();
console.log(accountInfo);
console.log(accountInfo.miniProgram.appId); // 小程序 appId
var WXBizDataCrypt = require('@/utils/WXBizDataCrypt.js')
var appId = accountInfo.miniProgram.appId
var sessionKey = JSON.parse(wx.getStorageSync("user")).session_key
var encryptedData = e.detail.encryptedData
var iv = e.detail.iv
var pc = new WXBizDataCrypt(appId, sessionKey)
var data = pc.decryptData(encryptedData, iv)
console.log('解密后 data: ', data)
savemicrotempphone({
bsGuid: wx.getStorageSync("bsGuid"),
tmpGuid: wx.getStorageSync("tmpGuid"),
phone: data.phoneNumber
}).then(result => {
if (result.code == 200) {
this.querygetWxUser()//执行代码
}
})
}
}
// #endif
//更换手机号
this.$refs.popup.close() //关闭
//
},
WXBizDataCrypt.js文件内容
var crypto = require('crypto')
function WXBizDataCrypt(appId, sessionKey) {
this.appId = appId
this.sessionKey = sessionKey
}
WXBizDataCrypt.prototype.decryptData = function (encryptedData, iv) {
// base64 decode
var sessionKey = new Buffer(this.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) {
throw new Error('Illegal Buffer')
}
if (decoded.watermark.appid !== this.appId) {
throw new Error('Illegal Buffer')
}
return decoded
}
module.exports = WXBizDataCrypt