微信小程序:登录自动弹出用户授权

备注:已不能这样使用了,缅怀一下

小程序启动时,不是先运行app.js然后再调用index.js,而是异步执行的。
邀请好友答题,好友第一次进来要进行微信登录-->获取access-token-->获取用户信息-->绑定个人信息-->首页逻辑处理-->跳转好友pk页等,流程比价复杂并且还有数据交叉使用情况。
一开始我以index作为首页,因为app.js和index.js异步执行,使用Promise也发现启动过程很是繁琐复杂。所以参考了《知乎答题王》多加了一个home页。

  • app.js调用wx.login,处理微信登录和个人后台系统登录;
  • index.js调用wx.getUserInfo,作为启动页来获取用户个人信息;
  • home.js作为首页来处理业务逻辑。

流程清晰了不少。如果有后台系统验证用户信息以及用户权限等业务,建议增加一个启动页。

获取用户信息拒绝后,默认不会再重新弹出授权框,需要调用wx.openSetting打开手机《设置》允许使用数据

微信小程序:登录自动弹出用户授权_第1张图片

// index.js  登录业务:
onLoad: function (options) {
    wx.showLoading({
      title: '登录中'
    })
    wx.getSetting({
      success: res => {
        console.log(res)
        if (res.authSetting['scope.userInfo'] === true) { // 成功授权
          // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
          wx.getUserInfo({
            success: res => {
              console.log(res)
              this.setUserInfoAndNext(res)
            },
            fail: res => {
              console.log(res)
            }
          })
        } else if (res.authSetting['scope.userInfo'] === false) { // 授权弹窗被拒绝
          wx.openSetting({
            success: res => {
              console.log(res)
            },
            fail: res => {
              console.log(res)
            }
          })
        } else { // 没有弹出过授权弹窗
          wx.getUserInfo({
            success: res => {
              console.log(res)
              this.setUserInfoAndNext(res)
            },
            fail: res => {
              console.log(res)
              wx.openSetting({
                success: res => {
                  console.log(res)
                },
                fail: res => {
                  console.log(res)
                }
              })
            }
          })
        }
      }
    })
  },

  // 获取个人信息成功,然后处理剩下的业务或跳转首页
  setUserInfoAndNext(res) {
    // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
    // 所以此处加入 callback 以防止这种情况
    if (this.userInfoReadyCallback) {
      this.userInfoReadyCallback(res)
    }
    wx.hideLoading()
    // 跳转首页
    setTimeout(() => {
      wx.reLaunch({
        url: '../home/home'
      })
    }, 1000)
  },

从 2018/4/30 开始,使用 wx.getUserInfo 接口直接弹出授权框的开发方式将逐步不再支持,(因为Facebook用户隐私泄密事件引发的社会关注),想获取用户隐私信息必须要友好!
腾讯公告:小程序与小游戏获取用户信息接口调整

  • 一、小程序
    1、使用 button 组件,并将 open-type 指定为 getUserInfo 类型,获取用户基本信息。
    详情参考文档:
    https://developers.weixin.qq.com/miniprogram/dev/component/button.html
    2、使用 open-data 展示用户基本信息。
    详情参考文档:
    https://developers.weixin.qq.com/miniprogram/dev/component/open-data.html

  • 二、小游戏
    1、使用用户信息按钮 UserInfoButton。
    详情参考文档:
    https://developers.weixin.qq.com/minigame/dev/document/open-api/user-info/wx.createUserInfoButton.html
    2、开放数据域下的展示用户信息。
    详细参考文档:
    https://developers.weixin.qq.com/minigame/dev/document/open-api/data/wx.getUserInfo.html

你可能感兴趣的:(微信小程序:登录自动弹出用户授权)