微信小程序~wx.getUserInfo逐漸廢棄,小程序登錄過程將如何優化?


很多的時候我們在做小程序應用的時候,希望用戶在使用小程序前進行登錄授權,之前登錄后通過wx.getUserInfo直接彈出授權的登錄方式官方的意思是將不再支持,而是讓用戶通過下面的方式授權用戶信息

<button open-type="getUserInfo" bindgetuserinfo="getUserInfoAction">授權用戶信息</button>
這樣的話當小程序在使用前一定需要用戶登錄,或者已經進行到需要用戶登錄的操作時;這樣的話就需要一個button授權頁面。這種改變,感覺個人還是喜歡默認彈層的的授權方式,這個方式可能一時不適應吧,有種排斥。
下面是通過button授權的方式做的一個登錄:這里我只是展示了login.js 與 index.js 過程,有不對或者不好的地方歡迎加群交流指正。
login.js
const ajax = require("../../common/ajax.js")
const tips = require("../../common/tips.js")
Page({
  /**
   * 頁面的初始數據
   */
  data: {

  },

  /**
   * 生命周期函數--監聽頁面加載
   */
  onLoad: function (options) {
    let that = this;
    
  },
  getUserInfoAction(res){
    let that = this;
    const encryptedData = res.detail.encryptedData;
    const iv = res.detail.iv;

    if (encryptedData && iv){
      // console.log("允許")
      that.login().then((login)=>{

        const params = {
          "code": login.code,
          "encryptedData": encryptedData,
          "iv": iv,
          "type": "small_wechat"
        }

        ajax.posts(params, "api/passport/thirdSign").then((res) => {
         
          let userinfo = {
            avatar: res.data.data.avatar,
            nickname: res.data.data.nickname,
            token: res.data.data.token,
            user_id: res.data.data.user_id
          }
          wx.setStorageSync("userinfo", userinfo);

          // console.log(wx.getStorageSync("userinfo"));
          if (wx.getStorageSync("userinfo")){
            wx.redirectTo({
              url: '/page/index/index'
            })
          }
          

          
        }).catch((errMsg) => {
          tips.showToast("網絡連接失敗", "none")
          console.log(errMsg)
        })

      }).catch((errMsg) => {
        console.log("登錄:" + errMsg)
      })

    }else{
      // console.log("拒絕")
      tips.showToast("請授權公開信息,登錄小程序", "none")
    }

  },
  login(){
    // 登錄
    let promise = new Promise((resolve, reject) => {
      wx.login({
        success: function (res) {
          if (res.code) {
            resolve(res)
          } else {
            tips.showToast("登錄失敗", "none")
          }
        },
        fail: function (err) {
          reject(err)
        }
      })

    })
    return promise;
  }
})

index.js

const tips = require("../../common/tips.js")
Page({

  /**
   * 頁面的初始數據
   */
  data: {
    
  },

  /**
   * 生命周期函數--監聽頁面加載
   */
  onLoad: function (options) {
    let that = this;
    if (!wx.getStorageSync("userinfo")) {
      //是否登錄
      that.isloginindex()
    }

  },
  isloginindex() {
    //是否進入首頁
    if (wx.getStorageSync("userinfo")) {
      console.log("登錄")
    } else {
      //無信息
      console.log("否登錄")
      wx.redirectTo({
        url: '/page/login/login'
      })
    }
  }
})
 
 通過button open-type="getUserInfo"的方式授權登錄小程序流程,還沒有想到一個更好的辦法,目前是這么干的;如果有不對或者更好方式的歡迎指正或者一起交流
 
 

 


免責聲明!

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



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