美文网首页微信小程序
小程序登录流程

小程序登录流程

作者: Grayly吖 | 来源:发表于2019-06-12 21:08 被阅读371次

一、登录原理

1、调用wx.login获得 code

  • WXML
  <view>
    <text>第1步:</text>
    <button type="primary" bindtap="wxlogin" size="mini">微信登录</button>
  </view>
  • JS
  // 第1步:微信登录, 得到code
  wxlogin() {
    wx.login({
      success: (res) => {
        console.log("微信登录", res);
        this.setData({
          code: res.code
        })
      },
      fail(err) {
        console.log(err);
      }
    })
  },

2、获取客户信息,wx.getUserInfo (要先授权), 获得 encryptedData,iv

官方文档说明

(因为微信官方考虑到用户隐私,所以关闭了用户进入小程序时自动弹出获取用户信息的接口,只能通过button绑定getuserinfo事件来获取用户信息)

  • WXML
<view>
    <text>第2步:</text>
    <button type="warn" open-type="getUserInfo" bindgetuserinfo="getUserInfo" size="mini">
        获取用户授权信息
    </button>
</view>
  • JS
  // 第2步: 获取用户授权信息,得到encryptedData,iv
  getUserInfo(event) {
    console.log("用户授权信息", event.detail);
    let detail = event.detail;
    this.setData({
      encryptedData: detail.encryptedData,
      iv: detail.iv
    })
  },

3、调用login接口,传入code,encryptedData,iv, 后台返回获得token

  • WXML
<view>
    <text>第3步:</text>
    <button type="primary" bindtap="login" size="mini">登录(我们自己的服务器)</button>
</view>
  • JS
  // 第3步:登录(我们自己的服务器)
  login() {
    let url = "/user/login";
    let data = {
      code: this.data.code,
      encryptedData: this.data.encryptedData,
      iv: this.data.iv
    }
    app.$http.post(url, data, true).then(res => {
      console.log("登录", res);

      // 第4步,把后台返回的token存到本地缓存
      try {
        wx.setStorageSync('token', res.user.token)
      } catch (e) { }
    })
  },

二、一键登录(三合一)

  • XML
  <button open-type="getUserInfo" bindgetuserinfo="login" type="default" size="mini" class='f14 ml-10'>
    立即登入
  </button>
  • JS
  // 一键登录
  login(event) {
    // 1、获取 encryptedData, iv 
    let { encryptedData, iv } = event.detail;
    // 微信登录
    wx.login({
      success: (res) => {
        // 2、获取code
        let code = res.code;
        // 3、登录后台服务器
        let url = "/user/login";
        let data = { encryptedData, iv, code }
        app.$http.post(url, data, true).then(res => {
          console.log("登录成功", res);
          this.setData({
            token: res.user.token
          })
          // 4、把token存到本地缓存
          try {
            wx.setStorageSync('token', res.user.token)
          } catch (e) { }
        })
      }
    })
  },

三、授权

wx.authorize()

  • 举个栗子
  onLoad: function (options) {

    // 查看用户是否授权
    wx.getSetting({
      success(res) {
        console.log("录音授权", res.authSetting['scope.record'])
        let record = res.authSetting['scope.record'];
        if (!record) {
          wx.authorize({
            scope: 'scope.record',
            success() {
              // 用户已经同意小程序使用录音功能,后续调用 wx.startRecord 接口不会弹窗询问
              wx.startRecord()
            }
          })
        }
      }
    })
  },

相关文章

网友评论

    本文标题:小程序登录流程

    本文链接:https://www.haomeiwen.com/subject/fpbrfctx.html