【小程序】使用button的open-type="getUserInfo"引导用户进行授权

一、 前言

小程序官方文档,上面说明

wx.getUserInfo(OBJECT) 注意:此接口有调整,使用该接口将不再出现授权弹窗,请使用

<button open-type="getUserInfo"></button>

引导用户主动进行授权操作
当用户未授权过,调用该接口将直接报错 当用户授权过,可以使用该接口获取用户信息

如上文,之前用户未授权过时,调用wx.getUserInfo会调出授权框;但现在在用户未授权过时调用该接口,会直接走fail方法。

所以我们要使用上述button来请求用户授权。

二、主体

index页面作为展示授权按钮的页面,并且在app.json中将index作为首页。在判断用户授权之后跳转到其他页面。

index.wxml

<button 
	wx:if="{{canIUse}}" 
	open-type="getUserInfo" 
	bindgetuserinfo="bindGetUserInfo"
>授权登录</button>
<view wx:else>请升级微信版本</view>

index.js

Page({
  data: {
	 //判断小程序的API,回调,参数,组件等是否在当前版本可用。
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad: function() {
    // 查看是否授权
    wx.getSetting({
      success: function(res){
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function(res) {
              console.log(res.userInfo)
              //用户已经授权过
            }
          })
        }
      }
    })
  },
  bindGetUserInfo: function(e) {
    console.log(e.detail.userInfo)
    if (e.detail.userInfo){
      //用户按了允许授权按钮
    } else {
      //用户按了拒绝按钮
    }
  }
})

*tips:授权之后要跳转到的页面若为 tabBar中的页面 ,则不可以用wx.navigateTo和wx.redirecTo,而应该用wx.switchTab或wx.reLaunch。

UniApp 是一套基于 Vue.js 的跨平台框架,用于快速开发微信小程序、H5、支付宝小程序以及更多。下面是一个简单的 UniApp 项目中,利用 `open-type=chooseAvatar` 属性来让用户选择头像的基本代码示例: ```html <!-- uni-app 页面模板 --> <template> <view class="container"> <button @click="handleChooseAvatar">选择头像</button> <image :src="selectedAvatar" :mode="isShowAvatar ? 'scaleToFill' : 'noBorder'" /> </view> </template> <script> export default { data() { return { selectedAvatar: '', isShowAvatar: false, }; }, methods: { handleChooseAvatar() { this.$api.openSetting({ success(res) { if (res.authSetting['scope.userInfo']) { this.getUserInfo(); } else { // 如果用户授权,可以引导用户去设置中心开启权限 console.log('用户授权'); } } }); }, getUserInfo() { uni.getUserInfo({ openType: 'getAvatar', // 这里是关键部分,注意是 getAvatar 而不是 chooseAvatar avatarField: ['head肖像'], success(res) { const avatarUrl = res.tempAvatar; this.selectedAvatar = avatarUrl; // 更新头像 URL this.isShowAvatar = true; // 显示已选头像 }, fail(err) { console.error('获取用户信息失败', err); } }); } } }; </script> <style scoped> .container { display: flex; justify-content: space-between; } </style> ``` 在这个例子中,`getUserInfo` 方法负责调用微信小程序用户信息接口,并指定需要头像 (`openType: 'getAvatar'`)。请注意,微信小程序的实际API可能会有所不同,此代码仅供参考。
评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值