微信小程序获取用户手机号有2种,一种是前端自己解密,一种是获取后发给后端,后端去解密
重点:要在微信公众平台设置里面绑定微信开放平台账号,不然反解不出来用户手机号上代码:
<button style="font-size: 16px;" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">授权并获取手机号</button>
import WXBizDataCrypt from "@/util/WXBizDataCrypt.js"
onGetPhoneNumber(e){uni.login({provider: 'weixin',success: function ({ code }) {uni.request({url: 'https://api.weixin.qq.com/sns/jscode2session', // 请求微信服务器method: 'GET',data: {appid: '', //你的小程序的APPIDsecret: '', //你的小程序秘钥secret, js_code: code, //uni.login 登录成功后的codegrant_type: 'authorization_code' //此处为固定值},success: (res) => {console.log('获取信息', res.data);console.log(e, "获取手机号需要的参数");let pc = new WXBizDataCrypt('你的小程序的APPID', res.data.session_key);let data = pc.decryptData(e.detail.encryptedData, e.detail.iv);if (data.phoneNumber != '') {console.log(data.phoneNumber)}}});},fail: function (err) {uni.showToast({ title: '请前往小程序使用完整服务', icon: 'none' });reject(err);},})
}
官网文件获取路径
WXBizDataCrypt.js 文件
这个链接里面有解密包或者直接用我下面的代码var crypto = require('crypto')function WXBizDataCrypt(appId, sessionKey) {this.appId = appIdthis.sessionKey = sessionKey
}WXBizDataCrypt.prototype.decryptData = function (encryptedData, iv) {// base64 decodevar 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