修改授权逻辑
Uni-app H5 Deploy (Prod + Staging) / deploy (release) Successful in 48s

This commit is contained in:
kk
2026-07-11 10:28:43 +08:00
parent 0fc854cd33
commit 7b2e4dc72e
4 changed files with 226 additions and 79 deletions
+170 -23
View File
@@ -15,14 +15,16 @@ export default {
return {
statusText: '正在登录...',
deviceId: '',
action: '',
};
},
onLoad(options) {
this.deviceId = options.device_id || '';
this.action = options.action || '';
// #ifdef H5
// Mock 模式:跳过微信 OAuth,直接登录
if (config.mockWechatLogin) {
if (config.mockWechatLogin && this.action !== 'userinfo') {
this.mockLogin();
return;
}
@@ -33,14 +35,30 @@ export default {
if (!code) {
const urlParams = new URLSearchParams(window.location.search);
code = urlParams.get('code') || '';
// 同步获取 action(可能在 URL 参数中)
if (!this.action) {
this.action = urlParams.get('action') || '';
}
// 同步获取 device_id
if (!this.deviceId) {
this.deviceId = urlParams.get('device_id') || '';
}
}
if (code) {
// 有 code → 调用后端登录
this.handleCallback(code);
if (this.action === 'userinfo') {
// 获取用户信息流程
if (code) {
this.handleUserInfoCallback(code);
} else {
this.startUserInfoAuth();
}
} else {
// 无 code → 发起 OAuth 授权
this.startAuth();
// 登录流程
if (code) {
this.handleCallback(code);
} else {
this.startAuth();
}
}
// #endif
@@ -94,7 +112,7 @@ export default {
},
/**
* 处理授权回调(从 URL 中获取 code 后换取 openid,再用 openid 登录)
* 处理授权回调( code openid,再用 openid 登录)
*/
async handleCallback(code) {
const appNo = uni.getStorageSync('app_no') || getAppNo(detectPlatform());
@@ -108,35 +126,56 @@ export default {
try {
this.statusText = '正在验证身份...';
// 用 code 换取 openid后端处理,前端只传 code
const res = await gatewayPost('/api/v1/user/login', {
// 1. 用 code 换取 openidsnsapi_base 静默授权
const callbackRes = await gatewayPost('/api/v1/user/auth/exchange', {
app_no: appNo,
code: code,
});
const data = res.data || {};
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;
}
// 清除 URL 中的 code 参数,避免刷新重复处理
const url = new URL(window.location.href);
url.searchParams.delete('code');
url.searchParams.delete('state');
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;
console.log('[loading] login result:', JSON.stringify(result, null, 2));
// 清除 URL 中的 code 参数,避免刷新重复处理
const url = new URL(window.location.href);
url.searchParams.delete('code');
url.searchParams.delete('state');
window.history.replaceState({}, '', url.toString());
// 存储 openid
uni.setStorageSync('openid', result.openid);
if (result.register) {
// 已注册 → JWT → 跳转首
// 已注册 → 存 token → 进入开门
uni.setStorageSync('token', result.token);
// 不再存储 user_info,点击"我的"时再获取
this.goToHome();
} else {
// 未注册 → 缓存临时数据 → 跳注册页
// 未注册 → 存 temp_token → 跳注册页
uni.setStorageSync('temp_token', result.temp_token);
this.goToRegister();
}
@@ -151,6 +190,114 @@ export default {
}
},
/**
* 发起非静默授权获取用户信息(snsapi_userinfo,弹窗确认)
*/
async startUserInfoAuth() {
const platform = detectPlatform();
const appNo = getAppNo(platform);
if (!appNo) {
// 非微信环境,直接跳回首页
this.goToHomeWithAction();
return;
}
try {
this.statusText = '正在获取用户信息...';
// 回调地址:当前 loading 页,带 action=userinfo 和 device_id
const baseUri = config.authRedirectUri || (
window.location.origin.replace(/^http:/, 'https:') + window.location.pathname
);
const redirectUriObj = new URL(baseUri);
redirectUriObj.searchParams.set('action', 'userinfo');
if (this.deviceId) {
redirectUriObj.searchParams.set('device_id', this.deviceId);
}
const redirectUri = redirectUriObj.toString();
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) {
// 跳转微信授权页(弹窗确认)
window.location.href = data.data.auth_url;
} 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() {
const url = this.deviceId
? `/pages/index/index?device_id=${this.deviceId}`