85 lines
1.9 KiB
Vue
85 lines
1.9 KiB
Vue
<template>
|
|
<u-popup v-model="show" mode="bottom" border-radius="20">
|
|
<view class="p-30">
|
|
|
|
<view class="text-center u-font-32 u-m-b-20">
|
|
微信授权登录
|
|
</view>
|
|
|
|
<button
|
|
class="u-button bg-green text-white"
|
|
open-type="getPhoneNumber"
|
|
@getphonenumber="onGetPhone"
|
|
>
|
|
使用微信手机号授权登录
|
|
</button>
|
|
|
|
</view>
|
|
</u-popup>
|
|
</template>
|
|
|
|
<script>
|
|
export default {
|
|
data() {
|
|
return {
|
|
show: false
|
|
}
|
|
},
|
|
methods: {
|
|
open() {
|
|
this.show = true
|
|
},
|
|
|
|
// 微信授权手机号
|
|
onGetPhone(e) {
|
|
const { code } = e.detail
|
|
if (!code) {
|
|
this.$mytip.toast("授权失败")
|
|
return
|
|
}
|
|
this.doLogin(code)
|
|
},
|
|
|
|
// 登录逻辑
|
|
async doLogin(code) {
|
|
uni.showLoading({ title: "登录中...", mask: true })
|
|
|
|
try {
|
|
// ① 调后端:通过微信 code => openid + 手机号信息
|
|
const authRes = await this.$u.get(`/api/weChatAuth?code=${code}`)
|
|
|
|
// authRes: { openid, hasPhone: true/false, phoneList: [...] }
|
|
|
|
if (!authRes.hasPhone) {
|
|
// ② 未绑定手机号 → 让用户选择手机号
|
|
this.showPhoneSelector(authRes.phoneList, authRes.openid)
|
|
return
|
|
}
|
|
|
|
// ③ 已有绑定手机号 → 直接登录
|
|
await this.loginWithOpenId(authRes.openid)
|
|
|
|
} catch (err) {
|
|
this.$mytip.toast("登录失败")
|
|
}
|
|
},
|
|
|
|
// 提示选择手机号
|
|
showPhoneSelector(phoneList, openid) {
|
|
this.show = false
|
|
this.$emit("choosePhone", { phoneList, openid })
|
|
},
|
|
|
|
// 通过 openid 登录
|
|
async loginWithOpenId(openid) {
|
|
const loginRes = await this.$u.post('/api/weChatLoginByOpenId', { openid })
|
|
|
|
this.$u.vuex('vuex_token', loginRes.token)
|
|
this.$u.vuex('vuex_user', loginRes.loginUser)
|
|
|
|
uni.hideLoading()
|
|
uni.switchTab({ url: '/pages/index/index' })
|
|
}
|
|
}
|
|
}
|
|
</script> |