微信小程序授权获取用户信息

本文介绍了在微信小程序中如何实现用户授权获取个人信息的流程,包括使用`getUserProfile`和`getUserInfo`接口的条件及区别。通过示例代码展示了在不同版本小程序中授权登录的实现方式,帮助开发者避免踩坑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

小程序授权获取用户信息


因为看了官方的api和后来更新的信息, 当时自己也搞了一会儿, 踩坑了, 各位老铁们 可参考:
效果图如下:
在这里插入图片描述
话不多说直接上代码

wxml

<view wx:if="{{canIUse}}" class="flex_style">
	  <view class="headView flex_style">
			  <view class="flex_style"><image class="headImage" src='../../images/logo.png' mode='scaleToFill'></image></view>
		    <view class="titleText">申请获取以下权限</view>
		    <view class="contentText">获得你的公开信息(昵称,头像等)</view>

			<button wx:if="{{canIUseGetUserProfile}}" bindtap="getUserProfile" class="authBtn" type='primary'> 授权登录 </button>
      <button wx:else open-type="getUserInfo" bindgetuserinfo="getUserInfo" class="authBtn" type='primary'> 授权登录 </button>

		</view>
		
</view>

js

Page({
  data:{
    canIUseGetUserProfile:false,
    canIUse:wx.canIUse('button.open-type.getUserInfo')
  },
   onLoad: function(options) {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
  },
  // 此方法基础版本2.10.4以上可以支持
 getUserProfile(e) {
    console.log('点击授权登录了')
    wx.getUserProfile({
      desc:'用户信息',
      success: (res) => {
        console.log('222222',res)
        if (res.userInfo) {
          //用户按了允许授权按钮
          var that = this;
          // 获取到用户的信息了,打印到控制台上看下
          console.log("用户的信息如下:",res.userInfo);
         }
      }
    })
  },
getUserInfo(res) {
        if (res.detail.userInfo) {
          //用户按了允许授权按钮
          var that = this;
          // 获取到用户的信息了,打印到控制台上看下
          console.log("用户的信息如下:");
          console.log(res.detail.userInfo);
        } else {
          //用户按了拒绝按钮
        }
  },
})
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值