微信小程序一般要用到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)
})