微信小程序授权

官方文档

授权
部分接口需要经过用户授权同意才能调用。我们把这些接口按使用范围分成多个 scope ,用户选择对 scope 来进行授权,当授权给一个 scope 之后,其对应的所有接口都可以直接使用。
此类接口调用时:
如果用户未接受或拒绝过此权限,会弹窗询问用户,用户点击同意后方可调用接口;
如果用户已授权,可以直接调用接口;
如果用户已拒绝授权,则不会出现弹窗,而是直接进入接口 fail 回调。请开发者兼容用户拒绝授权的场景。

小程序用户信息组件示例代码(官方文档

<!-- 如果只是展示用户头像昵称,可以使用 <open-data /> 组件 -->
<open-data type="userAvatarUrl"></open-data>
<open-data type="userNickName"></open-data>
<!-- 需要使用 button 来授权登录 -->
<button wx:if="{{canIUse}}" open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">授权登录</button>
<view wx:else>请升级微信版本</view>
Page({
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad: function() {
    // 查看是否授权
    wx.getSetting({
      success (res){
        if (res.authSetting['scope.userInfo']) {
          // 已经授权,可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function(res) {
              console.log(res.userInfo)
            }
          })
        }
      }
    })
  },
  bindGetUserInfo (e) {
    console.log(e.detail.userInfo)
  }
  })

使用 promise 封装的wx请求

othersRequest(type) { 
  return new Promise((resolve, reject) => {
        wx[type]({        
        success: (res => {
        resolve(res);        }),        
        fail: (res => {  
                 reject(res)        })      })    })  },
  checkAuthorize() {    return request.othersRequest('getSetting').then(res => {      if (res.authSetting['scope.userInfo']) {        app.globalData.isAuthorization = true;        this.getUserInfo();        apiService.wechatLogin();      } else {        app.globalData.isAuthorization = false;      }    }).catch(err => {      request.errorHander(err);    })  },
  getUserInfo() {    return request.othersRequest('getUserInfo').then(res => {      const userInfo = this.refactorUserInfo(res.userInfo);      app.globalData.userInfo = userInfo;      this.setUserInfo(userInfo);
    }).catch(err => {      request.errorHander(err);    })  },
  wechatLogin() {    
  return request.othersRequest('login').then(res => {      globalData.wxLoginCode = res.code;      
      })
      .catch(err => {      
      this.errorHander(err);    })  },
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值