小程序引導用戶授權

用戶信息授權

對於小程序未授權的用戶,官方取消wx.getUserInfo方法的直接調用,首次授權必須主動觸發自定義按鈕,纔可調起官方授權組件

可以獲取到的信息有:暱稱、頭像、性別、國家、省份、城市、性別、語言

思路步驟

  1. wx.getSetting查看是否授權
  2. 已授權使用wx.getUserInfo獲取用戶信息,保存
  3. 未授權顯示帶有button的自定義頁面,bindGetUserInfo會返回用戶信息,該按鈕會調用微信官方授權

    <button open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">允許用戶授權</button>
  4. 授權完成保存用戶信息

項目實現

  1. app.js----我放在登陸方法之後

    // 查看是否授權,保存授權狀態
        wx.getSetting({
            success: function(res) {
                if (res.authSetting['scope.userInfo']) {
                    wx.setStorageSync('isAuthorize', 'true');
                    wx.getUserInfo({
                        success: function(res) {
                            wx.setStorageSync('userInfo', res.rawData);
                        }
                    })
                } else {
                    wx.setStorageSync('isAuthorize', 'false');
                }
            }
        })
  2. main.wxml------項目主頁面

    <!-- 小程序授權組件 -->
    <authorize id="authorize"></authorize>
  3. main.js------onload中進行判斷是否要顯示自定義的按鈕

    // 已授權隱藏彈框,未授權顯示彈框
    this.authorize = this.selectComponent("#authorize");
    if (wx.getStorageSync('isAuthorize')=='true'){
        this.authorize.hideDialog()
    }
  4. main.json-----主頁面配置參數

    "usingComponents": {
        "authorize": "自定義授權組件的路徑"
    }
  5. authorize.js------自定義帶有button的頁面/彈窗組件autiorize,這裏只貼出js部分

    /*authorize.js*/
    Component({
        options: {
            multipleSlots: true
        },
    
        data: {
            isHide: false,
            canIUse: wx.canIUse('button.open-type.getUserInfo')
        },
    
        methods: {
    
            //隱藏彈框
            hideDialog() {
                this.setData({
                    isHide: true
                })
            },
            // 授權信息保存
            bindGetUserInfo(e){
                wx.setStorageSync('isAuthorize', 'true');
                wx.setStorageSync('userInfo', JSON.stringify(e.detail.userInfo));
                this.hideDialog()
            }
    
        }
    })

    這樣整個授權就完成了!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章