微信小程序获取用户新接口采坑解决。
发布于 3 年前 作者 min74 2419 次浏览 来自 分享

问题描述

相信很多人在使用微信小程序新接口获取到用户信息时,或多或少都遇到过这种情况。

调用wx.getUserProfile 报错getUserProfile:fail can only be 
invoked by user TAP gesture.

这个错误信息是啥意思?大致的意思就是,需要将授权按钮设置为点击事件,也就是给对应的触发条件绑定一个bintap事件。

解决思路

第一步。确认代码无误。
首先我们需要在wxml中这样定义登录按钮。

<view class="login-btn">
  <button class="login-btn" style="background-color: #07C160;color:white;width:100%;"  open-type="getUserProfile" bindtap="getUserProfile">
    登录授权
  </button>
</view>

接着在js文件中定义如下的信息。

  getUserProfile() {
    wx.login({
      success(res) {
        let code = res.code;
        wx.getUserProfile({
          lang: 'en',
          desc: '获取授权',
          success: function (res) {
            console.log(res)
          }, fail: function (res) {
            console.log('fail-get-userinfo', res)
          }, complete: function () {
            console.log('complete-get-userinfo')
          }
        })
      }
    });
  },

在实际中发现,点击事件名称换做非getUserProfile名称,就不行了。

第二步,使用微信真机调试。
符合上面的两种情况,就可以获取到用户信息了。

希望对大家有所帮助。

1 回复

完善一下。完善js文件,wxml文件没有变动。需要将getUserProfile和login两个接口给分离开,如果getUserProfile包含在login里面,微信开发者工具发现不能调试。

Page({
  data: {
    code: '',
  },
  onLoad: function (e) {
  },
  // 调用wx.getUserProfile接口
  getUserProfile() {
    let that = this
    wx.getUserProfile({
      desc: '获取授权',
      success: function (res) {
        console.log(res)
        request.postRequest('wechat/login', {// 请求后端登录接口
          userInfo: res.userInfo,
          code: that.data.code,// 将wx.login中的code一并传入到后台
        }, function (res) {
        })
      }
    })
   // 调用wx.login接口
    wx.login({
      success: function (res) {
        that.setData({
          code: res.code// 将code复制给data变量
        })
      }
    })
  },
})
回到顶部