使用 Uniapp + UniCloud 云开发微信小程序获取用户信息

3,890 阅读4分钟

我正在参加跨端技术专题征文活动,详情查看:juejin.cn/post/710123…

前言

小程序作为前端必备技能,在学习过程中会需要让自己建立一个新的框架区域,让自己抛弃掉所用的技术框架:vuereactangular等。

但是目前也有许多第三方的开源框架供大家选择,比如适配reacttaro、适配vueuniapp都是基于现有的前端框架来实现跨端开发小程序的。

uniapp作为目前算是比较完善的多端应用集成者,有着完善的开发文档,也封装了大部分小程序端的API,并且还包含了阿里云、腾讯云的UniCloud云开发技术。

uniCloud 是 DCloud 联合阿里云、腾讯云,为开发者提供的基于 serverless 模式和 js 编程的云开发平台。

相对于专注于前端开发的人员,使用uniappunicloud来开发和入门小程序是比较不错的选择,毕竟不用自己购买服务器,也不用去找个后端开发人员做接口适配。一切需求和功能都可以自己搞定,从前端到后端,从开发到上线,甚至还能发布之后经过一段时间运营还可以开通流量主赚💰。

初始化数据库

创建云数据库

👉 打开UniCloud控制台注册登录后会进入到服务空间列表。

👉 创建一个服务空间

image.png

  • 服务商选择阿里云,毕竟阿里云的速度快,空间大,而且还免费。
  • 服务空间可以自己随意命名,只要符合规则即可。

👉 创建完成之后,会自动打开创建好的当前服务空间

image.png

👉 创建第一个数据表(用户信息)

image.png

  • 创建数据表分为两种方式:
    • 空表:需要自己定义表结构和索引等信息。
    • OpenDB表:可以直接使用uniCloud封装好的表结构。

👉 添加表结构(用户信息)

image.png

🌀 打开数据表的表结构之后,里面会有unCloud默认生成的一部分配置,包含权限、自动生成的ID等信息。

🔆 用户信息主要是用户在微信授权之后获取到的,比如头像昵称openId等。

数据表结构清单可以参考uniCloud官方文档

⭐️ properties中的属性

"properties": {
    "_id": {
      "description": "ID,系统自动生成"
    },
    "nickName": {
      "bsonType": "string",
      "label": "昵称",
      "description": "用户昵称,登录获取的"
    },
    "avatarUrl": {
      "bsonType": "string",
      "label": "头像",
      "description": "用户头像图片的 URL,登录获取的"
    },
    "mp_wx_openid": {
      "bsonType": "string",
      "description": "微信小程序平台openid"
    },
    "register_date": {
      "bsonType": "timestamp",
      "description": "注册时间",
      "forceDefaultValue": {
        "$env": "now"
      }
    }
  }

初始化项目

安装编辑器

使用uniapp需要使用对应的编辑器 - HbuilderX

image.png

如果想用vscode直接去开发uniapp,可以参考# 这可能是最好、最详细的VSCode开发uni-app教程吧

创建uniapp项目

image.png

  • 左侧选择uni-app选项
  • 项目名称和保存路径自定义即可。
  • 项目模板这里选择默认模板,如果你有其他需求,可以选择其他已经是完整项目的模板
  • 勾选启用uniCloud,并选择阿里云来作为项目的云开发。

关联阿里云

👉 项目目录下有一个uniCloud目录,右键这个目录后选择关联云服务空间或项目(此处需要登录uniCloud账号) image.png

👉 勾选之前在uniCloud控制台创建的云空间

image.png

启动项目

👉 在HbuilderX编辑器上找到 运行 - 运行到小程序模拟器 - 微信开发者工具

image.png

👉 启动小程序时,同时也会启动uniCloud控制台,用于后面上传云函数等操作

image.png

👉 至此,项目初始化完成了

image.png

新建云函数

👉 uniCloud目录下有一个专门存放云函数的目录 - cloudfunctions

👉 cloudfunctions目录下右键选择新建云函数

image.png

image.png

  • 云函数名称根据自己需求去定义即可。

登录注册用户信息

页面逻辑

👉 页面上在未登录时,会有一个登录按钮,点击登录按钮之后获取用户信息。

<template>
    <view class="content">
        <view class="flex padding justify-center">
            <button class="cu-btn round bg-red" @click="getUserInfo">立即登录</button>
        </view>
    </view>
</template>

👉 提示用户授权

getUserInfo() {
    const _this = this
    uni.getUserProfile({
        desc: '用于完善会员资料',
        success: (result) => {
            _this.userInfo = result.userInfo
            _this.wxLogin()
        },
        fail: () => {
            uni.hideLoading();
            uni.showModal({
                content: '获取用户信息失败',
                showCancel: false
            })
        }
    })
},
  • getUserProfile是uniapp封装的微信小程序api,用来获取用户信息授权

👉 调用云函数保存用户信息

wxLogin() {
    const _this = this
    uni.showLoading({
        title: '加载中'
    });

    uni.login({
        provider: 'weixin',
        success: (res) => {
            // 获取 code
            if (res.code) {
                uniCloud.callFunction({
                    name: 'user',
                    data: {
                        action: 'code2Session',
                        js_code: res.code,
                        user_info: _this.userInfo
                    },
                    success: (res) => {
                        console.log('云函数返回的值::::', res.result)
                        uni.hideLoading();
                        if (res.result.result.result._id) {
                            uni.setStorageSync('userInfo', JSON.stringify(res.result
                                    .result.result))
                            globalData.$UserInfo = res.result.result.result
                        }
                    },
                    fail: () => {
                        uni.hideLoading();
                        console.log('云函数调用失败')
                    }
                })
            }
        }
    })
}
  • uni.login函数是uniapp封装的微信小程序中的登录API,用来获取用户code
  • uniCloud.callFunction是用来调用云函数的方法
    • name: 云函数名称(在上面新建云函数时写的名称)
    • data:传给云函数的数据

image.png

云函数逻辑

'use strict';
const mp_wx_data = {
    AppID: '微信小程序APPID',
    AppSecret: '微信小程序AppSecret'
}

exports.main = async (event, context) => {
    //event为客户端上传的参数
    // console.log('event : ', JSON.stringify(event))

    const db = uniCloud.database();
    // 获取 `user` 集合的引用
    const pro_user = db.collection('pro-user');

    // 循环判断客户端传递过来的 action
    // 通过 action 判断请求对象

    let result = {};

    switch (event.action) {
        // 通过 code 获取用户 session
        case 'code2Session':
            const res_session = await uniCloud.httpclient.request(
                'https://api.weixin.qq.com/sns/jscode2session', {
                    method: 'GET',
                    data: {
                        appid: mp_wx_data.AppID,
                        secret: mp_wx_data.AppSecret,
                        js_code: event.js_code,
                        grant_type: 'authorization_code'
                    },
                    dataType: 'json'
                }
            )
            console.log(res_session)
            const success = res_session.status === 200 && res_session.data && res_session.data.openid

            if (!success) {
                return {
                    status: -2,
                    msg: '从微信获取登录信息失败'
                }
            }

            const res_user = await pro_user.where({
                mp_wx_openid: res_session.data.openid
            }).get()

            if (res_user.data && res_user.data.length === 0) {
                // 没有用户信息,进入注册
                const register = await uniCloud.callFunction({
                    name: 'user',
                    data: {
                        action: 'register',
                        open_id: res_session.data.openid,
                        user_info: event.user_info
                    }
                }).then(res => {
                    result = res
                })
            } else {
                const update = await uniCloud.callFunction({
                    name: 'user',
                    data: {
                        action: 'update',
                        open_id: res_session.data.openid,
                        _id: res_user.data[0]._id,
                        user_info: event.user_info
                    }
                }).then(res => {
                    result = res
                })
            }
            break;
        case 'register':
            const res_reg = await pro_user.add({
                nickName: event.user_info.nickName,
                avatarUrl: event.user_info.avatarUrl,
                mp_wx_openid: event.open_id,
                register_date: new Date().getTime()
            })

            if (res_reg.id) {
                const res_reg_val = await uniCloud.callFunction({
                    name: 'user',
                    data: {
                        action: 'getUser',
                        open_id: event.open_id
                    }
                }).then(res => {
                    result = res
                })
            } else {
                result = {
                    status: -1,
                    msg: '微信登录'
                }
            }
            break;
        case 'update':
            const res_update = await pro_user.doc(event._id).update({
                nickName: event.user_info.nickName,
                avatarUrl: event.user_info.avatarUrl,
                mp_wx_openid: event.open_id
            })

            const res_update_val = await uniCloud.callFunction({
                name: 'user',
                data: {
                    action: 'getUser',
                    open_id: event.open_id
                }
            }).then(res => {
                result = res
            })
            break;
        case 'getUser':
            const res_val = await pro_user.where({
                mp_wx_openid: event.open_id
            }).get()
            return res_val.data[0]
            break;
    }
    return result;
};
  • mp_wx_data中的值是在微信小程序后台开发管理中获取的,每个小程序的数据都是唯一的。
  • 这一部分是用来获取到数据表的方法。
    const db = uniCloud.database();
    const pro_user = db.collection('pro-user');
    
    • pro-user:数据表名称
  • 云函数中分为了四个模块:(模块名称可以根据需求来自定义)
    • code2Session:通过code获取用户信息,函数中调用的是微信提供的获取code的API
    • register:如果数据库中没有找到用户信息,就会执行register函数
    • update:如果数据库中有用户信息,可能需要更新
    • getUser:获取用户信息

image.png

登录成功显示用户信息

<template>
    <view class="content">
        <view v-if="isLogin">
            <view class="cu-list menu-avatar">
                <view class="cu-item">
                    <image class="cu-avatar round lg" :src="userInfo.avatarUrl" />
                    <view class="content">
                        <view class="text-black">蜡笔小心</view>
                        <view class="text-gray text-sm flex">
                            <view class="text-cut">
                                一屋两人三餐四季
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <view class="flex padding justify-center" v-else>
            <button class="cu-btn round bg-red" @click="getUserInfo">立即登录</button>
        </view>
    </view>
</template>
  • 这里没有做跳转页面的操作,全部是在一个页面上完成的。通过用户信息来判断isLogin状态

image.png

数据表中成功新增数据

image.png

总结

微信小程序获取用户信息的云开发已完成,大家可以开脑洞去实现自己需要的小程序。