view部分代码写法:
<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" withCredentials="true">立即登录</button>
编写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
获取电话号码核心代码:
//获取电话号码
import WXBizDataCrypt from "@/common/WXBizDataCrypt.js"
getPhoneNumber(e){
uni.login({
provider:"weixin",
scopes:"auth_base",
onlyAuthorize:true,
success:res=> {
userMessage(res.code).then((res)=>{
this.openid = res.data.openid
this.sessionkey = res.data.session_key
if(e.detail.errMsg=='getPhoneNumber:ok'){
this.iv=e.detail.iv;
this.encryptedData=e.detail.encryptedData
//对用户的电话号进行解密,这里的WXBizDataCrypt需要引入
let sessionkey = new WXBizDataCrypt(this.appid,this.sessionkey);
let data = sessionkey.decryptData(this.encryptedData,this.iv);
this.countryCode=data.countryCode;
this.phoneNumber=data.phoneNumber;
}
})
}
})
}
api.js中userMessage写法:appid和secret在微信公众平台上有
//获取微信的接口凭证openid 和 sessionkey
export function userMessage(code) {
return new Promise((resolve, reject) => {
uni.request({
url: 'https://api.weixin.qq.com/sns/jscode2session',
method: 'GET',
data: {
appid: '你的appid',
secret: '你的secret',
js_code: `${code}`,
grant_type: 'authorization_code'
},
success: res => {
resolve(res);
}
})
})
}