WeChat cloud development - get the user's openid and set it as a global variable

Create a cloud function

As shown in the figure, create a cloud function and upload it
Please add a picture description

// 云函数入口文件
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.
Please add a picture description
Please add a picture description

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)

Please add a picture description
As shown in the figure, the call is successful

Guess you like

Origin blog.csdn.net/qq_52109814/article/details/129865653