赞
踩
一、首先页面上引入button标签
//login.wxml
<button open-type="getPhoneNumber" type="primary" bindgetphonenumber="onGetPhoneNumber">
<image class="wx-btn" src="../../assets/images/index/wx-btn.png" />
<view>微信一键登录</view>
</button>
二、获取步骤
1、获取code
,一定要提前获取
onLoad(options) {
wx.login({
success(res) {
if (res.code) {
that.setData({
code: res.code
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
},
2、获取session_key和解密手机号
onGetPhoneNumber(e) { if (e.detail.errMsg.indexOf('ok') != -1) { var that = this; getOpenId(this.data.code).then(rs => { var session_key = rs.data.session_key; //解密手机号 var msg = e.detail.errMsg; var encryptedData = e.detail.encryptedData; var iv = e.detail.iv; wx.checkSession({ success: function () { //这里进行请求服务端解密手机号 (session_key, encryptedData, iv) that.onLogin(session_key, encryptedData, iv) }, fail: function (res) { console.log(res, '微信session已过期') that.getNewSession().then(session_key => { that.onLogin(session_key, encryptedData, iv) }, error => { Toast('获取数据失败'); }) } }) }) } else { let errMsg = e.detail.errMsg; console.log('获取密文向量失败', errMsg); if (errMsg.indexOf('deny' != -1)) { errMsg = "您已拒绝,请重新点击并授权登录" } if (errMsg.indexOf('bind' != -1)) { errMsg = "请先绑定后,再次点击并授权登录" } Toast(errMsg); } },
//重新获取code getNewSession() { return new Promise((resolve, reject) => { wx.login({ success(res) { if (res.code) { getOpenId(res.code).then(rs => { resolve(rs.data.session_key) }) } else { console.log('登录失败!' + res.errMsg) reject(res.errMsg) } } }) }) },
//登录 onLogin(session_key, encryptedData, iv) { wxLogin({ sessionKey: session_key, encryptedData, iv }).then(rs => { if (rs.data) { local.setSync("token", rs.data.token) local.setSync("userInfo", rs.data) this.uploadStore() //连接webScoket ws_connect(rs.data.id); //判断用户类型 if (rs.data.type == 2) { wx.switchTab({ url: '/pages/index/index' }); } else { wx.switchTab({ url: '/pages/mIndex/mIndex' }); } } else { Dialog.alert({ title: '提示', message: '系统不存在该用户,请联系管理员', }).then(() => { // on close }); } }) },
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。