| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- const STATUS_LABELS = {
- NOTPAY: '未支付',
- USERPAYING: '支付确认中',
- SUCCESS: '已支付',
- CLOSED: '已关闭',
- PAYERROR: '支付失败',
- REVOKED: '已撤销',
- REFUND: '已退款',
- };
- const FINAL_STATES = new Set(['SUCCESS', 'REFUND', 'CLOSED', 'REVOKED', 'PAYERROR']);
- const RECHECK_DELAYS_MS = [600, 1500];
- function waitForDelay(delay) {
- return new Promise(resolve => setTimeout(resolve, delay));
- }
- // The caller supplies the authorized, server-side order lookup.
- async function reconcilePaymentStatus(query, { recheck = false, wait = waitForDelay } = {}) {
- let { status } = await query();
- if (recheck) {
- for (const delay of RECHECK_DELAYS_MS) {
- if (status !== 'NOTPAY' && status !== 'USERPAYING') break;
- await wait(delay);
- ({ status } = await query());
- }
- }
- return status;
- }
- function getPaymentStatus(status, { previousStatus, cashierOutcome } = {}) {
- if (previousStatus === 'REFUND' || (previousStatus === 'SUCCESS' && status !== 'REFUND')) {
- status = previousStatus;
- }
- let label = '结果待确认';
- if (Object.hasOwn(STATUS_LABELS, status)) label = STATUS_LABELS[status];
- if (status === 'NOTPAY') {
- if (cashierOutcome === 'success') label = '支付结果确认中';
- if (cashierOutcome === 'cancelled') label = '已取消 · 暂未支付';
- }
- return { status, label, final: FINAL_STATES.has(status) };
- }
- function canOpenCashier(status, { previousStatus, cashierOutcome } = {}) {
- return status === 'NOTPAY' && !FINAL_STATES.has(previousStatus) && cashierOutcome !== 'success';
- }
- module.exports = { canOpenCashier, getPaymentStatus, reconcilePaymentStatus };
|