小程序用户授权

微信授权,官方建议使用button,当用户点击时发起授权操作。

实现步骤:

1、给首页点击部分wxml添加open-type和bindgetuserinfo

<button class='list' open-type="getUserInfo" bindgetuserinfo='func'></button>

 注意:不能使用view等其他元素,必须使用button。button样式,去边框。

.list{
  padding: 0rpx 40rpx;
  height: 80rpx;
  width: 100%;
  float: left;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: white;
}
.list:after{
   border:none;
}

2、 实现func函数

function func(e){
  if (e.detail.userInfo ){
    var data = {
      nickName: e.detail.userInfo.nickName,
      gender: e.detail.userInfo.gender,
    };
    wx.request({
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
      },
      url: '',
      data: data,
      success: function (res) {
        if(res.data.code == 200){
          // do something
        }
      }
    });
  }
}

 建议,首页每个需要点击的地方,都添加授权事件。

原文地址:https://www.cnblogs.com/greys/p/10730697.html