本文获取用户信息方式需要服务端配合,纯前端的可查看 微信小程序获取用户信息(纯前端)
若需获取 openid
和用户信息,可使用 wx.getUserInfo()
获取加密后的信息,传给服务端后解密。
小程序代码(uni-app 版)
<button type="primary" @click="mpWxLogin">
授权登录
</button>
async mpWxLogin() {
const {
code
} = await wx.login();
const {
encryptedData,
iv
} = await wx.getUserInfo();
// 调用服务端接口
const userInfo = await login({
code,
encryptedData,
iv
});
console.log(JSON.stringify(userInfo, null, 2));
},
服务端代码(node 版)
const crypto = require('crypto')
const axios = require('axios');
const appId = '';
const secret = '';
/**
* 微信小程序授权登录获取session_key
* @param {Object} options
* @param {String} options.code 小程序code
* @param {String} options.encryptedData 可选,存在encryptedData和iv时返回用户信息(包含unionid)
* @param {String} options.iv 可选
*/
const login = async options => {
const {
code,
encryptedData,
iv
} = options;
let url = 'https://api.weixin.qq.com/sns/jscode2session';
url += '?appid=' + appId;
url += '&secret=' + secret;
url += '&js_code=' + code + '&grant_type=authorization_code';
const { data } = await axios.get(url);
const userInfo = WXBizDataCrypt({
sessionKey: data.session_key,
encryptedData,
iv
})
return {
session_key: data.session_key,
openid: data.openid,
userInfo
}
}
/**
* 解密encryptedData 获取unionid
* @param {Object} options
* @param {String} options.sessionKey
* @param {String} options.encryptedData
* @param {String} options.iv
*/
const WXBizDataCrypt = options => {
const appId = wxConfigMp.appId;
let {
sessionKey,
encryptedData,
iv
} = options;
sessionKey = new Buffer(sessionKey, 'base64')
encryptedData = new Buffer(encryptedData, 'base64')
iv = new Buffer(iv, 'base64')
let decoded;
try {
// 解密
let decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv)
// 设置自动 padding 为 true,删除填充补位
decipher.setAutoPadding(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) {
throw new Error('Illegal Buffer')
}
return decoded
}
其他说明
官网上 wx.getUserProfile()
也能返回 encryptedData 和 iv,但亲测会报appid错误。
如果没有服务端,则可以使用 wx.getUserProfile()
获取用户信息,查看详情
其他服务端语言解密方式可见微信小程序官网