實(shí)現(xiàn)微信授權(quán)登錄
注意:獲取手機(jī)號信息之前需要先調(diào)用wx.login,否則可能出現(xiàn)第一次獲取用戶信息失敗問題
完整代碼如下
```
<template>
<view class="page">
<button class="wxLogin" open-type="getPhoneNumber"
@getphonenumber="getPhoneNumber">微信登錄</button>
</view>
</template>
<script>
export default {
data() {
return {
wxloginCode: '',
};
},
onLoad() {
let that = this
//
wx.login({
success(res) {
if (res.code) {
that.wxloginCode = res.code
console.log('code',that.wxloginCode)
? ? }
}
})
},
methods: {
getPhoneNumber(e) {
console.log('code',this.wxloginCode)
console.log('phone',e)
if (this.wxloginCode) {
if (e.detail.encryptedData.length < 1) {
uni.showToast({
title: '授權(quán)失敗,請重新授權(quán)',
icon: 'error'
})
return
}
//傳wx.login的code和getPhoneNumber的encryptedData、iv給后臺苹支,手機(jī)號解密操作在后臺砾隅。如需前臺解密代碼可以評論或私信
// let para = {
// jscode: this.wxloginCode,
// encryptedData: e.detail.encryptedData,
// iv: e.detail.iv,
// }
// that.$request('/wxAuth', 'POST', para, {
// isToken: false,
// 'Content-Type': 'application/x-www-form-urlencoded',
// }).then(res => {
// })
} else {
uni.showToast({
title: 'code獲取失敗,請重新授權(quán)',
icon: 'error'
})
return
}
},
}
}
</script>
<style lang="scss" scoped>
.page {
.wxLogin {
text-align: center;
width: 90%;
margin-top: 160rpx;
height: 90rpx;
line-height: 90rpx;
background: linear-gradient(-90deg, #0AB6FE 0%, #495AFF 100%);
box-shadow: 0rpx 12rpx 13rpx 0rpx rgba(51, 145, 255, 0.2);
border-radius: 45rpx;
font-size: 36rpx;
font-family: Source Han Sans CN;
font-weight: bold;
color: #FFFFFF;
}
}
</style>
```