小程序云开发登陆流程

index.js

onLoad: function () {
    that=this
    getOpenid()
  }
})
//获取openid同时获取云数据库用户信息
function getOpenid() {
  wx.cloud.callFunction({
    name: 'login',
    data: {},
    success: res => {
      app.globalData.openid = res.result.openid
      getUserInfo()
    },
    fail: err => {
      console.error('[云函数] [login] 调用失败', err)
    }
  })
}

function getUserInfo() {
  db.collection('mall_user').where({
    _openid: app.globalData.openid
  }).get().then(
    res => {
      console.log(res)
      if (res.data.length){
        app.globalData.userInfo = res.data[0].userInfo
      }
     
    }
  )
}

云函数login/index.js

exports.main = (event, context) => {
  console.log(event)
  console.log(context)
  // 获取 WX Context (微信调用上下文),包括 OPENID、APPID、及 UNIONID(需满足 UNIONID 获取条件)
  const wxContext = cloud.getWXContext()

  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  }
}

user.js

   onLoad(){
    that=this
     if(app.globalData.userInfo){
        this.setData({
          avatarUrl: app.globalData.userInfo.avatarUrl
        })
     }
  }
//登陆授权绑定事件
onGetUserInfo: function (e) {
    if (!e.detail.userInfo) return//用户拒绝
    app.globalData.userInfo = e.detail.userInfo
    that.setData({
      avatarUrl: e.detail.userInfo.avatarUrl,
    })
    //添加或更新用户
    db.collection('mall_user').where({
      _openid: app.globalData.openid
    }).get().then(
      res => {
        console.log(res)
        if (res.data.length==0){//不存在则添加
            db.collection('mall_user').add({
              data: {
                userInfo: e.detail.userInfo
              }
            })
        } else {//存在则更新
          db.collection('mall_user').doc(res.data[0]._id).update({
              data: {
                userInfo: e.detail.userInfo
              }
            })
        }
      }
    )
  }

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值