fix: allow switching unpaid invoice payments

go
codex 3 weeks ago
parent 1b8aaf5847
commit 2a15e396b1

@ -270,11 +270,10 @@ final class CloudApiController
public function invoiceStatus($request, $response, $args)
{
$actor = $this->billingActor($request);
return $this->json($response, [
'invoice' => CloudInvoiceDetailPageService::statusForUser(
return $this->json($response,
CloudInvoiceDetailPageService::statusForUser(
(int) $args['id'], (int) $actor['user_id']
),
]);
));
}
public function payInvoice($request, $response, $args)

@ -687,9 +687,9 @@ final class CloudPageController
$activePayment['status'] ?? ''
));
$activePaymentMessage = match ($activePaymentStatus) {
'creating' => '支付订单正在创建,请勿重复提交。',
'pending' => '已有待支付订单,正在恢复安全付款信息。',
'review' => '支付订单创建结果待核对,请勿再次提交,并联系管理员处理。',
'creating' => '上一笔支付订单正在创建;您仍可选择其他支付方式。',
'pending' => '已有待支付订单;可继续原订单或选择其他支付方式。',
'review' => '上一笔支付订单结果待核对;可选择其他支付方式,原订单若随后到账将计入账户余额。',
default => '',
};
$hasActivePayment = $activePayment !== null
@ -753,11 +753,13 @@ final class CloudPageController
'specification' => $specification,
'show_payment' => $hasActivePayment
|| ($payable && $paymentMethods !== []),
'payment_title' => $hasActivePayment
? '当前支付状态' : '选择支付方式',
'payment_description' => $hasActivePayment
? '页面只恢复已存在的支付尝试,不会创建或重复提交订单。'
: '选择支付方式后,点击“立即支付”将直接发起支付,请勿重复点击。',
'payment_title' => $payable && $paymentMethods !== []
? '选择支付方式' : '当前支付状态',
'payment_description' => $hasActivePayment && $payable
? '已有未完成支付订单;任一订单先到账即结清账单,后续到账款项将计入账户余额。'
: ($payable
? '选择支付方式后,点击“立即支付”将直接发起支付,请勿重复点击。'
: '该账单当前不可创建新的支付订单。'),
'active_payment_message' => $activePaymentMessage,
'active_payment_class' => $activePaymentStatus === 'review'
? 'invoice-payment-error' : 'invoice-payment-note',

@ -59,7 +59,7 @@ class UsdtController extends BaseController
if ($order === null) {
return $this->json($response, ['ret' => 0, 'result' => 0, 'status' => 'not_found'], 404);
}
(new UsdtPaymentService())->expire($order);
$order = (new UsdtPaymentService())->expire($order);
return $this->json($response, [
'ret' => 1,

@ -49,8 +49,10 @@ final class CloudInvoiceDetailPageService
);
$detail = $snapshot['invoice'];
$activePayment = $snapshot['active_payment'];
$canStartPayment = ($detail['payable'] ?? false) === true
&& $activePayment === null;
$canStartPayment = ($detail['payable'] ?? false) === true;
if ($activePayment !== null) {
$activePayment['can_submit'] = $canStartPayment;
}
return [
'invoice' => $detail,
'active_payment' => $activePayment,
@ -73,18 +75,21 @@ final class CloudInvoiceDetailPageService
private static function activePaymentLocked(int $invoiceId,
int $userId): ?array
{
$job = CloudJobService::blockingQueryForInvoice($invoiceId)
->where('user_id', $userId)
->orderByDesc('id')
->sharedLock()
->first(['id', 'user_id', 'invoice_id', 'kind', 'phase',
'outcome', 'effect_resolution', 'safe_to_resubmit']);
$payment = CloudInvoicePayment::where('invoice_id', $invoiceId)
->where('user_id', $userId)
->whereIn('status', ['creating', 'pending', 'creation_unknown'])
->orderByDesc('id')
->orderByDesc('updated_at')->orderByDesc('id')
->sharedLock()
->first();
$jobQuery = CloudJobService::blockingQueryForInvoice($invoiceId)
->where('user_id', $userId);
if ($payment !== null) {
$jobQuery->where('request_idempotency_key',
(string) $payment->idempotency_key);
}
$job = $jobQuery->orderByDesc('id')->sharedLock()
->first(['id', 'user_id', 'invoice_id', 'kind', 'phase',
'outcome', 'effect_resolution', 'safe_to_resubmit']);
if ($job === null && $payment === null) {
return null;
}
@ -112,7 +117,7 @@ final class CloudInvoiceDetailPageService
'status' => $status,
'task_id' => $job === null ? null : (string) $job->id,
'payment' => $safePayment,
'can_submit' => false,
'can_submit' => true,
];
}
@ -134,7 +139,20 @@ final class CloudInvoiceDetailPageService
if ($invoice === null) {
throw new CloudError('账单不存在', 404);
}
return CloudInvoiceService::status($invoice);
$status = CloudInvoiceService::status($invoice);
$activePayment = in_array(
(string) ($status['status'] ?? ''),
['open', 'overdue'],
true
) ? self::activePaymentLocked($invoiceId, $userId) : null;
if ($activePayment !== null) {
$activePayment['can_submit'] =
($status['payable'] ?? false) === true;
}
return [
'invoice' => $status,
'active_payment' => $activePayment,
];
}, 3
);
}

@ -66,6 +66,12 @@ final class CloudInvoicePaymentService
$fingerprint)) {
throw new CloudError('同一支付请求标识不能用于其他请求', 409);
}
CloudInvoicePayment::where('invoice_id', (int) $locked->id)
->where('user_id', (int) $user->id)
->where('idempotency_key', $key)
->whereIn('status', [
'creating', 'pending', 'creation_unknown',
])->update(['updated_at' => time()]);
return $prior;
}
if (!in_array((string) $locked->status,
@ -87,18 +93,43 @@ final class CloudInvoicePaymentService
409
);
}
if (CloudJobService::blockingQueryForInvoice(
(int) $locked->id)->exists()) {
throw new CloudError('该账单已有支付任务或结果不明的尝试', 409);
$sameMethodJob = CloudJobService::blockingQueryForInvoice(
(int) $locked->id
)->where('user_id', (int) $user->id)
->where('request_fingerprint', $fingerprint)
->orderByDesc('id')->lockForUpdate()->first();
if ($sameMethodJob !== null) {
CloudInvoicePayment::where('invoice_id', (int) $locked->id)
->where('user_id', (int) $user->id)
->where('idempotency_key',
(string) $sameMethodJob->request_idempotency_key)
->whereIn('status', [
'creating', 'pending', 'creation_unknown',
])->update(['updated_at' => time()]);
return $sameMethodJob;
}
if (CloudInvoicePayment::where('invoice_id', (int) $locked->id)
$sameMethodPayment = CloudInvoicePayment::where(
'invoice_id', (int) $locked->id
)->where('user_id', (int) $user->id)
->where('provider', $method)
->whereIn('status',
['creating', 'pending', 'creation_unknown'])
->lockForUpdate()->exists()) {
throw new CloudError(
'该账单已有支付订单或结果不明的尝试',
409
);
->orderByDesc('updated_at')->orderByDesc('id')
->lockForUpdate()->first();
if ($sameMethodPayment !== null) {
$sameMethodPayment->updated_at = time();
$sameMethodPayment->save();
$sameMethodPaymentJob = \App\Models\CloudJob::where(
'invoice_id', (int) $locked->id
)->where('user_id', (int) $user->id)
->where('kind', 'payment_create')
->where('request_idempotency_key',
(string) $sameMethodPayment->idempotency_key)
->orderByDesc('id')->lockForUpdate()->first();
if ($sameMethodPaymentJob !== null) {
return $sameMethodPaymentJob;
}
throw new CloudError('该支付方式已有未完成订单,请刷新后继续', 409);
}
$job = new \App\Models\CloudJob();
$job->invoice_id = $locked->id;
@ -442,15 +473,16 @@ final class CloudInvoicePaymentService
string $orderNo, string $idempotency, string $amount, int $userId,
int $now): void
{
// The invoice row is already locked by recordAttempt(). This final
// check is deliberately adjacent to the provider ledger insert so a
// second idempotency key can never create a concurrent external order.
// The invoice row is already locked by recordAttempt(). Keep at most
// one unfinished order per provider, while allowing the customer to
// switch to another provider before either order is paid.
if (CloudInvoicePayment::where('invoice_id', $invoiceId)
->where('idempotency_key', '<>', $idempotency)
->where('provider', $provider)
->whereIn('status', ['creating', 'pending', 'creation_unknown'])
->lockForUpdate()->exists()) {
throw new CloudError(
'该账单已有支付订单或结果不明的尝试',
'该支付方式已有未完成订单,请继续原订单或选择其他方式',
409
);
}
@ -466,6 +498,40 @@ final class CloudInvoicePaymentService
$payment->save();
}
/** Synchronize a provider terminal result without touching settled money. */
public static function markProviderOrdersTerminal(string $provider,
array $orderNumbers, string $status, ?int $now = null): int
{
$provider = trim($provider);
$orderNumbers = array_values(array_unique(array_filter(array_map(
static fn ($value): string => trim((string) $value),
$orderNumbers
), static fn (string $value): bool => $value !== '')));
if ($provider === '' || $orderNumbers === []
|| !in_array($status, ['failed', 'expired'], true)) {
return 0;
}
$now ??= time();
$payments = CloudInvoicePayment::where('provider', $provider)
->whereIn('provider_order_no', $orderNumbers)
->whereIn('status', ['creating', 'pending', 'creation_unknown'])
->orderBy('id')->lockForUpdate()->get();
if ($payments->isEmpty()) {
return 0;
}
CloudInvoicePayment::whereIn('id', $payments->pluck('id')->all())
->whereIn('status', ['creating', 'pending', 'creation_unknown'])
->update(['status' => $status, 'updated_at' => $now]);
foreach ($payments as $payment) {
self::resolveUnknownCreationFromProviderEvidence(
$payment,
'渠道终态证明原支付订单已创建',
$now
);
}
return $payments->count();
}
public static function settleForProvider(string $provider, string $orderNo): ?string
{
$payment = CloudInvoicePayment::where('provider', $provider)
@ -483,9 +549,11 @@ final class CloudInvoicePaymentService
/** A signed provider callback is authoritative proof that creation applied. */
private static function resolveUnknownCreationFromProviderEvidence(
CloudInvoicePayment $payment
CloudInvoicePayment $payment,
string $reason = '经签名支付回调确认原订单已由渠道接受',
?int $now = null
): void {
$now = time();
$now ??= time();
\App\Models\CloudJob::where('kind', 'payment_create')
->where('execution_mode', 'local')
->where('invoice_id', (int) $payment->invoice_id)
@ -498,8 +566,7 @@ final class CloudInvoicePaymentService
'effect_resolution' => 'applied',
'effect_resolved_at' => $now,
'effect_resolved_by' => null,
'effect_resolution_reason' =>
'经签名支付回调确认原订单已由渠道接受',
'effect_resolution_reason' => $reason,
'updated_at' => $now,
]);
}

@ -916,7 +916,10 @@ final class CloudWorkerService
}
$status = (string) $attempt->status;
if (in_array($status,
['pending', 'paid_invoice', 'credited_balance'], true)) {
[
'pending', 'failed', 'expired',
'paid_invoice', 'credited_balance',
], true)) {
return [true, ['id' => (string) $attempt->id], false, false, ''];
}
if ($status === 'not_created') {

@ -285,15 +285,9 @@ class StripePaymentService
? 'Stripe Checkout 会话已过期'
: 'Stripe 异步付款失败';
$provider = 'stripe_' . (string) $order->payment_method;
$payment = CloudInvoicePayment::where('provider', $provider)
->where('provider_order_no', $orderNo)
->lockForUpdate()->first();
if ($payment !== null && in_array((string) $payment->status,
['creating', 'pending', 'creation_unknown'], true)) {
$payment->status = $terminalStatus;
$payment->updated_at = $now;
$payment->save();
}
CloudInvoicePaymentService::markProviderOrdersTerminal(
$provider, [$orderNo], $terminalStatus, $now
);
} elseif ((string) $order->status !== 'paid'
&& in_array((string) $order->status,
['creating', 'creation_unknown', 'not_created'], true)) {

@ -35,12 +35,63 @@ class UsdtPaymentService
public function expire(UsdtPaymentOrder $order)
{
if ((string) $order->status === 'pending' && (int) $order->expires_at < time()) {
$order->status = 'expired';
$order->updated_at = time();
$order->save();
}
return $order;
$now = time();
return $order->getConnection()->transaction(function () use (
$order, $now
) {
$locked = UsdtPaymentOrder::where('id', (int) $order->id)
->lockForUpdate()->first();
if ($locked === null) {
return $order;
}
if ((string) $locked->status === 'pending'
&& (int) $locked->expires_at < $now) {
$locked->status = 'expired';
$locked->updated_at = $now;
$locked->save();
CloudInvoicePaymentService::markProviderOrdersTerminal(
'usdt', [(string) $locked->order_no], 'expired', $now
);
}
return $locked;
}, 3);
}
/** Expire every due order and its linked invoice-payment attempt atomically. */
public function expirePendingOrders(?int $now = null): int
{
$now ??= time();
$connection = (new UsdtPaymentOrder())->getConnection();
$total = 0;
do {
$expired = $connection->transaction(function () use ($now): int {
$orders = UsdtPaymentOrder::where('status', 'pending')
->where('business_type', 'recharge')
->where('expires_at', '<', $now)
->orderBy('id')->limit(250)->lockForUpdate()
->get(['id', 'order_no']);
if ($orders->isEmpty()) {
return 0;
}
$ids = $orders->pluck('id')->map(
static fn ($id): int => (int) $id
)->all();
$orderNumbers = $orders->pluck('order_no')->map(
static fn ($value): string => (string) $value
)->all();
UsdtPaymentOrder::whereIn('id', $ids)
->where('status', 'pending')->update([
'status' => 'expired',
'updated_at' => $now,
]);
CloudInvoicePaymentService::markProviderOrdersTerminal(
'usdt', $orderNumbers, 'expired', $now
);
return count($ids);
}, 3);
$total += $expired;
} while ($expired === 250);
return $total;
}
public function details(UsdtPaymentOrder $order)

@ -38,10 +38,8 @@ class UsdtScannerService
'error_message' => '结算进程中断,结果未知,未自动重试',
]);
$stats['expired'] = UsdtPaymentOrder::where('status', 'pending')
->where('business_type', 'recharge')
->where('expires_at', '<', $now)
->update(['status' => 'expired', 'updated_at' => $now]);
$stats['expired'] = (new UsdtPaymentService())
->expirePendingOrders($now);
$walletIds = UsdtPaymentOrder::whereIn('status', ['pending', 'expired'])
->where('business_type', 'recharge')

@ -564,20 +564,6 @@ function clearInvoicePaymentKeys(invoiceId) {
} catch {}
}
function hasPendingInvoicePaymentKey(invoiceId) {
const prefix = `${INVOICE_PAYMENT_STORAGE_PREFIX}${state.userId || 'unknown'}:${invoiceId}:`;
try {
for (let index = 0; index < sessionStorage.length; index += 1) {
const storageKey = sessionStorage.key(index);
if (!storageKey?.startsWith(prefix)) continue;
if (/^[A-Za-z0-9_.-]{16,128}$/.test(String(sessionStorage.getItem(storageKey) || ''))) {
return true;
}
}
} catch {}
return false;
}
async function copyText(value) {
if (navigator.clipboard?.writeText) {
try {
@ -812,6 +798,10 @@ function invoiceNeedsPolling(invoice = state.selectedInvoice) {
|| firstText(state.activePayment?.status).toLowerCase() === 'pending')) {
return true;
}
if (invoiceCanPay(invoice)
&& ['creating', 'pending', 'review'].includes(
firstText(state.activePayment?.status).toLowerCase()
)) return true;
return false;
}
@ -928,6 +918,22 @@ async function pollInvoiceStatus(generation) {
if (readSequence >= state.appliedReadSequence
&& update?.id && String(update.id) === String(state.selectedInvoice?.id || '')) {
state.appliedReadSequence = readSequence;
if (Object.prototype.hasOwnProperty.call(result || {}, 'active_payment')) {
const previousActivePayment = state.activePayment;
state.activePayment = result.active_payment
&& typeof result.active_payment === 'object'
&& !Array.isArray(result.active_payment)
? result.active_payment : null;
if (!state.activePayment
&& (previousActivePayment || state.onlinePaymentPending)) {
clearOnlinePaymentState(true);
clearInvoicePaymentKeys(state.selectedInvoice?.id);
byId('invoice-payment-result')?.replaceChildren();
} else if (state.activePayment
&& firstText(state.activePayment.status).toLowerCase() !== 'pending') {
clearOnlinePaymentState();
}
}
const nextInvoice = mergeInvoiceStatus(state.selectedInvoice, update);
if (entersProvisioningAfterPayment(previousInvoice, nextInvoice,
wasAwaitingOnlinePayment)) {
@ -996,8 +1002,8 @@ function renderOnlinePayment(container, payment) {
let box = container.querySelector('.cloud-payment-instructions');
if (!box) {
box = makeElement('div', 'cloud-payment-instructions');
container.append(box);
}
container.replaceChildren(box);
box.className = 'cloud-payment-instructions';
box.replaceChildren();
state.onlinePaymentPending = true;
@ -1068,6 +1074,8 @@ async function payInvoiceBalance(invoice, container) {
if (state.mutationBusy) return;
state.mutationBusy = true;
container.querySelectorAll('button').forEach(button => { button.disabled = true; });
const submit = byId('invoice-payment-submit');
if (submit) submit.disabled = true;
try {
const result = await api(`/api/v1/invoices/${encodeURIComponent(invoice.id)}/pay-balance`, {
method: 'POST',
@ -1124,6 +1132,7 @@ async function payInvoiceBalance(invoice, container) {
} finally {
state.mutationBusy = false;
container.querySelectorAll('button').forEach(button => { button.disabled = false; });
if (submit) submit.disabled = !state.selectedInvoicePaymentMethod;
}
}
@ -1139,6 +1148,8 @@ async function createInvoicePayment(invoice, method, container, paymentResult) {
if (state.mutationBusy) return;
state.mutationBusy = true;
container.querySelectorAll('button').forEach(button => { button.disabled = true; });
const submit = byId('invoice-payment-submit');
if (submit) submit.disabled = true;
const idempotencyKey = pendingInvoicePaymentKey(invoice.id, method.id);
try {
const result = await api(`/api/v1/invoices/${encodeURIComponent(invoice.id)}/payments`, {
@ -1155,9 +1166,19 @@ async function createInvoicePayment(invoice, method, container, paymentResult) {
paymentResult.replaceChildren(makeElement('p', 'invoice-payment-note',
'支付订单创建任务已接收,可在任务中心查看结果。'));
toast('支付订单创建任务已接收。', 'success');
observeTask(result, {
const observer = observeTask(result, {
onTerminal: task => {
if (taskSucceededWithoutRecovery(task) && task?.result?.payment) {
// A terminal task result is newer than every status GET already in
// flight. Project it immediately so a late response cannot restore
// an older payment attempt over the new instructions.
state.appliedReadSequence = ++state.readSequence;
state.activePayment = {
status: 'pending',
task_id: null,
payment: task.result.payment,
can_submit: true,
};
renderOnlinePayment(paymentResult, task.result.payment);
return;
}
@ -1166,14 +1187,19 @@ async function createInvoicePayment(invoice, method, container, paymentResult) {
}
const recoveryNotice = recoveryTaskFailureNotice(task);
const warning = !recoveryNotice && task.effect_may_have_applied
? ' 支付订单可能已在网关创建,请勿再次提交,并联系管理员处理。'
? ' 原支付订单可能已由网关创建;可选择其他支付方式,原订单若随后到账将计入账户余额。'
: '';
const failure = recoveryNotice || task.error || '支付订单创建失败。';
paymentResult.replaceChildren(makeElement('p',
'invoice-payment-error', `${failure}${warning}`));
toast(`${failure}${warning}`, 'error');
void refreshInvoiceDetail(invoice.id);
},
});
// Keep submit controls fenced until the durable task reaches a terminal
// state (or bounded observation stops). Switching is allowed after the
// provider order exists, not while the same creation request is in flight.
await observer.done;
} catch (error) {
const status = Number(error.status || 0);
const ambiguousHttpFailure = [408, 425, 429].includes(status);
@ -1189,6 +1215,7 @@ async function createInvoicePayment(invoice, method, container, paymentResult) {
} finally {
state.mutationBusy = false;
container.querySelectorAll('button').forEach(button => { button.disabled = false; });
if (submit) submit.disabled = !state.selectedInvoicePaymentMethod;
}
}
@ -1203,8 +1230,8 @@ function renderActiveInvoicePayment(activePayment, result) {
const taskId = firstText(activePayment?.task_id);
const prefix = taskId ? `任务 #${taskId} · ` : '';
const message = status === 'review'
? '支付订单创建结果待核对,请勿再次提交,并联系管理员处理。'
: '支付订单正在创建,请勿重复提交。';
? '上一笔支付订单结果待核对;可选择其他支付方式,原订单若随后到账将计入账户余额。'
: '上一笔支付订单正在创建;您仍可选择其他支付方式。';
result.replaceChildren(makeElement('p', status === 'review'
? 'invoice-payment-error' : 'invoice-payment-note', `${prefix}${message}`));
}
@ -1215,11 +1242,21 @@ function renderInvoicePaymentMethods(invoice, balance, methods, activePayment) {
const result = byId('invoice-payment-result');
if (!panel || !container || !result) return;
const invoiceStatus = firstText(invoice?.status).toLowerCase();
if (activePayment && typeof activePayment === 'object'
&& ['open', 'overdue'].includes(invoiceStatus)) {
text('invoice-payment-title', '当前支付状态');
const hasActivePayment = activePayment && typeof activePayment === 'object'
&& ['open', 'overdue'].includes(invoiceStatus);
if (hasActivePayment) {
text('invoice-payment-title', invoiceCanPay(invoice)
? '选择支付方式' : '当前支付状态');
text('invoice-payment-description', invoiceCanPay(invoice)
? '已有未完成支付订单;任一订单先到账即结清账单,后续到账款项将计入账户余额。'
: '该账单当前不可创建新的支付订单。');
renderActiveInvoicePayment(activePayment, result);
} else {
text('invoice-payment-title', '选择支付方式');
text('invoice-payment-description',
'页面只恢复已存在的支付尝试,不会创建或重复提交订单。');
'选择支付方式后,点击“立即支付”将直接发起支付,请勿重复点击。');
}
if (!invoiceCanPay(invoice)) {
container.replaceChildren();
const submit = byId('invoice-payment-submit');
if (submit) {
@ -1227,21 +1264,12 @@ function renderInvoicePaymentMethods(invoice, balance, methods, activePayment) {
submit.onclick = null;
}
state.selectedInvoicePaymentMethod = '';
panel.hidden = false;
renderActiveInvoicePayment(activePayment, result);
return;
}
if (activePayment) state.activePayment = null;
text('invoice-payment-title', '选择支付方式');
text('invoice-payment-description',
'选择支付方式后,点击“立即支付”将直接发起支付,请勿重复点击。');
if (!invoiceCanPay(invoice)) {
clearInvoicePaymentKeys(invoice.id);
clearOnlinePaymentState();
panel.hidden = true;
container.replaceChildren();
result.replaceChildren();
state.selectedInvoicePaymentMethod = '';
if (!hasActivePayment) {
clearInvoicePaymentKeys(invoice.id);
clearOnlinePaymentState();
result.replaceChildren();
}
panel.hidden = !hasActivePayment;
return;
}
@ -1545,7 +1573,6 @@ function hydrateInvoiceDetail(payload, expectedInvoiceId = document.body.dataset
}
const previousInvoice = state.selectedInvoice;
const wasAwaitingOnlinePayment = state.onlinePaymentPending;
const previousActivePayment = state.activePayment;
applySession(payload);
if (state.selectedInvoice
&& String(state.selectedInvoice.id) !== String(payload.invoice.id)) {
@ -1559,8 +1586,9 @@ function hydrateInvoiceDetail(payload, expectedInvoiceId = document.body.dataset
&& typeof payload.active_payment === 'object'
&& !Array.isArray(payload.active_payment)
? payload.active_payment : null;
if (previousActivePayment && !state.activePayment) {
if (!state.activePayment) {
clearOnlinePaymentState(true);
clearInvoicePaymentKeys(payload.invoice.id);
byId('invoice-payment-result')?.replaceChildren();
}
if (onlinePaymentHasExpired()) expireOnlinePaymentInstructions();
@ -1568,10 +1596,7 @@ function hydrateInvoiceDetail(payload, expectedInvoiceId = document.body.dataset
.toLowerCase() === 'pending'
&& state.activePayment?.payment
&& typeof state.activePayment.payment === 'object';
const restoredProviderPayment = hasPendingInvoicePaymentKey(payload.invoice.id);
state.onlinePaymentPending = Boolean(serverPendingPayment)
|| (invoiceCanPay(payload.invoice)
&& (state.onlinePaymentPending || restoredProviderPayment));
state.onlinePaymentPending = Boolean(serverPendingPayment);
if (state.onlinePaymentPending) {
state.onlinePaymentInvoiceId = String(payload.invoice.id);
if (state.onlinePaymentExpiresAt <= 0) {

@ -1,2 +1,2 @@
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
{assign var=venix_asset_version value='2026110118' scope='global'}
{assign var=venix_asset_version value='2026110119' scope='global'}

@ -24,6 +24,9 @@ $pageController = file_get_contents($root . '/app/Controllers/CloudPageControlle
$apiController = file_get_contents($root . '/app/Controllers/CloudApiController.php');
$apiMiddleware = file_get_contents($root . '/app/Middleware/CloudApi.php');
$invoiceService = file_get_contents($root . '/app/Services/Cloud/CloudInvoiceService.php');
$invoicePaymentService = file_get_contents(
$root . '/app/Services/Cloud/CloudInvoicePaymentService.php'
);
$invoicePageService = file_get_contents($root . '/app/Services/Cloud/CloudInvoicePageService.php');
$invoiceDetailPageService = file_get_contents(
$root . '/app/Services/Cloud/CloudInvoiceDetailPageService.php'
@ -126,7 +129,7 @@ $assert(str_contains($invoiceDetailTemplate, 'id="invoice-payment-title"')
'state.activePayment = payload.active_payment')
&& str_contains($invoiceDetailRuntime,
'renderActiveInvoicePayment(activePayment, result);'),
'Invoice detail must restore durable payment attempts without a new submit action.');
'Invoice detail must restore durable payment attempts while retaining payment choices.');
$assert(str_contains($pageController,
"\$invoice['renews_expires_at'] ?? \$invoice['due_at'] ?? null")
&& str_contains($invoiceDetailRuntime,
@ -216,8 +219,17 @@ $assert(substr_count($invoiceDetailPageService, '->sharedLock()') >= 4
&& substr_count($invoiceDetailPageService,
"->where('user_id', \$userId)") >= 3
&& str_contains($invoiceDetailPageService,
'return CloudInvoiceService::status($invoice);'),
"'invoice' => \$status")
&& str_contains($invoiceDetailPageService,
"'active_payment' => \$activePayment"),
'Full and lightweight invoice reads must use a consistent owner-scoped snapshot.');
$assert(str_contains($invoiceDetailPageService,
"->orderByDesc('updated_at')->orderByDesc('id')")
&& str_contains($invoiceDetailPageService,
"->where('request_idempotency_key',")
&& str_contains($invoiceDetailPageService,
'(string) $payment->idempotency_key'),
'The latest payment projection can merge an older unknown job into a newer order.');
$statusService = $section($invoiceService, 'public static function status(',
'public static function display(');
$assert(str_contains($statusService, "'fulfillment' =>")
@ -233,6 +245,11 @@ $pollMethod = $section($invoiceDetailRuntime, 'async function pollInvoiceStatus(
$assert(str_contains($pollMethod,
'api(`/api/v1/invoices/${encodeURIComponent(state.pollInvoiceId)}/status`')
&& substr_count($pollMethod, 'api(') === 1
&& str_contains($pollMethod,
"Object.prototype.hasOwnProperty.call(result || {}, 'active_payment')")
&& str_contains($pollMethod,
'state.activePayment = result.active_payment')
&& str_contains($pollMethod, 'clearOnlinePaymentState(true);')
&& str_contains($pollMethod, 'entersProvisioningAfterPayment(')
&& str_contains($pollMethod, 'resetProvisioningPollWindow();')
&& !str_contains($pollMethod, 'refreshInvoiceDetail('),
@ -244,6 +261,7 @@ $provisionFinished = $section($invoiceDetailRuntime, 'function provisionFinished
$assert(str_contains($needsPolling, 'state.onlinePaymentPending')
&& str_contains($needsPolling, '!onlinePaymentHasExpired()')
&& str_contains($needsPolling, 'invoiceCanPay(invoice)')
&& str_contains($needsPolling, "['creating', 'pending', 'review'].includes(")
&& str_contains($needsPolling, 'return false;')
&& !str_contains($needsPolling, 'provisionFinished(invoice)')
&& str_contains($provisionFinished,
@ -258,8 +276,12 @@ $onlinePaymentRender = $section($invoiceDetailRuntime,
'function renderOnlinePayment(', 'async function payInvoiceBalance(');
$detailHydration = $section($invoiceDetailRuntime,
'function hydrateInvoiceDetail(', 'async function refreshInvoiceDetail(');
$assert(str_contains($invoiceDetailRuntime, 'function hasPendingInvoicePaymentKey(')
&& str_contains($invoiceDetailRuntime, 'hasPendingInvoicePaymentKey(payload.invoice.id)')
$assert(!str_contains($invoiceDetailRuntime, 'function hasPendingInvoicePaymentKey(')
&& str_contains($detailHydration, 'if (!state.activePayment)')
&& str_contains($detailHydration,
'clearInvoicePaymentKeys(payload.invoice.id);')
&& str_contains($detailHydration,
'state.onlinePaymentPending = Boolean(serverPendingPayment);')
&& str_contains($invoiceDetailRuntime, 'resumeInvoicePolling();')
&& str_contains($paymentExpiry, 'STATUS_POLL_MAX_LIFETIME_MS')
&& str_contains($paymentExpiry, 'invoicePaymentDeadlineTimestamp(invoice)')
@ -379,23 +401,48 @@ $assert(!str_contains($providerPayment, 'confirm(')
&& $providerBusySet < $providerButtonsDisabled
&& $providerButtonsDisabled < $providerIdempotency
&& $providerIdempotency < $providerRequest
&& str_contains($providerPayment, 'const observer = observeTask(result, {')
&& str_contains($providerPayment, 'await observer.done;')
&& str_contains($providerPayment,
'state.appliedReadSequence = ++state.readSequence;')
&& str_contains($providerPayment, "status: 'pending'")
&& str_contains($providerPayment, 'state.mutationBusy = false;'),
'Provider payment must execute immediately while retaining idempotency and duplicate-submit protection.');
'Provider payment must keep controls fenced until durable creation is terminal and reject stale reads.');
$assert(str_contains($onlinePaymentRender, 'container.replaceChildren(box);'),
'Rendered provider instructions must replace stale task-status notices.');
$paymentChoices = $section($invoiceDetailRuntime,
'function renderInvoicePaymentMethods(', 'function invoiceProgressText(');
$activePaymentRender = strpos($paymentChoices,
'renderActiveInvoicePayment(activePayment, result);');
$choicesStart = strpos($paymentChoices, 'const choices = [];');
$assert(str_contains($invoiceDetailRuntime, 'balancePaymentAllowed: false')
&& str_contains($invoiceDetailRuntime,
'state.balancePaymentAllowed = payload?.balance_payment_allowed === true')
&& str_contains($paymentChoices, 'if (state.balancePaymentAllowed)')
&& str_contains($paymentChoices, 'if (!choices.length)')
&& str_contains($paymentChoices,
'state.selectedInvoicePaymentMethod = String(choices[0].id);'),
'state.selectedInvoicePaymentMethod = String(choices[0].id);')
&& $activePaymentRender !== false
&& $choicesStart !== false
&& $activePaymentRender < $choicesStart,
'Restricted accounts must not be offered a balance-payment control.');
$assert(!str_contains($invoiceDetailRuntime, "from '/cloud/runtime.js'")
&& !str_contains($invoiceDetailRuntime, 'from "/cloud/runtime.js"')
&& !str_contains($invoiceDetailRuntime, "import('/cloud/runtime.js')")
&& !str_contains($invoiceDetailRuntime, 'import("/cloud/runtime.js")'),
'The dedicated invoice runtime must not import the all-feature VM runtime.');
$enqueuePayment = $section($invoicePaymentService,
'public static function enqueue(', 'private static function paymentPurpose(');
$savePaymentAttempt = $section($invoicePaymentService,
'private static function saveAttempt(',
'public static function markProviderOrdersTerminal(');
$assert(str_contains($enqueuePayment,
"->where('request_fingerprint', \$fingerprint)")
&& str_contains($enqueuePayment, "->where('provider', \$method)")
&& str_contains($savePaymentAttempt, "->where('provider', \$provider)")
&& !str_contains($savePaymentAttempt,
'该账单已有支付订单或结果不明的尝试'),
'An unfinished order must not block switching to a different provider.');
$assert(!str_contains($legacyRuntime, 'function loadInvoiceDetail(')
&& !str_contains($legacyRuntime, 'function renderInvoiceDetail(')
&& !str_contains($legacyRuntime, 'INVOICE_PAYMENT_STORAGE_PREFIX'),

@ -18,6 +18,14 @@ namespace App\Services\Cloud {
{
return str_repeat('i', 32);
}
public static function encrypt(array $payload, string $purpose): string
{
return json_encode([
'purpose' => $purpose,
'payload' => $payload,
], JSON_THROW_ON_ERROR);
}
}
}
@ -30,6 +38,14 @@ namespace App\Services\Payment {
return true;
}
}
final class YipayConfig
{
public static function visibleMethods($user = null): array
{
return ['alipay'];
}
}
}
namespace {
@ -319,16 +335,95 @@ namespace {
'snapshot_json' => '{}',
'created_at' => $now,
]);
$paytaroJob = CloudInvoicePaymentService::enqueue(
$second,
User::find(1),
[
'method' => 'paytaro',
'idempotency_key' => 'invoice-switch-paytaro-0001',
],
'192.0.2.20',
'invoice-switch-test'
);
$yipayJob = CloudInvoicePaymentService::enqueue(
$second,
User::find(1),
[
'method' => 'yipay_alipay',
'idempotency_key' => 'invoice-switch-yipay-0002',
],
'192.0.2.20',
'invoice-switch-test'
);
$sameProviderJob = CloudInvoicePaymentService::enqueue(
$second,
User::find(1),
[
'method' => 'paytaro',
'idempotency_key' => 'invoice-switch-paytaro-0003',
],
'192.0.2.20',
'invoice-switch-test'
);
$sameRequestJob = CloudInvoicePaymentService::enqueue(
$second,
User::find(1),
[
'method' => 'paytaro',
'idempotency_key' => 'invoice-switch-paytaro-0001',
],
'192.0.2.20',
'invoice-switch-test'
);
$assert((int) $paytaroJob->id !== (int) $yipayJob->id
&& (int) $sameProviderJob->id === (int) $paytaroJob->id
&& (int) $sameRequestJob->id === (int) $paytaroJob->id
&& CloudJob::where('invoice_id', (int) $second->id)
->where('kind', 'payment_create')->count() === 2,
'An unfinished provider task blocked switching or duplicated one provider.');
CloudJob::whereIn('id', [(int) $paytaroJob->id, (int) $yipayJob->id])
->update([
'phase' => 'terminal',
'outcome' => 'succeeded',
'status' => 'succeeded',
'terminal_at' => $now,
'effect_may_have_applied' => 0,
'safe_to_resubmit' => 0,
'effect_resolution' => 'applied',
'effect_resolved_at' => $now,
'updated_at' => $now,
]);
$payment = new CloudInvoicePayment(); $payment->invoice_id = $second->id; $payment->user_id = 1;
$payment->provider = 'paytaro'; $payment->provider_order_no = 'PT-GATEWAY';
$payment->idempotency_key = 'invoice-gateway-test-0001'; $payment->amount = '12.50';
$payment->status = 'pending'; $payment->created_at = $payment->updated_at = $now; $payment->save();
CloudInvoicePaymentService::recordAttempt([
'invoice_id' => (int) $second->id,
'idempotency_key' => 'invoice-gateway-switch-0002',
'provider' => 'yipay_alipay',
], 'YIPAY-GATEWAY-LATE', '12.50', 1, $now + 1);
$alternatePayment = CloudInvoicePayment::where('user_id', 1)
->where('idempotency_key', 'invoice-gateway-switch-0002')->first();
$assert($alternatePayment !== null
&& (string) $alternatePayment->status === 'creating',
'An unpaid provider attempt blocked switching to another provider.');
$alternatePayment->status = 'pending';
$alternatePayment->save();
$user = User::find(1); $user->money = '50.00'; $user->save();
$outcome = CloudInvoiceService::settleCreditedPayment($payment);
$assert($outcome === 'paid_invoice' && User::find(1)->money === '37.50'
&& $second->fresh()->status === 'paid' && CloudRenewal::count() === 2
&& (int) $instance->fresh()->expires_at === $currentExpiry + 30 * 86400,
'Provider credit was not consumed exactly once to settle the invoice.');
$user = User::find(1); $user->money = '50.00'; $user->save();
$alternateOutcome = CloudInvoiceService::settleCreditedPayment(
$alternatePayment->fresh()
);
$assert($alternateOutcome === 'credited_balance'
&& User::find(1)->money === '50.00'
&& $second->fresh()->status === 'paid'
&& CloudRenewal::count() === 2,
'A later provider payment was not retained as account balance.');
$firstDisplayAfterLaterRenewal = CloudInvoiceService::display($paid->fresh());
$assert(($firstDisplayAfterLaterRenewal['renewal_result']['new_expires_at']
?? null) === (int) $firstRenewal->new_expires_at

@ -88,6 +88,7 @@ $schema->create('cloud_jobs', static function (Blueprint $table): void {
$table->integer('instance_id')->nullable();
$table->integer('user_id');
$table->string('kind');
$table->string('request_idempotency_key')->nullable();
$table->string('phase');
$table->string('outcome')->nullable();
$table->integer('attempts')->default(0);
@ -153,6 +154,7 @@ Capsule::table('cloud_jobs')->insert([
'instance_id' => null,
'user_id' => 1,
'kind' => 'payment_create',
'request_idempotency_key' => 'stripe-resume-key-0001',
'phase' => 'accepted',
'outcome' => null,
'attempts' => 1,
@ -168,10 +170,10 @@ $creating = CloudInvoiceDetailPageService::forUser(21, 1, $user);
$assert(($creating['active_payment']['status'] ?? null) === 'creating'
&& ($creating['active_payment']['task_id'] ?? null) === '31'
&& ($creating['active_payment']['payment'] ?? null) === null
&& ($creating['active_payment']['can_submit'] ?? true) === false
&& ($creating['active_payment']['can_submit'] ?? false) === true
&& $creating['payment_methods'] === []
&& $creating['balance_payment_allowed'] === false,
'A durable payment-create task without a provider row was not restored.');
&& $creating['balance_payment_allowed'] === true,
'A durable payment-create task blocked a new payment choice.');
Capsule::table('cloud_jobs')->where('id', 31)->update([
'phase' => 'terminal',
@ -212,8 +214,31 @@ $assert(($pending['active_payment']['status'] ?? null) === 'pending'
'idempotency_key',
$pending['active_payment']['payment'] ?? []
)
&& $pending['payment_methods'] === [],
'A pending provider payment was not safely restored across sessions.');
&& ($pending['active_payment']['can_submit'] ?? false) === true
&& $pending['payment_methods'] === []
&& $pending['balance_payment_allowed'] === true,
'A pending provider payment blocked a new payment choice.');
$pendingStatus = CloudInvoiceDetailPageService::statusForUser(21, 1);
$assert(($pendingStatus['invoice']['id'] ?? null) === '21'
&& ($pendingStatus['active_payment']['status'] ?? null) === 'pending'
&& ($pendingStatus['active_payment']['payment']['payment_value'] ?? null)
=== 'https://checkout.stripe.test/resume-safe',
'Lightweight invoice polling omitted the active provider payment.');
Capsule::table('cloud_invoice_payments')->where('id', 41)->update([
'status' => 'expired',
'updated_at' => $now + 1,
]);
$expiredStatus = CloudInvoiceDetailPageService::statusForUser(21, 1);
$assert(($expiredStatus['invoice']['payable'] ?? false) === true
&& array_key_exists('active_payment', $expiredStatus)
&& $expiredStatus['active_payment'] === null,
'A terminal provider order remained projected as an active payment lock.');
Capsule::table('cloud_invoice_payments')->where('id', 41)->update([
'status' => 'pending',
'updated_at' => $now,
]);
Capsule::table('cloud_invoices')->where('id', 21)->update([
'due_at' => $now - 1,
@ -224,6 +249,9 @@ $assert(($pastDeadline['invoice']['payable'] ?? true) === false
&& ($pastDeadline['active_payment']['payment']['payment_value'] ?? null)
=== 'https://checkout.stripe.test/resume-safe',
'Crossing the invoice deadline hid an already-created provider payment.');
Capsule::table('cloud_invoices')->where('id', 21)->update([
'due_at' => $now + 3600,
]);
Capsule::table('stripe_orders')->where('id', 51)->update(['user_id' => 2]);
$foreignProviderOrder = CloudInvoiceDetailPageService::forUser(21, 1, $user);
@ -246,9 +274,35 @@ $unknown = CloudInvoiceDetailPageService::forUser(21, 1, $user);
$assert(($unknown['active_payment']['status'] ?? null) === 'review'
&& ($unknown['active_payment']['task_id'] ?? null) === '31'
&& ($unknown['active_payment']['payment'] ?? null) === null
&& ($unknown['active_payment']['can_submit'] ?? true) === false
&& $unknown['payment_methods'] === [],
'An unknown payment-creation effect exposed retry or provider instructions.');
&& ($unknown['active_payment']['can_submit'] ?? false) === true
&& $unknown['payment_methods'] === []
&& $unknown['balance_payment_allowed'] === true,
'An unknown payment-creation effect blocked a distinct payment choice.');
Capsule::table('cloud_invoice_payments')->insert([
'id' => 42,
'invoice_id' => 21,
'user_id' => 1,
'provider' => 'stripe_alipay',
'provider_order_no' => 'stripe-resume-order-2',
'idempotency_key' => 'stripe-resume-key-0002',
'amount' => '10.00',
'status' => 'pending',
'created_at' => $now + 2,
'updated_at' => $now + 2,
]);
Capsule::table('stripe_orders')->insert([
'id' => 52,
'order_no' => 'stripe-resume-order-2',
'user_id' => 1,
'checkout_url' => 'https://checkout.stripe.test/resume-new',
]);
$latest = CloudInvoiceDetailPageService::forUser(21, 1, $user);
$assert(($latest['active_payment']['status'] ?? null) === 'pending'
&& ($latest['active_payment']['payment']['payment_value'] ?? null)
=== 'https://checkout.stripe.test/resume-new'
&& ($latest['active_payment']['can_submit'] ?? false) === true,
'An older unknown task was merged into a newer provider payment.');
$foreignRejected = false;
try {

@ -0,0 +1,231 @@
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { existsSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { join, normalize } from 'node:path';
import { fileURLToPath } from 'node:url';
const require = createRequire(import.meta.url);
let chromium;
try {
({ chromium } = require('playwright'));
} catch {
console.log('Cloud invoice payment runtime browser checks skipped: Playwright is unavailable.');
process.exit(0);
}
const browserExecutable = [
process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE,
chromium.executablePath(),
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
'/usr/bin/google-chrome',
'/usr/bin/chromium',
].find(path => path && existsSync(path));
if (!browserExecutable) {
console.log('Cloud invoice payment runtime browser checks skipped: Chromium is unavailable.');
process.exit(0);
}
const publicRoot = fileURLToPath(new URL('../public/', import.meta.url))
.replace(/\/+$/, '');
const runtimePath = join(publicRoot, 'cloud/invoice-detail-runtime.js');
const runtimeSource = await readFile(runtimePath, 'utf8');
const ids = [...runtimeSource.matchAll(/byId\('([^']+)'\)/g)]
.map(match => match[1])
.filter((id, index, all) => all.indexOf(id) === index);
const html = `<!doctype html><html><body data-invoice-id="21">${ids.map(id => {
if (['invoice-payment-submit', 'invoice-detail-refresh'].includes(id)) {
return `<button id="${id}" type="button"></button>`;
}
return `<div id="${id}"></div>`;
}).join('')}</body></html>`;
const server = createServer(async (request, response) => {
const url = new URL(request.url || '/', 'http://127.0.0.1');
if (url.pathname === '/') {
response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
response.end(html);
return;
}
if (!url.pathname.startsWith('/cloud/')) {
response.writeHead(404).end();
return;
}
const path = normalize(join(publicRoot, url.pathname));
if (!path.startsWith(`${publicRoot}/`)) {
response.writeHead(403).end();
return;
}
try {
response.writeHead(200, {
'Content-Type': 'application/javascript; charset=utf-8',
'Cache-Control': 'no-store',
});
response.end(await readFile(path));
} catch {
response.writeHead(404).end();
}
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('Test server failed.');
const browser = await chromium.launch({
headless: true,
executablePath: browserExecutable,
});
try {
const page = await browser.newPage();
await page.goto(`http://127.0.0.1:${address.port}/`);
await page.evaluate(() => {
const jsonResponse = (status, payload) => new Response(
JSON.stringify(payload),
{ status, headers: { 'Content-Type': 'application/json' } },
);
window.__resolveOldStatus = null;
window.fetch = async input => {
const path = new URL(String(input), location.href).pathname;
if (path === '/api/v1/invoices/21/status') {
return new Promise(resolve => {
window.__resolveOldStatus = payload => resolve(jsonResponse(200, payload));
});
}
if (path === '/api/v1/invoices/21/payments') {
return jsonResponse(202, {
task_id: '99',
status_url: '/api/v1/tasks/99',
});
}
if (path === '/api/v1/tasks/99') {
return jsonResponse(200, {
id: '99',
completed: true,
status: 'succeeded',
result: { payment: window.__newPayment },
});
}
throw new Error(`Unexpected fetch: ${path}`);
};
});
const now = Math.floor(Date.now() / 1000);
const invoice = {
id: '21',
purpose: 'renewal',
title: '实例续费',
status: 'open',
display_status: 'open',
payable: true,
amount: '10.00',
currency: 'USD',
created_at: now - 60,
due_at: now + 86400,
renews_expires_at: now + 86400,
validity_days: 30,
traffic_quota_bytes: 0,
items: [],
};
const oldPayment = {
invoice_id: '21',
method: 'stripe_card',
status: 'pending',
payment_kind: 'payurl',
payment_value: 'https://checkout.stripe.test/old',
label: 'Stripe Card',
expires_at: now + 900,
};
const newPayment = {
invoice_id: '21',
method: 'usdt',
status: 'pending',
payment_kind: 'usdt',
actual_amount: '1.500001',
receive_address: 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
label: 'USDT',
expires_at: now + 900,
};
const base = {
csrf_token: 'a'.repeat(64),
user_id: '1',
username: 'runtime-test',
balance: '0.00',
balance_payment_allowed: false,
payment_methods: [
{ id: 'stripe_card', name: 'Stripe Card' },
{ id: 'usdt', name: 'USDT' },
],
};
await page.evaluate(async ({ base, invoice, oldPayment, newPayment }) => {
window.__newPayment = newPayment;
window.__invoiceRuntime = await import(
`/cloud/invoice-detail-runtime.js?behavior=${Date.now()}`
);
window.__invoicePayload = {
...base,
invoice,
active_payment: {
status: 'pending',
task_id: null,
payment: oldPayment,
can_submit: true,
},
};
window.__invoiceRuntime.hydrateInvoiceDetail(window.__invoicePayload, '21');
}, { base, invoice, oldPayment, newPayment });
assert.equal(await page.locator('.invoice-payment-method-card').count(), 2);
assert.equal(await page.locator('#invoice-payment-submit').isEnabled(), true);
assert.equal(await page.locator('a[href="https://checkout.stripe.test/old"]').count(), 1);
await page.waitForFunction(() => typeof window.__resolveOldStatus === 'function',
null, { timeout: 5000 });
await page.locator('.invoice-payment-method-card[data-method-id="usdt"]').click();
await page.locator('#invoice-payment-submit').click();
await page.waitForFunction(() => document.querySelector(
'.cloud-payment-instructions strong'
)?.textContent?.includes('USDT'), null, { timeout: 5000 });
await page.evaluate(oldStatus => {
window.__resolveOldStatus(oldStatus);
}, {
invoice,
active_payment: {
status: 'pending',
task_id: null,
payment: oldPayment,
can_submit: true,
},
});
await page.waitForTimeout(50);
assert.match(
await page.locator('.cloud-payment-instructions strong').textContent(),
/USDT/,
'A late status response replaced the newer provider order.',
);
assert.equal(await page.locator('a[href="https://checkout.stripe.test/old"]').count(), 0);
await page.evaluate(({ base, invoice }) => {
sessionStorage.setItem('virt-cloud:invoice-payment:1:21:stripe_card',
'stripe-runtime-stale-key-0001');
sessionStorage.setItem('virt-cloud:invoice-payment:1:21:usdt',
'usdt-runtime-stale-key-0002');
window.__invoiceRuntime.stopInvoicePoll();
window.__invoiceRuntime.hydrateInvoiceDetail({
...base,
invoice,
active_payment: null,
}, '21');
}, { base, invoice });
assert.equal(await page.locator('.cloud-payment-instructions').count(), 0);
assert.equal(await page.locator('.invoice-payment-method-card').count(), 2);
assert.equal(await page.locator('#invoice-payment-submit').isEnabled(), true);
assert.equal(await page.evaluate(() => [...Array(sessionStorage.length).keys()]
.map(index => sessionStorage.key(index))
.filter(key => key?.startsWith('virt-cloud:invoice-payment:1:21:')).length), 0);
} finally {
await browser.close();
await new Promise(resolve => server.close(resolve));
}
console.log('Cloud invoice payment runtime browser behavior checks passed.');

@ -64,22 +64,28 @@ $assert(($view['amount_display'] ?? null) === '$12.51',
'Invoice presentation recomputed the authoritative total from line items.');
$resumePayload = $payload;
$resumePayload['invoice']['payable'] = false;
$resumePayload['invoice']['payable'] = true;
$resumePayload['balance_payment_allowed'] = true;
$resumePayload['balance'] = '20.00';
$resumePayload['payment_methods'] = [[
'id' => 'stripe_card',
'name' => 'Stripe · 银行卡',
]];
$resumePayload['active_payment'] = [
'status' => 'review',
'task_id' => '91',
'payment' => null,
'can_submit' => false,
'can_submit' => true,
];
$resumeView = $invoke($controller, 'invoiceDetailView', [$resumePayload]);
$assert(($resumeView['show_payment'] ?? false) === true
&& ($resumeView['payment_title'] ?? null) === '当前支付状态'
&& ($resumeView['payment_title'] ?? null) === '选择支付方式'
&& str_contains(
(string) ($resumeView['active_payment_message'] ?? ''),
'请勿再次提交'
'可选择其他支付方式'
)
&& ($resumeView['payment_methods'] ?? null) === [],
'Invoice first paint exposed retry instead of an active-payment fence.');
&& count($resumeView['payment_methods'] ?? []) === 2,
'Invoice first paint did not allow switching from an unfinished payment.');
$gracePayload = $payload;
$gracePayload['invoice']['status'] = 'overdue';

@ -2769,6 +2769,8 @@ namespace {
$missingPaymentKey = 'payment-missing-0001';
$pendingPaymentKey = 'payment-pending-0001';
$unknownPaymentKey = 'payment-unknown-0001';
$expiredPaymentKey = 'payment-expired-0001';
$failedPaymentKey = 'payment-failed-0001';
Capsule::table('cloud_invoice_payments')->insert([
[
'invoice_id' => 502, 'user_id' => 1, 'provider' => 'paytaro',
@ -2784,12 +2786,30 @@ namespace {
'amount' => 10, 'status' => 'creation_unknown',
'created_at' => $now - 30, 'updated_at' => $now - 30,
],
[
'invoice_id' => 504, 'user_id' => 1, 'provider' => 'usdt',
'provider_order_no' => 'provider-expired-0001',
'idempotency_key' => $expiredPaymentKey,
'amount' => 10, 'status' => 'expired',
'created_at' => $now - 30, 'updated_at' => $now - 30,
],
[
'invoice_id' => 505, 'user_id' => 1,
'provider' => 'stripe_card',
'provider_order_no' => 'provider-failed-0001',
'idempotency_key' => $failedPaymentKey,
'amount' => 10, 'status' => 'failed',
'created_at' => $now - 30, 'updated_at' => $now - 30,
],
]);
$missingPaymentJobId = $insertPaymentJob($missingPaymentKey, 501);
$pendingPaymentJobId = $insertPaymentJob($pendingPaymentKey, 502);
$unknownPaymentJobId = $insertPaymentJob($unknownPaymentKey, 503);
$expiredPaymentJobId = $insertPaymentJob($expiredPaymentKey, 504);
$failedPaymentJobId = $insertPaymentJob($failedPaymentKey, 505);
foreach ([$missingPaymentJobId, $pendingPaymentJobId,
$unknownPaymentJobId] as $paymentJobId) {
$unknownPaymentJobId, $expiredPaymentJobId,
$failedPaymentJobId] as $paymentJobId) {
$assert(CloudWorkerService::expireDueTasksForOwner(
1, $paymentJobId, 1
) === 1, 'A due local payment task was not terminalized.');
@ -2797,6 +2817,8 @@ namespace {
$missingPaymentJob = CloudJob::find($missingPaymentJobId);
$pendingPaymentJob = CloudJob::find($pendingPaymentJobId);
$unknownPaymentJob = CloudJob::find($unknownPaymentJobId);
$expiredPaymentJob = CloudJob::find($expiredPaymentJobId);
$failedPaymentJob = CloudJob::find($failedPaymentJobId);
$pendingPaymentResult = json_decode(
(string) $pendingPaymentJob->result_json, true,
flags: JSON_THROW_ON_ERROR
@ -2816,7 +2838,13 @@ namespace {
&& (bool) $unknownPaymentJob->effect_may_have_applied
&& !(bool) $unknownPaymentJob->safe_to_resubmit
&& $unknownPaymentJob->error_code === 'payment_creation_unknown'
&& Capsule::table('cloud_invoice_payments')->count() === 2,
&& $expiredPaymentJob->phase === 'terminal'
&& $expiredPaymentJob->outcome === 'succeeded'
&& $expiredPaymentJob->effect_resolution === 'applied'
&& $failedPaymentJob->phase === 'terminal'
&& $failedPaymentJob->outcome === 'succeeded'
&& $failedPaymentJob->effect_resolution === 'applied'
&& Capsule::table('cloud_invoice_payments')->count() === 4,
'Payment deadline fallback retried a provider POST or misclassified its durable attempt.');
$nullDispatchOperation = md5('null-dispatch-deadline-fixture');

@ -278,6 +278,22 @@ Capsule::table('cloud_invoice_payments')->insert([
'amount' => '2.00', 'status' => 'pending',
'created_at' => time(), 'updated_at' => time(),
]);
$expiredJobAt = time();
Capsule::table('cloud_jobs')->insert([
'kind' => 'payment_create',
'execution_mode' => 'local',
'invoice_id' => 998,
'user_id' => (int) $user->id,
'request_idempotency_key' => 'stripe-invoice-expired-0001',
'phase' => 'terminal',
'outcome' => 'failed',
'effect_may_have_applied' => 1,
'effect_resolution' => 'unknown',
'effect_resolved_at' => null,
'effect_resolved_by' => null,
'effect_resolution_reason' => '',
'updated_at' => $expiredJobAt,
]);
$expiredEvent = [
'id' => 'evt_expired123456', 'object' => 'event',
'type' => 'checkout.session.expired', 'livemode' => true,
@ -299,8 +315,17 @@ if ((string) Capsule::table('stripe_orders')
->where('id', $expiring->id)->value('status') !== 'expired'
|| (string) Capsule::table('cloud_invoice_payments')
->where('provider_order_no', $expiring->order_no)
->value('status') !== 'expired') {
failStripePaymentTest('Stripe expired session did not become terminal.');
->value('status') !== 'expired'
|| (string) Capsule::table('cloud_jobs')
->where('request_idempotency_key', 'stripe-invoice-expired-0001')
->value('effect_resolution') !== 'applied'
|| (string) Capsule::table('cloud_jobs')
->where('request_idempotency_key', 'stripe-invoice-expired-0001')
->value('effect_resolution_reason')
!== '渠道终态证明原支付订单已创建') {
failStripePaymentTest(
'Stripe expired session did not release payment and unknown creation locks.'
);
}
$invoiceOrder = $service->createOrder($user, '3.00', 'card', '127.0.0.1',
@ -332,8 +357,12 @@ $service->processWebhook($invoiceBody,
stripeSignature($invoiceBody, $webhookSecret, time()));
if ((string) Capsule::table('cloud_invoice_payments')
->where('provider_order_no', $invoiceOrder->order_no)
->value('status') !== 'credited_balance') {
failStripePaymentTest('Stripe Webhook did not invoke invoice settlement.');
->value('status') !== 'credited_balance'
|| (string) User::find($user->id)->money !== '15.34'
|| Capsule::table('code')->where('type', 10007)->count() !== 2) {
failStripePaymentTest(
'Stripe excess payment was not retained exactly once in account balance.'
);
}
$actor = new class { public function isAdmin() { return false; } };

@ -3,6 +3,7 @@
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\User;
use App\Models\UsdtPaymentOrder;
use App\Services\Payment\TronAddress;
use App\Services\Payment\UsdtConfig;
use App\Services\Payment\UsdtPaymentService;
@ -364,6 +365,36 @@ Capsule::table('cloud_jobs')->insert([
'created_at' => $paymentJobNow - 120,
'updated_at' => $paymentJobNow - 1,
]);
Capsule::table('cloud_invoice_payments')->where('id', $invoiceAttempt->id)
->update(['status' => 'pending', 'updated_at' => time()]);
Capsule::table('usdt_payment_orders')->where('id', $invoiceOrder->id)->update([
'status' => 'pending',
'expires_at' => time() - 1,
'updated_at' => time(),
]);
$emptyClient = new class {
public function transfersTo($address, $minimum, $maximum) { return []; }
};
$expiryScanner = new class($emptyClient) extends UsdtScannerService {
private $fakeClient;
public function __construct($fakeClient) { $this->fakeClient = $fakeClient; }
protected function client(array $settings) { return $this->fakeClient; }
};
$expiryStats = $expiryScanner->run();
if ((int) $expiryStats['expired'] < 1
|| (string) Capsule::table('usdt_payment_orders')
->where('id', $invoiceOrder->id)->value('status') !== 'expired'
|| (string) Capsule::table('cloud_invoice_payments')
->where('id', $invoiceAttempt->id)->value('status') !== 'expired'
|| (string) Capsule::table('cloud_jobs')
->where('request_idempotency_key', 'usdt-invoice-payment-0001')
->value('effect_resolution') !== 'applied'
|| (string) Capsule::table('cloud_jobs')
->where('request_idempotency_key', 'usdt-invoice-payment-0001')
->value('effect_resolution_reason')
!== '渠道终态证明原支付订单已创建') {
failUsdtTest('Expired USDT invoice order did not release its payment attempt.');
}
$providerOrderCountBeforeInvoiceSettlement = Capsule::table('usdt_payment_orders')->count();
// The scanner bridge must retain a provider credit if its linked business
// invoice disappeared after the payment order was created.
@ -407,7 +438,7 @@ if ((int) $invoiceStats['credited'] !== 1
|| (int) $resolvedPaymentJob->effect_resolved_at < $paymentJobNow
|| $resolvedPaymentJob->effect_resolved_by !== null
|| (string) $resolvedPaymentJob->effect_resolution_reason
!== '经签名支付回调确认原订单已由渠道接受'
!== '渠道终态证明原支付订单已创建'
|| (int) $resolvedPaymentJob->finalization_incident !== 0
|| Capsule::table('cloud_jobs')->count() !== 1
|| Capsule::table('usdt_payment_orders')->count()
@ -415,10 +446,93 @@ if ((int) $invoiceStats['credited'] !== 1
failUsdtTest('Native USDT invoice settlement bridge failed.');
}
$bulkExpiredAt = time();
$bulkRows = [];
for ($index = 1; $index <= 251; $index++) {
$orderNo = sprintf('USDT-BULK-%04d', $index);
$bulkRows[] = [
'order_no' => $orderNo,
'business_type' => 'recharge',
'business_order_no' => $orderNo,
'paylist_id' => null,
'user_id' => 1,
'wallet_id' => 1,
'amount' => '1.00',
'exchange_rate' => '7.0000',
'actual_amount' => '1.000000',
'amount_atomic' => 9000000 + $index,
'currency' => 'CNY',
'token' => 'USDT',
'network' => 'tron',
'contract_address' => UsdtConfig::CONTRACT_ADDRESS,
'receive_address' => $walletAddress,
'status' => 'pending',
'txid' => null,
'block_number' => 0,
'block_timestamp' => 0,
'expires_at' => $bulkExpiredAt - 1,
'paid_at' => 0,
'created_at' => $bulkExpiredAt - 120,
'updated_at' => $bulkExpiredAt - 120,
'error_message' => '',
];
}
foreach (array_chunk($bulkRows, 100) as $chunk) {
Capsule::table('usdt_payment_orders')->insert($chunk);
}
$bulkService = new UsdtPaymentService();
$bulkExpired = $bulkService->expirePendingOrders($bulkExpiredAt);
if ($bulkExpired !== 251
|| Capsule::table('usdt_payment_orders')
->where('order_no', 'like', 'USDT-BULK-%')
->where('status', '<>', 'expired')->exists()) {
failUsdtTest('USDT expiration did not converge across bounded batches.');
}
$singleOrderNo = 'USDT-SINGLE-EXPIRED';
Capsule::table('usdt_payment_orders')->insert([
'order_no' => $singleOrderNo,
'business_type' => 'recharge',
'business_order_no' => $singleOrderNo,
'paylist_id' => null,
'user_id' => 1,
'wallet_id' => 1,
'amount' => '1.00',
'exchange_rate' => '7.0000',
'actual_amount' => '1.000000',
'amount_atomic' => 9999999,
'currency' => 'CNY',
'token' => 'USDT',
'network' => 'tron',
'contract_address' => UsdtConfig::CONTRACT_ADDRESS,
'receive_address' => $walletAddress,
'status' => 'pending',
'txid' => null,
'block_number' => 0,
'block_timestamp' => 0,
'expires_at' => $bulkExpiredAt - 1,
'paid_at' => 0,
'created_at' => $bulkExpiredAt - 120,
'updated_at' => $bulkExpiredAt - 120,
'error_message' => '',
]);
$singleExpired = $bulkService->expire(
UsdtPaymentOrder::where('order_no', $singleOrderNo)->firstOrFail()
);
if ((string) $singleExpired->status !== 'expired') {
failUsdtTest('The first USDT status read did not return the terminal order.');
}
$controllerSource = file_get_contents(dirname(__DIR__) . '/app/Controllers/UsdtController.php');
$serviceSource = file_get_contents(
dirname(__DIR__) . '/app/Services/Payment/UsdtPaymentService.php'
);
if ($controllerSource === false
|| $serviceSource === false
|| strpos($controllerSource, "->whereNotExists(function (\$query)") === false
|| strpos($controllerSource, "cloud_invoice_payments.provider_order_no") === false) {
|| strpos($controllerSource, "cloud_invoice_payments.provider_order_no") === false
|| strpos($controllerSource,
'$order = (new UsdtPaymentService())->expire($order);') === false
|| strpos($serviceSource, "->limit(250)->lockForUpdate()") === false) {
failUsdtTest('Native USDT invoice orders are exposed by the recharge status endpoint.');
}

Loading…
Cancel
Save