This commit is contained in:
jeremygan2021
2026-02-12 17:32:22 +08:00
parent 5a7b2032c4
commit abb1fe7c5e
3 changed files with 152 additions and 34 deletions

View File

@@ -20,8 +20,70 @@ export default function UserIndex() {
try { await Taro.chooseAddress() } catch(e) {}
}
const login = () => {
Taro.reLaunch({ url: '/pages/index/index' })
const login = async () => {
try {
// 1. 获取微信登录 Code
const { code } = await Taro.login()
if (!code) throw new Error('登录失败:无法获取 Code')
// 2. 调用后端登录 (仅 Code)
const res = await Taro.request({
url: 'https://market.quant-speed.com/api/wechat/login/',
method: 'POST',
data: { code }
})
console.log('code:', code)
if (res.statusCode === 200 && res.data.token) {
Taro.setStorageSync('token', res.data.token)
Taro.setStorageSync('userInfo', res.data)
setUserInfo(res.data)
Taro.showToast({ title: '登录成功', icon: 'success' })
} else {
throw new Error(res.data.error || '登录请求失败')
}
} catch (e) {
Taro.showToast({ title: e.message || '登录失败', icon: 'none' })
}
}
const getPhoneNumber = async (e) => {
const { code: phoneCode, errMsg } = e.detail
if (errMsg !== "getPhoneNumber:ok") {
Taro.showToast({ title: '获取手机号失败', icon: 'none' })
return
}
try {
Taro.showLoading({ title: '登录中...' })
// 1. 获取登录 Code
const { code: loginCode } = await Taro.login()
// 2. 调用后端登录 (Code + PhoneCode)
const res = await Taro.request({
url: 'https://market.quant-speed.com/api/wechat/login/',
method: 'POST',
data: {
code: loginCode,
phone_code: phoneCode
}
})
Taro.hideLoading()
if (res.statusCode === 200 && res.data.token) {
Taro.setStorageSync('token', res.data.token)
Taro.setStorageSync('userInfo', res.data)
setUserInfo(res.data)
Taro.showToast({ title: '授权登录成功', icon: 'success' })
} else {
throw new Error(res.data.error || '登录失败')
}
} catch(err) {
Taro.hideLoading()
Taro.showToast({ title: err.message || '系统异常', icon: 'none' })
}
}
const serviceGroups = [
@@ -65,9 +127,24 @@ export default function UserIndex() {
</View>
<View className='info-col'>
<Text className='nickname'>{userInfo?.nickname || '未登录用户'}</Text>
<Text className='uid'>ID: {userInfo ? '888888' : '----'}</Text>
<Text className='uid'>ID: {userInfo ? (userInfo.phone_number || userInfo.id || '----') : '----'}</Text>
{!userInfo && (
<Button className='btn-login' onClick={login}> / </Button>
<View className='login-btns'>
<Button
className='btn-login'
onClick={login}
style={{ marginRight: '10px' }}
>
</Button>
<Button
className='btn-login primary'
openType="getPhoneNumber"
onGetPhoneNumber={getPhoneNumber}
>
</Button>
</View>
)}
</View>
<View className='card-bg-effect' />