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
}
})
}
}
)
}