使用Promise獲取用戶信息

前言

在4月份的時候,微信發出了公告:小程序與小遊戲獲取用戶信息接口調整,請開發者注意升級。javascript

後續瀏覽了一下有關獲取用戶信息的接口的API(wx.getUserInfo(OBJECT)),裏面有提到此接口有調整,使用該接口將再也不出現受權彈窗html

當用戶未受權過,調用該接口將直接報錯;當用戶受權過,能夠使用該接口獲取用戶信息java

看來得引導用戶主動點擊受權按鈕了。下面將介紹如何經過使用Promise來實現獲取用戶信息。es6

獲取用戶信息流程圖

受權流程圖

首先創建wechat.js

class Wechat {

    /**
     * 登陸
     * @return {Promise} 
     */
    static login() {
        return new Promise((resolve, reject) => wx.login({ success: resolve, fail: reject }));
    }

    /**
    * 獲取用戶是否受權
    * @return {Promise} 
    */
    static getSetting() {
        return new Promise((resolve, reject) => wx.getSetting({ success: resolve, fail: reject }));
    }

    /**
     * 打開受權設置
     */
    static openSetting() {
        return new Promise((resolve, reject) => wx.openSetting({ success: resolve, fail: reject }));
    }

    /**
     * 獲取用戶信息
     * @return {Promise} 
     */
    static getUserInfo() {
        return new Promise((resolve, reject) => wx.getUserInfo({ success: resolve, fail: reject }));
    }

    /**
     * 發起網絡請求
     * @param {string} url  
     * @param {object} params 
     * @return {Promise} 
     */
    static request(url, params, method = "GET", type = "json") {
        return new Promise((resolve, reject) => {
            let opts = {
                url: url,
                data: Object.assign({}, params),
                method: method,
                header: { 'Content-Type': type },
                success: resolve,
                fail: reject
            }
            wx.request(opts);
        });
    }


    /**
     * 處理app.js中定義的回調函數;在onload中調用
     * @param {webchatApp} app 
     * @param {function} handle 
     */
    static handleCallback(app, handle) {
        if (app.globalData.params) {
            handle();
        } else {
            app.openIdCallback = data => {
                if (data !== null) {
                    handle();
                }
            }
        }
    }


}

export default Wechat;

修改app.js

//app.js
import wechat from "./utils/wechat.js";
App({
  onLaunch() {
    let params = {};
    wechat.login().then(data => {
      return data;
    }).then(data => {
      params.jsCode = data;
      return wechat.getSetting()
    }).then(data => {
      params.auth = data.authSetting['scope.userInfo'] === true;
      return params;
    }).then(data => {
      if (data.auth) {
        //已經受權
        //獲取用戶信息
        console.log('已經受權');
        return wechat.getUserInfo();
      } else {
        console.log('未受權');
      }
      return data;
    }).then(data => {
      //增長回調
      if (data.auth == undefined) {
        params.ui = data;
      }
      this.globalData.params = params;
      if (this.openIdCallback) {
        this.openIdCallback(data);
      }
    }).catch(e => {
      console.log(e);
      return Promise.reject(e);
    });
  },
  globalData: {
    params: null,
  }
})

修改index.wxml

<!--index.wxml-->
<view class="container" wx:if="{{!auth}}">
    <button wx:if="{{canIUse}}" open-type="getUserInfo" bindgetuserinfo="onGotUserInfo">微信受權</button>
    <view wx:else>請升級微信版本</view>
</view>
<view wx:else>
    {{userInfo}}
</view>

修改index.js

//index.js
//獲取應用實例
import wechat from "../../utils/wechat.js";

const app = getApp()

Page({
  data: {
    auth: false,
    call: false,
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件處理函數

  onLoad: function () {
    wechat.handleCallback(app, () => {
      console.log(app.globalData)
      let auth = app.globalData.params.auth;
      let ui = app.globalData.params.ui;
      this.setData({
        auth: auth,
        userInfo: ui !== undefined ? ui.rawData : {},
        call: true
      });
      if (!auth) {
        this.showAuthDialog();
      }
    });
  },
  onGotUserInfo: function (e) {
    console.log(e.detail.encryptedData);
    console.log(e.detail.iv);
    //此處如何能獲取到用戶信息 能夠回傳用戶信息至服務器便可
    //獲取到用戶信息同時 this.setData({auth: true})
  },
  onShow: function () {
    if (!this.data.auth && this.data.call) {
      this.showAuthDialog();
    }
  },
  showAuthDialog: function () {
    wx.showModal({
      title: '用戶未受權',
      content: '須要受權獲取您的公開信息;請點擊微信受權-容許-便可正常使用。',
      showCancel: false
    })
  }
})

最後有關Promse的用法,能夠參考Promise 對象(ECMAScript 6 入門——阮一峯)web

相關文章
相關標籤/搜索