微信小程式雲開發--->>獲取使用者openid並全域性呼叫
阿新 • • 發佈:2020-09-21
1.我們用雲開發模板建立小程式專案時,在該目錄下有login雲函式,我們可以利用它實現獲取openid,右鍵上傳並部署,雲端安裝依賴後
2.開啟app.js,在onLaunch: function(){}內填入以下程式碼呼叫login雲函式獲取openid
這樣可以實現開啟小程式時獲取使用者openid
//app.js App({ getOpenId: null, onLaunch: function () { if (!wx.cloud) { console.error('請使用 2.2.3 或以上的基礎庫以使用雲能力') } else { this.getOpenId = (function(that){ return new Promise((resolve, reject) =>{ wx.cloud.callFunction({ name: 'login', data: {}, success: res => { that.globalData.openid = res.result.openid resolve(res.result.openid) }, fail: err => { console.error('[雲函式] [login] 呼叫失敗', err) } }) }) })(this) } } })
3.在想要呼叫的頁面使用getOpenId即可獲取
const app = getApp(); app.getOpenId.then(res => { console.log(res, 'then-res') })4.這種方法可以有效避免因為非同步而拿不到openid的情況