微信小程序获取openid

微信小程序一般要用到openid是在需要到支付接口调用时用到,比如获取签名的时候就要用到,我们可以在全局app.js里面获取得到,然后给其它页面调用,具体步骤如下:

1.我们进到app.js里面获取,生命周期函数的执行都会先执行app.js里面的onlaunch()方法,让每次用户进入到页面时先获取到它的openid,获取代码如下:

//app.js
const {
  host,
} = require("/config/config.js")  //蓝牙格子柜总配置接口

var replace = require('/utils/replace.js')//这个是我封装好的方法不用管它


App({
  onLaunch: function () {

    console.log('rep',replace)
    // console.log(host)
  //获取用户的openid

    wx.login({//调用wx.login()获取登录凭证code;

     success:res => {
         
      //  console.log('res',res.code)
       wx.request({
         url: host+'/module/brushCard/pay/login',
         method:"post",
         header: {
           'content-type': 'application/x-www-form-urlencoded',
         },
         data:{//后台让你传过去的请求参数
           code:res.code,
           wxAppid: "wxcbec42f8c5117bdb",
           sign:"13e1961f6f374660b80b7e0a6185bd3a"
         },
         success: request => {
           var openId = request.data.data
           this.globalData.openId = openId   //赋值给下面的globalData,方便全局调用
           if (this.userInfoReadyCallback) {  //如果你是在onload请求,有时候会先执行onload方法,加入这个,防止onload方法先执行
             this.userInfoReadyCallback(res)
           }
         }
       })
     }
   })
  },
  deteleObject: replace.deteleObject,  //这个是上面我封装的方法时,为了给其它页面调用时命名的方法
  globalData: {
    userInfo: null,
    openId:null,
  }
})

2.接着就可以在页面的js里面调用了,现在.js文件里面引入app.js里面的方法,先赋值定义变量:

var app = get app(),接着就可以在接口请求所需要用到openid参数时调用了,代码如下:

//点击发起支付方式
    wx.request({
      url: host + "/blue/api/creatOrder" ,
      method:"post",
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: {
        deviceNo: that.data.deviceNo,
        wxAppid: "wxcbec42f8c5117bdb",
        sign:"13e1961f6f374660b80b7e0a6185bd3a",
        goodId: that.data.goods_Info[index].id,
        openid: app.globalData.openId,    //这就是我们在app.js页面调用到的openid
        aisleId: that.data.goods_Info[index].aisleId
      },
      success: res => {
        console.log('resss',  res)
        
     
    })

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值