Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 258fa4a9f5 | |||
| 45147426e0 | |||
| 7b2e4dc72e | |||
| 0fc854cd33 | |||
| 20649c67a9 |
+20
-4
@@ -30,7 +30,7 @@
|
|||||||
const urlParams = new URLSearchParams(window.location.search);
|
const urlParams = new URLSearchParams(window.location.search);
|
||||||
deviceId = urlParams.get('device_id') || '';
|
deviceId = urlParams.get('device_id') || '';
|
||||||
|
|
||||||
// 兜底:从路径解析(如 /pages/index/index/N1154)
|
// 兜底:从路径解析(如 /N1154)
|
||||||
if (!deviceId) {
|
if (!deviceId) {
|
||||||
const path = window.location.pathname;
|
const path = window.location.pathname;
|
||||||
const segments = path.split('/').filter(Boolean);
|
const segments = path.split('/').filter(Boolean);
|
||||||
@@ -46,10 +46,26 @@
|
|||||||
const code = urlParams.get('code');
|
const code = urlParams.get('code');
|
||||||
|
|
||||||
if (code) {
|
if (code) {
|
||||||
// 有 code → 进入授权 Loading 页处理,保留 code 参数
|
// 有 code → 进入授权 Loading 页处理
|
||||||
|
// 从 state 中解析 device_id 和 action(OAuth 标准保证 state 原样回传)
|
||||||
|
let action = '';
|
||||||
|
let callbackDeviceId = deviceId || '';
|
||||||
|
try {
|
||||||
|
const stateStr = urlParams.get('state');
|
||||||
|
if (stateStr) {
|
||||||
|
const stateObj = JSON.parse(decodeURIComponent(stateStr));
|
||||||
|
action = stateObj.action || action;
|
||||||
|
callbackDeviceId = stateObj.device_id || callbackDeviceId;
|
||||||
|
}
|
||||||
|
} catch (_) {
|
||||||
|
// state 解析失败,忽略
|
||||||
|
}
|
||||||
let loadingUrl = '/pages/auth/loading?code=' + encodeURIComponent(code);
|
let loadingUrl = '/pages/auth/loading?code=' + encodeURIComponent(code);
|
||||||
if (deviceId) {
|
if (action) {
|
||||||
loadingUrl += '&device_id=' + deviceId;
|
loadingUrl += '&action=' + action;
|
||||||
|
}
|
||||||
|
if (callbackDeviceId) {
|
||||||
|
loadingUrl += '&device_id=' + callbackDeviceId;
|
||||||
}
|
}
|
||||||
uni.redirectTo({ url: loadingUrl });
|
uni.redirectTo({ url: loadingUrl });
|
||||||
return;
|
return;
|
||||||
|
|||||||
+1
-1
@@ -29,7 +29,7 @@ const dev = {
|
|||||||
user_info: {
|
user_info: {
|
||||||
user_id: 'mock_user_001',
|
user_id: 'mock_user_001',
|
||||||
phone: '13264706088',
|
phone: '13264706088',
|
||||||
open_id: 'test_open_id',
|
open_id: 'mock_openid_002',
|
||||||
union_id: 'test_union_id',
|
union_id: 'test_union_id',
|
||||||
nickname: '测试用户',
|
nickname: '测试用户',
|
||||||
avatar: 'https://img.wewemivending.com/vms/us/img/uploads/2025/12/18/6943d37c7d82b3439.jpeg',
|
avatar: 'https://img.wewemivending.com/vms/us/img/uploads/2025/12/18/6943d37c7d82b3439.jpeg',
|
||||||
|
|||||||
+207
-48
@@ -15,33 +15,54 @@ export default {
|
|||||||
return {
|
return {
|
||||||
statusText: '正在登录...',
|
statusText: '正在登录...',
|
||||||
deviceId: '',
|
deviceId: '',
|
||||||
|
action: '',
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
onLoad(options) {
|
onLoad(options) {
|
||||||
this.deviceId = options.device_id || '';
|
this.deviceId = options.device_id || '';
|
||||||
|
this.action = options.action || '';
|
||||||
|
|
||||||
// #ifdef H5
|
// #ifdef H5
|
||||||
// Mock 模式:跳过微信 OAuth,直接登录
|
// Mock 模式:跳过微信 OAuth,直接登录
|
||||||
if (config.mockWechatLogin) {
|
if (config.mockWechatLogin && this.action !== 'userinfo') {
|
||||||
this.mockLogin();
|
this.mockLogin();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 优先从页面参数获取 code(App.vue 跳转时带过来)
|
// 从 URL 参数获取 code(App.vue 跳转时带过来)
|
||||||
// 兜底从 URL search 参数获取(微信直接回调时)
|
|
||||||
let code = options.code || '';
|
let code = options.code || '';
|
||||||
if (!code) {
|
if (!code) {
|
||||||
const urlParams = new URLSearchParams(window.location.search);
|
const urlParams = new URLSearchParams(window.location.search);
|
||||||
code = urlParams.get('code') || '';
|
code = urlParams.get('code') || '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 兜底:从 localStorage 恢复(redirect_uri 参数为主,localStorage 为备用)
|
||||||
|
if (!this.action) {
|
||||||
|
this.action = localStorage.getItem('__auth_action') || '';
|
||||||
|
}
|
||||||
|
if (!this.deviceId) {
|
||||||
|
this.deviceId = localStorage.getItem('__auth_device_id') || '';
|
||||||
|
}
|
||||||
|
// 清理 localStorage(一次性使用,避免残留影响下次流程)
|
||||||
|
localStorage.removeItem('__auth_action');
|
||||||
|
localStorage.removeItem('__auth_device_id');
|
||||||
|
console.log('[loading] onLoad - action:', this.action, 'deviceId:', this.deviceId, 'code:', code ? 'yes' : 'no');
|
||||||
|
|
||||||
|
if (this.action === 'userinfo') {
|
||||||
|
// 获取用户信息流程
|
||||||
|
if (code) {
|
||||||
|
this.handleUserInfoCallback(code);
|
||||||
|
} else {
|
||||||
|
this.startUserInfoAuth();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 登录流程
|
||||||
if (code) {
|
if (code) {
|
||||||
// 有 code → 调用后端登录
|
|
||||||
this.handleCallback(code);
|
this.handleCallback(code);
|
||||||
} else {
|
} else {
|
||||||
// 无 code → 发起 OAuth 授权
|
|
||||||
this.startAuth();
|
this.startAuth();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
// #endif
|
// #endif
|
||||||
|
|
||||||
// #ifndef H5
|
// #ifndef H5
|
||||||
@@ -51,7 +72,7 @@ export default {
|
|||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
/**
|
/**
|
||||||
* 发起 OAuth 授权
|
* 发起 OAuth 授权(静默授权,只获取 openid)
|
||||||
*/
|
*/
|
||||||
async startAuth() {
|
async startAuth() {
|
||||||
const platform = detectPlatform();
|
const platform = detectPlatform();
|
||||||
@@ -66,21 +87,28 @@ export default {
|
|||||||
try {
|
try {
|
||||||
this.statusText = '正在获取授权...';
|
this.statusText = '正在获取授权...';
|
||||||
|
|
||||||
// 回调地址必须是 HTTPS,使用配置文件中的地址
|
// 回调地址:必须与微信公众号后台注册地址一致,不能带自定义参数
|
||||||
const redirectUri = config.authRedirectUri || (
|
const redirectUri = config.authRedirectUri || (
|
||||||
window.location.origin.replace(/^http:/, 'https:') + window.location.pathname
|
window.location.origin.replace(/^http:/, 'https:') + window.location.pathname
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// 使用 snsapi_base 静默授权,不弹窗
|
||||||
const res = await gatewayGet('/api/v1/user/auth/url', {
|
const res = await gatewayGet('/api/v1/user/auth/url', {
|
||||||
app_no: appNo,
|
app_no: appNo,
|
||||||
scopes: 'snsapi_userinfo',
|
scopes: 'snsapi_base',
|
||||||
redirect_uri: redirectUri,
|
redirect_uri: redirectUri,
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = res.data || {};
|
const data = res.data || {};
|
||||||
if (data.code === 0 && data.data && data.data.auth_url) {
|
if (data.code === 0 && data.data && data.data.auth_url) {
|
||||||
// 跳转微信授权页
|
// 通过 state 传递 device_id(OAuth 标准保证 state 原样回传)
|
||||||
window.location.href = data.data.auth_url;
|
let authUrl = data.data.auth_url;
|
||||||
|
if (this.deviceId) {
|
||||||
|
const stateVal = encodeURIComponent(JSON.stringify({ device_id: this.deviceId }));
|
||||||
|
authUrl += (authUrl.includes('?') ? '&' : '?') + 'state=' + stateVal;
|
||||||
|
}
|
||||||
|
// 跳转微信授权页(静默,不弹窗)
|
||||||
|
window.location.href = authUrl;
|
||||||
} else {
|
} else {
|
||||||
uni.showToast({ title: data.message || '获取授权失败', icon: 'none' });
|
uni.showToast({ title: data.message || '获取授权失败', icon: 'none' });
|
||||||
setTimeout(() => this.goToScan(), 1500);
|
setTimeout(() => this.goToScan(), 1500);
|
||||||
@@ -93,7 +121,7 @@ export default {
|
|||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 处理授权回调(从 URL 中获取 code 后调用后端 /login)
|
* 处理授权回调(用 code 换 openid,再用 openid 登录)
|
||||||
*/
|
*/
|
||||||
async handleCallback(code) {
|
async handleCallback(code) {
|
||||||
const appNo = uni.getStorageSync('app_no') || getAppNo(detectPlatform());
|
const appNo = uni.getStorageSync('app_no') || getAppNo(detectPlatform());
|
||||||
@@ -107,17 +135,27 @@ export default {
|
|||||||
try {
|
try {
|
||||||
this.statusText = '正在验证身份...';
|
this.statusText = '正在验证身份...';
|
||||||
|
|
||||||
const res = await gatewayPost('/api/v1/user/login', {
|
// 1. 用 code 换取 openid(snsapi_base 静默授权)
|
||||||
|
const callbackRes = await gatewayPost('/api/v1/user/auth/exchange', {
|
||||||
app_no: appNo,
|
app_no: appNo,
|
||||||
code: code,
|
code: code,
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = res.data || {};
|
const callbackData = callbackRes.data || {};
|
||||||
console.log('[loading] login response:', JSON.stringify(data, null, 2));
|
console.log('[loading] auth callback response:', JSON.stringify(callbackData, null, 2));
|
||||||
|
|
||||||
if (data.code === 0 && data.data) {
|
if (callbackData.code !== 0 || !callbackData.data) {
|
||||||
const result = data.data;
|
uni.showToast({ title: callbackData.message || '授权失败', icon: 'none' });
|
||||||
console.log('[loading] login result:', JSON.stringify(result, null, 2));
|
setTimeout(() => this.goToScan(), 1500);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const openid = callbackData.data.openid;
|
||||||
|
if (!openid) {
|
||||||
|
uni.showToast({ title: '获取用户标识失败', icon: 'none' });
|
||||||
|
setTimeout(() => this.goToScan(), 1500);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// 清除 URL 中的 code 参数,避免刷新重复处理
|
// 清除 URL 中的 code 参数,避免刷新重复处理
|
||||||
const url = new URL(window.location.href);
|
const url = new URL(window.location.href);
|
||||||
@@ -125,17 +163,29 @@ export default {
|
|||||||
url.searchParams.delete('state');
|
url.searchParams.delete('state');
|
||||||
window.history.replaceState({}, '', url.toString());
|
window.history.replaceState({}, '', url.toString());
|
||||||
|
|
||||||
|
// 存储 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));
|
||||||
|
|
||||||
|
if (data.code === 0 && data.data) {
|
||||||
|
const result = data.data;
|
||||||
|
|
||||||
if (result.register) {
|
if (result.register) {
|
||||||
// 已注册 → 缓存 JWT → 跳转首页
|
// 已注册 → 存 token → 进入开门页
|
||||||
uni.setStorageSync('token', result.token);
|
uni.setStorageSync('token', result.token);
|
||||||
uni.setStorageSync('user_info', result.user_info);
|
|
||||||
console.log('[loading] stored user_info:', JSON.stringify(result.user_info, null, 2));
|
|
||||||
this.goToHome();
|
this.goToHome();
|
||||||
} else {
|
} else {
|
||||||
// 未注册 → 缓存临时数据 → 跳转注册页
|
// 未注册 → 存 temp_token → 跳注册页
|
||||||
uni.setStorageSync('temp_token', result.temp_token);
|
uni.setStorageSync('temp_token', result.temp_token);
|
||||||
uni.setStorageSync('auth_info', result.auth_info);
|
|
||||||
console.log('[loading] stored auth_info:', JSON.stringify(result.auth_info, null, 2));
|
|
||||||
this.goToRegister();
|
this.goToRegister();
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -149,6 +199,115 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发起非静默授权获取用户信息(snsapi_userinfo,弹窗确认)
|
||||||
|
*/
|
||||||
|
async startUserInfoAuth() {
|
||||||
|
const platform = detectPlatform();
|
||||||
|
const appNo = getAppNo(platform);
|
||||||
|
|
||||||
|
if (!appNo) {
|
||||||
|
// 非微信环境,直接跳回首页
|
||||||
|
this.goToHomeWithAction();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
this.statusText = '正在获取用户信息...';
|
||||||
|
|
||||||
|
// 回调地址:必须与微信公众号后台注册地址一致,不能带自定义参数
|
||||||
|
const redirectUri = config.authRedirectUri || (
|
||||||
|
window.location.origin.replace(/^http:/, 'https:') + window.location.pathname
|
||||||
|
);
|
||||||
|
|
||||||
|
const res = await gatewayGet('/api/v1/user/auth/url', {
|
||||||
|
app_no: appNo,
|
||||||
|
scopes: 'snsapi_userinfo',
|
||||||
|
redirect_uri: redirectUri,
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = res.data || {};
|
||||||
|
if (data.code === 0 && data.data && data.data.auth_url) {
|
||||||
|
// 通过 state 传递 action 和 device_id(OAuth 标准保证 state 原样回传)
|
||||||
|
const stateObj = { action: 'userinfo' };
|
||||||
|
if (this.deviceId) {
|
||||||
|
stateObj.device_id = this.deviceId;
|
||||||
|
}
|
||||||
|
let authUrl = data.data.auth_url;
|
||||||
|
authUrl += (authUrl.includes('?') ? '&' : '?') + 'state=' + encodeURIComponent(JSON.stringify(stateObj));
|
||||||
|
// 跳转微信授权页(弹窗确认)
|
||||||
|
window.location.href = authUrl;
|
||||||
|
} 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
this.statusText = '正在获取用户信息...';
|
||||||
|
|
||||||
|
// 清除 URL 中的 code/action 参数,避免刷新重复处理
|
||||||
|
const url = new URL(window.location.href);
|
||||||
|
url.searchParams.delete('code');
|
||||||
|
url.searchParams.delete('state');
|
||||||
|
url.searchParams.delete('action');
|
||||||
|
window.history.replaceState({}, '', url.toString());
|
||||||
|
|
||||||
|
// 用 code 调用 /api/v1/user/info 获取用户信息
|
||||||
|
const res = await gatewayGet('/api/v1/user/info', {
|
||||||
|
app_no: appNo,
|
||||||
|
code: code,
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = res.data || {};
|
||||||
|
console.log('[loading] user info response:', JSON.stringify(data, null, 2));
|
||||||
|
|
||||||
|
if (data.code === 0 && data.data) {
|
||||||
|
const userInfo = data.data;
|
||||||
|
// 存入缓存
|
||||||
|
uni.setStorageSync('user_info', {
|
||||||
|
nickname: userInfo.nickname || '',
|
||||||
|
avatar: userInfo.avatar || '',
|
||||||
|
phone: userInfo.phone || '',
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
console.warn('[loading] 获取用户信息失败:', data.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 跳回首页(我的 tab)
|
||||||
|
this.goToHomeWithAction();
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[Auth] handleUserInfoCallback error:', e);
|
||||||
|
this.goToHomeWithAction();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 跳回首页并标记为"我的"tab
|
||||||
|
*/
|
||||||
|
goToHomeWithAction() {
|
||||||
|
const url = this.deviceId
|
||||||
|
? `/pages/index/index?device_id=${this.deviceId}&action=mine`
|
||||||
|
: '/pages/index/index?action=mine';
|
||||||
|
uni.redirectTo({ url });
|
||||||
|
},
|
||||||
|
|
||||||
goToHome() {
|
goToHome() {
|
||||||
const url = this.deviceId
|
const url = this.deviceId
|
||||||
? `/pages/index/index?device_id=${this.deviceId}`
|
? `/pages/index/index?device_id=${this.deviceId}`
|
||||||
@@ -176,61 +335,61 @@ export default {
|
|||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mock 登录(开发环境模拟不同用户状态)
|
* Mock 登录(跳过微信授权,调用真实登录接口)
|
||||||
*/
|
*/
|
||||||
async mockLogin() {
|
async mockLogin() {
|
||||||
const mode = config.mockWechatLogin;
|
const mode = config.mockWechatLogin;
|
||||||
const mock = config.mockUser;
|
const mock = config.mockUser;
|
||||||
|
const mockOpenid = mock.user_info.open_id;
|
||||||
|
|
||||||
if (mode === 'register' || mode === 'login') {
|
// 'skip' 模式直接登录,不调接口
|
||||||
// 调用真实登录接口,用测试 code
|
if (mode === 'skip') {
|
||||||
this.statusText = '模拟:获取授权信息...';
|
this.statusText = '模拟登录中...';
|
||||||
const appNo = uni.getStorageSync('app_no') || getAppNo(detectPlatform()) || config.mockAppNo;
|
uni.setStorageSync('token', mock.token);
|
||||||
|
uni.setStorageSync('openid', mockOpenid);
|
||||||
|
console.log('[Auth] Mock skip → home');
|
||||||
|
setTimeout(() => this.goToHome(), 500);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 'register' / 'login' 模式:调用真实登录接口,传 mock openid
|
||||||
|
this.statusText = '模拟:调用登录接口...';
|
||||||
|
const appNo = uni.getStorageSync('app_no') || config.mockAppNo;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await gatewayPost('/api/v1/user/login', {
|
const res = await gatewayPost('/api/v1/user/login', {
|
||||||
app_no: appNo,
|
app_no: appNo,
|
||||||
code: 'test_code',
|
openid: mockOpenid,
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = res.data || {};
|
const data = res.data || {};
|
||||||
|
console.log('[Auth] Mock login response:', JSON.stringify(data, null, 2));
|
||||||
|
|
||||||
if (data.code === 0 && data.data) {
|
if (data.code === 0 && data.data) {
|
||||||
const result = data.data;
|
const result = data.data;
|
||||||
|
|
||||||
|
// 存储 openid
|
||||||
|
uni.setStorageSync('openid', result.openid || mockOpenid);
|
||||||
|
|
||||||
if (result.register) {
|
if (result.register) {
|
||||||
// 已注册
|
// 已注册 → 存 token → 跳首页
|
||||||
uni.setStorageSync('token', result.token);
|
uni.setStorageSync('token', result.token);
|
||||||
uni.setStorageSync('user_info', result.user_info);
|
|
||||||
console.log('[Auth] Mock: existing user → home');
|
console.log('[Auth] Mock: existing user → home');
|
||||||
this.goToHome();
|
this.goToHome();
|
||||||
} else {
|
} else {
|
||||||
// 未注册 → 存真实的 temp_token,合并 mock 头像昵称
|
// 未注册 → 存 temp_token → 跳注册页
|
||||||
const authInfo = {
|
|
||||||
...mock.user_info,
|
|
||||||
...result.auth_info,
|
|
||||||
};
|
|
||||||
uni.setStorageSync('temp_token', result.temp_token);
|
uni.setStorageSync('temp_token', result.temp_token);
|
||||||
uni.setStorageSync('auth_info', authInfo);
|
console.log('[Auth] Mock: new user → register');
|
||||||
console.log('[Auth] Mock: new user → register, temp_token:', result.temp_token);
|
|
||||||
this.goToRegister();
|
this.goToRegister();
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
uni.showToast({ title: data.message || '登录接口返回异常', icon: 'none' });
|
uni.showToast({ title: data.message || '登录失败', icon: 'none' });
|
||||||
console.error('[Auth] Mock login failed:', data);
|
console.error('[Auth] Mock login failed:', data);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('[Auth] Mock login error:', e);
|
console.error('[Auth] Mock login error:', e);
|
||||||
uni.showToast({ title: '网络请求失败', icon: 'none' });
|
uni.showToast({ title: '网络请求失败', icon: 'none' });
|
||||||
}
|
}
|
||||||
|
|
||||||
} else {
|
|
||||||
// 'skip' → 直接登录
|
|
||||||
this.statusText = '模拟登录中...';
|
|
||||||
uni.setStorageSync('token', mock.token);
|
|
||||||
uni.setStorageSync('user_info', mock.user_info);
|
|
||||||
console.log('[Auth] Mock: skip → home');
|
|
||||||
setTimeout(() => this.goToHome(), 500);
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
+106
-8
@@ -141,7 +141,7 @@
|
|||||||
|
|
||||||
<!-- 底部左右箭头导航条 -->
|
<!-- 底部左右箭头导航条 -->
|
||||||
<page-nav-bar
|
<page-nav-bar
|
||||||
:hasPrev="true"
|
:hasPrev="canGoBack"
|
||||||
:hasNext="false"
|
:hasNext="false"
|
||||||
@prev="handleNavPrev"
|
@prev="handleNavPrev"
|
||||||
@next="handleNavNext"
|
@next="handleNavNext"
|
||||||
@@ -163,8 +163,8 @@
|
|||||||
<script>
|
<script>
|
||||||
import PageNavBar from '@/components/page-nav-bar/page-nav-bar.vue';
|
import PageNavBar from '@/components/page-nav-bar/page-nav-bar.vue';
|
||||||
import config from '@/config/env.js';
|
import config from '@/config/env.js';
|
||||||
import { get } from '@/utils/request.js';
|
import { get, gatewayGet } from '@/utils/request.js';
|
||||||
import { checkLoginWithPrompt, getCachedUserInfo } from '@/utils/auth-guard.js';
|
import { checkLoginWithPrompt, getCachedUserInfo, isLoggedIn } from '@/utils/auth-guard.js';
|
||||||
import { isVConsoleEnabled, showVConsole, hideVConsole } from '@/utils/vconsole';
|
import { isVConsoleEnabled, showVConsole, hideVConsole } from '@/utils/vconsole';
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
@@ -180,6 +180,7 @@ export default {
|
|||||||
userInfo: { nickname: '', phone: '', avatar: '' },
|
userInfo: { nickname: '', phone: '', avatar: '' },
|
||||||
avatarClickCount: 0,
|
avatarClickCount: 0,
|
||||||
avatarClickTimer: null,
|
avatarClickTimer: null,
|
||||||
|
fromPage: '', // 记录从哪个页面跳转过来的
|
||||||
menuList: [
|
menuList: [
|
||||||
{ title: '我的订单', action: 'order' },
|
{ title: '我的订单', action: 'order' },
|
||||||
{ title: '常见问题', action: 'faq' },
|
{ title: '常见问题', action: 'faq' },
|
||||||
@@ -193,6 +194,10 @@ export default {
|
|||||||
};
|
};
|
||||||
},
|
},
|
||||||
computed: {
|
computed: {
|
||||||
|
canGoBack() {
|
||||||
|
// 有上一页,或者从 tab 切换过来的,都可以返回
|
||||||
|
return getCurrentPages().length > 1 || this.fromPage === 'tab';
|
||||||
|
},
|
||||||
maskedPhone() {
|
maskedPhone() {
|
||||||
const p = this.userInfo.phone;
|
const p = this.userInfo.phone;
|
||||||
return p ? p.substring(0,3) + '****' + p.substring(7) : '';
|
return p ? p.substring(0,3) + '****' + p.substring(7) : '';
|
||||||
@@ -221,17 +226,29 @@ export default {
|
|||||||
this.isWechat = /MicroMessenger/i.test(navigator.userAgent);
|
this.isWechat = /MicroMessenger/i.test(navigator.userAgent);
|
||||||
// #endif
|
// #endif
|
||||||
|
|
||||||
|
// 处理"我的"用户信息授权回调(从 loading 页跳回)
|
||||||
|
if (options.action === 'mine') {
|
||||||
|
this.currentTab = 'mine';
|
||||||
|
this.fromPage = 'navigate';
|
||||||
|
}
|
||||||
|
|
||||||
// 支持通过 tab 参数切换到"我的"页面
|
// 支持通过 tab 参数切换到"我的"页面
|
||||||
if (options.tab === 'mine') {
|
if (options.tab === 'mine') {
|
||||||
this.currentTab = 'mine';
|
this.currentTab = 'mine';
|
||||||
|
this.fromPage = 'navigate';
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.device_id) {
|
if (options.device_id) {
|
||||||
this.deviceId = options.device_id;
|
this.deviceId = options.device_id;
|
||||||
|
uni.setNavigationBarTitle({ title: `智能货柜-${this.deviceId}` });
|
||||||
this.fetchProducts();
|
this.fetchProducts();
|
||||||
} else if (!options.tab) {
|
} else if (!options.tab && options.action !== 'mine') {
|
||||||
// 无设备编号且非 tab 跳转,跳回扫码页
|
// 无设备编号且非 tab/action 跳转,提示并跳至扫码页
|
||||||
|
uni.showToast({ title: '请扫描设备二维码', icon: 'none' });
|
||||||
|
setTimeout(() => {
|
||||||
uni.redirectTo({ url: '/pages/index/scan' });
|
uni.redirectTo({ url: '/pages/index/scan' });
|
||||||
|
}, 1500);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 加载缓存的用户信息
|
// 加载缓存的用户信息
|
||||||
@@ -250,9 +267,21 @@ export default {
|
|||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
switchTab(tab) {
|
switchTab(tab) {
|
||||||
|
if (tab === 'mine') {
|
||||||
// 切换到"我的"Tab 时检查登录
|
// 切换到"我的"Tab 时检查登录
|
||||||
if (tab === 'mine' && !checkLoginWithPrompt('mine')) return;
|
if (!checkLoginWithPrompt('mine')) return;
|
||||||
this.currentTab = tab;
|
this.currentTab = tab;
|
||||||
|
this.fromPage = 'tab';
|
||||||
|
// 已有缓存的用户信息则直接显示,否则发起非静默授权获取
|
||||||
|
const cached = getCachedUserInfo();
|
||||||
|
if (cached && cached.nickname) {
|
||||||
|
this.userInfo = { ...this.userInfo, ...cached };
|
||||||
|
} else {
|
||||||
|
this.startUserInfoAuth();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.currentTab = tab;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
switchCategory(cat) { this.activeCategory = cat; },
|
switchCategory(cat) { this.activeCategory = cat; },
|
||||||
getDisplayPrice(item) {
|
getDisplayPrice(item) {
|
||||||
@@ -271,6 +300,61 @@ export default {
|
|||||||
}
|
}
|
||||||
console.log('[index] this.userInfo:', JSON.stringify(this.userInfo, null, 2));
|
console.log('[index] this.userInfo:', JSON.stringify(this.userInfo, null, 2));
|
||||||
},
|
},
|
||||||
|
// 发起非静默授权获取用户信息(snsapi_userinfo)
|
||||||
|
async startUserInfoAuth() {
|
||||||
|
// Mock 模式下,直接使用 mock 数据
|
||||||
|
if (config.mockWechatLogin) {
|
||||||
|
const cached = getCachedUserInfo();
|
||||||
|
if (cached && cached.nickname) {
|
||||||
|
this.userInfo = { ...this.userInfo, ...cached };
|
||||||
|
} else {
|
||||||
|
this.userInfo = {
|
||||||
|
nickname: config.mockUser.user_info.nickname || '',
|
||||||
|
phone: config.mockUser.user_info.phone || '',
|
||||||
|
avatar: config.mockUser.user_info.avatar || '',
|
||||||
|
};
|
||||||
|
uni.setStorageSync('user_info', this.userInfo);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const appNo = uni.getStorageSync('app_no');
|
||||||
|
if (!appNo) {
|
||||||
|
console.warn('[index] 无法获取应用信息');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 回调地址:必须与微信公众号后台注册地址一致,不能带自定义参数
|
||||||
|
const redirectUri = config.authRedirectUri || (
|
||||||
|
window.location.origin.replace(/^http:/, 'https:') + window.location.pathname
|
||||||
|
);
|
||||||
|
|
||||||
|
// 获取非静默授权链接(会弹窗确认)
|
||||||
|
const res = await gatewayGet('/api/v1/user/auth/url', {
|
||||||
|
app_no: appNo,
|
||||||
|
scopes: 'snsapi_userinfo',
|
||||||
|
redirect_uri: redirectUri,
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = res.data || {};
|
||||||
|
if (data.code === 0 && data.data && data.data.auth_url) {
|
||||||
|
// 通过 state 传递 action 和 device_id(OAuth 标准保证 state 原样回传)
|
||||||
|
const stateObj = { action: 'userinfo' };
|
||||||
|
if (this.deviceId) {
|
||||||
|
stateObj.device_id = this.deviceId;
|
||||||
|
}
|
||||||
|
let authUrl = data.data.auth_url;
|
||||||
|
authUrl += (authUrl.includes('?') ? '&' : '?') + 'state=' + encodeURIComponent(JSON.stringify(stateObj));
|
||||||
|
// 跳转微信授权页(弹窗确认)
|
||||||
|
window.location.href = authUrl;
|
||||||
|
} else {
|
||||||
|
console.warn('[index] 获取授权链接失败:', data.message);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[index] startUserInfoAuth error:', e);
|
||||||
|
}
|
||||||
|
},
|
||||||
async fetchProducts() {
|
async fetchProducts() {
|
||||||
this.loading = true;
|
this.loading = true;
|
||||||
|
|
||||||
@@ -316,7 +400,16 @@ export default {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
handleNavPrev() { this.currentTab = 'home'; },
|
handleNavPrev() {
|
||||||
|
if (this.fromPage === 'navigate') {
|
||||||
|
// 从其他页面 navigateTo 过来的,返回上一页
|
||||||
|
uni.navigateBack();
|
||||||
|
} else if (this.fromPage === 'tab') {
|
||||||
|
// 从首页 tab 切换过来的,切换回首页
|
||||||
|
this.currentTab = 'home';
|
||||||
|
}
|
||||||
|
// 其他情况不执行操作
|
||||||
|
},
|
||||||
handleNavNext() { uni.showToast({ title: '暂无下一页', icon: 'none' }); },
|
handleNavNext() { uni.showToast({ title: '暂无下一页', icon: 'none' }); },
|
||||||
handleAvatarClick() {
|
handleAvatarClick() {
|
||||||
this.avatarClickCount++;
|
this.avatarClickCount++;
|
||||||
@@ -348,7 +441,11 @@ export default {
|
|||||||
uni.clearStorageSync();
|
uni.clearStorageSync();
|
||||||
uni.showToast({ title: '已退出登录', icon: 'success' });
|
uni.showToast({ title: '已退出登录', icon: 'success' });
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
location.reload();
|
// 跳转到干净的URL,去掉code/state参数,避免重复使用旧code
|
||||||
|
const url = new URL(window.location.href);
|
||||||
|
url.searchParams.delete('code');
|
||||||
|
url.searchParams.delete('state');
|
||||||
|
window.location.href = url.toString();
|
||||||
}, 1000);
|
}, 1000);
|
||||||
},
|
},
|
||||||
onVConsoleChange(e) {
|
onVConsoleChange(e) {
|
||||||
@@ -371,6 +468,7 @@ page { height: 100%; background-color: #fff; }
|
|||||||
|
|
||||||
/* ====== 首页样式 ====== */
|
/* ====== 首页样式 ====== */
|
||||||
.home-page { display: flex; flex-direction: column; height: 100%; }
|
.home-page { display: flex; flex-direction: column; height: 100%; }
|
||||||
|
|
||||||
.product-area { flex: 1; overflow-y: auto; height: 0; }
|
.product-area { flex: 1; overflow-y: auto; height: 0; }
|
||||||
|
|
||||||
/* 热销商品标题 + 装饰 */
|
/* 热销商品标题 + 装饰 */
|
||||||
|
|||||||
@@ -101,7 +101,25 @@ export default {
|
|||||||
methods: {
|
methods: {
|
||||||
handleScan() {
|
handleScan() {
|
||||||
// #ifdef H5
|
// #ifdef H5
|
||||||
uni.showToast({ title: 'H5 环境暂不支持扫码', icon: 'none' });
|
// 检测是否在微信环境
|
||||||
|
const isWechat = /MicroMessenger/i.test(navigator.userAgent);
|
||||||
|
if (isWechat) {
|
||||||
|
// 微信环境:拉起微信扫一扫
|
||||||
|
// 注意:需要后端配合引入微信 JS-SDK 并完成签名配置
|
||||||
|
uni.showToast({ title: '请使用微信扫一扫功能', icon: 'none' });
|
||||||
|
// 如果已配置微信 JS-SDK,可以使用:
|
||||||
|
// wx.scanQRCode({
|
||||||
|
// needResult: 1,
|
||||||
|
// scanType: ['qrCode', 'barCode'],
|
||||||
|
// success: (res) => {
|
||||||
|
// const result = res.resultStr;
|
||||||
|
// this.parseScanResult(result);
|
||||||
|
// }
|
||||||
|
// });
|
||||||
|
} else {
|
||||||
|
// 非微信环境
|
||||||
|
uni.showToast({ title: '请使用微信扫码或在小程序中打开', icon: 'none' });
|
||||||
|
}
|
||||||
// #endif
|
// #endif
|
||||||
|
|
||||||
// #ifdef MP-WEIXIN
|
// #ifdef MP-WEIXIN
|
||||||
|
|||||||
@@ -69,6 +69,7 @@
|
|||||||
|
|
||||||
<script>
|
<script>
|
||||||
import { gatewayPost } from '@/utils/request.js';
|
import { gatewayPost } from '@/utils/request.js';
|
||||||
|
import config from '@/config/env.js';
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
data() {
|
data() {
|
||||||
@@ -153,7 +154,7 @@ export default {
|
|||||||
}, 1000);
|
}, 1000);
|
||||||
},
|
},
|
||||||
|
|
||||||
// 注册
|
// 注册(Mock 模式也走真实接口)
|
||||||
async handleRegister() {
|
async handleRegister() {
|
||||||
if (!this.canSubmit) return;
|
if (!this.canSubmit) return;
|
||||||
|
|
||||||
@@ -183,16 +184,21 @@ export default {
|
|||||||
|
|
||||||
const ret = res.data || {};
|
const ret = res.data || {};
|
||||||
if (ret.code === 0 && ret.data) {
|
if (ret.code === 0 && ret.data) {
|
||||||
// 合并微信授权信息(头像、昵称)到 user_info
|
// 保存 token
|
||||||
const authInfo = uni.getStorageSync('auth_info') || {};
|
|
||||||
const userInfo = {
|
|
||||||
...authInfo,
|
|
||||||
...ret.data.user_info,
|
|
||||||
};
|
|
||||||
|
|
||||||
// 保存 token 和用户信息
|
|
||||||
uni.setStorageSync('token', ret.data.token);
|
uni.setStorageSync('token', ret.data.token);
|
||||||
|
|
||||||
|
// Mock 模式下,合并真实注册信息和 mock 配置
|
||||||
|
if (config.mockWechatLogin) {
|
||||||
|
const mockInfo = config.mockUser.user_info;
|
||||||
|
const userInfo = {
|
||||||
|
user_id: ret.data.user_id || mockInfo.user_id,
|
||||||
|
phone: this.phone, // 使用真实注册的手机号
|
||||||
|
nickname: mockInfo.nickname,
|
||||||
|
avatar: mockInfo.avatar,
|
||||||
|
};
|
||||||
uni.setStorageSync('user_info', userInfo);
|
uni.setStorageSync('user_info', userInfo);
|
||||||
|
console.log('[register] Mock 模式,合并用户信息:', userInfo);
|
||||||
|
}
|
||||||
|
|
||||||
// 清除临时数据
|
// 清除临时数据
|
||||||
uni.removeStorageSync('temp_token');
|
uni.removeStorageSync('temp_token');
|
||||||
@@ -200,19 +206,7 @@ export default {
|
|||||||
|
|
||||||
uni.hideLoading();
|
uni.hideLoading();
|
||||||
uni.showToast({ title: '注册成功', icon: 'success' });
|
uni.showToast({ title: '注册成功', icon: 'success' });
|
||||||
|
setTimeout(() => this.navigateToTarget(), 1500);
|
||||||
// 跳转到扫码时的页面(优先使用缓存的扫码URL)
|
|
||||||
setTimeout(() => {
|
|
||||||
const scanRedirectUrl = uni.getStorageSync('__scan_redirect_url');
|
|
||||||
uni.removeStorageSync('__scan_redirect_url'); // 使用后立即清除
|
|
||||||
|
|
||||||
const url = scanRedirectUrl
|
|
||||||
? scanRedirectUrl
|
|
||||||
: this.deviceId
|
|
||||||
? `/pages/index/index?device_id=${this.deviceId}`
|
|
||||||
: '/pages/index/index';
|
|
||||||
uni.redirectTo({ url });
|
|
||||||
}, 1500);
|
|
||||||
} else {
|
} else {
|
||||||
uni.hideLoading();
|
uni.hideLoading();
|
||||||
uni.showToast({ title: ret.message || '注册失败', icon: 'none' });
|
uni.showToast({ title: ret.message || '注册失败', icon: 'none' });
|
||||||
@@ -223,6 +217,19 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// 跳转到目标页面
|
||||||
|
navigateToTarget() {
|
||||||
|
const scanRedirectUrl = uni.getStorageSync('__scan_redirect_url');
|
||||||
|
uni.removeStorageSync('__scan_redirect_url');
|
||||||
|
|
||||||
|
const url = scanRedirectUrl
|
||||||
|
? scanRedirectUrl
|
||||||
|
: this.deviceId
|
||||||
|
? `/pages/index/index?device_id=${this.deviceId}`
|
||||||
|
: '/pages/index/index';
|
||||||
|
uni.redirectTo({ url });
|
||||||
|
},
|
||||||
|
|
||||||
showAgreement(type) {
|
showAgreement(type) {
|
||||||
const title = type === 'user' ? '用户协议' : '隐私政策';
|
const title = type === 'user' ? '用户协议' : '隐私政策';
|
||||||
uni.showToast({ title: title + '开发中', icon: 'none' });
|
uni.showToast({ title: title + '开发中', icon: 'none' });
|
||||||
|
|||||||
@@ -40,10 +40,11 @@ export function request(options = {}) {
|
|||||||
// 公开接口(授权/登录/注册相关)不带 Authorization,避免 CORS 预检和 JWT 拦截
|
// 公开接口(授权/登录/注册相关)不带 Authorization,避免 CORS 预检和 JWT 拦截
|
||||||
const publicPaths = [
|
const publicPaths = [
|
||||||
'/api/v1/user/auth/url',
|
'/api/v1/user/auth/url',
|
||||||
'/api/v1/user/auth/callback',
|
'/api/v1/user/auth/exchange',
|
||||||
'/api/v1/user/login',
|
'/api/v1/user/login',
|
||||||
'/api/v1/user/register',
|
'/api/v1/user/register',
|
||||||
'/api/v1/user/sms/send',
|
'/api/v1/user/sms/send',
|
||||||
|
'/api/v1/user/info',
|
||||||
];
|
];
|
||||||
const isPublic = publicPaths.some((p) => url.includes(p));
|
const isPublic = publicPaths.some((p) => url.includes(p));
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user