微信小程序授权登录并登记手机号码,以下是根据小程序官网梳理的流程图,方便自己理解;
官方指引:小程序登录
// 微信授权登录bindGetUserInfo: function(e) {// 将用户信息存入全局变量,供绑定手机号使用app.globalData.encryptedData=e.detail.encryptedDataapp.globalData.iv=e.detail.ivif (e.detail.userInfo) {//用户按了允许授权按钮var that = this;// 获取到用户的信息了,打印到控制台上看下// console.log(e.detail.userInfo)wx.login({success: res => {var code = res.codeconsole.log("用户的code:" + res.code)//调用后端接口获取openIdwx.request({url: 'http://localhost:8080/login/WechatLogin',method: 'POST',data: {code: res.code},header: {'content-type': 'application/x-www-form-urlencoded'},// 执行成功将数据存入本地缓存success: res => {console.log(res.data)if (res.data) {console.log("用户的openid:" + res.data.openid)app.globalData.userInfo['user_id'] = res.data.user_idwx.setStorageSync('openid', res.data.openid)} else {console.log('微信授权失败喽,请重新授权')}//将用户信息放入缓存,登记手机号后与手机号一起存储let that = thislet userInfo = e.detail.userInfo;app.globalData.userInfo['avatarUrl'] = userInfo.avatarUrl; // 头像app.globalData.userInfo['nickName'] = userInfo.nickName; // 昵称app.globalData.userInfo['gender'] = userInfo.gender; // 性别app.globalData.userInfo['userId'] = userInfo.userId;//写入缓存wx.setStorageSync('userInfo', app.globalData.userInfo);that.setData({showAvata: true})// 授权成功绑定手机号wx.navigateTo({url: '/pages/my/login/bingphonenum/bingphonenum'})}})}})//授权成功后,通过改变 isHide 的值,让实现页面显示出来,把授权页面隐藏起来that.setData({isHide: false})}}