Prechádzať zdrojové kódy

未登录允许查看柜类商品

skyline 1 mesiac pred
rodič
commit
73ea846ea6

+ 25 - 12
haha-mp/src/App.vue

@@ -4,9 +4,9 @@ import { onLaunch, onShow, onHide } from "@dcloudio/uni-app";
 /**
  * 应用启动
  */
-onLaunch(() => {
-  console.log("App Launch");
-  checkLoginStatus();
+onLaunch((options: any) => {
+  console.log("App Launch, options:", JSON.stringify(options));
+  checkLoginStatus(options);
 });
 
 /**
@@ -30,22 +30,35 @@ onHide(() => {
   }
 });
 
+/**
+ * 免登录白名单页面
+ * 这些页面允许未登录用户直接访问
+ */
+const LOGIN_WHITE_LIST = [
+  'pages/login/login',
+  'pages/products/products',
+];
+
 /**
  * 检查登录状态
- * 如果未登录且当前不在登录页,则跳转到登录页
+ * 如果未登录且当前不在白名单页面,则跳转到登录页
  */
-const checkLoginStatus = () => {
+const checkLoginStatus = (launchOptions?: any) => {
   const token = uni.getStorageSync('accessToken');
 
-  // 获取当前页面路径
-  const pages = getCurrentPages();
-  const currentPage = pages[pages.length - 1];
-  const currentPath = currentPage ? currentPage.route : '';
+  // 优先从启动参数获取目标页面路径(onLaunch时getCurrentPages为空)
+  let currentPath = launchOptions?.path || '';
+  if (!currentPath) {
+    const pages = getCurrentPages();
+    const currentPage = pages[pages.length - 1];
+    currentPath = currentPage ? currentPage.route : '';
+  }
 
-  console.log('[App] 检查登录状态 - token:', token ? '已存在' : '不存在', ', 当前页面:', currentPath);
+  console.log('[App] 检查登录状态 - token:', token ? '已存在' : '不存在', ', 目标页面:', currentPath);
 
-  // 如果没有token且不在登录页,跳转到登录页
-  if (!token && currentPath !== 'pages/login/login') {
+  // 如果没有token且不在白名单页面,跳转到登录页
+  const isWhiteListed = LOGIN_WHITE_LIST.some(path => currentPath.indexOf(path) !== -1);
+  if (!token && !isWhiteListed) {
     console.log('[App] 未登录,跳转到登录页');
     uni.reLaunch({
       url: '/pages/login/login'

+ 1 - 1
haha-mp/src/api/device.ts

@@ -107,5 +107,5 @@ export interface DeviceProductsResponse {
  * @param deviceId 设备ID
  */
 export const getDeviceProducts = (deviceId: string): Promise<DeviceProductsResponse> => {
-  return get<DeviceProductsResponse>(`/device/products/${deviceId}`);
+  return get<DeviceProductsResponse>(`/device/products/${deviceId}`, undefined, { skipAuth: true });
 };

+ 33 - 9
haha-mp/src/pages/my/my.vue

@@ -6,8 +6,8 @@
         <image class="avatar-icon" src="/static/icons/user.svg" mode="aspectFit"></image>
       </view>
       <view class="user-details">
-        <view class="user-name">微信用户</view>
-        <view class="user-phone">130****1579</view>
+        <view class="user-name">{{ displayName }}</view>
+        <view class="user-phone">{{ displayPhone }}</view>
       </view>
     </view>
 
@@ -107,20 +107,44 @@
 </template>
 
 <script setup lang="ts">
-import { ref, onMounted } from 'vue';
-import { mockApi } from '../../utils/mock';
+import { ref, computed, onMounted } from 'vue';
+import { onShow } from '@dcloudio/uni-app';
 import { logout as logoutApi } from '../../api/user';
 import { getCouponCount } from '../../api/coupon';
-import { clearAuth } from '../../utils/auth';
+import { clearAuth, getUserInfo as getStoredUserInfo } from '../../utils/auth';
 
 const userInfo = ref<any>(null);
 const availableCouponCount = ref(0);
 
-onMounted(async () => {
-  const response = await mockApi.getUserInfo();
-  if (response.success) {
-    userInfo.value = response.data;
+// 显示用户名
+const displayName = computed(() => {
+  return userInfo.value?.nickname || '微信用户';
+});
+
+// 显示手机号(脱敏)
+const displayPhone = computed(() => {
+  const phone = userInfo.value?.phone;
+  if (phone && phone.length >= 7) {
+    return phone.substring(0, 3) + '****' + phone.substring(phone.length - 4);
   }
+  return phone || '未绑定手机号';
+});
+
+// 每次页面显示时刷新用户信息
+onShow(() => {
+  loadUserInfo();
+});
+
+const loadUserInfo = () => {
+  const stored = getStoredUserInfo();
+  if (stored) {
+    userInfo.value = stored;
+  }
+};
+
+onMounted(async () => {
+  // 加载用户信息(从本地存储)
+  loadUserInfo();
   // 加载可用优惠券数量
   try {
     const result = await getCouponCount();

+ 7 - 2
haha-mp/src/pages/products/products.vue

@@ -101,7 +101,7 @@
 
     <!-- 底部操作栏 -->
     <view v-if="!loading && !errorMsg" class="bottom-bar">
-      <view class="btn-exit" @click="goBack">退出</view>
+      <view class="btn-back" @click="goBack">返回</view>
       <view class="btn-open" @click="handleOpenDoor">开门购物</view>
     </view>
   </view>
@@ -274,6 +274,11 @@ const handleOpenDoor = async () => {
 
 // 返回
 const goBack = () => {
+  // 校验登录状态,未登录则跳转到登录页
+  if (!isLoggedIn()) {
+    uni.reLaunch({ url: '/pages/login/login' });
+    return;
+  }
   uni.navigateBack({
     fail: () => {
       uni.reLaunch({ url: '/pages/index/index' });
@@ -562,7 +567,7 @@ const goBack = () => {
   background: #fff;
   box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.08);
 }
-.btn-exit {
+.btn-back {
   flex: 1;
   text-align: center;
   padding: 22rpx 0;

+ 6 - 1
haha-mp/src/utils/auth.ts

@@ -60,11 +60,16 @@ export const removeUserInfo = (): void => {
 };
 
 /**
- * 清除所有登录信息
+ * 清除所有登录信息及会话数据
  */
 export const clearAuth = (): void => {
   removeToken();
   removeUserInfo();
+  // 清除购物流程相关数据
+  uni.removeStorageSync('currentDeviceId');
+  uni.removeStorageSync('currentOutTradeNo');
+  uni.removeStorageSync('currentOrderNo');
+  uni.removeStorageSync('shoppingPollingActive');
 };
 
 /**

+ 14 - 10
haha-mp/src/utils/request.ts

@@ -15,6 +15,8 @@ interface RequestConfig {
   data?: any;
   header?: any;
   timeout?: number;
+  /** 是否跳过添加token,用于免登录接口 */
+  skipAuth?: boolean;
 }
 
 /**
@@ -33,22 +35,24 @@ interface ResponseData<T = any> {
  */
 export const request = <T = any>(config: RequestConfig): Promise<T> => {
   return new Promise((resolve, reject) => {
-    const { url, method = 'GET', data, header = {}, timeout = API_CONFIG.timeout } = config;
+    const { url, method = 'GET', data, header = {}, timeout = API_CONFIG.timeout, skipAuth = false } = config;
 
     // 构建完整URL
     let fullUrl = url.startsWith('http') ? url : `${API_CONFIG.baseUrl}${url}`;
 
-    // 添加token到请求头
-    const token = getToken();
-    if (token) {
-      header['accessToken'] = token;
+    // 添加token到请求头(skipAuth为true时跳过)
+    if (!skipAuth) {
+      const token = getToken();
+      if (token) {
+        header['accessToken'] = token;
 
       if (API_CONFIG.enableLog) {
         console.log('[请求拦截] 添加token到请求头:', token.substring(0, 8) + '...');
       }
-    } else {
-      if (API_CONFIG.enableLog) {
-        console.warn('[请求拦截] 未找到token,请求将不携带token');
+      } else {
+        if (API_CONFIG.enableLog) {
+          console.warn('[请求拦截] 未找到token,请求将不携带token');
+        }
       }
     }
 
@@ -145,8 +149,8 @@ export const request = <T = any>(config: RequestConfig): Promise<T> => {
 /**
  * GET请求
  */
-export const get = <T = any>(url: string, data?: any): Promise<T> => {
-  return request<T>({ url, method: 'GET', data });
+export const get = <T = any>(url: string, data?: any, options?: { skipAuth?: boolean }): Promise<T> => {
+  return request<T>({ url, method: 'GET', data, ...options });
 };
 
 /**