商城系統 注冊

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

2020-09-27|HiShop
導讀:微信 小程序 官方登錄方式修改,要求通過button點擊登錄,和大家分享一下我的解決方案。 原先的登錄邏輯是注冊一個全局login方法, login方法中首先調用wx.login靜默登錄,獲取臨時登錄...

微信小程序官方登錄方式修改,要求通過button點擊登錄,和大家分享一下解決方案。

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

原先的登錄邏輯是注冊一個全局login方法, login方法中首先調用wx.login靜默登錄,獲取臨時登錄憑證code,在開發(fā)者服務器后臺調用 api,使用 code 換取 openid 和 session_key 。然后調用wx.getUserInfo獲取用戶信息。

現在的實現邏輯是寫一個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,
    // });
  }

就醬愉快的重構結束~

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

電話咨詢 預約演示 0元開店