Create a cloud function
As shown in the figure, create a cloud function and upload it
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
// 云函数入口函数
exports.main = async (event, context) => {
const wxContext = cloud.getWXContext()
return {
event,
openid: wxContext.OPENID,
appid: wxContext.APPID,
unionid: wxContext.UNIONID,
}
}
Initialize cloud development
Initialize the cloud function in app.js in the root directory
App({
onLaunch:function(){
//云开发环境测试
wx.cloud.init({
env:"qfb-7ghqo63b396f0b1f"
})
wx.cloud.callFunction({
name: 'get_openId',
success: res => {
//获取用户openid
this.globalData.user_openid = res.result.openid
console.log(this.globalData.user_openid)
}
})
},
As shown in the figure, the user's openid is printed in the debugger, which is consistent with the openid in the cloud database.
global call
In the previous step, the openid has been stored in globalData, so the openid can be used in any file.
console.log("这是全局变量Openid"+app.globalData.user_openid,res)
As shown in the figure, the call is successful