wxml:
<button class="button" hover-class="button-hover" open-type="getUserInfo" bindgetuserinfo="getuserInfo"
>点击授权</button>
js:
const db = wx.cloud.database();
const util = require('../../utils/util.js');
const app = getApp();
Page({
data: {
nickName: "", //保存昵称
avatarUrl: "",//保存头像
},
onLoad: function (options) {
},
//用户登录授权
getuserInfo(e) {
wx.cloud.callFunction({
name: 'getopenid',//调用云函数获取用户唯一openid
complete: res => {
const openid = res.result.openid
db.collection('user').where({
_openid: openid
}).get().then(res => {
console.log(res)
//确保数据库只有一份该用户的信息
if (res.data == "") {
console.log("授权登录成功")
this.setData({
isFirstLogin: 1
})
// 跳转到主界面
wx.navigateTo({
url: '/xxxx/xxxx/xxxx',//登录成功后要跳转的页面
})
db.collection('user').add({
data: {
nickName: e.detail.userInfo.nickName,
avatarUrl: e.detail.userInfo.avatarUrl,
time: util.formatTime(new Date()),
}
})
} else {
console.log("已经登录过不用授权")
wx.switchTab({
url: '/xxxx/xxxx/xxxx',//登录成功后要跳转的页面
})
}
})
}
})
this.setData({
nickName: e.detail.userInfo.nickName,
avatarUrl: e.detail.userInfo.avatarUrl
})
},
云函数getopenid:
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
env: "xxxxxx"//自己的环境名
})
// 云函数入口函数
exports.main = async (event, context) => {
const wxContext = cloud.getWXContext()
return {
event,
openid: wxContext.OPENID,
}
}