关于微信小程序获取手机号并使用云函数解密、存入数据库,请见我的这篇博文:
https://blog.csdn.net/weixin_43900888/article/details/110120330
本文将省略上述操作。
思路:拿到用户手机号后,将判断此用户的手机号是否已在云数据库中,若存在,则直接跳转到主页,若不存在,则在数据库中新增这个手机号,再跳转到主页。

const app = getApp()
const db = wx.cloud.database()
const admin = db.collection('user')

   ......

   data:{
     isLogin:false,
     tlp:''
    },
   ......

    getPhoneNumber(e)
    {
      const that=this
       wx.cloud.callFunction({
            name:'getPhone', //获取手机号操作的云函数名
            data:{
                cloudID:e.detail.cloudID
            }
        }).then(res=>{
            console.log("获取成功",res)
            this.setData({
              tlp:res.result.list[0].data.phoneNumber//将获取的手机号赋值给data中的变量tlp
            })
            admin.get().then(re => {
                let users = re.data;//将数据库的user表存在users中
                for(let i=0;i<users.length;i++)//遍历user表,判断该手机号是否存在
                {
                  if(users[i].telephone===that.data.tlp)
                  {
                    that.setData({
                      isLogin:true//如果存在,将布尔值设为true
                    })
                    break;
                  }
                }
                if(that.data.isLogin===true)
                {
                  wx.redirectTo({
                    url: '../homepage/homepage'//跳转到首页
                })
                }
                else
                {
                  admin.add({
                    data:{
                        telephone:res.result.list[0].data.phoneNumber
                    },
                    
                    success: r => {
                      console.log('[数据库] [新增记录] 成功,记录 _id: ', r._id)
                      wx.redirectTo({
                        url: '../homepage/homepage'//写入数据库后跳转到首页
                    })
                    },
                    fail: err => {
                      console.error('[数据库] [新增记录] 失败:', err)
                    }
                    
                  })
                }
                  
                })
            
          })
    }

注:
telephone:res.result.list[0].data.phoneNumber 处,要注意这里的res和wx.cloud.callFunction的res写法一致,不要和admin.get()的re一致,也不要和admin.add的r一致,否则将报错:找不到list。这是因为,res.result.list[0].data.phoneNumber是云函数获取的数据,应为云函数wx.cloud.callFunction的返回值res。

Logo

华为AI开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐