payment-status.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. const STATUS_LABELS = {
  2. NOTPAY: '未支付',
  3. USERPAYING: '支付确认中',
  4. SUCCESS: '已支付',
  5. CLOSED: '已关闭',
  6. PAYERROR: '支付失败',
  7. REVOKED: '已撤销',
  8. REFUND: '已退款',
  9. };
  10. const FINAL_STATES = new Set(['SUCCESS', 'REFUND', 'CLOSED', 'REVOKED', 'PAYERROR']);
  11. const RECHECK_DELAYS_MS = [600, 1500];
  12. function waitForDelay(delay) {
  13. return new Promise(resolve => setTimeout(resolve, delay));
  14. }
  15. // The caller supplies the authorized, server-side order lookup.
  16. async function reconcilePaymentStatus(query, { recheck = false, wait = waitForDelay } = {}) {
  17. let { status } = await query();
  18. if (recheck) {
  19. for (const delay of RECHECK_DELAYS_MS) {
  20. if (status !== 'NOTPAY' && status !== 'USERPAYING') break;
  21. await wait(delay);
  22. ({ status } = await query());
  23. }
  24. }
  25. return status;
  26. }
  27. function getPaymentStatus(status, { previousStatus, cashierOutcome } = {}) {
  28. if (previousStatus === 'REFUND' || (previousStatus === 'SUCCESS' && status !== 'REFUND')) {
  29. status = previousStatus;
  30. }
  31. let label = '结果待确认';
  32. if (Object.hasOwn(STATUS_LABELS, status)) label = STATUS_LABELS[status];
  33. if (status === 'NOTPAY') {
  34. if (cashierOutcome === 'success') label = '支付结果确认中';
  35. if (cashierOutcome === 'cancelled') label = '已取消 · 暂未支付';
  36. }
  37. return { status, label, final: FINAL_STATES.has(status) };
  38. }
  39. function canOpenCashier(status, { previousStatus, cashierOutcome } = {}) {
  40. return status === 'NOTPAY' && !FINAL_STATES.has(previousStatus) && cashierOutcome !== 'success';
  41. }
  42. module.exports = { canOpenCashier, getPaymentStatus, reconcilePaymentStatus };