微信小程序之button组件--wx.login()

微信小程序之button组件

'''
推荐使用button组件获取授权微信用户的信息

点击按钮事件自动触发获取wx.getUserInfo
'''

1. // pages/login/login.wxml

<view>
    <button class="submit" open-type="getUserInfo" bindgetuserinfo="onClickSubmit">登录 | 注册</button>
</view>

2. // pages/login/login.js ---wx.login()

onClickSubmit: function(e) {
    //wx.login用于给当前用户获取一个登录凭证(有效期五分钟),即:response.code
    //点击按钮事件自动触发获取wx.getUserInfo,参数e.detail.userInfo,获取微信用户信息。
    wx.login({
      success: (response) => {
        wx.request({
          url: api.Login,
          data: {
            phone: this.data.phone,
            code: this.data.code,
            nickname: e.detail.userInfo.nickName,
            avatar: e.detail.userInfo.avatarUrl,
            wx_code: response.code
          },
          method: 'POST',
          success: function(res) {
            if (res.data.status) {
              app.initUserInfo(res.data.data, e.detail.userInfo);
              wx.navigateBack();
            } else {
              wx.showToast({
                title: res.data.message,
                icon: 'none'
              })
            }
          }
        })
      }
    })
  },
  

3. //app.js -----app.initUserInfo(),登录信息初始化,并缓冲到本地

App({
  onLaunch: function() {
    var userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.globalData.userInfo = userInfo;
    }
  },
  globalData: {
    userInfo: null
  },
  initUserInfo: function(tokenInfo, userInfo) {
    var info = {
      nickName: userInfo.nickName,
      avatarUrl: userInfo.avatarUrl,
      token: tokenInfo.token,
      phone: tokenInfo.phone
    };
    this.globalData.userInfo = info
    wx.setStorageSync('userInfo', info);
  },
  logoutUserInfo:function(){
    wx.removeStorageSync('userInfo');
    this.globalData.userInfo=null;
  }
})

猜你喜欢

转载自www.cnblogs.com/daviddd/p/12456433.html