赞
踩
需求:
1. 用户打开小程序,在user表中记录用户的相关信息,可以导出在别的地方做记录
2. 在页面中也需要能够显示用户姓名头像等信息
3. 由于用户的昵称可以随时改,需要每次登录的时候更新一下信息,否则的话,导出来的用户表和微信里的用户名称对不上
基本逻辑:
1. 打开小程序阶段,onload的时候,通过云函数自动获取openid,并在user表中匹配,如果已经注册过,将hasRegistered设置为true
2. 用户点击按钮登录,调用bindgetuserinfo="getUserInfo"方法,获取用户信息
3. 然后根据1的判断结果,决定是新增用户,还是更新用户信息
4. 之后继续别的业务逻辑
index.js代码如下:
- const app = getApp()
- const DB = wx.cloud.database()
- wx.cloud.init()
-
- Page({
- data:{
- hasRegistered: false
- },
- onLoad: function(){
- //onLoad过程中,判断用户是否已经注册
- let that = this
- //获取openid,存入storage
- wx.cloud.callFunction({
- name:"getOpenId",
- success(res){
- wx.setStorageSync('openid', res.result.openid)
- }
- }),
- //使用openid判断是否已经注册过
- DB.collection('user').where({
- _openid: wx.getStorageSync('openid')
- }).get({
- success(res){
- if(res.data.length > 0){
- that.setData({
- hasRegistered: true //将hasRegistered更新为true
- })
- }
- }
- })
- },
- //bindgetuserinfo调用此函数,获取userInfo,存入storage,新增或者更新时使用
- getUserInfo: function(e){
- wx.setStorageSync('userInfo', e.detail.userInfo)
- //已注册,更新用户信息;没注册,新增用户
- let that = this
- if(that.data.hasRegistered){
- this.updateUser()
- }else{
- this.addUser()
- }
- },
- //新增用户,并将hasReigstered设置为true
- addUser(){
- let that = this
- DB.collection('user').add({
- data:{
- name: wx.getStorageSync('userInfo').nickName,
- gender: wx.getStorageSync('userInfo').gender,
- city: wx.getStorageSync('userInfo').city,
- province: wx.getStorageSync('userInfo').province,
- country: wx.getStorageSync('userInfo').country,
- avatarUrl: wx.getStorageSync('userInfo').avatarUrl
- },
- success(res){
- that.setData({
- hasRegistered: true
- })
- console.log("新增用户成功",res)
- }
- })
- },
- //更新用户数据
- updateUser(){
- DB.collection('user').where({
- _openid: wx.getStorageSync('openid')
- }).update({
- data:{
- name: wx.getStorageSync('userInfo').nickName,
- gender: wx.getStorageSync('userInfo').gender,
- city: wx.getStorageSync('userInfo').city,
- province: wx.getStorageSync('userInfo').province,
- country: wx.getStorageSync('userInfo').country,
- avatarUrl: wx.getStorageSync('userInfo').avatarUrl
- },
- success(res){
- console.log("更新用户信息成功",res)
- }
- })
- }
- })

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。