原生小程序實現登錄授權與封裝統一調用接口


一。登錄思路

先通過 wx.login 返回 res.code 到后台接口換取 openId, sessionKey, unionId。然后通過 wx.getUserInfo 獲取用戶信息

如果要獲取用戶敏感信息則要 wx.getUserInfo 返回的數據傳到后台進行解析(我這邊是用大佬封裝好的api進行解析 )。

 

二。代碼

1。小程序封裝統一請求接口

function Request(url, param, method, isJson) {
  const resUrl = wx.getStorageSync('url') + url;
  return new Promise((resolve, reject) => {
    wx.request({
      url: resUrl,
      data: param,
      header: {
        'content-type': isJson ? 'application/json' : 'application/x-www-form-urlencoded'
      },
      method: method,
      dataType: 'json',
      responseType: 'text',
      success: function (res) {
        // console.log("返回結果------")
        // console.log(res)
        resolve(res.data)
      },
      fail: function (err) {
        // console.log("請求失敗:" + err.errMsg)
        wx.showToast({
          title: '請求失敗',
          icon: 'none',
          duration: 2000,
          mask: true
        })
      }
    })
  }).then((resData) => {
    return resData;
  })
}
module.exports = {
  Request: Request
}
 
2。創建一個api包專門區別放調用后台接口,我這個是api包里的user.js
const requests = require("../utils/request.js")
module.exports = {
  // 登錄
  wxLogin: (data) => {
    return requests.Request("/wx/login/wx-login.json", { jsCode: data }, 'post', true);
  },

  //獲取用戶信息
  getUserInfo: (data) => {
    return requests.Request("/wx/login/get-user-info.json", data, 'post', true);
  },

  //獲取用戶手機號
  getUserPhone: (data) => {
    return requests.Request("/wx/login/get-user-phone.json", data, 'post', true);
  }
}
 
3.修改下app.js
const userRequest = require("/api/user.js")
App({
  onLaunch: function () {
    // 展示本地存儲能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    wx.setStorageSync('url', "http://localhost:8087");

    this.getUserInfo();
  },
  onShow() { },
  getUserInfo() {
    let that = this;
    // 登錄
    wx.login({
      success: res => {
        // 發送 res.code 到后台換取 openId, sessionKey, unionId
        userRequest.wxLogin(res.code).then((res) => {
          if (res.code === "SUCCESS") {
            wx.setStorageSync('sessionKey', res.data.sessionKey);
            that.globalData.userInfo = res.data.wxUser;
            // 由於 getUserInfo 是網絡請求,可能會在 Page.onLoad 之后才返回
            // 所以此處加入 callback 以防止這種情況
            if (that.userInfoReadyCallback) {
              that.userInfoReadyCallback(res.data.wxUser)
            }
          } else {
            wx.showToast({
              title: '登錄失敗',
              icon: 'none',
              duration: 2000,
              mask: true
            })
          }
        });
      }
    })
  },
  globalData: {
    userInfo: null
  }
})
 
4.別的頁面調用
onLoad: function () {
    let that = this;
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          //用戶授權了
          that.setData({
            isShowAuth: false
          })
          that.initData();
        } else {
          //用戶還沒授權,彈出授權窗
          that.setData({
            isShowAuth: true
          })
        }
      }
    })
  }
 
5.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM