微信小程序实现登录授权,并将获取到的用户授权信息存储到数据库中(个人学习笔记)
1.微信小程序授权登录实现原理图(如下)
2.WXML中的代码
<view class="container">
<view class="userinfo">
<!-- 授权前 -->
<block wx:if="{{!hasUserInfo}}">
<button bindtap="getUserProfile"> 获取头像昵称 </button>
</block>
<!-- 授权后 -->
<block wx:else>
<view class="users">
<image class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
<text class="userinfo-nickname">{{userInfo.nickName}}</text>
</view>
</block>
</view>
</view>
3.JS代码
Page({
data: {
userInfo: {},
hasUserInfo: false
},
onLoad() {
const userinfo = wx.getStorageSync('userinfo') || {}
console.log(Object.keys(userinfo));
if (Object.keys(userinfo).length == 0) {
this.setData({
userInfo: userinfo,
hasUserInfo: false
})
} else {
this.setData({
userInfo: userinfo,
hasUserInfo: true
})
}
},
getUserProfile(e) {
let that = this
wx.getUserProfile({
desc: '用于获取用户个人信息',
success: function (detail) {
console.log(detail);
wx.login({
success: res => {
var code = res.code;
wx.request({
url: 'http://127.0.0.1:8888/api/wxuser',
method: 'post',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
data: {
encryptedData: detail.encryptedData,
iv: detail.iv,
code: code,
userInfo: detail.rawData
},
success: (res) => {
console.log("res:", res.data)
wx.setStorageSync('userinfo', detail.userInfo)
wx.setStorageSync('token', res.data.token)
that.setData({
userInfo: detail.userInfo,
hasUserInfo: true
})
},
fail: function () {
console.log('系统错误')
}
})
}
});
},
fail: function () {
wx.showModal({
content: '取消授权将会影响相关服务,您确定取消授权吗?',
success (res) {
if (res.confirm) {
wx.showToast({
title: '已取消授权',
duration: 1500
})
} else if (res.cancel) {
that.getUserProfile()
}
}
})
}
})
}
})
4. WXSS代码
.users {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.userinfo-avatar {
height: 260rpx;
width: 260rpx;
border-radius: 50%;
}
5.后端代码(express)
module.exports = {
jwtSecretKey: 'advance8',
expiresIn: '8640h'
}
const express = require('express')
const router = express.Router()
const wxuserHandle = require('../router_handle/wxuser')
router.post('/wxuser', wxuserHandle.wxuser)
module.exports = router
- 主要代码(如果不想多个文件,可以将wxuserHandle.wxuser这个位置内容替换为exports.wxuser的内容)
const request = require('request')
const db = require('../db/config')
const jwt = require('jsonwebtoken')
const config = require('../config')
const { jwtSecretKey } = require('../config')
exports.wxuser = (req, res) => {
let params = req.body
let code = params.code;
let encryptedData = params.encryptedData;
let iv = params.iv;
let userInfo = JSON.parse(params.userInfo)
let appid = "换成自己的appid";
let secret = "换成自己的secret";
let grant_type = "authorization_code";
let url = "https://api.weixin.qq.com/sns/jscode2session?grant_type="+grant_type+"&appid="+appid+"&secret="+secret+"&js_code="+code;
request(url, (err, response, body) => {
if (!err && response.statusCode == 200) {
let _data = JSON.parse(body)
_data.code = code
_data.session_key = ''
const wxToken = jwt.sign(_data, jwtSecretKey, { expiresIn: config.expiresIn })
const sql = `select * from wxuser where user_id = ?`
db.query(sql, _data.openid, (err, result) => {
if (err) return res.cc(err)
if (result.length === 0) {
const sql = `insert into wxuser set ?`
db.query(sql, { user_id: _data.openid, nickName: userInfo.nickName, avatar: userInfo.avatarUrl, gender: userInfo.gender }, (err, result) => {
if (err) return res.cc(err)
if (result.affectedRows !== 1) return res.cc('授权失败,请重试')
res.send({
token: 'Bearer ' + wxToken,
status: 200,
messages: 'WX 授权成功'
})
})
}else {
const sql = `update wxuser set ? where user_id = ?`
db.query(sql, [{ user_id: _data.openid, nickName: userInfo.nickName, avatar: userInfo.avatarUrl, gender: userInfo.gender }, _data.openid], (err, result) => {
if (err) return res.cc(err)
res.send({
token: 'Bearer ' + wxToken,
status: 200,
messages: 'WX1 授权成功'
})
})
}
})
} else {
res.cc('请求openid失败')
}
})
}
- 注意: 在返回token的字符串拼接时,Bearer 后面必须有一个空格
最终效果:
-
数据库中的结果 -
授权成功后存储数据结果 -
小程序演示
|