Compare commits

...

5 Commits

Author SHA1 Message Date
kk 3a154198e9 清除缓存
Uni-app H5 Deploy (Prod + Staging) / deploy (release) Successful in 42s
2026-07-10 15:25:36 +08:00
kk c84c9df5d4 注册后跳回首页/增加用户信息缓存日志
Uni-app H5 Deploy (Prod + Staging) / deploy (release) Successful in 45s
2026-07-10 15:13:53 +08:00
kk 71606ebfe5 mock清除登录状态机制/mock的user_info字段更新
Uni-app H5 Deploy (Prod + Staging) / deploy (release) Successful in 48s
2026-07-10 14:02:26 +08:00
kk a7e0366fb7 支持用户授权注册登录mock 2026-07-09 18:49:56 +08:00
kk 5bb31516a0 保留code参数
Uni-app H5 Deploy (Prod + Staging) / deploy (release) Successful in 45s
2026-07-02 19:32:07 +08:00
6 changed files with 221 additions and 33 deletions
+39 -8
View File
@@ -1,16 +1,37 @@
<script> <script>
import { initEnv } from '@/utils/env.js'; import { initEnv } from '@/utils/env.js';
import config from '@/config/env.js';
export default { export default {
onLaunch: function(options) { onLaunch: function(options) {
console.log('App Launch') console.log('App Launch')
// 0. Mock 模式:仅首次进入时清除登录状态(刷新时保留)
if (config.mockWechatLogin) {
const mockInitialized = uni.getStorageSync('__mock_initialized');
if (!mockInitialized) {
uni.removeStorageSync('token');
uni.removeStorageSync('user_info');
uni.removeStorageSync('temp_token');
uni.removeStorageSync('auth_info');
uni.setStorageSync('__mock_initialized', 'true');
console.log('[Mock] 首次进入,清除登录状态');
} else {
console.log('[Mock] 刷新页面,保留登录状态');
}
}
// 1. 环境检测 + 缓存 app_no/platform // 1. 环境检测 + 缓存 app_no/platform
initEnv(); initEnv();
// #ifdef H5 // #ifdef H5
// 2. 解析 URL 路径中的设备编号(如 /A1036) // 2. 解析设备编号:优先从 query 参数获取,其次从路径解析
let deviceId = ''; let deviceId = '';
const urlParams = new URLSearchParams(window.location.search);
deviceId = urlParams.get('device_id') || '';
// 兜底:从路径解析(如 /pages/index/index/N1154
if (!deviceId) {
const path = window.location.pathname; const path = window.location.pathname;
const segments = path.split('/').filter(Boolean); const segments = path.split('/').filter(Boolean);
if (segments.length > 0) { if (segments.length > 0) {
@@ -19,29 +40,39 @@
deviceId = last; deviceId = last;
} }
} }
}
// 3. 检查 URL 中是否有授权回调的 code // 3. 检查 URL 中是否有授权回调的 code
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code'); const code = urlParams.get('code');
if (code) { if (code) {
// 有 code → 进入授权 Loading 页处理 // 有 code → 进入授权 Loading 页处理,保留 code 参数
const loadingUrl = deviceId let loadingUrl = '/pages/auth/loading?code=' + encodeURIComponent(code);
? `/pages/auth/loading?device_id=${deviceId}` if (deviceId) {
: '/pages/auth/loading'; loadingUrl += '&device_id=' + deviceId;
}
uni.redirectTo({ url: loadingUrl }); uni.redirectTo({ url: loadingUrl });
return; return;
} }
// 4. 检查 JWT // 4. 判断是否为根路径或设备编号路径(如 / 或 /N1154)
const currentPath = window.location.pathname;
const isRootOrDevice = currentPath === '/' || /^\/[A-Z][A-Z0-9]+$/.test(currentPath);
// 5. 检查 JWT
const token = uni.getStorageSync('token'); const token = uni.getStorageSync('token');
if (token) { if (token) {
// 有 JWT → 直接进入首页 if (isRootOrDevice) {
// 根路径/设备编号路径 → 跳转首页
const homeUrl = deviceId const homeUrl = deviceId
? `/pages/index/index?device_id=${deviceId}` ? `/pages/index/index?device_id=${deviceId}`
: '/pages/index/scan'; : '/pages/index/scan';
uni.redirectTo({ url: homeUrl }); uni.redirectTo({ url: homeUrl });
} else {
// 其他业务页面 → 留在当前页面
console.log('[App] 已登录,保留在当前页面');
}
} else { } else {
// 无 JWT → 进入授权 Loading 页 // 无 JWT → 进入授权 Loading 页
const loadingUrl = deviceId const loadingUrl = deviceId
+20 -1
View File
@@ -6,7 +6,7 @@ const dev = {
apiBaseUrl: 'http://192.168.0.23:4000', apiBaseUrl: 'http://192.168.0.23:4000',
// 网关地址(vms-gateway,端口 4001)— 用户授权、短信等接口走网关 // 网关地址(vms-gateway,端口 4001)— 用户授权、短信等接口走网关
apiGatewayUrl: 'https://gateway.arklinksmart.cn', apiGatewayUrl: 'http://192.168.0.23:4001',
// 授权回调地址(微信 OAuth redirect_uri,必须 HTTPS,指向前端页面) // 授权回调地址(微信 OAuth redirect_uri,必须 HTTPS,指向前端页面)
authRedirectUri: 'https://m.arklinksmart.cn/pages/auth/loading', authRedirectUri: 'https://m.arklinksmart.cn/pages/auth/loading',
@@ -16,6 +16,25 @@ const dev = {
// 是否开启请求日志 // 是否开启请求日志
enableRequestLog: true, enableRequestLog: true,
// Mock 微信登录(跳过 OAuth 流程)
// 'skip' → 直接登录进首页
// 'register' → 模拟新用户,走注册流程
// 'login' → 模拟已注册用户,走登录流程
// false → 走真实微信 OAuth
mockWechatLogin: 'register',
mockAppNo: '60000001102001',
mockUser: {
token: 'mock_token_dev_2024',
user_info: {
user_id: 'mock_user_001',
phone: '13264706088',
open_id: 'test_open_id',
union_id: 'test_union_id',
nickname: '测试用户',
avatar: 'https://img.wewemivending.com/vms/us/img/uploads/2025/12/18/6943d37c7d82b3439.jpeg',
},
},
}; };
export default dev; export default dev;
+83 -2
View File
@@ -21,9 +21,19 @@ export default {
this.deviceId = options.device_id || ''; this.deviceId = options.device_id || '';
// #ifdef H5 // #ifdef H5
// 检查 URL 中是否有授权回调的 code // Mock 模式:跳过微信 OAuth,直接登录
if (config.mockWechatLogin) {
this.mockLogin();
return;
}
// 优先从页面参数获取 code(App.vue 跳转时带过来)
// 兜底从 URL search 参数获取(微信直接回调时)
let code = options.code || '';
if (!code) {
const urlParams = new URLSearchParams(window.location.search); const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code'); code = urlParams.get('code') || '';
}
if (code) { if (code) {
// 有 code → 调用后端登录 // 有 code → 调用后端登录
@@ -103,8 +113,11 @@ export default {
}); });
const data = res.data || {}; const data = res.data || {};
console.log('[loading] 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;
console.log('[loading] login result:', JSON.stringify(result, null, 2));
// 清除 URL 中的 code 参数,避免刷新重复处理 // 清除 URL 中的 code 参数,避免刷新重复处理
const url = new URL(window.location.href); const url = new URL(window.location.href);
@@ -116,11 +129,13 @@ export default {
// 已注册 → 缓存 JWT → 跳转首页 // 已注册 → 缓存 JWT → 跳转首页
uni.setStorageSync('token', result.token); uni.setStorageSync('token', result.token);
uni.setStorageSync('user_info', result.user_info); 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 {
// 未注册 → 缓存临时数据 → 跳转注册页 // 未注册 → 缓存临时数据 → 跳转注册页
uni.setStorageSync('temp_token', result.temp_token); uni.setStorageSync('temp_token', result.temp_token);
uni.setStorageSync('auth_info', result.auth_info); 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 {
@@ -142,6 +157,14 @@ export default {
}, },
goToRegister() { goToRegister() {
// 记录扫码时的原始 URL,注册完成后跳回
const scanUrl = this.deviceId
? `/pages/index/index?device_id=${this.deviceId}`
: '';
if (scanUrl) {
uni.setStorageSync('__scan_redirect_url', scanUrl);
}
const url = this.deviceId const url = this.deviceId
? `/pages/register/register?device_id=${this.deviceId}` ? `/pages/register/register?device_id=${this.deviceId}`
: '/pages/register/register'; : '/pages/register/register';
@@ -151,6 +174,64 @@ export default {
goToScan() { goToScan() {
uni.redirectTo({ url: '/pages/index/scan' }); uni.redirectTo({ url: '/pages/index/scan' });
}, },
/**
* Mock 登录(开发环境模拟不同用户状态)
*/
async mockLogin() {
const mode = config.mockWechatLogin;
const mock = config.mockUser;
if (mode === 'register' || mode === 'login') {
// 调用真实登录接口,用测试 code
this.statusText = '模拟:获取授权信息...';
const appNo = uni.getStorageSync('app_no') || getAppNo(detectPlatform()) || config.mockAppNo;
try {
const res = await gatewayPost('/api/v1/user/login', {
app_no: appNo,
code: 'test_code',
});
const data = res.data || {};
if (data.code === 0 && data.data) {
const result = data.data;
if (result.register) {
// 已注册
uni.setStorageSync('token', result.token);
uni.setStorageSync('user_info', result.user_info);
console.log('[Auth] Mock: existing user → home');
this.goToHome();
} else {
// 未注册 → 存真实的 temp_token,合并 mock 头像昵称
const authInfo = {
...mock.user_info,
...result.auth_info,
};
uni.setStorageSync('temp_token', result.temp_token);
uni.setStorageSync('auth_info', authInfo);
console.log('[Auth] Mock: new user → register, temp_token:', result.temp_token);
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' });
}
} 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);
}
},
}, },
}; };
</script> </script>
+46 -1
View File
@@ -103,7 +103,7 @@
<!-- 蓝色个人信息区域 --> <!-- 蓝色个人信息区域 -->
<view class="user-header"> <view class="user-header">
<view class="user-info"> <view class="user-info">
<view class="avatar-wrapper"> <view class="avatar-wrapper" @click="handleAvatarClick">
<image class="avatar" :src="userInfo.avatar || '/static/default-avatar.png'" mode="aspectFill" /> <image class="avatar" :src="userInfo.avatar || '/static/default-avatar.png'" mode="aspectFill" />
</view> </view>
<view class="user-detail"> <view class="user-detail">
@@ -122,6 +122,13 @@
</view> </view>
</view> </view>
<!-- 退出登录 -->
<view class="menu-list logout-btn" @click="handleLogout">
<view class="menu-item">
<text class="menu-text" style="color: #e4393c; text-align: center; width: 100%;">退出登录</text>
</view>
</view>
<!-- 开发调试工具仅开发环境显示 --> <!-- 开发调试工具仅开发环境显示 -->
<view v-if="isDev" class="dev-tools"> <view v-if="isDev" class="dev-tools">
<view class="dev-tools-title">开发工具</view> <view class="dev-tools-title">开发工具</view>
@@ -171,6 +178,8 @@ export default {
categoryList: [], categoryList: [],
activeCategory: 'all', activeCategory: 'all',
userInfo: { nickname: '', phone: '', avatar: '' }, userInfo: { nickname: '', phone: '', avatar: '' },
avatarClickCount: 0,
avatarClickTimer: null,
menuList: [ menuList: [
{ title: '我的订单', action: 'order' }, { title: '我的订单', action: 'order' },
{ title: '常见问题', action: 'faq' }, { title: '常见问题', action: 'faq' },
@@ -254,11 +263,13 @@ export default {
// 从缓存加载用户信息 // 从缓存加载用户信息
loadUserInfo() { loadUserInfo() {
const cached = getCachedUserInfo(); const cached = getCachedUserInfo();
console.log('[index] getCachedUserInfo:', JSON.stringify(cached, null, 2));
if (cached) { if (cached) {
this.userInfo = { ...this.userInfo, ...cached }; this.userInfo = { ...this.userInfo, ...cached };
} else { } else {
this.userInfo = { nickname: '', phone: '', avatar: '' }; this.userInfo = { nickname: '', phone: '', avatar: '' };
} }
console.log('[index] this.userInfo:', JSON.stringify(this.userInfo, null, 2));
}, },
async fetchProducts() { async fetchProducts() {
this.loading = true; this.loading = true;
@@ -307,6 +318,39 @@ export default {
}, },
handleNavPrev() { this.currentTab = 'home'; }, handleNavPrev() { this.currentTab = 'home'; },
handleNavNext() { uni.showToast({ title: '暂无下一页', icon: 'none' }); }, handleNavNext() { uni.showToast({ title: '暂无下一页', icon: 'none' }); },
handleAvatarClick() {
this.avatarClickCount++;
clearTimeout(this.avatarClickTimer);
if (this.avatarClickCount >= 10) {
// 点击10次,清除缓存
this.avatarClickCount = 0;
this.clearCacheAndReload();
} else {
// 2秒后重置计数
this.avatarClickTimer = setTimeout(() => {
this.avatarClickCount = 0;
}, 2000);
}
},
handleLogout() {
uni.showModal({
title: '退出登录',
content: '确定要退出登录吗?',
success: (res) => {
if (res.confirm) {
this.clearCacheAndReload();
}
}
});
},
clearCacheAndReload() {
uni.clearStorageSync();
uni.showToast({ title: '已退出登录', icon: 'success' });
setTimeout(() => {
location.reload();
}, 1000);
},
onVConsoleChange(e) { onVConsoleChange(e) {
const enabled = e.detail.value; const enabled = e.detail.value;
if (enabled) { if (enabled) {
@@ -455,6 +499,7 @@ page { height: 100%; background-color: #fff; }
.menu-item:last-child { border-bottom: none; } .menu-item:last-child { border-bottom: none; }
.menu-text { font-size: 30rpx; color: #333; } .menu-text { font-size: 30rpx; color: #333; }
.menu-arrow { font-size: 28rpx; color: #ccc; } .menu-arrow { font-size: 28rpx; color: #ccc; }
.logout-btn { margin-top: 20rpx; }
/* 开发工具区域 */ /* 开发工具区域 */
.dev-tools { margin-top: 20rpx; background-color: #fff; border-radius: 16rpx; overflow: hidden; } .dev-tools { margin-top: 20rpx; background-color: #fff; border-radius: 16rpx; overflow: hidden; }
+17 -7
View File
@@ -183,9 +183,16 @@ export default {
const ret = res.data || {}; const ret = res.data || {};
if (ret.code === 0 && ret.data) { if (ret.code === 0 && ret.data) {
// 合并微信授权信息(头像、昵称)到 user_info
const authInfo = uni.getStorageSync('auth_info') || {};
const userInfo = {
...authInfo,
...ret.data.user_info,
};
// 保存 token 和用户信息 // 保存 token 和用户信息
uni.setStorageSync('token', ret.data.token); uni.setStorageSync('token', ret.data.token);
uni.setStorageSync('user_info', ret.data.user_info); uni.setStorageSync('user_info', userInfo);
// 清除临时数据 // 清除临时数据
uni.removeStorageSync('temp_token'); uni.removeStorageSync('temp_token');
@@ -194,9 +201,14 @@ export default {
uni.hideLoading(); uni.hideLoading();
uni.showToast({ title: '注册成功', icon: 'success' }); uni.showToast({ title: '注册成功', icon: 'success' });
// 跳转首页 // 跳转到扫码时的页面(优先使用缓存的扫码URL)
setTimeout(() => { setTimeout(() => {
const url = this.deviceId 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?device_id=${this.deviceId}`
: '/pages/index/index'; : '/pages/index/index';
uni.redirectTo({ url }); uni.redirectTo({ url });
@@ -349,10 +361,8 @@ page {
/* 底部协议 */ /* 底部协议 */
.agreement { .agreement {
position: absolute; margin-top: 80rpx;
bottom: 80rpx; padding-bottom: env(safe-area-inset-bottom);
left: 0;
right: 0;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
+3 -1
View File
@@ -72,7 +72,9 @@ export function logout() {
*/ */
export function getCachedUserInfo() { export function getCachedUserInfo() {
try { try {
return uni.getStorageSync('user_info') || null; const userInfo = uni.getStorageSync('user_info');
console.log('[auth-guard] getCachedUserInfo raw:', JSON.stringify(userInfo, null, 2));
return userInfo || null;
} catch { } catch {
return null; return null;
} }