小程序授權流程

微信小程序開發用戶授權登錄

在這裏插入圖片描述
微信官方的開放文檔:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html

說明:
小程序調用wx.login() 獲取 臨時登錄憑證code ,並回傳到開發者服務器
開發者服務器以code換取 用戶唯一標識openid 和 會話密鑰session_key。
臨時登錄憑證code只能使用一次

OpenID:
在關注者與公衆號產生消息交互後,公衆號可獲得關注者的OpenID
1.1 普通用戶的標識,對當前公衆號唯一
1.2 不同的公衆號,同一個用戶,openid不同
unionid
同一用戶,對同一個微信開放平臺下的不同應用,unionid是相同的。
也就是說:
如果開發者擁有多個移動應用、網站應用、和公衆帳號(包括小程序),可通過unionid來區分用戶的唯一性,因爲只要是同一個微信開放平臺帳號下的移動應用、網站應用和公衆帳號(包括小程序),用戶的unionid是唯一的。
實踐方法
1、調用 wx.login 獲取 code。
2、使用 wx.getSetting 獲取用戶的授權情況
2.1 如果用戶已經授權,直接調用 API wx.getUserInfo 獲取用戶最新的信息;
2.2 用戶未授權,在界面中顯示一個按鈕提示用戶登入,當用戶點擊並授權後就獲取到用戶的最新信息。
3、將獲取到的用戶數據連同wx.login返回的code一同傳給後端


import {
  me,
  xmini,
} from '../config/xmini';
import api from '../api/index';
import {
  clone
} from '../utils/index';
const app = getApp();
module.exports = {
  authCode: 0,
  // 登錄的邏輯
  updatedAuthCode(callback) {
    const that = this
    wx.login({
      success(auth) {
        if (auth.code) {
          console.log('auth code :', auth);
          that.authCode = auth.code;
          callback && callback.call(that, auth.code)
        }
      }
    })
  },
  // 獲取用戶信息
  getUserInfo(res) {
    // 登錄前,先清除下之前登錄相關的緩存數據
    app.clearUserInfo();
    //這裏是清除登錄相關信息
    xmini.store.dispatch('setUserInfo', {})
    xmini.store.dispatch('setAddresses', []);
    console.log(res)

    const detail = res.detail;
    console.log(detail)
    if (detail.errMsg == 'getUserInfo:ok') {
      console.log('xxxx')
        wx.showLoading({
          title: '登錄中...',
        })
        this.postLogin({
          data: {
            code: this.authCode,
            // userInfo: res.userInfo,
            encryptedData: encodeURIComponent(detail.encryptedData),
            iv: encodeURIComponent(detail.iv),
          },
          success: loginRes => {
            //更新code
            this.updatedAuthCode();

            wx.hideLoading();
          },
          fail: loginErr => {
            //
            wx.showToast(loginErr.errmsg)
          }
        });
      // })
    } else {
      // 失敗!
      if (detail.errMsg === 'getUserInfo:fail auth deny' || detail.errMsg === 'getUserInfo:fail:auth deny') {
        // 獲取用戶信息授權失敗,展示引導
        wx.showModal({
          title: '提示',
          content: '需要你到授權,才能使用完整版的好食期',
          confirmText: '知道了',
          showCancel: false,
          success(res) {
            console.log(res)
          }
        });

      }
    }
  },

  getPhoneNumber(e) {
    console.log('getPhoneNumber:', e)
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      // 更新code 解析手機號
        wx.showLoading();
        api.userAuthPrepose({
          type: 2,
          code: this.authCode,
          encryptedData: encodeURIComponent(e.detail.encryptedData),
          iv: encodeURIComponent(e.detail.iv),
        }, (res) => {
          //更新code
          this.updatedAuthCode();

          let userInfo = clone(xmini.store.state.user.userInfo)
          userInfo.authPhone = true;
          //這裏更新存儲的用戶信息和地址
          xmini.store.dispatch('setUserInfo', userInfo) 
          xmini.store.dispatch('setAddresses');
        }, (err) => {
          //更新code
          this.updatedAuthCode();
          console.log(err);
        })
      // })
    }
  },

  postLogin({ data = {}, success, fail }){
    const that = this;
    api.login({
      isLoading: false,
      type: 2,
      ...data,
    }, (res) => {
      const { data } = res;
      const userId = data.user_id;

      // 更新code
      that.updatedAuthCode()
      // data.userId = userId;
      if (userId) {
        console.log('登錄成功');
        xmini.piwikUpdate({
          isTrackWorking: true,
          userId: data.user_id || '',
          openId: data.wechat_open_id || '',
        });

        // data.authPhone=false; //!!test
        // 更新store
        xmini.store.dispatch('setUserInfo', data)
        success && success.call(that, res);
      } else {
        wx.showToast('用戶登錄信息有誤,請重新登錄');
        fail && fail.call(that, res);
      }
      //更新收貨地址
      xmini.store.dispatch('setAddresses');
    }, (err) => {
      // 更新code
      that.updatedAuthCode()
      //更新收貨地址
      xmini.store.dispatch('setAddresses');
      fail && fail.call(that, err);
      return true;
    });
  },
  // 更新登錄
  updatedLogin({ success, fail}) {
    const that = this;
    // 獲取 用戶是否授過權
    wx.getSetting({
      success(res) {
        console.log(res.authSetting)
        // 判斷權限
        if (res.authSetting['scope.userInfo']) {
          // 獲取login code
          that.updatedAuthCode((code) => {
            console.log(code);
            // 獲取用戶信息
            wx.getUserInfo({
              success(res) {
                // console.log(res);
                // 登錄
                that.postLogin({
                  data: {
                    code,
                    encryptedData: encodeURIComponent(res.encryptedData),
                    iv: encodeURIComponent(res.iv),
                  },
                  success: res => {
                    console.log(res);
                    success && success(res);
                  },
                  fail: err => {
                    // console.log(err);
                    fail && fail(err);
                  }
                })
              },
              fail(err) {
                fail && fail(err);
              }
            })
            // end
          })
          // end
        }
      }
    })
  },
};

小結:在真實的業務場景中,我們希望,用戶進入小程序時,未登錄情況下可以正常瀏覽商品,對小程序有個基本的認知,不要直接彈出框要求用戶授權,否則會干擾用戶,導致新用戶的流失,當用戶需要使用一些高級功能和場景,這個時候再去要求用戶授權,這樣用戶授權的機率會大大提高。

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