openIndex.js 2.0 KB
//index.js
//获取应用实例
const app = getApp()

Page({
  data: {

  },

  getOpenId() {
    let that = this
    wx.login({
      success: (res) => {
        let url = 'wxapp/public/getSessionKey'
        let param = {
          code: res.code,
        }

        app.post(url, param).then((res) => {
          console.log(res)
          that.setData({
            openid: res.data.openid,
            session_key: res.data.session_key
          })
          wx.getSetting({
            success: res => {
              if (res.authSetting['scope.userInfo'] === true) {
                wx.getUserInfo({
                  success: reg => {
                    that.setData({
                      encrypted_data: reg.encryptedData,
                      iv: reg.iv
                    })
                   that.login()
                  }
                })
              }

            }
          })

        }).catch((errMsg) => {
        })


      }
    });
  },

  // 获取用户权限信息
  getUserInfo(e) {
    console.log(e)
    let that = this;
    if (e.detail.errMsg == "getUserInfo:ok") {
      that.setData({
        encrypted_data: e.detail.encryptedData,
        iv: e.detail.iv
      })
      that.login()
    }
  },
  // 登录
  login() {
    let that = this;
    let url = "wxapp/public/login";
    let data = {
      openid: that.data.openid,
      session_key: that.data.session_key,
      encrypted_data: that.data.encrypted_data,
      iv: that.data.iv,
    }
    app.post(url, data).then((res) => {
      wx.setStorageSync("token", res.data.token);
      wx.showLoading({
        title: '正在进入',
      })

      let t = setInterval(function () {
        clearInterval(t)
        wx.switchTab({
          url: '/pages/index/index',
        })
        wx.hideLoading()
      }, 1500)

    }).catch((err) => {

    })



    // }).catch((errMsg) => { })

  },




  // 111
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getOpenId();
  },








})