微信小程序云函数如何获取openId

1、先创建一个获取云函数的方法

2、在云函数的js文件中放入代码

// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 获取openid
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  return {
    event,
    openid: wxContext.OPENID,
    // appid: wxContext.APPID,
    // unionid: wxContext.UNIONID,
  }
}

3、在小程序的js中调用该方法

const db = wx.cloud;

  /**
   * 云函数获取openid
   * 并存入缓存中
   */
  getCloudOpenId() {
    db.callFunction({
      name:'getOpenId'
    }).then(res => {
      console.log('openid:',res.result.openid)
      if(res.result && res.result.openid) {
        //获取成功
        this.globalData.openid = res.result.openid
        wx.setStorageSync('openid',res.result.openid)
      }
    }).catch(res => {
      wx.showToast({
        title: '获取openId失败',
        image:'/images/warning.png',
        duration: 2000
      })
      console.log(res)
    })
  },

工作忙,但还是要记得点外卖哦

欢迎关注我的外卖公众号,领优惠红包!还有电影票、酒店、滴滴红包哦

 

我刚做的小程序哦,欢迎交流程序问题哦~ 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值