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的情況