微信小程序登陸方式的修改解決方案

微信小程序官方登陸方式修改,要求經過button點擊登陸,和你們分享一下個人解決方案。html

原先的登陸邏輯是註冊一個全局login方法, login方法中首先調用wx.login靜默登陸,獲取臨時登陸憑證code,在開發者服務器後臺調用 api,使用 code 換取 openid 和 session_key 。而後調用wx.getUserInfo獲取用戶信息。redux

如今的實現邏輯是寫一個button中轉頁,進入小程序wx.getUserInfo獲取失敗後跳轉到button中轉頁,點擊button調用bindgetuserinfo方法,該方法返回的detail數據與wx.getUserInfo方法返回的信息一致,此時也能夠獲取到用戶信息。回調成功後wx.navigateBack({})回原頁面。小程序

下面貼上部分代碼片斷:微信小程序

async bindGetUserInfo(event) {
    const { detail } = event;

    const isSuccess = detail.errMsg === 'getUserInfo:ok';

    if (isSuccess) {
      this.authSuccess(detail);
      return;
    }
    // 用戶拒絕受權
    // wx.navigateBack({});
  }
  
  
  
  async authSuccess(detail) {
    await this.getToken(detail);
    wx.navigateBack({});

    // this.nextHander();
  }
  
  
  
保存用戶信息
 async getToken(detail) {
    console.log('getToken', detail);

    const session_key = wx.getStorageSync('session_key');

    const { encryptedData: encrypted_data, iv } = detail;
    const that = this;

    // 保存用戶信息到服務器
    const { data: { user, up_token, token, is_created } } = await this.fetch({
      url: '/api/artisan/wechat/login',
      data: {
        session_key,
        encrypted_data,
        iv,
      },
      method: 'POST',
    });
    wx.setStorageSync('user', user);
    this.$root.$parent.store.set('up_token', up_token, 30);
    // 存儲用戶標識符到本地
    this.$root.$parent.store.set('token', token, 30);
    this.$root.$parent.store.set('is_created', is_created, 30);
    //  redux
    // store.dispatch({
    //   type: 'SET_IS_CREATED',
    //   payload: is_created,
    // });
  }
複製代碼

就醬愉快的重構結束~api

相關文章
相關標籤/搜索