Files
consumer-front/src/pages/auth/loading.vue
T

525 lines
17 KiB
Vue
Raw Normal View History

2026-07-02 18:25:23 +08:00
<template>
<view class="loading-page">
<view class="loading-spinner"></view>
<text class="loading-text">{{ statusText }}</text>
</view>
</template>
<script>
import config from '@/config/env.js';
import { gatewayGet, gatewayPost } from '@/utils/request.js';
import { detectPlatform, getAppNo } from '@/utils/env.js';
export default {
data() {
return {
statusText: '正在登录...',
deviceId: '',
2026-07-11 10:28:43 +08:00
action: '',
2026-07-02 18:25:23 +08:00
};
},
onLoad(options) {
this.deviceId = options.device_id || '';
2026-07-11 10:28:43 +08:00
this.action = options.action || '';
2026-07-02 18:25:23 +08:00
// #ifdef H5
2026-07-09 18:49:56 +08:00
// Mock 模式:跳过微信 OAuth,直接登录
2026-07-11 10:28:43 +08:00
if (config.mockWechatLogin && this.action !== 'userinfo') {
2026-07-09 18:49:56 +08:00
this.mockLogin();
return;
}
2026-07-11 11:01:22 +08:00
// 从 URL 参数获取 codeApp.vue 跳转时带过来)
// 支付宝回调参数名是 auth_code,微信是 code
let code = options.code || options.auth_code || '';
2026-07-02 19:32:07 +08:00
if (!code) {
const urlParams = new URLSearchParams(window.location.search);
code = urlParams.get('code') || urlParams.get('auth_code') || '';
2026-07-02 19:32:07 +08:00
}
2026-07-02 18:25:23 +08:00
2026-07-17 12:20:20 +08:00
// 解析 state 参数(OAuth 标准保证 state 原样回传,包含 action 和 device_id
if (!this.action || !this.deviceId) {
const stateRaw = options.state || '';
if (stateRaw) {
try {
const stateObj = JSON.parse(decodeURIComponent(stateRaw));
if (!this.action && stateObj.action) {
this.action = stateObj.action;
}
if (!this.deviceId && stateObj.device_id) {
this.deviceId = stateObj.device_id;
}
} catch (_) {
// state 解析失败,继续用 localStorage 兜底
}
}
}
// 兜底:从 localStorage 恢复(页面复用时 onLoad 不触发,localStorage 由跳转函数清理)
2026-07-11 11:01:22 +08:00
if (!this.action) {
this.action = localStorage.getItem('__auth_action') || '';
}
if (!this.deviceId) {
this.deviceId = localStorage.getItem('__auth_device_id') || '';
}
console.log('[loading] onLoad - action:', this.action, 'deviceId:', this.deviceId, 'code:', code ? 'yes' : 'no');
2026-07-11 10:28:43 +08:00
if (this.action === 'userinfo') {
// 获取用户信息流程
if (code) {
this.handleUserInfoCallback(code);
} else {
this.startUserInfoAuth();
}
2026-07-02 18:25:23 +08:00
} else {
2026-07-11 10:28:43 +08:00
// 登录流程
if (code) {
this.handleCallback(code);
} else {
this.startAuth();
}
2026-07-02 18:25:23 +08:00
}
// #endif
// #ifndef H5
// 小程序环境暂不支持,跳回扫码页
uni.redirectTo({ url: '/pages/index/scan' });
// #endif
},
methods: {
/**
* 发起 OAuth 授权(静默授权,只获取 openid)
2026-07-02 18:25:23 +08:00
*/
async startAuth() {
2026-07-11 17:52:33 +08:00
// 清除上次使用的 code 标记
uni.removeStorageSync('__used_auth_code');
2026-07-02 18:25:23 +08:00
const platform = detectPlatform();
const appNo = getAppNo(platform);
if (!appNo) {
// 非微信环境,跳转注册页(手机号注册)
this.goToRegister();
return;
}
try {
this.statusText = '正在获取授权...';
// 存入 localStorage(页面复用时 onLoad 不会重新触发,需要从 localStorage 读取)
if (this.deviceId) {
localStorage.setItem('__auth_device_id', this.deviceId);
}
2026-07-11 11:37:53 +08:00
// 回调地址:必须与微信公众号后台注册地址一致,不能带自定义参数
const redirectUri = config.authRedirectUri || (
2026-07-02 19:04:08 +08:00
window.location.origin.replace(/^http:/, 'https:') + window.location.pathname
2026-07-02 18:25:23 +08:00
);
2026-07-15 17:37:23 +08:00
// 静默授权:微信用 snsapi_base,支付宝用 auth_base
const scopes = platform === 'alipay' ? 'auth_base' : 'snsapi_base';
2026-07-17 14:40:21 +08:00
// 构建 state(包含 device_id,回调时原样回传)
const stateObj = {};
if (this.deviceId) {
stateObj.device_id = this.deviceId;
}
2026-07-02 18:25:23 +08:00
const res = await gatewayGet('/api/v1/user/auth/url', {
app_no: appNo,
2026-07-15 17:37:23 +08:00
scopes: scopes,
2026-07-02 18:25:23 +08:00
redirect_uri: redirectUri,
2026-07-17 14:40:21 +08:00
state: Object.keys(stateObj).length > 0 ? JSON.stringify(stateObj) : '',
2026-07-02 18:25:23 +08:00
});
const data = res.data || {};
if (data.code === 0 && data.data && data.data.auth_url) {
2026-07-17 14:40:21 +08:00
// 后端已将 state 写入授权 URL,直接跳转
window.location.href = data.data.auth_url;
2026-07-02 18:25:23 +08:00
} else {
uni.showToast({ title: data.message || '获取授权失败', icon: 'none' });
setTimeout(() => this.goToScan(), 1500);
}
} catch (e) {
console.error('[Auth] startAuth error:', e);
uni.showToast({ title: '网络请求失败', icon: 'none' });
setTimeout(() => this.goToScan(), 1500);
}
},
/**
2026-07-11 10:28:43 +08:00
* 处理授权回调(用 code 换 openid,再用 openid 登录)
2026-07-02 18:25:23 +08:00
*/
async handleCallback(code) {
const appNo = uni.getStorageSync('app_no') || getAppNo(detectPlatform());
if (!appNo) {
uni.showToast({ title: '无法获取应用信息', icon: 'none' });
this.goToScan();
return;
}
2026-07-11 17:52:33 +08:00
// 防止 code 重复提交:先检查再标记
const usedCode = uni.getStorageSync('__used_auth_code');
if (usedCode === code) {
console.warn('[loading] code 已使用过,跳过');
return;
}
uni.setStorageSync('__used_auth_code', code);
// 立即清除 URL 中的 code 参数,避免刷新重复处理
const url = new URL(window.location.href);
url.searchParams.delete('code');
url.searchParams.delete('auth_code');
2026-07-11 17:52:33 +08:00
url.searchParams.delete('state');
window.history.replaceState({}, '', url.toString());
2026-07-02 18:25:23 +08:00
try {
this.statusText = '正在验证身份...';
2026-07-11 10:28:43 +08:00
// 1. 用 code 换取 openidsnsapi_base 静默授权)
const callbackRes = await gatewayPost('/api/v1/user/auth/exchange', {
2026-07-02 18:25:23 +08:00
app_no: appNo,
code: code,
});
2026-07-11 10:28:43 +08:00
const callbackData = callbackRes.data || {};
console.log('[loading] auth callback response:', JSON.stringify(callbackData, null, 2));
if (callbackData.code !== 0 || !callbackData.data) {
uni.showToast({ title: callbackData.message || '授权失败', icon: 'none' });
setTimeout(() => this.goToScan(), 1500);
return;
}
const openid = callbackData.data.openid;
if (!openid) {
uni.showToast({ title: '获取用户标识失败', icon: 'none' });
setTimeout(() => this.goToScan(), 1500);
return;
}
// 存储 openid
uni.setStorageSync('openid', openid);
// 2. 用 openid 调用登录接口
this.statusText = '正在登录...';
const loginRes = await gatewayPost('/api/v1/user/login', {
app_no: appNo,
openid: openid,
});
const data = loginRes.data || {};
console.log('[loading] login response:', JSON.stringify(data, null, 2));
2026-07-02 18:25:23 +08:00
if (data.code === 0 && data.data) {
const result = data.data;
2026-07-02 18:25:23 +08:00
if (result.register) {
2026-07-11 10:28:43 +08:00
// 已注册 → 存 token → 进入开门页
2026-07-02 18:25:23 +08:00
uni.setStorageSync('token', result.token);
// 存储 user_info(接口返回的字段,后续 snsapi_userinfo 授权可补充)
const existing = uni.getStorageSync('user_info') || {};
uni.setStorageSync('user_info', {
user_id: result.user_id || existing.user_id || '',
phone: result.phone || existing.phone || '',
nickname: result.nickname || existing.nickname || '',
avatar: result.avatar || existing.avatar || '',
});
2026-07-02 18:25:23 +08:00
this.goToHome();
} else {
2026-07-11 10:28:43 +08:00
// 未注册 → 存 temp_token → 跳注册页
2026-07-02 18:25:23 +08:00
uni.setStorageSync('temp_token', result.temp_token);
this.goToRegister();
}
} else {
uni.showToast({ title: data.message || '登录失败', icon: 'none' });
setTimeout(() => this.goToScan(), 1500);
}
} catch (e) {
console.error('[Auth] login error:', e);
uni.showToast({ title: '网络请求失败', icon: 'none' });
setTimeout(() => this.goToScan(), 1500);
}
},
2026-07-11 10:28:43 +08:00
/**
* 发起非静默授权获取用户信息(snsapi_userinfo,弹窗确认)
*/
async startUserInfoAuth() {
2026-07-11 17:52:33 +08:00
// 清除上次使用的 code 标记
uni.removeStorageSync('__used_auth_code');
2026-07-11 10:28:43 +08:00
const platform = detectPlatform();
const appNo = getAppNo(platform);
if (!appNo) {
// 非微信环境,直接跳回首页
this.goToHomeWithAction();
return;
}
try {
this.statusText = '正在获取用户信息...';
// 存入 localStorage(页面复用时 onLoad 不会重新触发,需要从 localStorage 读取)
localStorage.setItem('__auth_action', 'userinfo');
if (this.deviceId) {
localStorage.setItem('__auth_device_id', this.deviceId);
}
2026-07-11 11:37:53 +08:00
// 回调地址:必须与微信公众号后台注册地址一致,不能带自定义参数
const redirectUri = config.authRedirectUri || (
2026-07-11 10:28:43 +08:00
window.location.origin.replace(/^http:/, 'https:') + window.location.pathname
);
2026-07-15 17:37:23 +08:00
// 用户信息授权:微信用 snsapi_userinfo,支付宝用 auth_user
const scopes = platform === 'alipay' ? 'auth_user' : 'snsapi_userinfo';
2026-07-17 14:40:21 +08:00
// 构建 state(包含 action 和 device_id,回调时原样回传)
const stateObj = { action: 'userinfo' };
if (this.deviceId) {
stateObj.device_id = this.deviceId;
}
2026-07-11 10:28:43 +08:00
const res = await gatewayGet('/api/v1/user/auth/url', {
app_no: appNo,
2026-07-15 17:37:23 +08:00
scopes: scopes,
2026-07-11 10:28:43 +08:00
redirect_uri: redirectUri,
2026-07-17 14:40:21 +08:00
state: JSON.stringify(stateObj),
2026-07-11 10:28:43 +08:00
});
const data = res.data || {};
if (data.code === 0 && data.data && data.data.auth_url) {
2026-07-17 14:40:21 +08:00
// 后端已将 state 写入授权 URL,直接跳转
window.location.href = data.data.auth_url;
2026-07-11 10:28:43 +08:00
} else {
uni.showToast({ title: data.message || '获取授权失败', icon: 'none' });
setTimeout(() => this.goToHomeWithAction(), 1500);
}
} catch (e) {
console.error('[Auth] startUserInfoAuth error:', e);
uni.showToast({ title: '网络请求失败', icon: 'none' });
setTimeout(() => this.goToHomeWithAction(), 1500);
}
},
/**
* 处理用户信息授权回调(用 code 调 /api/v1/user/info 获取头像昵称)
*/
async handleUserInfoCallback(code) {
const appNo = uni.getStorageSync('app_no') || getAppNo(detectPlatform());
if (!appNo) {
this.goToHomeWithAction();
return;
}
2026-07-11 17:52:33 +08:00
// 防止 code 重复提交
const usedCode = uni.getStorageSync('__used_auth_code');
if (usedCode === code) {
console.warn('[loading] code 已使用过,跳过');
return;
}
uni.setStorageSync('__used_auth_code', code);
// 立即清除 URL 中的 code/action 参数,避免刷新重复处理
const url = new URL(window.location.href);
url.searchParams.delete('code');
url.searchParams.delete('auth_code');
2026-07-11 17:52:33 +08:00
url.searchParams.delete('state');
url.searchParams.delete('action');
window.history.replaceState({}, '', url.toString());
2026-07-11 10:28:43 +08:00
try {
this.statusText = '正在获取用户信息...';
2026-07-11 11:59:09 +08:00
// 用 code 调用 POST /api/v1/user/info 获取用户信息(必须用 POST,GET 是另一个端点)
console.log('[loading] 请求 POST user/info, app_no:', appNo, 'code:', code);
const res = await gatewayPost('/api/v1/user/info', {
2026-07-11 10:28:43 +08:00
app_no: appNo,
code: code,
});
const data = res.data || {};
2026-07-11 11:59:09 +08:00
console.log('[loading] user/info response:', JSON.stringify(data, null, 2));
console.log('[loading] user/info statusCode:', res.statusCode);
2026-07-11 10:28:43 +08:00
if (data.code === 0 && data.data) {
const userInfo = data.data;
// 合并已有缓存(保留 user_id 等字段),覆盖头像昵称手机
const existing = uni.getStorageSync('user_info') || {};
2026-07-11 10:28:43 +08:00
uni.setStorageSync('user_info', {
...existing,
user_id: userInfo.user_id || existing.user_id || '',
nickname: userInfo.nickname || existing.nickname || '',
avatar: userInfo.avatar || existing.avatar || '',
phone: userInfo.phone || existing.phone || '',
2026-07-11 10:28:43 +08:00
});
} else {
console.warn('[loading] 获取用户信息失败:', data.message);
}
// 跳回首页(我的 tab
this.goToHomeWithAction();
} catch (e) {
console.error('[Auth] handleUserInfoCallback error:', e);
this.goToHomeWithAction();
}
},
/**
* 跳回首页并标记为"我的"tab
*/
goToHomeWithAction() {
// 兼容页面复用:优先 this.deviceId,其次 localStorage
const deviceId = this.deviceId || localStorage.getItem('__auth_device_id') || '';
const url = deviceId
? `/pages/index/index?device_id=${deviceId}&action=mine`
2026-07-11 10:28:43 +08:00
: '/pages/index/index?action=mine';
localStorage.removeItem('__auth_device_id');
localStorage.removeItem('__auth_action');
2026-07-11 10:28:43 +08:00
uni.redirectTo({ url });
},
2026-07-02 18:25:23 +08:00
goToHome() {
const deviceId = this.deviceId || localStorage.getItem('__auth_device_id') || '';
const url = deviceId
? `/pages/index/index?device_id=${deviceId}`
2026-07-02 18:25:23 +08:00
: '/pages/index/index';
localStorage.removeItem('__auth_device_id');
2026-07-02 18:25:23 +08:00
uni.redirectTo({ url });
},
goToRegister() {
// 记录扫码时的原始 URL,注册完成后跳回
const scanUrl = this.deviceId
? `/pages/index/index?device_id=${this.deviceId}`
: '';
if (scanUrl) {
uni.setStorageSync('__scan_redirect_url', scanUrl);
}
2026-07-02 18:25:23 +08:00
const url = this.deviceId
? `/pages/register/register?device_id=${this.deviceId}`
: '/pages/register/register';
uni.redirectTo({ url });
},
goToScan() {
uni.redirectTo({ url: '/pages/index/scan' });
},
2026-07-09 18:49:56 +08:00
/**
* Mock 登录(跳过微信授权,调用真实登录接口)
2026-07-09 18:49:56 +08:00
*/
async mockLogin() {
const mode = config.mockWechatLogin;
const mock = config.mockUser;
const mockUserInfo = mock.user_info;
const mockOpenid = mockUserInfo.open_id;
2026-07-09 18:49:56 +08:00
// 'skip' 模式直接登录,不调接口
if (mode === 'skip') {
2026-07-09 18:49:56 +08:00
this.statusText = '模拟登录中...';
uni.setStorageSync('token', mock.token);
uni.setStorageSync('openid', mockOpenid);
// 按生产结构存储 user_info
uni.setStorageSync('user_info', {
user_id: mockUserInfo.user_id,
phone: mockUserInfo.phone,
nickname: mockUserInfo.nickname,
avatar: mockUserInfo.avatar,
});
console.log('[Auth] Mock skip → home');
2026-07-09 18:49:56 +08:00
setTimeout(() => this.goToHome(), 500);
return;
}
// 'register' / 'login' 模式:调用真实登录接口,传 mock openid
this.statusText = '模拟:调用登录接口...';
const appNo = uni.getStorageSync('app_no') || config.mockAppNo;
try {
const res = await gatewayPost('/api/v1/user/login', {
app_no: appNo,
openid: mockOpenid,
});
const data = res.data || {};
console.log('[Auth] Mock login response:', JSON.stringify(data, null, 2));
if (data.code === 0 && data.data) {
const result = data.data;
// 存储 openid
uni.setStorageSync('openid', result.openid || mockOpenid);
if (result.register) {
// 已注册 → 存 token + user_info → 跳首页
uni.setStorageSync('token', result.token);
// 按生产结构存储 user_info(接口返回优先,mock 补充)
uni.setStorageSync('user_info', {
user_id: result.user_id || mockUserInfo.user_id,
phone: result.phone || mockUserInfo.phone,
nickname: result.nickname || mockUserInfo.nickname,
avatar: result.avatar || mockUserInfo.avatar,
});
console.log('[Auth] Mock: existing user → home');
this.goToHome();
} else {
// 未注册 → 存 temp_token → 跳注册页
uni.setStorageSync('temp_token', result.temp_token);
console.log('[Auth] Mock: new user → register');
this.goToRegister();
}
} else {
uni.showToast({ title: data.message || '登录失败', icon: 'none' });
console.error('[Auth] Mock login failed:', data);
}
} catch (e) {
console.error('[Auth] Mock login error:', e);
uni.showToast({ title: '网络请求失败', icon: 'none' });
2026-07-09 18:49:56 +08:00
}
},
2026-07-02 18:25:23 +08:00
},
};
</script>
<style scoped>
page {
height: 100%;
background-color: #fff;
}
.loading-page {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
background-color: #fff;
}
.loading-spinner {
width: 64rpx;
height: 64rpx;
border: 6rpx solid #e5e5e5;
border-top-color: #2979ff;
border-radius: 50%;
animation: spin 0.8s linear infinite;
margin-bottom: 32rpx;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
.loading-text {
font-size: 28rpx;
color: #999;
}
</style>