此篇可在实用教程10(见下方链接)的基础上继续开发,也可以在任何微信小程序中直接使用。
https://blog.csdn.net/weixin_41192489/article/details/128835069
用户登录鉴权逻辑
核心技术:通过云函数获取用户的openid
要想使用云函数,需先开通并初始化云环境,可参考下方链接进行配置
https://blog.csdn.net/weixin_41192489/article/details/128797403
创建云函数 get_openid
在 cloudfunctions 文件夹上点击鼠标右键的快捷菜单中选择新建 Node.js 云函数
命名为 get_openid,便会自动生成默认的云函数。
cloudfunctions\get_openid\config.json
{ "permissions": { "openapi": [ ] } }
cloudfunctions\get_openid\index.js
// 云函数入口文件 const cloud = require('wx-server-sdk') cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境 // 云函数入口函数 exports.main = async (event, context) => { const wxContext = cloud.getWXContext() return { event, openid: wxContext.OPENID, appid: wxContext.APPID, unionid: wxContext.UNIONID, } }
cloudfunctions\get_openid\package.json
{ "name": "get_openid", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "wx-server-sdk": "~2.6.3" } }
上传部署云函数
在目标云函数上右键快捷菜单选择上传并部署
云函数前的文件夹变成绿色,即表示部署成功。
删除云函数
仅在本地无法删除云函数,需先去微信云函数控制台删除该云函数才行!
云端删除后,回到本地同步云函数列表
此时该云函数的文件夹从绿色变成灰色,右键快捷菜单删除即可。
使用云函数
getOpenID() { return new Promise((resolve) => { wx.cloud.callFunction({ name: 'get_openid' // 云函数的名称 }).then(res => { // 从云函数返回的结果中提取出目标数据 resolve(res.result.openid); }) }) },
小程序启动时,开始用户登录鉴权
app.js 的 onLaunch 中
// 生命周期--小程序启动时执行 async onLaunch() { const openid = await this.getOpenID(); this.login(openid) }
用户登录鉴权的实现
app.js
login(openid) { let that = this wx.cloud.database().collection('user').where({ _openid: openid }).get().then(res => { // 查询openid是否已注册(是否在 user 表中) let data = res.data if (data.length > 0) { let userInfo = data[0] // 判断openid是否审核通过(有No) if (userInfo.No) { // 审核通过,保持进入页,将用户信息写入缓存 wx.setStorageSync('userInfo', userInfo) } else { // 已注册但待审核,跳转到注册页查看审核状态 that.gotoRegister("已注册") } } else { // 未注册,跳转到注册页注册 that.gotoRegister("注册") } }) }, gotoRegister(type) { wx.reLaunch({ url: '/pages/register/index?type=' + type }) },