fix(payment): quote Paytaro charges in CNY

go
codex 8 hours ago
parent c911264d71
commit 8fc0057ae0

@ -155,6 +155,8 @@ class PaytaroController extends AdminController
'paytaro_method_uuid' => strtolower($methodUuid),
'paytaro_min_amount' => $minimum,
'paytaro_max_amount' => $maximum,
'paytaro_quote_minutes' => (string) max(5, min(1440, (int) ($payload['paytaro_quote_minutes']
?? $current['paytaro_quote_minutes']))),
'paytaro_request_timeout_seconds' => (string) max(3, min(60, (int) ($payload['paytaro_request_timeout_seconds'] ?? 15))),
];
}

@ -547,6 +547,22 @@ final class CloudInvoicePaymentService
return $status;
}
/** Confirm the provider order exists, while leaving the invoice payable. */
public static function recordProviderReview(string $provider, string $orderNo, int $now): void
{
$payment = CloudInvoicePayment::where('provider', $provider)
->where('provider_order_no', $orderNo)->lockForUpdate()->first();
if ($payment === null || in_array((string) $payment->status, ['paid_invoice', 'credited_balance'], true)) {
return;
}
if (in_array((string) $payment->status, ['creating', 'creation_unknown', 'not_created'], true)) {
$payment->status = 'pending';
$payment->updated_at = $now;
$payment->save();
}
self::resolveUnknownCreationFromProviderEvidence($payment, '渠道已收款,支付报价待核对', $now);
}
/** A signed provider callback is authoritative proof that creation applied. */
private static function resolveUnknownCreationFromProviderEvidence(
CloudInvoicePayment $payment,

@ -19,6 +19,7 @@ class PaytaroConfig
'paytaro_method_uuid' => '',
'paytaro_min_amount' => '1.00',
'paytaro_max_amount' => '10000.00',
'paytaro_quote_minutes' => '30',
'paytaro_request_timeout_seconds' => '15',
];
@ -50,6 +51,7 @@ class PaytaroConfig
$values['paytaro_test_mode'] = self::truthy($values['paytaro_test_mode']);
$values['paytaro_min_amount'] = PaymentAmount::normalize($values['paytaro_min_amount']);
$values['paytaro_max_amount'] = PaymentAmount::normalize($values['paytaro_max_amount']);
$values['paytaro_quote_minutes'] = max(5, min(1440, (int) $values['paytaro_quote_minutes']));
$values['paytaro_request_timeout_seconds'] = max(3, min(60, (int) $values['paytaro_request_timeout_seconds']));
return $values;
}

@ -21,13 +21,15 @@ class PaytaroPaymentService
$amount = $this->validateAmount($rawAmount, $settings);
$orderNo = $this->orderNo();
$now = time();
$quote = PaymentCheckoutQuotes::prepare('paytaro', $amount, $now,
$now + (int) $settings['paytaro_quote_minutes'] * 60);
if (PaytaroOrder::where('user_id', (int) $user->id)->where('created_at', '>=', $now - 60)->count() >= 5) {
throw new \RuntimeException('Paytaro 下单过于频繁,请稍后重试');
}
$connection = (new PaytaroOrder())->getConnection();
$connection->transaction(function () use (
$user, $amount, $orderNo, $now, $businessContext
$user, $amount, $orderNo, $now, $businessContext, $quote
) {
$lockedUser = User::where('id', (int) $user->id)->lockForUpdate()->first();
if ($lockedUser === null) {
@ -53,6 +55,7 @@ class PaytaroPaymentService
$order->created_at = $now;
$order->updated_at = $now;
$order->save();
PaymentCheckoutQuotes::persist($quote, $orderNo, (int) $user->id);
CloudInvoicePaymentService::recordAttempt(
$businessContext, $orderNo, $amount, (int) $user->id, $now
@ -67,7 +70,7 @@ class PaytaroPaymentService
'notify_url' => $baseUrl . '/paytaro/callback',
'return_url' => rtrim((string) $returnBaseUrl, '/') . '/paytaro/return',
'name' => 'Account balance recharge',
'money' => $amount,
'money' => PaymentCheckoutQuotes::formatUnits('CNY', $quote->expected_units),
];
try {
$gateway = $this->gatewayClient($settings)->createOrder($payload);
@ -113,17 +116,17 @@ class PaytaroPaymentService
$now = time();
$credited = false;
$duplicate = false;
$review = false;
$asset = isset($payload['pid']) ? strtoupper(trim((string) ($payload['currency'] ?? 'CNY'))) : 'MGATE';
$connection = (new PaytaroOrder())->getConnection();
$connection->transaction(function () use ($notification, $orderNo, $tradeNo, $eventKey, $now, &$credited, &$duplicate) {
$connection->transaction(function () use (
$notification, $orderNo, $tradeNo, $eventKey, $now, $asset, &$credited, &$duplicate, &$review
) {
$order = PaytaroOrder::where('order_no', $orderNo)->lockForUpdate()->first();
if ($order === null) {
throw new \RuntimeException('Paytaro 本地订单不存在');
}
if ($notification['amount_cents'] !== null
&& PaytaroProtocol::amountToCents($order->amount) !== (string) $notification['amount_cents']) {
throw new \RuntimeException('Paytaro 回调金额不匹配');
}
if ((string) $order->gateway_trade_no !== '' && (string) $order->gateway_trade_no !== $tradeNo) {
throw new \RuntimeException('Paytaro 平台订单号不匹配');
}
@ -133,13 +136,19 @@ class PaytaroPaymentService
$existing = PaytaroCallbackEvent::where('event_key', $eventKey)->first();
if ($existing !== null) {
if ((string) $order->status !== 'paid' || (int) $existing->processed_at <= 0) {
if ((int) $existing->processed_at <= 0) {
throw new \RuntimeException('Paytaro 重复回调事件状态异常');
}
$review = PaymentCheckoutQuotes::find('paytaro', $orderNo)?->status === 'review';
$duplicate = true;
return;
}
if ((string) $order->status === 'paid') {
$received = PaymentCheckoutQuotes::find('paytaro', $orderNo)?->received_units
?? (int) PaytaroProtocol::amountToCents($order->amount);
if ($received !== (int) $notification['amount_cents']) {
throw new \RuntimeException('Paytaro 已支付金额与回调不一致');
}
$duplicate = true;
return;
}
@ -162,11 +171,28 @@ class PaytaroPaymentService
$event->processed_at = 0;
$event->save();
$quote = PaymentCheckoutQuotes::receive('paytaro', $orderNo, (int) $order->user_id,
(string) $order->amount, (int) PaytaroProtocol::amountToCents($order->amount),
(int) $notification['amount_cents'], $tradeNo, $now, null, $asset);
if ($quote->status === 'review') {
$review = true;
$order->gateway_trade_no = $tradeNo;
$order->status = 'pending';
$order->payment_value = null;
$order->error_message = '收款凭证已保存,需人工核对';
$order->updated_at = $now;
$order->save();
$event->processed_at = $now;
$event->save();
CloudInvoicePaymentService::recordProviderReview('paytaro', $orderNo, $now);
return;
}
$paylist = Paylist::where('id', (int) $order->paylist_id)->lockForUpdate()->first();
if ($paylist === null || (string) $paylist->tradeno !== $orderNo || (int) $paylist->userid !== (int) $order->user_id) {
throw new \RuntimeException('Paytaro 关联充值订单无效');
}
$credited = RechargeCreditService::creditLocked($paylist, self::LEDGER_TYPE, true);
$credited = RechargeCreditService::creditLocked($paylist, self::LEDGER_TYPE, true, $quote);
if (CloudInvoicePayment::where('provider', 'paytaro')
->where('provider_order_no', $orderNo)->exists()) {
CloudInvoicePaymentService::settleForProvider('paytaro', $orderNo);
@ -182,7 +208,7 @@ class PaytaroPaymentService
$event->save();
}, 3);
return ['credited' => $credited, 'duplicate' => $duplicate, 'order_no' => $orderNo];
return ['credited' => $credited, 'duplicate' => $duplicate, 'review' => $review, 'order_no' => $orderNo];
}
public function returnOrderNo(array $payload)
@ -208,6 +234,10 @@ class PaytaroPaymentService
$connection = (new PaytaroOrder())->getConnection();
$connection->transaction(function () use ($orderNo, $tradeNo, $kind, $value, &$order) {
$order = PaytaroOrder::where('order_no', $orderNo)->lockForUpdate()->first();
if ($order !== null && (string) $order->gateway_trade_no === $tradeNo
&& PaymentCheckoutQuotes::find('paytaro', $orderNo)?->receipt_ref !== null) {
return; // The signed receipt arrived before the create response.
}
if ($order === null || (string) $order->status !== 'creating') {
throw new \RuntimeException('Paytaro 本地订单状态无效');
}

@ -1,6 +1,7 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
require __DIR__ . '/Support/PaymentCheckoutFixture.php';
$System_Config = ['baseUrl' => 'https://panel.example.com'];
@ -11,6 +12,8 @@ use App\Services\Payment\PaytaroPaymentService;
use App\Services\Payment\PaytaroProtocol;
use App\Services\Payment\PaytaroSigner;
use App\Services\Payment\PaymentOrderCreationException;
use App\Services\Payment\PaymentCheckoutQuotes;
use App\Services\Payment\PaymentRateService;
use App\Models\Code;
use App\Models\User;
use GuzzleHttp\Client;
@ -184,9 +187,10 @@ $capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'defau
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->getConnection('default')->getSchemaBuilder();
createPaymentCheckoutFixture($schema);
$schema->create('configurations', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->nullable();
$table->string('name')->unique();
$table->text('value')->nullable();
});
$schema->create('user', function (Blueprint $table) {
@ -362,9 +366,13 @@ Capsule::table('cloud_invoices')->insert([
'user_id' => 1, 'plan_id' => 1, 'due_at' => time() + 1800,
'amount' => '43.00', 'status' => 'open'],
]);
PaymentRateService::override('USD/CNY', '7.20', time() + 3600, 9, 'Paytaro test quote');
$invoiceCreateGateway = new class {
public array $outbound = [];
public function createOrder(array $payload)
{
$this->outbound = $payload;
return [
'gateway_trade_no' => '202609270000000011',
'payment_kind' => 'payurl',
@ -386,6 +394,8 @@ $createdAttempt = Capsule::table('cloud_invoice_payments')
if ($createdAttempt === null
|| (string) $createdAttempt->status !== 'creating'
|| (string) $createdAttempt->provider !== 'paytaro'
|| ($invoiceCreateGateway->outbound['money'] ?? '') !== '302.40'
|| (float) $createdAttempt->amount !== 42.0
|| !Capsule::table('paylist')->where('tradeno', (string) $createdInvoiceOrder->order_no)->exists()) {
fwrite(STDERR, 'Paytaro invoice attempt was not recorded with the local order.' . PHP_EOL);
exit(1);
@ -450,20 +460,22 @@ $callback = [
'pid' => 'A1B2C3D4E5F',
'type' => 'alipay',
'out_trade_no' => $orderNo,
'money' => '100.00',
'money' => '727.20',
'trade_no' => '202608151234567890',
'trade_status' => 'TRADE_SUCCESS',
'sign_type' => 'MD5',
];
$callback['sign'] = PaytaroSigner::sign($callback, $secret);
$service = new PaytaroPaymentService();
$now = time();
PaymentCheckoutQuotes::persist(PaymentCheckoutQuotes::prepare('paytaro', '100.00', $now, $now + 1800), $orderNo, 1);
$first = $service->processCallback($callback);
$second = $service->processCallback($callback);
$displayCode = (string) Capsule::table('code')->where('type', PaytaroPaymentService::LEDGER_TYPE)->value('code');
if (!$first['credited'] || $first['duplicate'] || $second['credited'] || !$second['duplicate']
|| (float) Capsule::table('user')->where('id', 1)->value('money') !== 100.0
|| (float) Capsule::table('user')->where('id', 2)->value('aff_money') !== 10.0
|| (float) Capsule::table('user')->where('id', 1)->value('money') !== 101.0
|| (float) Capsule::table('user')->where('id', 2)->value('aff_money') !== 10.1
|| Capsule::table('code')->where('type', PaytaroPaymentService::LEDGER_TYPE)->count() !== 1
|| Capsule::table('payback')->count() !== 1
|| preg_match('/^[A-F0-9]{8}$/', $displayCode) !== 1
@ -558,11 +570,13 @@ Capsule::table('cloud_jobs')->insert([
'updated_at' => $paymentJobNow - 1,
]);
$providerOrderCountBeforeInvoiceCallback = Capsule::table('paytaro_orders')->count();
$now = time();
PaymentCheckoutQuotes::persist(PaymentCheckoutQuotes::prepare('paytaro', '25.00', $now, $now + 1800), $invoiceOrderNo, 1);
$invoiceCallback = [
'pid' => 'A1B2C3D4E5F',
'type' => 'alipay',
'out_trade_no' => $invoiceOrderNo,
'money' => '25.00',
'money' => '180.00',
'trade_no' => '202609271234567891',
'trade_status' => 'TRADE_SUCCESS',
'sign_type' => 'MD5',
@ -576,7 +590,7 @@ if (!$invoiceResult['credited']
->where('provider_order_no', $invoiceOrderNo)->value('status') !== 'credited_balance'
|| (string) Capsule::table('paytaro_orders')->where('order_no', $invoiceOrderNo)
->value('status') !== 'paid'
|| (float) Capsule::table('user')->where('id', 1)->value('money') !== 125.0
|| (float) Capsule::table('user')->where('id', 1)->value('money') !== 126.0
|| $resolvedPaymentJob === null
|| (string) $resolvedPaymentJob->phase !== 'terminal'
|| (string) $resolvedPaymentJob->outcome !== 'failed'
@ -594,6 +608,19 @@ if (!$invoiceResult['credited']
exit(1);
}
$underpaid = $callback;
$underpaid['out_trade_no'] = (string) $createdInvoiceOrder->order_no;
$underpaid['trade_no'] = '202609270000000011';
$underpaid['money'] = '42.00';
$underpaid['sign'] = PaytaroSigner::sign($underpaid, $secret);
$review = $service->processCallback($underpaid);
if (!$review['review'] || $review['credited']
|| !$service->processCallback($underpaid)['duplicate']
|| PaymentCheckoutQuotes::find('paytaro', (string) $createdInvoiceOrder->order_no)?->review_reason !== 'amount_mismatch'
|| (float) User::find(1)->money !== 126.0) {
throw new RuntimeException('A Paytaro underpayment was credited or its evidence was not preserved.');
}
$smartyDirectory = sys_get_temp_dir() . '/sspanel-paytaro-smarty';
if (!is_dir($smartyDirectory) && !mkdir($smartyDirectory, 0700, true) && !is_dir($smartyDirectory)) {
fwrite(STDERR, 'Could not create the Paytaro Smarty test directory.' . PHP_EOL);

Loading…
Cancel
Save