- 官方的解释
前端代码
- 使用的是uni
- 一定要尽量保证uni.login和获取用户信息wx.getWeRunData api一起请求,尽量避免在后台储存session_key
uni.getProvider({
service: 'oauth',
success: function(res) {
console.log(res.provider)
if (~res.provider.indexOf('weixin')) {
uni.login({
success(res) {
if (res.code) {
code = res.code;
// #ifdef MP-WEIXIN
wx.getWeRunData({
async success(res) {
res.code = code;
const step = await getStep(res);//调用后台接口进行解密
}
})
// #endif
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
}
}
});
后台代码
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