微信小程序獲取手機號流程


小程序中獲取手機號前提


小程序需企業認證,才可以獲取用戶的手機號,個人開發者是不能獲取的

嗶嗶下


官方文檔給出需先登錄才可獲取手機號 傳送門
思路為:login登錄獲取code-->code傳給后台-->后台根據code獲取sessionKey
前台通過觸發獲取手機號事件得到加密數據-->傳給后台,后台通過之前獲取的
sessionKey來解密,並將數據返回給前台

注意項


code傳給后台時后台需去訪問官網給的接口去檢驗 傳送門

擼碼

  getPhoneNumber: function (e) {
    let _this = this;
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      //校驗是否過期
      wx.checkSession({
        success: function () {
          // session_key 未過期,並且在本生命周期一直有效
          _this.gettel(e);//獲取手機號
        },
        fail: function () {
          // session_key 已經失效,需要重新執行登錄流程
          wx.login({
            success: function (res) {
              wx.request({
                url: 'xxxxxx',
                method: 'post',
                data: {
                  code: res.code
                },
                header: {
                  'Content-Type': 'application/x-www-form-urlencoded'
                },
                success: function (r) {
                  _this.gettel(e);//獲取手機號
                },
                fail: function (err) {
                  console.log("登錄失敗");
                  console.log(err);
                }
              })
            }
          })
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '需獲取信息才可查看歷史預約',
      })
    }
  },
  gettel: function (e) {
    let _this = this;
    let iv = e.detail.iv;
    let encryptedData = e.detail.encryptedData;
    wx.request({
      url: 'xxxxxxxxxxxxxxxx',
      method: 'post',
      data: {
        iv: iv,
        encryptedData: encryptedData
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res);//手機號在這里面哦
        <!--let item = JSON.parse(res.data.data);-->
      },
      fail: function (err) {
        console.log(err);
      }
    })
  }

在嗶嗶下

wx.login首次登錄我寫在需要獲取手機號時的page中onload事件中
因為login返回的code有時效,所以在需要的時候在調用


免責聲明!

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



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