如果只是單純的展示用戶信息,那么最簡單的方案就是
文檔中組件:

<open-data type="groupName" open-gid="xxxxxx"></open-data> <open-data type="userAvatarUrl"></open-data> <open-data type="userGender" lang="zh_CN"></open-data>
如果是需要將用戶信息通過接口傳遞到后台,那么需要強制授權:
小程序目前在測試版和體驗版限制通過wx.getUserInfo({})獲取彈出授權框。
支持通過按鈕點擊獲取授權的方式:
//注意:wx.authorize({scope: "scope.userInfo"}),無法彈出授權窗口
<button open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 獲取頭像昵稱 </button>
小程序目前不支持,打開時就彈出授權窗,只能使用按鈕觸發,按鈕觸發授權方案:
//此處時拒絕授權的警告窗口,如果用戶點擊拒絕,則會彈出這個窗口,確定按鈕再次綁定授權彈窗事件。 <view class="authorize-warning" hidden="{{!isShowAhturoizeWarning}}"> <view class="box"> <view class="title">警告</view> <view class="content">拒絕授權后,將無法通知您。。。。。點擊“取消”拒絕提醒,點擊“確定”再次嘗試授權?</view> <view class="footer"> <button bindtap="cancelAuthroize">取消</button> <button open-type="getUserInfo" bindgetuserinfo="getAuthorize">確定</button> </view> </view> </view>
getUserInfo(){//同意授權,獲取用戶信息,encryptedData是加密字符串,里面包含unionid和openid信息 wx.getUserInfo({ withCredentials: true,//此處設為true,才會返回encryptedData等敏感信息 success: res => { // 可以將 res 發送給后台解碼出 unionId app.globalData.userInfo = res.userInfo; app.globalData.encryptedData = res.encryptedData; app.globalData.iv = res.iv; this.saveUserInfo(); console.log(res) } }) }, getAuthorize(){//彈出授權窗函數 if(this.data.acceptAuthorize) {//判斷是否已經授權過 // 獲取用戶信息 wx.getSetting({ success: res => { if (res.authSetting['scope.userInfo']) { // 已經授權,可以直接調用 getUserInfo 獲取頭像昵稱,不會彈框 this.getUserInfo(); this.setData({ isShowAhturoizeWarning: false }) } else { this.setData({ isShowAhturoizeWarning:true }) } } }) } else {//如果已經授權過直接登錄 this.saveUserInfo() }, cancelAuthroize(){ this.setData({ isShowAhturoizeWarning: false, acceptAuthorize:false }); app.globalData.unionid=null; this.saveUserInfo(); }
