获取用户微信绑定的手机号需要使用button的"open-type='getPhoneNumber'",在获取之前需要检测(checkSession)是否登录。
wxml:
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber"></button>js:
data:{ showLogin: false, //显示授权框 session_key: null, openid: null},// 检测是否登录checkSession: function() { var that = this; wx.checkSession({ success(res) { wx.getStorage({ key: 'phone', success(res) { if (res.data) { that.setData({ phoneNumber: res.data }) } else { that.setData({ showLogin: true }) } } }); }, fail(res) { that.login(); that.setData({ showLogin: true }) } })},// 登录login: function() { var that = this; wx.login({ success: res => { if (res.code) { wx.request({ url: 'xxx', method: "GET", data: { code: res.code }, header: { "content-type": "application/json" }, success: function(res) { that.setData({ openid: res.data.data.openid, session_key: res.data.data.session_key }); }, fail: function(res) { that.login() } }) } // 发送 res.code 到后台换取 openId, sessionKey, unionId } });},// 获取手机号getPhoneNumber: function(e) { var that = this, data = { encryptedData: e.detail.encryptedData, iv: e.detail.iv, openid: that.data.openid, session_key: that.data.session_key }; if (e.detail.errMsg == 'getPhoneNumber:fail user deny') { wx.showToast({ title: '授权失败,请重新授权', icon: 'none', duration: 2000 }) } else { wx.showLoading({ title: '授权中', mask: true }); that.setData({ showLogin: false, }); wx.request({ method: "GET", url: 'xxx', data: data, header: { 'content-type': 'application/json' // 默认值 }, success: function(res) { if (res.data.status == 1001) { var phoneNum = res.data.data; that.setData({ showLogin: false, phoneNumber: phoneNum }); // 存储手机号 wx.setStorage({ key: 'phone', data: phoneNum }) } // 隐藏授权框 wx.hideLoading() }, fail: function(res) { wx.showToast({ title: '授权失败,请重新授权', icon: 'none', duration: 2000 }); that.setData({ showLogin: true, }); that.login(); } }); } },














