Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9ecd6d963b | |||
| 925ebe9bb9 | |||
| 258fa4a9f5 | |||
| 45147426e0 | |||
| 7b2e4dc72e |
+27
-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,33 @@
|
|||||||
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 解析失败,忽略
|
||||||
|
}
|
||||||
|
// 存入 localStorage,确保 loading 页面复用时也能获取(redirectTo 可能不触发 onLoad)
|
||||||
|
if (action) {
|
||||||
|
localStorage.setItem('__auth_action', action);
|
||||||
|
}
|
||||||
|
if (callbackDeviceId) {
|
||||||
|
localStorage.setItem('__auth_device_id', callbackDeviceId);
|
||||||
|
}
|
||||||
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;
|
||||||
|
|||||||
+207
-21
@@ -15,33 +15,51 @@ 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 恢复(页面复用时 onLoad 不触发,localStorage 由跳转函数清理)
|
||||||
|
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');
|
||||||
|
|
||||||
|
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
|
||||||
@@ -66,7 +84,12 @@ export default {
|
|||||||
try {
|
try {
|
||||||
this.statusText = '正在获取授权...';
|
this.statusText = '正在获取授权...';
|
||||||
|
|
||||||
// 回调地址必须是 HTTPS,使用配置文件中的地址
|
// 存入 localStorage(页面复用时 onLoad 不会重新触发,需要从 localStorage 读取)
|
||||||
|
if (this.deviceId) {
|
||||||
|
localStorage.setItem('__auth_device_id', this.deviceId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 回调地址:必须与微信公众号后台注册地址一致,不能带自定义参数
|
||||||
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
|
||||||
);
|
);
|
||||||
@@ -80,8 +103,20 @@ export default {
|
|||||||
|
|
||||||
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 原样回传)
|
||||||
|
let authUrl = data.data.auth_url;
|
||||||
|
if (this.deviceId) {
|
||||||
|
const stateVal = encodeURIComponent(JSON.stringify({ device_id: this.deviceId }));
|
||||||
|
try {
|
||||||
|
const urlObj = new URL(authUrl);
|
||||||
|
urlObj.searchParams.set('state', stateVal);
|
||||||
|
authUrl = urlObj.toString();
|
||||||
|
} catch (_) {
|
||||||
|
authUrl += (authUrl.includes('?') ? '&' : '?') + 'state=' + stateVal;
|
||||||
|
}
|
||||||
|
}
|
||||||
// 跳转微信授权页(静默,不弹窗)
|
// 跳转微信授权页(静默,不弹窗)
|
||||||
window.location.href = data.data.auth_url;
|
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);
|
||||||
@@ -94,7 +129,7 @@ export default {
|
|||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 处理授权回调(从 URL 中获取 code 后换取 openid,再用 openid 登录)
|
* 处理授权回调(用 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());
|
||||||
@@ -108,18 +143,27 @@ export default {
|
|||||||
try {
|
try {
|
||||||
this.statusText = '正在验证身份...';
|
this.statusText = '正在验证身份...';
|
||||||
|
|
||||||
// 用 code 换取 openid(后端处理,前端只传 code)
|
// 1. 用 code 换取 openid(snsapi_base 静默授权)
|
||||||
const res = await gatewayPost('/api/v1/user/login', {
|
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);
|
||||||
@@ -128,15 +172,27 @@ export default {
|
|||||||
window.history.replaceState({}, '', url.toString());
|
window.history.replaceState({}, '', url.toString());
|
||||||
|
|
||||||
// 存储 openid
|
// 存储 openid
|
||||||
uni.setStorageSync('openid', result.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);
|
||||||
// 不再存储 user_info,点击"我的"时再获取
|
|
||||||
this.goToHome();
|
this.goToHome();
|
||||||
} else {
|
} else {
|
||||||
// 未注册 → 缓存临时数据 → 跳转注册页
|
// 未注册 → 存 temp_token → 跳注册页
|
||||||
uni.setStorageSync('temp_token', result.temp_token);
|
uni.setStorageSync('temp_token', result.temp_token);
|
||||||
this.goToRegister();
|
this.goToRegister();
|
||||||
}
|
}
|
||||||
@@ -151,10 +207,140 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发起非静默授权获取用户信息(snsapi_userinfo,弹窗确认)
|
||||||
|
*/
|
||||||
|
async startUserInfoAuth() {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 回调地址:必须与微信公众号后台注册地址一致,不能带自定义参数
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
const stateVal = encodeURIComponent(JSON.stringify(stateObj));
|
||||||
|
let authUrl = data.data.auth_url;
|
||||||
|
try {
|
||||||
|
const urlObj = new URL(authUrl);
|
||||||
|
urlObj.searchParams.set('state', stateVal);
|
||||||
|
authUrl = urlObj.toString();
|
||||||
|
} catch (_) {
|
||||||
|
authUrl += (authUrl.includes('?') ? '&' : '?') + 'state=' + stateVal;
|
||||||
|
}
|
||||||
|
// 跳转微信授权页(弹窗确认)
|
||||||
|
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 调用 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', {
|
||||||
|
app_no: appNo,
|
||||||
|
code: code,
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = res.data || {};
|
||||||
|
console.log('[loading] user/info response:', JSON.stringify(data, null, 2));
|
||||||
|
console.log('[loading] user/info statusCode:', res.statusCode);
|
||||||
|
|
||||||
|
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() {
|
||||||
|
// 兼容页面复用:优先 this.deviceId,其次 localStorage
|
||||||
|
const deviceId = this.deviceId || localStorage.getItem('__auth_device_id') || '';
|
||||||
|
const url = deviceId
|
||||||
|
? `/pages/index/index?device_id=${deviceId}&action=mine`
|
||||||
|
: '/pages/index/index?action=mine';
|
||||||
|
localStorage.removeItem('__auth_device_id');
|
||||||
|
localStorage.removeItem('__auth_action');
|
||||||
|
uni.redirectTo({ url });
|
||||||
|
},
|
||||||
|
|
||||||
goToHome() {
|
goToHome() {
|
||||||
const url = this.deviceId
|
const deviceId = this.deviceId || localStorage.getItem('__auth_device_id') || '';
|
||||||
? `/pages/index/index?device_id=${this.deviceId}`
|
const url = deviceId
|
||||||
|
? `/pages/index/index?device_id=${deviceId}`
|
||||||
: '/pages/index/index';
|
: '/pages/index/index';
|
||||||
|
localStorage.removeItem('__auth_device_id');
|
||||||
uni.redirectTo({ url });
|
uni.redirectTo({ url });
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
+68
-54
@@ -164,7 +164,7 @@
|
|||||||
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, gatewayGet } 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 {
|
||||||
@@ -226,22 +226,24 @@ 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';
|
this.fromPage = 'navigate';
|
||||||
// 获取用户信息
|
|
||||||
this.fetchUserInfo();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.device_id) {
|
if (options.device_id) {
|
||||||
this.deviceId = options.device_id;
|
this.deviceId = options.device_id;
|
||||||
// 动态设置导航栏标题
|
|
||||||
uni.setNavigationBarTitle({ title: `智能货柜-${this.deviceId}` });
|
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' });
|
uni.showToast({ title: '请扫描设备二维码', icon: 'none' });
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
uni.redirectTo({ url: '/pages/index/scan' });
|
uni.redirectTo({ url: '/pages/index/scan' });
|
||||||
@@ -265,14 +267,20 @@ export default {
|
|||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
switchTab(tab) {
|
switchTab(tab) {
|
||||||
// 切换到"我的"Tab 时检查登录
|
|
||||||
if (tab === 'mine' && !checkLoginWithPrompt('mine')) return;
|
|
||||||
this.currentTab = tab;
|
|
||||||
// 记录来源:从 tab 切换的
|
|
||||||
if (tab === 'mine') {
|
if (tab === 'mine') {
|
||||||
|
// 切换到"我的"Tab 时检查登录
|
||||||
|
if (!checkLoginWithPrompt('mine')) return;
|
||||||
|
this.currentTab = tab;
|
||||||
this.fromPage = 'tab';
|
this.fromPage = 'tab';
|
||||||
// 获取用户信息
|
// 已有缓存的用户信息则直接显示,否则发起非静默授权获取
|
||||||
this.fetchUserInfo();
|
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; },
|
||||||
@@ -292,24 +300,14 @@ 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 fetchUserInfo() {
|
async startUserInfoAuth() {
|
||||||
const appNo = uni.getStorageSync('app_no') || config.mockAppNo;
|
// Mock 模式下,直接使用 mock 数据
|
||||||
|
|
||||||
if (!appNo) {
|
|
||||||
console.warn('[index] 无法获取应用信息');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mock 模式下,从缓存读取用户信息
|
|
||||||
if (config.mockWechatLogin) {
|
if (config.mockWechatLogin) {
|
||||||
console.log('[index] Mock 模式,从缓存读取用户信息');
|
|
||||||
const cached = getCachedUserInfo();
|
const cached = getCachedUserInfo();
|
||||||
if (cached) {
|
if (cached && cached.nickname) {
|
||||||
// 有缓存(注册后存储的),直接使用
|
|
||||||
this.userInfo = { ...this.userInfo, ...cached };
|
this.userInfo = { ...this.userInfo, ...cached };
|
||||||
} else {
|
} else {
|
||||||
// 无缓存,使用 mock 数据(已注册用户)
|
|
||||||
this.userInfo = {
|
this.userInfo = {
|
||||||
nickname: config.mockUser.user_info.nickname || '',
|
nickname: config.mockUser.user_info.nickname || '',
|
||||||
phone: config.mockUser.user_info.phone || '',
|
phone: config.mockUser.user_info.phone || '',
|
||||||
@@ -320,41 +318,57 @@ export default {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const appNo = uni.getStorageSync('app_no');
|
||||||
|
if (!appNo) {
|
||||||
|
console.warn('[index] 无法获取应用信息');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 调用接口获取用户信息
|
// 存入 localStorage(loading 页面复用时 onLoad 不会重新触发,需要从 localStorage 读取)
|
||||||
const res = await gatewayGet('/api/v1/user/info', {
|
localStorage.setItem('__auth_action', 'userinfo');
|
||||||
|
if (this.deviceId) {
|
||||||
|
localStorage.setItem('__auth_device_id', this.deviceId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 回调地址:必须与微信公众号后台注册地址一致,不能带自定义参数
|
||||||
|
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,
|
app_no: appNo,
|
||||||
|
scopes: 'snsapi_userinfo',
|
||||||
|
redirect_uri: redirectUri,
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = res.data || {};
|
const data = res.data || {};
|
||||||
console.log('[index] fetchUserInfo response:', JSON.stringify(data, null, 2));
|
if (data.code === 0 && data.data && data.data.auth_url) {
|
||||||
|
// 通过 state 传递 action 和 device_id(OAuth 标准保证 state 原样回传)
|
||||||
if (data.code === 0 && data.data) {
|
const stateObj = { action: 'userinfo' };
|
||||||
const userInfo = data.data;
|
if (this.deviceId) {
|
||||||
this.userInfo = {
|
stateObj.device_id = this.deviceId;
|
||||||
nickname: userInfo.nickname || '',
|
}
|
||||||
phone: userInfo.phone || '',
|
const stateVal = encodeURIComponent(JSON.stringify(stateObj));
|
||||||
avatar: userInfo.avatar || '',
|
// 解析 auth_url,安全地设置 state 参数(避免重复)
|
||||||
};
|
let authUrl = data.data.auth_url;
|
||||||
// 存入缓存
|
try {
|
||||||
uni.setStorageSync('user_info', this.userInfo);
|
const urlObj = new URL(authUrl);
|
||||||
console.log('[index] fetchUserInfo success:', JSON.stringify(this.userInfo, null, 2));
|
urlObj.searchParams.set('state', stateVal);
|
||||||
} else if (data.code === 1010) {
|
authUrl = urlObj.toString();
|
||||||
// 用户未注册,需要重新走授权流程获取 temp_token
|
} catch (_) {
|
||||||
console.warn('[index] 用户未注册,重新授权');
|
// URL 解析失败时直接拼接
|
||||||
uni.removeStorageSync('token');
|
authUrl += (authUrl.includes('?') ? '&' : '?') + 'state=' + stateVal;
|
||||||
uni.removeStorageSync('user_info');
|
}
|
||||||
// 跳转到 loading 页重新授权(会获取 temp_token 后跳注册页)
|
console.log('[index] 跳转授权页:', authUrl);
|
||||||
const deviceId = this.deviceId || '';
|
// 跳转微信授权页(弹窗确认)
|
||||||
const loadingUrl = deviceId
|
window.location.href = authUrl;
|
||||||
? `/pages/auth/loading?device_id=${deviceId}`
|
|
||||||
: '/pages/auth/loading';
|
|
||||||
uni.redirectTo({ url: loadingUrl });
|
|
||||||
} else {
|
} else {
|
||||||
console.warn('[index] fetchUserInfo failed:', data.message);
|
console.warn('[index] 获取授权链接失败:', data.message);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('[index] fetchUserInfo error:', e);
|
console.error('[index] startUserInfoAuth error:', e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
async fetchProducts() {
|
async fetchProducts() {
|
||||||
|
|||||||
@@ -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