小程序前端代码
// 登录
login(){
wx.login({
success:loginRes => {
if (loginRes.code) {
wx.getUserInfo({
success: user => {
uni.request({
url:"http://192.168.0.22:8666/wxLogin",
method:"POST",
data:{
code:loginRes.code,
encryptedData:user.encryptedData,
iv:user.iv
},
success:reqRes => {
console.log(reqRes)
}
})
}
})
} else {
console.log('登录失败!' + user.errMsg)
}
}
})
}
node代码
需要安装:
npm install crypto-js
npm install js-base64
注意: appid和secret要换掉 切记无脑copy
/**
*封装的工具类(可以直接copy使用)
*
*/
const request = require('request')
const CryptoJS = require('crypto-js')
const Base64 = require('js-base64')
const { resolve } = require('path')
class WechatUtil {
constructor() {
this.reqUrl = "https://api.weixin.qq.com/sns/jscode2session"
this.appid = "你的微信小程序appid"
this.secret = "你的微信小程序secret "
this.grant_type = "authorization_code"
this.openId = null
this.sessionKey = null
}
getOpenId(){
return this.openId
}
getSessionKey(){
return this.sessionKey
}
// 获取 sessionKey openid
getSessionKeyOropenid(code) {
return new Promise((resolve, reject) => {
let url = `${this.reqUrl}?appid=${this.appid}&secret=${this.secret}&js_code=${code}&grant_type=${this.grant_type}`
request.post(url, {}, (error, res, body) => {
if (error) {
console.error(error)
reject(error)
}
if(res.statusCode == 200){
let jsonBody = JSON.parse(body)
this.openId = jsonBody.openId
this.sessionKey = jsonBody.session_key
resolve(this.sessionKey)
}
})
})
}
// 解密获取用户信息
getWechatUserInfo(encryptedData, ivv, sessionKey) {
if(!sessionKey){
sessionKey = this.sessionKey
}
let key = CryptoJS.enc.Base64.parse(sessionKey)
let iv = CryptoJS.enc.Base64.parse(ivv)
let decrypt = CryptoJS.AES.decrypt(encryptedData, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
})
return JSON.parse(Base64.decode(CryptoJS.enc.Base64.stringify(decrypt)))
}
}
module.exports = WechatUtil
调用方式
// 微信小程序登录
const WechatUtil = require("../utils/WechatUtil")
const wechatUtil = new WechatUtil()
router.post("/wxLogin", (req, res, next) => {
const { code, encryptedData, iv } = req.body
wechatUtil.getSessionKeyOropenid(code).then(e => {
// 获取微信用户信息
const wechatUserInfo = wechatUtil.getWechatUserInfo(encryptedData, iv)
res.json({
msg: "登录成功",
data: wechatUserInfo
})
}).catch(err => {
res.json({
msg: "授权失败",
error: err
})
})
})
前端请求结果