微信小程序授权获取手机号
1、先调用wx.login(),获取到code,code为用户登录凭证(有效期五分钟);
2、点击授权获取手机号;
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber"></button>
getPhoneNumber (e) {
console.log(e.detail.iv)
console.log(e.detail.encryptedData)
}
3、将code、iv、encryptedData传给后台解析获取手机号4、后台接口实现如下,使用nodejs
const rp = require('request-promise'); const crypto = require('crypto'); async function getSessionKey(code) {//通过code获取 OpenID 和 session_key try { let options = { method: 'GET', url: 'https://api.weixin.qq.com/sns/jscode2session', qs: { grant_type: 'authorization_code', js_code: code, secret: "小程序密钥", appid: "小程序appid" } }; let sessionData = await rp(options); sessionData = JSON.parse(sessionData); if (sessionData.session_key) { return sessionData.session_key; } } catch (e) { return null; } } async function getPhone(code, iv, encryptedData) {//通过code, iv, encryptedData解密手机号 let session_key = await getSessionKey(code); let sessionKey = Buffer.from(session_key, 'base64'); encryptedData = Buffer.from(encryptedData, 'base64'); iv = Buffer.from(iv, 'base64'); let decoded; try { var decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv);// 解密 decipher.setAutoPadding(true);// 设置自动 padding 为 true,删除填充补位 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 !== "小程序appid") {//替换为真实appid throw new Error('appid错误'); } return decoded; }