支付问题优化

This commit is contained in:
zhangguoping 2026-01-09 16:40:32 +08:00
parent 46500f1c93
commit 72f530a9e4
1 changed files with 41 additions and 266 deletions

View File

@ -266,30 +266,18 @@
<script> <script>
// 支付页面模块化实现 // 支付页面模块化实现
const API_BASE_URL = 'https://pay.cdlsxd.cn'; const API_BASE_URL = 'https://pay.cdlsxd.cn';
// ========== 配置模块 ========== // ========== 配置模块 ==========
const CONFIG = { const CONFIG = {
API: { API: {
LIST: API_BASE_URL + '/pay/front/api/v1/payPage/list', LIST: API_BASE_URL + '/pay/front/api/v1/payPage/list',
SUBMIT: API_BASE_URL + '/pay/front/api/v1/payPage/submit', SUBMIT: API_BASE_URL + '/pay/front/api/v1/payPage/submit',
QUERY: API_BASE_URL + '/pay/front/api/v1/payPage/query' QUERY: API_BASE_URL + '/pay/front/api/v1/payPage/query'
}, },
POLLING: {
MAX_ATTEMPTS: 30,
DELAY: 2000,
TIMEOUT: 60000,
REQUEST_TIMEOUT: 10000
},
LOCAL_STORAGE: {
AUTO_REDIRECT: 'auto-redirect',
AUTO_REDIRECT_TIMESTAMP: 'auto-redirect-timestamp'
},
PAYMENT_STATUS: { PAYMENT_STATUS: {
PROCESSING: 2, PROCESSING: 2,
SUCCESS: 3 SUCCESS: 3
}, },
REDIRECT_DELAY: 3000, REDIRECT_DELAY: 3000
// 自动跳转标记的有效期(毫秒)
REDIRECT_FLAG_EXPIRY: 10 * 60 * 1000 // 10分钟
}; };
// ========== 工具函数模块 ========== // ========== 工具函数模块 ==========
@ -313,13 +301,6 @@
const orderNoPattern = /^[a-zA-Z0-9_]{10,32}$/; const orderNoPattern = /^[a-zA-Z0-9_]{10,32}$/;
return orderNoPattern.test(orderNo); return orderNoPattern.test(orderNo);
}, },
// 检查是否为同域请求
isSameOrigin(url) {
const parser = document.createElement('a');
parser.href = url;
return parser.origin === window.location.origin;
},
// 显示Loading效果 // 显示Loading效果
showLoading(text = "支付处理中,请稍等...") { showLoading(text = "支付处理中,请稍等...") {
@ -342,41 +323,6 @@
document.getElementById("pay-container").style.display = "block"; document.getElementById("pay-container").style.display = "block";
}, },
// 清除支付状态标记
clearRedirectFlag() {
localStorage.removeItem(CONFIG.LOCAL_STORAGE.AUTO_REDIRECT);
localStorage.removeItem(CONFIG.LOCAL_STORAGE.AUTO_REDIRECT_TIMESTAMP);
},
// 设置支付状态标记
setRedirectFlag(value) {
localStorage.setItem(CONFIG.LOCAL_STORAGE.AUTO_REDIRECT, value);
localStorage.setItem(CONFIG.LOCAL_STORAGE.AUTO_REDIRECT_TIMESTAMP, Date.now().toString());
},
// 获取支付状态标记
getRedirectFlag() {
return localStorage.getItem(CONFIG.LOCAL_STORAGE.AUTO_REDIRECT);
},
// 检查自动跳转标记是否有效
isRedirectFlagValid() {
const flag = localStorage.getItem(CONFIG.LOCAL_STORAGE.AUTO_REDIRECT);
const timestampStr = localStorage.getItem(CONFIG.LOCAL_STORAGE.AUTO_REDIRECT_TIMESTAMP);
if (!flag || !timestampStr) {
return false;
}
const timestamp = parseInt(timestampStr, 10);
if (isNaN(timestamp)) {
return false;
}
// 检查标记是否在有效期内
return (Date.now() - timestamp) < CONFIG.REDIRECT_FLAG_EXPIRY;
},
// 显示支付状态确认弹窗 // 显示支付状态确认弹窗
showPaymentStatusModal() { showPaymentStatusModal() {
const modal = document.getElementById('payment-status-modal'); const modal = document.getElementById('payment-status-modal');
@ -421,44 +367,6 @@
} }
}; };
// ========== 轮询处理模块 ==========
const PollingManager = {
// 处理轮询超时
handleTimeout() {
Utils.closeLoading();
// 清除自动跳转标记
Utils.clearRedirectFlag();
this.showError("支付结果查询超时,请稍后手动查询订单状态。");
},
// 处理超过最大轮询次数
handleMaxAttempts() {
Utils.closeLoading();
// 清除自动跳转标记
Utils.clearRedirectFlag();
this.showError("支付结果查询次数已达上限,请稍后手动查询订单状态。");
},
// 显示轮询错误信息
showError(message) {
const payContainer = document.getElementById("pay-container");
payContainer.innerHTML = `
<div style="text-align: center; padding: 40px;">
<h3 style="color: #ff5500;">支付结果查询失败</h3>
<p style="margin: 20px 0;">${message}</p>
<div style="display: flex; justify-content: center; gap: 20px;">
<button onclick="location.reload()" style="background-color: #007bff; color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer;">
重新查询
</button>
<button onclick="Utils.clearRedirectFlag(); PaymentManager.fetchPaymentMethods()" style="background-color: #6c757d; color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer;">
返回支付
</button>
</div>
</div>
`;
}
};
// ========== 支付管理模块 ========== // ========== 支付管理模块 ==========
const PaymentManager = { const PaymentManager = {
// 处理支付回调 // 处理支付回调
@ -473,126 +381,41 @@
// 显示查询支付结果的loading // 显示查询支付结果的loading
Utils.showLoading("正在查询支付结果..."); Utils.showLoading("正在查询支付结果...");
// 轮询状态 // 单次查询订单状态
const pollState = { fetch(`${CONFIG.API.QUERY}?no=${id}`, {
attempts: 0, method: "POST",
startTime: Date.now(), timeout: 10000
lastDelay: CONFIG.POLLING.DELAY, })
errorCount: 0 .then(async (response) => {
}; if (!response.ok) throw new Error(`HTTP错误: ${response.status}`);
return await response.json();
// 取消请求的控制器
let abortController = null;
// 计算动态轮询间隔
function getDynamicDelay(attempts, errorCount) {
// 初始间隔较短,随着尝试次数增加而延长
let baseDelay = CONFIG.POLLING.DELAY;
// 每5次尝试增加基础间隔
const delayIncrease = Math.floor(attempts / 5) * 500;
// 网络错误时增加额外延迟
const errorDelay = errorCount * 1000;
// 计算最终延迟,不超过最大间隔
const finalDelay = Math.min(baseDelay + delayIncrease + errorDelay, 10000);
return finalDelay;
}
// 执行轮询
function pollOrderStatus() {
// 检查是否超时
if (Date.now() - pollState.startTime > CONFIG.POLLING.TIMEOUT) {
PollingManager.handleTimeout();
return;
}
// 检查是否超过最大轮询次数
if (pollState.attempts >= CONFIG.POLLING.MAX_ATTEMPTS) {
PollingManager.handleMaxAttempts();
return;
}
pollState.attempts++;
// 取消之前的请求(如果有)
if (abortController) {
abortController.abort();
}
// 创建新的取消控制器
abortController = new AbortController();
// 查询订单状态
fetch(`${CONFIG.API.QUERY}?no=${id}`, {
method: "POST",
timeout: CONFIG.POLLING.REQUEST_TIMEOUT,
signal: abortController.signal
}) })
.then(async (response) => { .then((data) => {
if (!response.ok) throw new Error(`HTTP错误: ${response.status}`); switch (data.status) {
return await response.json(); case CONFIG.PAYMENT_STATUS.PROCESSING: // 处理中
}) Utils.closeLoading();
.then((data) => { Utils.showToast("支付处理中,请稍后再试");
pollState.errorCount = 0; // 重置错误计数 break;
switch (data.status) { case CONFIG.PAYMENT_STATUS.SUCCESS: // 支付成功
case CONFIG.PAYMENT_STATUS.PROCESSING: // 处理中 PaymentManager.handlePaymentSuccess(data);
// 计算动态延迟 break;
const dynamicDelay = getDynamicDelay(pollState.attempts, pollState.errorCount); default: // 其他状态(待支付/失败/关闭)
pollState.lastDelay = dynamicDelay; // 显示未查到支付状态的提示
Utils.closeLoading();
// 延迟后继续轮询 Utils.showToast("未查到支付状态");
setTimeout(pollOrderStatus, dynamicDelay); }
break; })
case CONFIG.PAYMENT_STATUS.SUCCESS: // 支付成功 .catch((error) => {
PaymentManager.handlePaymentSuccess(data); // 网络错误或请求失败
break; console.error("查询订单状态失败:", error);
default: // 其他状态(待支付/失败/关闭) Utils.closeLoading();
// 显示未查到支付状态的提示 Utils.showToast("查询失败,请稍后重试");
Utils.closeLoading(); });
Utils.showToast("未查到支付状态");
// 重新显示支付状态确认弹窗
Utils.showPaymentStatusModal();
}
})
.catch((error) => {
// 检查是否为取消错误
if (error.name === 'AbortError') {
console.log("轮询请求已取消");
return;
}
// 网络错误或请求失败
console.error("查询订单状态失败:", error);
pollState.errorCount++;
// 如果是第5次或10次失败显示网络不稳定提示
if (pollState.attempts % 5 === 0) {
const loadingText = document.querySelector('.loading-text');
if (loadingText) {
loadingText.textContent = `支付处理中,请稍等...(网络不稳定,正在重试)`;
}
}
// 计算动态延迟,网络错误时增加延迟
const dynamicDelay = getDynamicDelay(pollState.attempts, pollState.errorCount);
pollState.lastDelay = dynamicDelay;
setTimeout(pollOrderStatus, dynamicDelay);
});
}
// 开始轮询
pollOrderStatus();
}, },
// 处理支付成功 // 处理支付成功
handlePaymentSuccess(data) { handlePaymentSuccess(data) {
Utils.closeLoading(); Utils.closeLoading();
// 清除自动跳转标记,避免影响后续支付
Utils.clearRedirectFlag();
// 显示支付成功提示 // 显示支付成功提示
const payContainer = document.getElementById("pay"); const payContainer = document.getElementById("pay");
@ -632,17 +455,6 @@
} }
}, },
// 处理支付取消
handlePaymentCanceled() {
Utils.closeLoading();
// 清除自动跳转标记,避免影响后续支付
Utils.clearRedirectFlag();
// 显示支付取消提示
const payContainer = document.getElementById("pay");
payContainer.innerHTML = `<p style="color: #666; margin-bottom: 20px;">支付已取消,您可以重新选择支付方式</p>`;
PaymentManager.fetchPaymentMethods();
},
// 获取支付方式列表 // 获取支付方式列表
fetchPaymentMethods() { fetchPaymentMethods() {
const id = Utils.getQueryParam("no"); const id = Utils.getQueryParam("no");
@ -670,8 +482,6 @@
}) })
.catch((error) => { .catch((error) => {
Utils.closeLoading(); Utils.closeLoading();
// 清除自动跳转标记
Utils.clearRedirectFlag();
console.error("获取支付方式失败:", error); console.error("获取支付方式失败:", error);
const pay = document.getElementById("pay"); const pay = document.getElementById("pay");
pay.innerHTML = ` pay.innerHTML = `
@ -695,27 +505,12 @@
const pay = document.getElementById("pay"); const pay = document.getElementById("pay");
pay.innerHTML = "<h3>支付环境异常,请检查</h3>"; pay.innerHTML = "<h3>支付环境异常,请检查</h3>";
} else if (data.data.length === 1) { } else if (data.data.length === 1) {
// 检查是否是从支付页面返回 // 只有一种支付方式,自动跳转
if (Utils.getRedirectFlag() != 2 || !Utils.isRedirectFlagValid()) { window.location.href = `${CONFIG.API.SUBMIT}?pay_channel_id=${data.data[0].pay_channel_id}&no=${id}`;
// 首次访问或标记已失效,且只有一种支付方式,自动跳转
Utils.setRedirectFlag(2);
window.location.href = `${CONFIG.API.SUBMIT}?pay_channel_id=${data.data[0].pay_channel_id}&no=${id}`;
} else {
// 从支付页面返回,显示支付状态确认弹窗
Utils.closeLoading();
Utils.showPaymentStatusModal();
}
} else { } else {
// 多种支付方式,先检查是否从支付页面返回 Utils.closeLoading();
if (Utils.getRedirectFlag() == 2 && Utils.isRedirectFlagValid()) { // 多种支付方式,展示支付界面
// 从支付页面返回,显示支付状态确认弹窗 PaymentManager.renderPaymentMethods(data.data);
Utils.closeLoading();
Utils.showPaymentStatusModal();
} else {
Utils.closeLoading();
// 首次访问或标记已失效,展示支付界面
PaymentManager.renderPaymentMethods(data.data);
}
} }
}, },
@ -801,13 +596,10 @@
Utils.showLoading(); Utils.showLoading();
// 尝试导航到支付页面,如果失败则显示错误 // 尝试导航到支付页面,如果失败则显示错误
try { try {
Utils.setRedirectFlag(2);
window.location.href = `${CONFIG.API.SUBMIT}?pay_channel_id=${selectedMethod.value}&no=${no}`; window.location.href = `${CONFIG.API.SUBMIT}?pay_channel_id=${selectedMethod.value}&no=${no}`;
// 设置超时检查,如果长时间未跳转则显示错误 // 设置超时检查,如果长时间未跳转则显示错误
setTimeout(() => { setTimeout(() => {
Utils.closeLoading(); Utils.closeLoading();
// 清除自动跳转标记,避免影响后续支付
Utils.clearRedirectFlag();
const payContainer = document.getElementById("pay"); const payContainer = document.getElementById("pay");
payContainer.innerHTML = ` payContainer.innerHTML = `
<h3 style="color: red;">支付提交超时</h3> <h3 style="color: red;">支付提交超时</h3>
@ -819,8 +611,6 @@
}, 5000); }, 5000);
} catch (error) { } catch (error) {
Utils.closeLoading(); Utils.closeLoading();
// 清除自动跳转标记,避免影响后续支付
Utils.clearRedirectFlag();
alert("支付提交失败,请重试"); alert("支付提交失败,请重试");
console.error("支付提交失败:", error); console.error("支付提交失败:", error);
} }
@ -830,28 +620,16 @@
} }
}; };
// 监听页面可见性变化
document.addEventListener("visibilitychange", function () {
if (!document.hidden && localStorage.getItem(CONFIG.LOCAL_STORAGE.AUTO_REDIRECT) == 2 && Utils.isRedirectFlagValid()) {
// 当页面从隐藏变为可见,且有有效标记时,显示支付状态确认弹窗
// 这样无论用户是支付成功后切换回来,还是点击完成跳回来,都能让用户确认支付状态
Utils.closeLoading();
Utils.showPaymentStatusModal();
}
});
// 页面加载时执行 // 页面加载时执行
window.onload = function () { window.onload = function () {
// 检查是否有return参数或已尝试支付的标记 // 检查是否有return参数
if (Utils.getQueryParam("return") || (localStorage.getItem(CONFIG.LOCAL_STORAGE.AUTO_REDIRECT) == 2 && Utils.isRedirectFlagValid())) { if (Utils.getQueryParam("return")) {
// 用户从支付页面返回,显示支付状态确认弹窗 // 用户从支付页面返回,显示支付状态确认弹窗
Utils.closeLoading(); Utils.closeLoading();
Utils.showPaymentStatusModal(); Utils.showPaymentStatusModal();
} else { } else {
// 首次访问或标记已失效,清除可能的旧标记并设置新标记 // 首次访问,获取支付方式
Utils.clearRedirectFlag(); PaymentManager.fetchPaymentMethods();
Utils.setRedirectFlag(1);
PaymentManager.fetchPaymentMethods(); // 获取支付方式
} }
// 绑定弹窗按钮事件 // 绑定弹窗按钮事件
@ -867,9 +645,6 @@
document.getElementById('btn-unpaid').addEventListener('click', function() { document.getElementById('btn-unpaid').addEventListener('click', function() {
// 隐藏弹窗 // 隐藏弹窗
Utils.hidePaymentStatusModal(); Utils.hidePaymentStatusModal();
// 清除支付状态标记
Utils.clearRedirectFlag();
Utils.setRedirectFlag(1);
// 重新获取支付方式 // 重新获取支付方式
PaymentManager.fetchPaymentMethods(); PaymentManager.fetchPaymentMethods();
}); });
@ -887,4 +662,4 @@
{{end}} {{end}}
</html> </html>
{{end}} {{end}}