獲取方式
目前小程序獲取用戶一共有3中(自己接觸到的),但由于這個API一直在改,所以不確定后期是否有變動,還是要多關注官方公告。
方式一
使用wx.getUserInfo
實例:
- wxml 文件
<button open-type="getUserInfo" bindgetuserinfo="onGetUserInfo">獲取用戶信息</button>
- open-type=“getUserInfo” 小程序早期用來觸發用戶信息授權的按鈕屬性,點擊按鈕時會彈出授權窗口,獲取用戶頭像、昵稱等基本信息;
- bindgetuserinfo=“onGetUserInfo” 用戶點擊按鈕之后,如果授權了,觸發的回調事件綁定(接收授權結果)。
- js 文件
onGetUserInfo(e) {const { encryptedData, iv } = e.detail;wx.login({success: res => {const code = res.code;auth.getUserProfile({code, encryptedData, iv}).then(res => {console.log('解密后的用戶信息', res.data);}).catch(err=>{console.log('解密失敗', err);});}});
},
- js 部分獲取到
encryptedData, iv
以后,通過調用wx.login
獲取到code
。然后調用后端接口解密。
- 后端接口文件
app.post('/wxmp/getUserProfile', async (req, res) => {const { code, encryptedData, iv } = req.body;try {// 調用微信 jscode2session 接口const response