feat(payment): display charge and credit currencies

go
codex 7 hours ago
parent c6557c0cd1
commit 3c054cf5b3

@ -0,0 +1,98 @@
<?php
namespace App\Controllers\Admin;
use App\Controllers\AdminController;
use App\Services\Auth;
use App\Services\Payment\PaymentRateService;
use App\Services\Payment\PaymentReconciliation;
final class PaymentReconciliationController extends AdminController
{
public function index($request, $response, $args)
{
[$asset, $review] = $this->filters($request);
$totals = $rows = [];
$tableError = false;
$orders = null;
try {
$totals = PaymentReconciliation::totals();
if ($asset !== 'USD') {
$orders = PaymentReconciliation::quotedOrders($asset, $review)
->orderByDesc('received_at')->orderByDesc('order_no')->paginate(30);
$orders->setPath('/admin/payment-reconciliation');
$orders->appends(['asset' => $asset, 'review' => $review ? '1' : '0']);
$refunds = PaymentReconciliation::refundRecords($orders->pluck('order_no')->all());
foreach ($orders as $quote) {
$rows[] = PaymentReconciliation::record($quote, $refunds->get($quote->order_no));
}
}
} catch (\Illuminate\Database\QueryException) {
$tableError = true;
}
$rates = [];
foreach (['USD/CNY', 'USDT/USD'] as $pair) {
$rate = PaymentRateService::status($pair);
$times = [
'source_at' => $rate['source_at'], 'fetched_at' => $rate['fetched_at'],
'valid_until' => $rate['current']['valid_until'] ?? null, 'attempted_at' => $rate['attempted_at'],
];
foreach ($times as $key => $seconds) {
$rate[$key . '_display'] = $seconds === null ? '—' : gmdate('Y-m-d H:i:s', (int) $seconds);
}
$rates[$pair] = $rate;
}
$this->setViewTheme('venix');
return $this->view()
->assign('rates', $rates)->assign('totals', $totals)
->assign('asset', $asset)->assign('review', $review)
->assign('quote_rows', $rows)->assign('orders', $orders)
->assign('table_error', $tableError)
->assign('rate_saved', $request->getParam('rate_saved') === '1')
->display('admin/payment-reconciliation/index.tpl');
}
public function overrideRate($request, $response, $args)
{
$payload = $request->getParsedBody();
$payload = is_array($payload) ? $payload : [];
$minutes = filter_var($payload['minutes'] ?? null, FILTER_VALIDATE_INT, [
'options' => ['min_range' => 1, 'max_range' => 4320],
]);
try {
if ($minutes === false
|| !is_string($payload['pair'] ?? null)
|| !is_string($payload['rate'] ?? null) || !is_string($payload['reason'] ?? null)) {
throw new \InvalidArgumentException('请填写有效的币对、汇率、有效分钟数和理由');
}
PaymentRateService::override($payload['pair'], trim($payload['rate']),
time() + $minutes * 60, (int) Auth::getUser()->id, $payload['reason']);
} catch (\InvalidArgumentException $error) {
return $response->withJson(['ret' => 0, 'message' => $error->getMessage()], 422);
}
return $response->withRedirect('/admin/payment-reconciliation?rate_saved=1', 303);
}
public function export($request, $response, $args)
{
[$asset, $review] = $this->filters($request);
$file = tmpfile();
if ($file === false) {
throw new \RuntimeException('无法创建对账导出');
}
PaymentReconciliation::csv($file, $asset, $review);
rewind($file);
return $response->withBody(new \Slim\Http\Stream($file))
->withHeader('Content-Type', 'text/csv; charset=utf-8')
->withHeader('Content-Disposition', 'attachment; filename="payments-' . $asset . '.csv"')
->withHeader('Cache-Control', 'no-store, private');
}
private function filters($request): array
{
$asset = $request->getParam('asset', 'CNY');
return [in_array($asset, PaymentReconciliation::ASSETS, true) ? $asset : 'CNY',
$request->getParam('review') === '1'];
}
}

@ -3,12 +3,15 @@
namespace App\Controllers\Admin;
use App\Controllers\AdminController;
use App\Models\CloudInvoicePayment;
use App\Models\PaymentCheckoutQuote;
use App\Models\YipayOrder;
use App\Models\YipayRefund;
use App\Services\AdminPermission;
use App\Services\AdminDataMasker;
use App\Services\Auth;
use App\Services\Payment\PaymentAmount;
use App\Services\Payment\PaymentReconciliation;
use App\Services\Payment\YipayClient;
use App\Services\Payment\YipayConfig;
use App\Services\Payment\YipayPaymentService;
@ -37,6 +40,7 @@ class YipayController extends AdminController
->leftJoin('user', 'user.id', '=', 'yipay_orders.user_id')
->select(
'yipay_orders.id',
'yipay_orders.order_no',
'yipay_orders.user_id',
'yipay_orders.payment_type',
'yipay_orders.amount',
@ -71,8 +75,20 @@ class YipayController extends AdminController
$orders = $query->orderBy('yipay_orders.id', 'desc')->paginate(30);
$orders->setPath('/admin/yipay');
$orders->appends(['keyword' => $keyword, 'status' => $status, 'payment_type' => $paymentType]);
$orderNos = $orders->pluck('order_no')->all();
$quotes = PaymentCheckoutQuote::whereIn('order_no', $orderNos)->get()->keyBy('order_no');
$refunds = PaymentReconciliation::refundRecords($orderNos);
$invoiceOrders = CloudInvoicePayment::whereIn('provider', ['yipay_alipay', 'yipay_wxpay'])
->whereIn('provider_order_no', $orderNos)->pluck('provider_order_no')->flip();
foreach ($orders as $order) {
$order->setAttribute('user_email', AdminDataMasker::email($order->user_email));
$quote = $quotes->get($order->order_no);
$refund = $refunds->get($order->order_no);
$order->setAttribute('reconciliation', $quote === null ? [] : PaymentReconciliation::record($quote, $refund));
$order->setAttribute('refund_state', $refund->status ?? '');
$order->setAttribute('can_refund', $order->status === 'paid' && $quote?->status === 'accepted'
&& !$invoiceOrders->has($order->order_no)
&& ($refund === null || $refund->status === 'gateway_accepted'));
}
$summary['total'] = YipayOrder::count();

@ -311,10 +311,14 @@ final class CloudApiController
if ($invoice === null) {
throw new CloudError('账单不存在', 404);
}
$job = CloudInvoicePaymentService::enqueue($invoice, $this->user($request),
CloudInput::object($request),
(string) $request->getServerParam('REMOTE_ADDR', ''),
(string) $request->getHeaderLine('User-Agent'));
try {
$job = CloudInvoicePaymentService::enqueue($invoice, $this->user($request),
CloudInput::object($request),
(string) $request->getServerParam('REMOTE_ADDR', ''),
(string) $request->getHeaderLine('User-Agent'));
} catch (\App\Services\Payment\PaymentRateUnavailable) {
return $this->json($response, ['ret' => 0, 'error_code' => 'rate_unavailable'], 422);
}
return $this->json($response, [
'task_id' => (string) $job->id,
'status_url' => '/api/v1/tasks/' . (int) $job->id,

@ -6,6 +6,8 @@ use App\Models\CloudInvoicePayment;
use App\Models\Configurations;
use App\Models\PaytaroOrder;
use App\Services\Auth;
use App\Services\Payment\PaymentCheckoutQuotes;
use App\Services\Payment\PaymentRateUnavailable;
use App\Services\Config;
use App\Services\Payment\PaytaroPaymentService;
@ -22,16 +24,22 @@ class PaytaroController extends BaseController
$request->getHeaderLine('User-Agent'),
$this->currentReturnBaseUrl($request)
);
return $this->json($response, [
$quote = PaymentCheckoutQuotes::checkout('paytaro', (string) $order->order_no, (int) $user->id);
if ($quote['checkout_state'] !== 'payable') {
return $this->json($response, ['code' => -1, 'error_code' => $quote['checkout_state']], 409);
}
return $this->json($response, $quote + [
'code' => 0,
'msg' => '订单创建成功',
'amount' => number_format((float) $order->amount, 2, '.', ''),
'order_no' => (string) $order->order_no,
'url' => (string) $order->payment_value,
'payment_kind' => (string) $order->payment_kind,
'payment_label' => '支付宝扫码支付',
'status_url' => '/user/paytaro/status',
'poll_interval' => 3000,
]);
} catch (PaymentRateUnavailable $exception) {
return $this->json($response, ['code' => -1, 'error_code' => 'rate_unavailable'], 422);
} catch (\InvalidArgumentException $exception) {
return $this->json($response, ['code' => -1, 'msg' => $exception->getMessage()], 422);
} catch (\Throwable $exception) {
@ -46,21 +54,32 @@ class PaytaroController extends BaseController
if (!$user->isLogin) {
return $this->json($response, ['ret' => 0, 'result' => 0, 'status' => 'not_found'], 404);
}
$orderNo = $request->getParam('order_no');
if ($orderNo !== null && (!is_string($orderNo) || !preg_match('/^[A-Za-z0-9_-]{1,64}$/D', $orderNo))) {
return $this->json($response, ['ret' => 0, 'result' => 0, 'status' => 'not_found'], 404);
}
$order = PaytaroOrder::where('user_id', (int) $user->id)
->whereNotExists(function ($query) {
$query->selectRaw('1')->from('cloud_invoice_payments')
->whereColumn('cloud_invoice_payments.provider_order_no', 'paytaro_orders.order_no')
->where('cloud_invoice_payments.provider', 'paytaro');
})
->when($orderNo !== null, static fn ($query) => $query->where('order_no', $orderNo))
->orderBy('id', 'desc')->first();
if ($order === null) {
return $this->json($response, ['ret' => 0, 'result' => 0, 'status' => 'not_found'], 404);
}
$quote = PaymentCheckoutQuotes::checkout('paytaro', (string) $order->order_no, (int) $user->id);
$status = (string) $order->status;
if (in_array($status, ['pending', 'expired', 'creation_unknown'], true)
&& in_array($quote['checkout_state'], ['review', 'expired'], true)) {
$status = $quote['checkout_state'];
}
return $this->json($response, [
'ret' => 1,
'result' => (string) $order->status === 'paid' ? 1 : 0,
'status' => (string) $order->status,
'balance' => (string) $order->status === 'paid'
'result' => $status === 'paid' ? 1 : 0,
'status' => $status,
'balance' => $status === 'paid'
? number_format((float) $user->newQuery()->where('id', (int) $user->id)->value('money'), 2, '.', '')
: null,
]);
@ -93,7 +112,7 @@ class PaytaroController extends BaseController
->where('provider', 'paytaro')->exists()) {
return $response->withRedirect('/user/cloud/invoices', 302);
}
return $response->withRedirect('/user/code?payment=paytaro', 302);
return $response->withRedirect('/user/code?payment=paytaro&order_no=' . rawurlencode($orderNo), 302);
} catch (\Throwable $exception) {
error_log('Paytaro return rejected: ' . $exception->getMessage());
return $this->plain($response, '支付返回信息无效', 400);

@ -4,6 +4,8 @@ namespace App\Controllers;
use App\Models\UsdtPaymentOrder;
use App\Services\Auth;
use App\Services\Payment\PaymentCheckoutQuotes;
use App\Services\Payment\PaymentRateUnavailable;
use App\Services\Payment\UsdtConfig;
use App\Services\Payment\UsdtPaymentService;
@ -18,10 +20,14 @@ class UsdtController extends BaseController
try {
$order = (new UsdtPaymentService())->createRechargeOrder($user, $request->getParam('price'));
return $this->json($response, [
$quote = PaymentCheckoutQuotes::checkout('usdt', (string) $order->order_no, (int) $user->id);
if ($quote['checkout_state'] !== 'payable') {
return $this->json($response, ['code' => -1, 'error_code' => $quote['checkout_state']], 409);
}
return $this->json($response, $quote + [
'code' => 0,
'msg' => '订单创建成功',
'amount' => number_format((float) $order->amount, 2, '.', ''),
'order_no' => (string) $order->order_no,
'actual_amount' => (string) $order->actual_amount,
'token' => 'USDT',
'network' => 'tron',
@ -32,6 +38,8 @@ class UsdtController extends BaseController
'status_url' => '/user/usdt/status',
'poll_interval' => 3000,
]);
} catch (PaymentRateUnavailable $exception) {
return $this->json($response, ['code' => -1, 'error_code' => 'rate_unavailable'], 422);
} catch (\InvalidArgumentException $exception) {
return $this->json($response, ['code' => -1, 'msg' => $exception->getMessage()], 422);
} catch (\Throwable $exception) {
@ -47,6 +55,10 @@ class UsdtController extends BaseController
return $this->json($response, ['ret' => 0, 'result' => 0, 'status' => 'not_found'], 404);
}
$orderNo = $request->getParam('order_no');
if ($orderNo !== null && (!is_string($orderNo) || !preg_match('/^[A-Za-z0-9_-]{1,64}$/D', $orderNo))) {
return $this->json($response, ['ret' => 0, 'result' => 0, 'status' => 'not_found'], 404);
}
$order = UsdtPaymentOrder::where('business_type', 'recharge')
->where('user_id', (int) $user->id)
->whereNotExists(function ($query) {
@ -54,6 +66,7 @@ class UsdtController extends BaseController
->whereColumn('cloud_invoice_payments.provider_order_no', 'usdt_payment_orders.order_no')
->where('cloud_invoice_payments.provider', 'usdt');
})
->when($orderNo !== null, static fn ($query) => $query->where('order_no', $orderNo))
->orderBy('id', 'desc')
->first();
if ($order === null) {
@ -61,11 +74,17 @@ class UsdtController extends BaseController
}
$order = (new UsdtPaymentService())->expire($order);
$quote = PaymentCheckoutQuotes::checkout('usdt', (string) $order->order_no, (int) $user->id);
$status = (string) $order->status;
if (in_array($status, ['pending', 'expired', 'creation_unknown'], true)
&& in_array($quote['checkout_state'], ['review', 'expired'], true)) {
$status = $quote['checkout_state'];
}
return $this->json($response, [
'ret' => 1,
'result' => (string) $order->status === 'paid' ? 1 : 0,
'status' => (string) $order->status,
'balance' => (string) $order->status === 'paid'
'result' => $status === 'paid' ? 1 : 0,
'status' => $status,
'balance' => $status === 'paid'
? number_format((float) $user->newQuery()->where('id', (int) $user->id)->value('money'), 2, '.', '')
: null,
]);

@ -6,6 +6,8 @@ use App\Models\CloudInvoicePayment;
use App\Models\Configurations;
use App\Models\YipayOrder;
use App\Services\Auth;
use App\Services\Payment\PaymentCheckoutQuotes;
use App\Services\Payment\PaymentRateUnavailable;
use App\Services\Config;
use App\Services\Payment\YipayPaymentService;
@ -23,16 +25,22 @@ class YipayController extends BaseController
$request->getHeaderLine('User-Agent'),
$this->currentReturnBaseUrl($request)
);
return $this->json($response, [
$quote = PaymentCheckoutQuotes::checkout('yipay_' . (string) $order->payment_type, (string) $order->order_no, (int) $user->id);
if ($quote['checkout_state'] !== 'payable') {
return $this->json($response, ['code' => -1, 'error_code' => $quote['checkout_state']], 409);
}
return $this->json($response, $quote + [
'code' => 0,
'msg' => '订单创建成功',
'amount' => number_format((float) $order->amount, 2, '.', ''),
'order_no' => (string) $order->order_no,
'url' => (string) $order->payment_value,
'payment_kind' => (string) $order->payment_kind,
'payment_label' => (string) $order->payment_type === 'wxpay' ? '微信扫码支付' : '支付宝扫码支付',
'status_url' => '/user/yipay/status',
'poll_interval' => 3000,
]);
} catch (PaymentRateUnavailable $exception) {
return $this->json($response, ['code' => -1, 'error_code' => 'rate_unavailable'], 422);
} catch (\InvalidArgumentException $exception) {
return $this->json($response, ['code' => -1, 'msg' => $exception->getMessage()], 422);
} catch (\Throwable $exception) {
@ -47,21 +55,32 @@ class YipayController extends BaseController
if (!$user->isLogin) {
return $this->json($response, ['ret' => 0, 'result' => 0, 'status' => 'not_found'], 404);
}
$orderNo = $request->getParam('order_no');
if ($orderNo !== null && (!is_string($orderNo) || !preg_match('/^[A-Za-z0-9_-]{1,64}$/D', $orderNo))) {
return $this->json($response, ['ret' => 0, 'result' => 0, 'status' => 'not_found'], 404);
}
$order = YipayOrder::where('user_id', (int) $user->id)
->whereNotExists(function ($query) {
$query->selectRaw('1')->from('cloud_invoice_payments')
->whereColumn('cloud_invoice_payments.provider_order_no', 'yipay_orders.order_no')
->whereIn('cloud_invoice_payments.provider', ['yipay_alipay', 'yipay_wxpay']);
})
->when($orderNo !== null, static fn ($query) => $query->where('order_no', $orderNo))
->orderBy('id', 'desc')->first();
if ($order === null) {
return $this->json($response, ['ret' => 0, 'result' => 0, 'status' => 'not_found'], 404);
}
$quote = PaymentCheckoutQuotes::checkout('yipay_' . (string) $order->payment_type, (string) $order->order_no, (int) $user->id);
$status = (string) $order->status;
if (in_array($status, ['pending', 'expired', 'creation_unknown'], true)
&& in_array($quote['checkout_state'], ['review', 'expired'], true)) {
$status = $quote['checkout_state'];
}
return $this->json($response, [
'ret' => 1,
'result' => (string) $order->status === 'paid' ? 1 : 0,
'status' => (string) $order->status,
'balance' => (string) $order->status === 'paid'
'result' => $status === 'paid' ? 1 : 0,
'status' => $status,
'balance' => $status === 'paid'
? number_format((float) $user->newQuery()->where('id', (int) $user->id)->value('money'), 2, '.', '')
: null,
]);
@ -95,7 +114,7 @@ class YipayController extends BaseController
->where('provider', 'yipay_' . (string) $order->payment_type)->exists()) {
return $response->withRedirect('/user/cloud/invoices', 302);
}
return $response->withRedirect('/user/code?payment=yipay', 302);
return $response->withRedirect('/user/code?payment=yipay&order_no=' . rawurlencode($orderNo), 302);
} catch (\Throwable $exception) {
error_log('Yipay return rejected: ' . $exception->getMessage());
return $this->plain($response, '支付结果验证失败', 400);

@ -109,6 +109,9 @@ final class CloudInvoiceDetailPageService
if ($status === 'pending' && $payment !== null) {
try {
$safePayment = CloudInvoicePaymentService::display($payment);
if (in_array($safePayment['checkout_state'] ?? '', ['review', 'expired'], true)) {
$status = $safePayment['checkout_state'];
}
} catch (CloudError) {
// A missing provider ledger is itself uncertain evidence.
// Keep the invoice fenced and expose no stale payment link.

@ -11,6 +11,8 @@ use App\Models\UsdtPaymentOrder;
use App\Models\User;
use App\Models\YipayOrder;
use App\Services\Config;
use App\Services\Payment\PaymentCheckoutQuotes;
use App\Services\Payment\PaymentRateUnavailable;
use App\Services\Payment\PaytaroConfig;
use App\Services\Payment\PaytaroPaymentService;
use App\Services\Payment\StripeConfig;
@ -131,6 +133,9 @@ final class CloudInvoicePaymentService
}
throw new CloudError('该支付方式已有未完成订单,请刷新后继续', 409);
}
if (!PaymentCheckoutQuotes::canQuote($method)) {
throw new PaymentRateUnavailable();
}
$job = new \App\Models\CloudJob();
$job->invoice_id = $locked->id;
$job->user_id = $user->id;
@ -604,7 +609,7 @@ final class CloudInvoicePaymentService
if ($order === null) {
throw new CloudError('在线支付订单不存在', 404);
}
return array_merge($result, ['payment_kind' => (string) $order->payment_kind,
return self::displayQuote($result, $order, ['payment_kind' => (string) $order->payment_kind,
'payment_value' => (string) $order->payment_value,
'label' => $provider === 'yipay_wxpay'
? '易支付 · 微信' : '易支付 · 支付宝']);
@ -615,7 +620,7 @@ final class CloudInvoicePaymentService
if ($order === null) {
throw new CloudError('在线支付订单不存在', 404);
}
return array_merge($result, ['payment_kind' => (string) $order->payment_kind,
return self::displayQuote($result, $order, ['payment_kind' => (string) $order->payment_kind,
'payment_value' => (string) $order->payment_value,
'label' => 'Paytaro · 支付宝']);
}
@ -629,6 +634,8 @@ final class CloudInvoicePaymentService
return array_merge($result, [
'payment_kind' => 'payurl',
'payment_value' => (string) $order->checkout_url,
'charge_amount' => CloudMoney::decimal(CloudMoney::cents((string) $payment->amount)),
'charge_currency' => 'USD',
'label' => $provider === 'stripe_alipay'
? 'Stripe · 支付宝' : 'Stripe · 银行卡',
]);
@ -638,9 +645,15 @@ final class CloudInvoicePaymentService
if ($order === null) {
throw new CloudError('USDT 支付订单不存在', 404);
}
return array_merge($result, ['payment_kind' => 'usdt', 'label' => 'USDT-TRC20',
return self::displayQuote($result, $order, ['payment_kind' => 'usdt', 'label' => 'USDT-TRC20',
'actual_amount' => (string) $order->actual_amount,
'receive_address' => (string) $order->receive_address,
'expires_at' => (int) $order->expires_at]);
'receive_address' => (string) $order->receive_address]);
}
private static function displayQuote(array $result,
YipayOrder|PaytaroOrder|UsdtPaymentOrder $order, array $instructions): array
{
$quote = PaymentCheckoutQuotes::checkout($result['method'], (string) $order->order_no, (int) $order->user_id);
return array_replace($result, $quote, $quote['checkout_state'] === 'payable' ? $instructions : []);
}
}

@ -429,8 +429,12 @@ final class CloudInvoicePresentation
'creating' => 'billing.payment.active.creating',
'pending' => 'billing.payment.active.pending',
'review' => 'billing.payment.active.review',
'expired' => 'billing.payment.expired.body',
default => '',
};
if ($status === 'review' && ($activePayment['payment']['checkout_state'] ?? '') === 'review') {
$message = 'billing.payment.fx_review';
}
return [
$message,
$status === 'review'

@ -14,7 +14,7 @@ final class PaymentCheckoutQuotes
$pair = self::pair($provider);
$rate = PaymentRateService::current($pair, $now);
if ($rate === null) {
throw new \InvalidArgumentException('当前支付汇率不可用,请选择其他付款方式');
throw new PaymentRateUnavailable();
}
$acceptUntil ??= $payUntil;
if ($payUntil <= $now || $acceptUntil < $payUntil) {
@ -65,6 +65,35 @@ final class PaymentCheckoutQuotes
return ($lock ? $query->lockForUpdate() : $query)->first();
}
/** Share amounts and deadlines only from the owner-scoped durable quote. */
public static function checkout(string $provider, string $orderNo, int $userId,
?int $now = null): array
{
$quote = self::find($provider, $orderNo);
if ($quote === null || $quote->user_id !== $userId || $quote->quote_version !== 1) {
return ['checkout_state' => 'review'];
}
$state = match (true) {
$quote->status === 'review' => 'review',
$quote->status === 'accepted' => 'accepted',
$quote->pay_until <= ($now ?? time()) => 'expired',
default => 'payable',
};
return [
'checkout_state' => $state,
'amount' => CloudMoney::decimal($quote->usd_cents),
'charge_amount' => self::formatUnits($quote->asset, $quote->expected_units),
'charge_currency' => $quote->asset,
'expires_at' => $quote->pay_until,
];
}
public static function canQuote(string $provider): bool
{
return str_starts_with($provider, 'stripe_')
|| PaymentRateService::current(self::pair($provider)) !== null;
}
/** Caller holds the provider order and has authenticated the payment evidence. */
public static function receive(string $provider, string $orderNo, int $userId, string $usd,
int $legacyExpectedUnits, int $receivedUnits, string $receipt, int $now,

@ -83,6 +83,7 @@ final class PaymentRateService
}
return [
'current' => $current,
'feed' => self::FEEDS[$pair][0],
'source_at' => $automatic['source_at'] ?? null,
'fetched_at' => $automatic['fetched_at'] ?? null,
'attempted_at' => $state['attempted_at'] ?? null,

@ -0,0 +1,13 @@
<?php
namespace App\Services\Payment;
final class PaymentRateUnavailable extends \InvalidArgumentException
{
public const MESSAGE = '当前支付汇率不可用,请选择其他付款方式';
public function __construct()
{
parent::__construct(self::MESSAGE);
}
}

@ -0,0 +1,91 @@
<?php
namespace App\Services\Payment;
use App\Models\PaymentCheckoutQuote;
use App\Models\StripeOrder;
use App\Models\YipayRefund;
use App\Services\Cloud\CloudMoney;
use Brick\Math\BigDecimal;
final class PaymentReconciliation
{
public const ASSETS = ['CNY', 'USDT', 'USD'];
public static function totals(): array
{
$rows = PaymentCheckoutQuote::query()->select('asset')
->selectRaw("SUM(CASE WHEN status = 'accepted' THEN received_units ELSE 0 END) AS received")
->selectRaw("SUM(CASE WHEN status = 'accepted' THEN credit_cents ELSE 0 END) AS credited")
->selectRaw("SUM(CASE WHEN status = 'review' THEN 1 ELSE 0 END) AS needs_review")
->groupBy('asset')->get()->keyBy('asset');
$stripe = (string) StripeOrder::where('status', 'paid')->sum('amount');
$totals = [];
foreach (['CNY' => 2, 'USDT' => 6] as $asset => $scale) {
$row = $rows->get($asset);
$totals[$asset] = [
'received' => (string) BigDecimal::ofUnscaledValue((string) ($row->received ?? 0), $scale),
'credited' => (string) BigDecimal::ofUnscaledValue((string) ($row->credited ?? 0), 2),
'review' => (int) ($row->needs_review ?? 0),
];
}
$usd = (string) BigDecimal::of($stripe)->toScale(2);
$totals['USD'] = ['received' => $usd, 'credited' => $usd, 'review' => 0];
return $totals;
}
public static function quotedOrders(string $asset, bool $review)
{
return PaymentCheckoutQuote::where('asset', $asset)
->when($review, static fn ($query) => $query->where('status', 'review'));
}
public static function record(PaymentCheckoutQuote $quote, ?YipayRefund $refund = null): array
{
// An unverified reported currency must never be counted as CNY or USDT.
$received = $quote->received_units !== null && $quote->review_reason !== 'currency_mismatch'
? PaymentCheckoutQuotes::formatUnits($quote->asset, $quote->received_units) : '';
return [
'order' => $quote->order_no,
'provider' => $quote->provider,
'asset' => $quote->asset,
'status' => $quote->status,
'reason' => $quote->review_reason ?? '',
'usd_amount' => $quote->quote_version === 1 ? CloudMoney::decimal($quote->usd_cents) : '',
'quoted' => $quote->quote_version === 1
? PaymentCheckoutQuotes::formatUnits($quote->asset, $quote->expected_units) : '',
'received' => $received,
'credited' => $quote->credit_cents === null ? '' : CloudMoney::decimal($quote->credit_cents),
'refund_status' => $refund->status ?? '',
'refund_cny' => $refund->gateway_amount ?? '',
'refund_usd' => $refund->amount ?? '',
'time' => $quote->received_at ?? $quote->quoted_at,
];
}
public static function refundRecords(array $orders)
{
return YipayRefund::whereIn('order_no', $orders)->get()->keyBy('order_no');
}
public static function csv($stream, string $asset, bool $review): void
{
fputcsv($stream, ['order', 'provider', 'asset', 'status', 'reason', 'usd_amount', 'quoted',
'received', 'credited', 'refund_status', 'refund_cny', 'refund_usd', 'timestamp_utc'], escape: '');
if ($asset === 'USD') {
if (!$review) {
foreach (StripeOrder::where('status', 'paid')->orderBy('id')->lazyById(500) as $order) {
fputcsv($stream, [$order->order_no, 'stripe_' . $order->payment_method, 'USD', 'paid', '',
$order->amount, $order->amount, $order->amount, $order->amount, '', '', '', $order->paid_at], escape: '');
}
}
return;
}
self::quotedOrders($asset, $review)->chunkById(500, static function ($rows) use ($stream): void {
$refunds = self::refundRecords($rows->pluck('order_no')->all());
foreach ($rows as $quote) {
fputcsv($stream, self::record($quote, $refunds->get($quote->order_no)), escape: '');
}
}, 'order_no');
}
}

@ -286,6 +286,9 @@ $app->group('/admin', function () {
$this->get('/stripe', 'App\Controllers\Admin\StripeController:index');
$this->post('/stripe/config', 'App\Controllers\Admin\StripeController:save')->add(new SuperAdmin());
$this->post('/stripe/test', 'App\Controllers\Admin\StripeController:test')->add(new SuperAdmin());
$this->get('/payment-reconciliation', 'App\Controllers\Admin\PaymentReconciliationController:index');
$this->get('/payment-reconciliation/export', 'App\Controllers\Admin\PaymentReconciliationController:export')->add(new SuperAdmin());
$this->post('/payment-reconciliation/rate', 'App\Controllers\Admin\PaymentReconciliationController:overrideRate')->add(new SuperAdmin());
// User Mange
$this->get('/user', 'App\Controllers\Admin\UserController:index');

@ -167,6 +167,7 @@ async function api(path, options = {}) {
? t('billing.error.invalid_input')
: t('billing.error.request', { status: response.status }));
error.status = response.status;
error.code = payload?.error_code;
throw error;
}
return payload;
@ -728,6 +729,13 @@ function resumeInvoicePolling() {
}
function renderOnlinePayment(container, payment) {
if (payment.checkout_state && payment.checkout_state !== 'payable') {
clearOnlinePaymentState();
const key = payment.checkout_state === 'expired' ? 'billing.payment.expired.body'
: payment.checkout_state === 'review' ? 'billing.payment.fx_review' : 'billing.payment.status_reconciling';
container.replaceChildren(makeElement('p', 'invoice-payment-note', t(key)));
return;
}
clearOnlinePaymentExpiryTimer();
const generation = ++state.paymentRenderGeneration;
let box = container.querySelector('.cloud-payment-instructions');
@ -744,7 +752,7 @@ function renderOnlinePayment(container, payment) {
const paymentExpiresAt = serviceTimestamp(payment.expires_at);
state.onlinePaymentExpiresAt = paymentExpiresAt === null
? onlinePaymentFallbackExpiresAt(state.selectedInvoice)
: Math.min(paymentExpiresAt, Date.now() + STATUS_POLL_MAX_LIFETIME_MS);
: paymentExpiresAt;
let qrValue = '';
if (payment.payment_kind === 'usdt') {
@ -789,6 +797,16 @@ function renderOnlinePayment(container, payment) {
}
box.append(makeElement('small', '', t('billing.payment.poll_notice')));
}
if (payment.charge_currency && payment.charge_currency !== 'USD') {
box.prepend(makeElement('small', '', t('billing.payment.quote', {
usd: payment.amount, amount: payment.charge_amount, currency: payment.charge_currency,
})));
}
if (paymentExpiresAt !== null) {
box.append(makeElement('small', '', t('billing.payment.quote_deadline', {
time: browserTime(payment.expires_at),
})));
}
void appendPaymentQr(box, qrValue, generation);
scheduleOnlinePaymentExpiry(generation);
if (generation === state.paymentRenderGeneration && state.onlinePaymentPending) {
@ -931,9 +949,10 @@ async function createInvoicePayment(invoice, method, container, paymentResult) {
&& !creationStillInProgress) {
clearInvoicePaymentKey(invoice.id, method.id);
}
toast(error.code === 'INVALID_TASK_RECEIPT'
? t('billing.payment.receipt_invalid')
: t('billing.error.request', { status: status || 0 }), 'error');
const message = error.code === 'INVALID_TASK_RECEIPT' ? t('billing.payment.receipt_invalid')
: error.code === 'rate_unavailable' ? t('billing.payment.rate_unavailable')
: t('billing.error.request', { status: status || 0 });
toast(message, 'error');
if ([403, 409].includes(status)) {
await refreshInvoiceDetail(invoice.id);
}

@ -3,8 +3,10 @@
var payTimer = null;
var payStatusUrl = "";
var payOrderNo = "";
var payStatusInterval = 3000;
var payDeadline = 0;
var payExpiryTimer = null;
var payStatusRequest = null;
var payStatusInFlight = false;
var payPollSerial = 0;
@ -13,6 +15,8 @@
var payDialog = document.getElementById("vuPayDialog");
var payTitle = document.getElementById("vuPayTitle");
var payInfo = document.getElementById("vuPayInfo");
var payQuote = document.getElementById("vuPayQuote");
var payExpiry = document.getElementById("vuPayExpiry");
var payOpen = document.getElementById("vuPayOpen");
var payOpenLabel = document.getElementById("vuPayOpenLabel");
var qrcodeBox = document.getElementById("qrcode");
@ -96,6 +100,7 @@
if (!response.ok) {
var requestError = new Error("request_failed");
requestError.status = response.status;
requestError.code = data.error_code;
throw requestError;
}
return data;
@ -295,11 +300,14 @@
var url = new URL(window.location.href);
url.searchParams.delete("payment");
url.searchParams.delete("pid");
url.searchParams.delete("order_no");
window.history.replaceState(null, "", url.pathname + (url.search ? url.search : "") + url.hash);
}
function closePayDialog() {
stopPayPolling(true);
if (payExpiryTimer !== null) window.clearTimeout(payExpiryTimer);
payExpiryTimer = null;
if (!payDialog) return;
payDialog.classList.remove("is-open");
payDialog.setAttribute("aria-hidden", "true");
@ -316,10 +324,29 @@
return false;
}
if (payTitle) payTitle.textContent = isUsdt ? t("recharge.order.usdt_title") : (data.payment_label || t("recharge.order.qr_title"));
payInfo.textContent = isUsdt ? t("recharge.order.usdt_info") : t("recharge.order.qr_info", { amount: "$ " + data.amount });
var checkoutLinkEnabled = data.payment_type !== "paytaro" && (!isUsdt || (data.checkout_link_enabled === true && Boolean(data.url)));
var expiresAt = Number(data.expires_at) * 1000;
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) {
alertPay(t("recharge.payment.expired"), "error", t("recharge.payment.incomplete_title"));
return false;
}
payInfo.textContent = isUsdt ? t("recharge.order.usdt_info") : t("recharge.dialog.info");
if (payQuote) payQuote.textContent = t("recharge.order.quote", {
usd: data.amount, amount: data.charge_amount, currency: data.charge_currency
});
if (payExpiry) payExpiry.textContent = t("recharge.order.quote_deadline", {
time: window.VenixUserCopy.date(expiresAt, { hour12: false })
});
if (payExpiryTimer !== null) window.clearTimeout(payExpiryTimer);
payExpiryTimer = window.setTimeout(function () {
closePayDialog();
alertPay(t("recharge.payment.expired"), "error", t("recharge.payment.incomplete_title"));
}, expiresAt - Date.now());
var directUrl = data.payment_type === "paytaro"
? (isPaytaroMobileDevice() ? paytaroMobileUrl(data.url) : "")
: data.url;
var checkoutLinkEnabled = Boolean(directUrl) && (!isUsdt || data.checkout_link_enabled === true);
payOpen.hidden = !checkoutLinkEnabled;
if (checkoutLinkEnabled) payOpen.setAttribute("href", data.url);
if (checkoutLinkEnabled) payOpen.setAttribute("href", directUrl);
else payOpen.removeAttribute("href");
if (payOpenLabel) payOpenLabel.textContent = isUsdt ? t("recharge.order.open_cashier") : t("recharge.dialog.open_link");
if (chainDetails) chainDetails.hidden = !isUsdt;
@ -341,7 +368,7 @@
function checkPayStatus(statusUrl, signal) {
if (!statusUrl) return Promise.resolve();
return postForm(statusUrl, {}, signal).then(function (data) {
return postForm(statusUrl, payOrderNo ? { order_no: payOrderNo } : {}, signal).then(function (data) {
if (String(data.result) === "1") {
closePayDialog();
if (currentBalance && data.balance !== null && typeof data.balance !== "undefined") currentBalance.textContent = "$ " + data.balance;
@ -354,6 +381,9 @@
if (data.status === "expired" || data.status === "failed") {
closePayDialog();
alertPay(t(data.status === "expired" ? "recharge.payment.expired" : "recharge.payment.failed"), "error", t("recharge.payment.incomplete_title"));
} else if (data.status === "review") {
closePayDialog();
alertPay(t("recharge.payment.review"), "error", t("recharge.payment.incomplete_title"));
}
}).catch(function (error) {
if (error && error.name === "AbortError") return;
@ -370,6 +400,7 @@
payStatusInFlight = false;
if (clearConfiguration) {
payStatusUrl = "";
payOrderNo = "";
payDeadline = 0;
}
}
@ -395,12 +426,14 @@
});
}
function startPayPolling(statusUrl, interval) {
function startPayPolling(statusUrl, interval, orderNo, expiresAt) {
stopPayPolling(true);
payStatusUrl = String(statusUrl || "");
payOrderNo = String(orderNo || "");
if (!payStatusUrl) return;
payStatusInterval = Math.max(2000, Math.min(15000, Number(interval) || 3000));
payDeadline = Date.now() + 15 * 60 * 1000;
if (Number(expiresAt) > 0) payDeadline = Math.min(payDeadline, Number(expiresAt) * 1000);
schedulePayStatus(0);
}
@ -423,25 +456,14 @@
topWindow().location.href = data.url;
return;
}
if (definition.type === "paytaro" && isPaytaroMobileDevice()) {
startPayPolling(data.status_url || definition.statusUrl, data.poll_interval);
var mobileUrl = paytaroMobileUrl(data.url);
if (!mobileUrl) {
openPayDialog(data);
return;
}
topWindow().location.assign(mobileUrl);
return;
}
if (definition.type !== "usdt" && isMobileDevice()) {
topWindow().location.href = data.url;
return;
}
if (!openPayDialog(data)) return;
startPayPolling(data.status_url || definition.statusUrl, data.poll_interval);
}).catch(function () {
startPayPolling(data.status_url || definition.statusUrl, data.poll_interval, data.order_no, data.expires_at);
}).catch(function (error) {
qsa("[data-recharge-method]").forEach(function (button) { button.disabled = false; });
alertPay(t("recharge.request.failed"), "error", t("recharge.request.failed_title"));
var key = error.code === "rate_unavailable" ? "recharge.order.rate_unavailable"
: error.code === "review" ? "recharge.payment.review"
: error.code === "expired" ? "recharge.payment.expired" : "recharge.request.failed";
alertPay(t(key), "error", t("recharge.request.failed_title"));
});
}
@ -453,10 +475,11 @@
renderBrowserTimes();
var returnParams = new URLSearchParams(window.location.search);
var returnedOrderNo = returnParams.get("order_no");
if (returnParams.get("payment") === "yipay") {
startPayPolling("/user/yipay/status", 3000);
startPayPolling("/user/yipay/status", 3000, returnedOrderNo);
} else if (returnParams.get("payment") === "paytaro") {
startPayPolling("/user/paytaro/status", 3000);
startPayPolling("/user/paytaro/status", 3000, returnedOrderNo);
} else if (returnParams.get("payment") === "stripe") {
startPayPolling("/user/stripe/status", 3000);
}

@ -235,9 +235,11 @@ return [
$recharge('recharge.order.usdt_info',
'请按下方网络和数量完成转账,支付数量必须完全一致。',
'description', [], 'critical'),
$recharge('recharge.order.qr_info',
'订单金额:{amount},请扫码完成支付。', 'description',
['amount' => 'string']),
$recharge('recharge.order.quote', '充值 {usd} USD · 实际应付 {amount} {currency}', 'label',
['usd' => 'string', 'amount' => 'string', 'currency' => 'string']),
$recharge('recharge.order.quote_deadline', '支付截止 {time}', 'label', ['time' => 'string']),
$recharge('recharge.order.rate_unavailable', '当前汇率不可用,请选择其他付款方式。', 'warning'),
$recharge('recharge.payment.review', '原订单需核对,付款入口已关闭。如已扣款,请联系管理员。', 'warning'),
$recharge('recharge.order.open_cashier', '打开收银台', 'button'),
$recharge('recharge.payment.success', '支付成功,余额已入账。',
'notice'),

@ -161,7 +161,11 @@ return [
$entry('billing.payment.active.pending', 'billing', 'cloud.invoice_detail', '已有待支付订单;可继续原订单或选择其他支付方式。', 'status'),
$entry('billing.payment.active.review', 'billing', 'cloud.invoice_detail', '上一笔支付订单结果待核对;可选择其他支付方式,原订单若随后到账将计入账户余额。', 'warning'),
$entry('billing.payment.expired.title', 'billing', 'cloud.invoice_detail', '支付订单已过期', 'title'),
$entry('billing.payment.expired.body', 'billing', 'cloud.invoice_detail', '请重新选择支付方式并确认,以生成新的支付订单。', 'description'),
$entry('billing.payment.expired.body', 'billing', 'cloud.invoice_detail', '原支付报价已过期。付款前请先确认原订单是否已扣款。', 'description'),
$entry('billing.payment.quote', 'billing', 'cloud.invoice_detail', '账单 {usd} USD · 实际应付 {amount} {currency}', 'label', ['usd' => 'string', 'amount' => 'string', 'currency' => 'string']),
$entry('billing.payment.quote_deadline', 'billing', 'cloud.invoice_detail', '支付截止 {time}', 'label', ['time' => 'string']),
$entry('billing.payment.fx_review', 'billing', 'cloud.invoice_detail', '原订单需核对,付款入口已关闭。如已扣款,请联系管理员。', 'warning'),
$entry('billing.payment.rate_unavailable', 'billing', 'cloud.invoice_detail', '当前汇率不可用,请选择其他付款方式。', 'warning'),
$entry('billing.payment.usdt.amount', 'billing', 'cloud.invoice_detail', '请支付 {amount} USDT(TRC20)', 'label', ['amount' => 'string']),
$entry('billing.payment.address_unavailable', 'billing', 'cloud.invoice_detail', '收款地址不可用'),
$entry('billing.payment.usdt.notice', 'billing', 'cloud.invoice_detail', '支付订单具有时效;链上确认后自动结清账单。', 'description'),

@ -0,0 +1,85 @@
{assign var=admin_title value='支付汇率与对账'}
{include file='admin/static_header.tpl'}
<div class="d-grid gap-4 py-3">
<header>
<h1 class="h3">支付汇率与对账</h1>
<p class="text-muted mb-0">按应收币种查看实收金额、美元入账和待核对记录。</p>
</header>
{if $rate_saved}<div class="alert alert-success mb-0" role="status">应急报价已保存,应用于新建订单。</div>{/if}
<section class="card card-body">
<h2 class="h5">当前行情</h2>
<div class="table-responsive"><table class="table align-middle">
<thead><tr><th scope="col">币对</th><th scope="col">新单汇率</th><th scope="col">来源</th><th scope="col">源时间 UTC</th><th scope="col">获取时间 UTC</th><th scope="col">有效至 UTC</th><th scope="col">刷新状态</th></tr></thead>
<tbody>{foreach $rates as $pair => $rate}
<tr>
<th scope="row">{$pair|escape}</th>
<td>{if $rate.current}{$rate.current.rate|escape}{else}暂停新单{/if}</td>
<td>{$rate.feed|escape}{if $rate.current && $rate.current.source == 'manual'} · 应急报价{/if}</td>
<td>{$rate.source_at_display|escape}</td>
<td>{$rate.fetched_at_display|escape}</td>
<td>{$rate.valid_until_display|escape}</td>
<td>{$rate.error|default:'—'|escape}{if $rate.attempted_at}<br><small>{$rate.attempted_at_display|escape}</small>{/if}</td>
</tr>
{/foreach}</tbody>
</table></div>
{if $admin_can_manage}
<details>
<summary class="fw-semibold">设置应急报价</summary>
<form class="row g-3 mt-1" method="post" action="/admin/payment-reconciliation/rate">
<input type="hidden" name="_admin_csrf" value="{$admin_csrf_token|escape}">
<label class="col-md-2">币对<select class="form-select" name="pair">
<option value="USD/CNY">USD/CNY</option><option value="USDT/USD">USDT/USD</option>
</select></label>
<label class="col-md-2">汇率<input class="form-control" type="number" step="0.000000000001" min="0.000000000001" name="rate" required></label>
<label class="col-md-2">有效分钟数<input class="form-control" type="number" min="1" max="4320" name="minutes" required></label>
<label class="col-md">原因<input class="form-control" name="reason" maxlength="240" required></label>
<div class="col-auto align-self-end"><button class="btn btn-primary" type="submit">保存报价</button></div>
</form>
</details>
{/if}
</section>
<section class="card card-body">
<h2 class="h5">按币种汇总</h2>
<p class="text-muted">CNY 和 USDT 汇总新版已验证收款,USD 汇总 Stripe。入账为退款前金额,退款在明细中单列。</p>
{if $table_error}<div class="alert alert-warning">支付对账表不可用,请核对数据库迁移。</div>{else}
<div class="table-responsive"><table class="table align-middle">
<thead><tr><th scope="col">收款币种</th><th scope="col">实收</th><th scope="col">入账 USD</th><th scope="col">待核对</th></tr></thead>
<tbody>{foreach $totals as $currency => $total}
<tr><th scope="row">{$currency|escape}</th><td>{$total.received|escape}</td><td>{$total.credited|escape}</td><td>{$total.review|escape}</td></tr>
{/foreach}</tbody>
</table></div>
<form class="d-flex flex-wrap gap-2 align-items-end" method="get" action="/admin/payment-reconciliation">
<label>币种<select class="form-select" name="asset">
{foreach $totals as $currency => $total}
<option value="{$currency|escape}" {if $currency == $asset}selected{/if}>{$currency|escape}</option>
{/foreach}
</select></label>
<label class="pb-2"><input type="checkbox" name="review" value="1" {if $review}checked{/if}> 只看待核对</label>
<button class="btn btn-light" type="submit">筛选</button>
{if $admin_can_manage}<a class="btn btn-outline-primary" href="/admin/payment-reconciliation/export?asset={$asset|escape}&amp;review={if $review}1{else}0{/if}">导出 CSV</a>{/if}
</form>
{if $asset == 'USD'}<p class="mt-3 mb-0"><a href="/admin/stripe">查看 Stripe 订单</a></p>{else}
<div class="table-responsive mt-3"><table class="table align-middle">
<thead><tr><th scope="col">订单</th><th scope="col">渠道</th><th scope="col">应付 {$asset|escape}</th><th scope="col">实收 {$asset|escape}</th><th scope="col">入账 USD</th><th scope="col">状态</th><th scope="col">退款</th></tr></thead>
<tbody>{foreach $quote_rows as $order}
<tr>
<td>{if $admin_can_manage}<code>{$order.order|escape}</code>{else}—{/if}</td>
<td>{$order.provider|escape}</td><td>{$order.quoted|default:'—'|escape}</td><td>{$order.received|default:'—'|escape}</td><td>{$order.credited|default:'—'|escape}</td>
<td>{if $order.status == 'review'}待核对 <small class="text-muted">{$order.reason|escape}</small>
{elseif $order.status == 'accepted'}已核实收款{else}已报价{/if}</td>
<td>{if $order.refund_status != ''}
{$order.refund_status|escape} · {$order.refund_cny|default:'—'|escape} CNY / {$order.refund_usd|escape} USD
{else}—{/if}</td>
</tr>
{foreachelse}<tr><td colspan="7" class="text-muted">暂无符合条件的记录</td></tr>{/foreach}</tbody>
</table></div>
{if $orders}{$orders->links()}{/if}
{/if}
{/if}
</section>
</div>
{include file='admin/static_footer.tpl'}

@ -11,12 +11,13 @@
<div><h1>Paytaro 支付</h1><p>通过官方 MAPI 通道管理支付宝收款、固定回调和本地入账订单。</p></div>
<span class="badge {if $paytaro_config.paytaro_enabled}bg-success{else}bg-secondary{/if}">{if $paytaro_config.paytaro_enabled}已启用{else}未启用{/if}</span>
</header>
<div><a class="btn btn-outline-primary btn-sm" href="/admin/payment-reconciliation?asset=CNY">支付汇率与对账</a></div>
<section class="pt-stats">
<article class="pt-stat"><span>全部订单</span><strong>{$paytaro_summary.total}</strong></article>
<article class="pt-stat"><span>等待支付</span><strong>{$paytaro_summary.pending}</strong></article>
<article class="pt-stat"><span>成功订单</span><strong>{$paytaro_summary.paid}</strong></article>
<article class="pt-stat"><span>成功入账</span><strong>¥ {$paytaro_summary.paid_amount}</strong></article>
<article class="pt-stat"><span>已付款单原始面额</span><strong>{$paytaro_summary.paid_amount} USD</strong></article>
</section>
<section class="pt-panel">
@ -33,6 +34,7 @@
<div class="pt-field"><label for="ptMinimum">最低充值金额</label><input class="form-control" id="ptMinimum" name="paytaro_min_amount" type="number" min="0.01" max="1000000" step="0.01" value="{$paytaro_config.paytaro_min_amount|escape}"></div>
<div class="pt-field"><label for="ptMaximum">最高充值金额</label><input class="form-control" id="ptMaximum" name="paytaro_max_amount" type="number" min="0.01" max="1000000" step="0.01" value="{$paytaro_config.paytaro_max_amount|escape}"></div>
<div class="pt-field"><label for="ptTimeout">请求超时(秒)</label><input class="form-control" id="ptTimeout" name="paytaro_request_timeout_seconds" type="number" min="3" max="60" value="{$paytaro_config.paytaro_request_timeout_seconds|escape}"></div>
<div class="pt-field"><label for="ptQuoteMinutes">支付报价有效期(分钟)</label><input class="form-control" id="ptQuoteMinutes" name="paytaro_quote_minutes" type="number" min="5" max="1440" value="{$paytaro_config.paytaro_quote_minutes|escape}"></div>
</div>
<div class="pt-actions"><button class="btn btn-primary" id="ptSave" type="submit" {if !$admin_can_manage|default:false}disabled{/if}><i class="mdi mdi-content-save-outline me-1"></i>保存配置</button><button class="btn btn-light" id="ptTest" type="button" {if !$admin_can_manage|default:false}disabled{/if}><i class="mdi mdi-lan-connect me-1"></i>测试连接</button><div class="pt-notice" id="ptNotice" role="status" aria-live="polite"></div></div>
</form>
@ -43,7 +45,7 @@
{if $paytaro_table_error != ''}<div class="pt-warning">{$paytaro_table_error|escape}</div>{/if}
<form class="pt-filter" method="get" action="/admin/paytaro"><input class="form-control" name="keyword" type="search" value="{$paytaro_filters.keyword|escape}" placeholder="{if $admin_can_manage|default:false}记录 ID、用户 ID 或用户邮箱{else}记录 ID 或用户 ID{/if}"><select class="form-select" name="status"><option value="">全部状态</option><option value="creating" {if $paytaro_filters.status == 'creating'}selected{/if}>创建中</option><option value="pending" {if $paytaro_filters.status == 'pending'}selected{/if}>待支付</option><option value="paid" {if $paytaro_filters.status == 'paid'}selected{/if}>已支付</option><option value="failed" {if $paytaro_filters.status == 'failed'}selected{/if}>失败</option></select><button class="btn btn-light" type="submit"><i class="mdi mdi-magnify me-1"></i>筛选</button></form>
{if $paytaro_orders}<div class="pt-table-wrap"><table class="pt-table"><thead><tr><th>用户</th><th>金额</th><th>状态</th><th>创建时间</th></tr></thead><tbody>{foreach $paytaro_orders as $order}<tr><td>{$order->user_email|default:'已删除用户'|escape}<br><small class="text-muted">用户 ID {$order->user_id} · 记录 ID {$order->id}</small></td><td>¥ {$order->amount}</td><td><span class="pt-pill {if $order->status == 'paid'}is-paid{elseif $order->status == 'pending' || $order->status == 'creating'}is-pending{elseif $order->status == 'failed'}is-failed{/if}">{if $order->status == 'creating'}创建中{elseif $order->status == 'pending'}待支付{elseif $order->status == 'paid'}已支付{elseif $order->status == 'failed'}失败{else}{$order->status|escape}{/if}</span></td><td>{date('Y-m-d H:i:s', $order->created_at)}</td></tr>{foreachelse}<tr><td colspan="4" class="pt-empty">暂无订单</td></tr>{/foreach}</tbody></table></div><div class="pt-pagination">{$paytaro_orders->links()}</div>{/if}
{if $paytaro_orders}<div class="pt-table-wrap"><table class="pt-table"><thead><tr><th>用户</th><th>金额</th><th>状态</th><th>创建时间</th></tr></thead><tbody>{foreach $paytaro_orders as $order}<tr><td>{$order->user_email|default:'已删除用户'|escape}<br><small class="text-muted">用户 ID {$order->user_id} · 记录 ID {$order->id}</small></td><td>{$order->amount|escape} USD</td><td><span class="pt-pill {if $order->status == 'paid'}is-paid{elseif $order->status == 'pending' || $order->status == 'creating'}is-pending{elseif $order->status == 'failed'}is-failed{/if}">{if $order->status == 'creating'}创建中{elseif $order->status == 'pending'}待支付{elseif $order->status == 'paid'}已支付{elseif $order->status == 'failed'}失败{else}{$order->status|escape}{/if}</span></td><td>{date('Y-m-d H:i:s', $order->created_at)}</td></tr>{foreachelse}<tr><td colspan="4" class="pt-empty">暂无订单</td></tr>{/foreach}</tbody></table></div><div class="pt-pagination">{$paytaro_orders->links()}</div>{/if}
</section>
</div>

@ -11,6 +11,7 @@
<div><h1>Stripe 支付</h1><p>使用 Stripe 托管 Checkout 收取银行卡和支付宝付款,面板不接触银行卡资料。</p></div>
<span class="badge {if $stripe_config.stripe_enabled}bg-success{else}bg-secondary{/if}">{if $stripe_config.stripe_enabled}已启用{else}未启用{/if}</span>
</header>
<div><a class="btn btn-outline-primary btn-sm" href="/admin/payment-reconciliation?asset=USD">支付汇率与对账</a></div>
<section class="st-stats">
<article class="st-stat"><span>全部订单</span><strong>{$stripe_summary.total}</strong></article>

@ -10,12 +10,13 @@
<div><h1>原生 USDT 收款</h1><p>TRON 地址池、链上订单和到账扫描。</p></div>
<span class="badge {if $usdt_config.usdt_enabled}bg-success{else}bg-secondary{/if}">{if $usdt_config.usdt_enabled}已启用{else}未启用{/if}</span>
</header>
<div><a class="btn btn-outline-primary btn-sm" href="/admin/payment-reconciliation?asset=USDT">支付汇率与对账</a></div>
<section class="us-stats">
<article class="us-stat"><span>全部订单</span><strong>{$usdt_summary.total}</strong></article>
<article class="us-stat"><span>等待到账</span><strong>{$usdt_summary.pending}</strong></article>
<article class="us-stat"><span>成功订单</span><strong>{$usdt_summary.paid}</strong></article>
<article class="us-stat"><span>成功入账</span><strong>¥ {$usdt_summary.paid_amount}</strong></article>
<article class="us-stat"><span>已付款单原始面额</span><strong>{$usdt_summary.paid_amount} USD</strong></article>
<article class="us-stat"><span>需人工处理的链上记录</span><strong>{$usdt_summary.attention}</strong></article>
</section>
@ -112,7 +113,7 @@
</td>
<td>余额充值<br><small class="text-muted">记录 ID {$order->id}</small></td>
<td>{if $order->user_email}{$order->user_email|escape}<br><small>用户 ID {$order->user_id}</small>{else}-{/if}</td>
<td>¥ {$order->amount}</td>
<td>{$order->amount|escape} USD</td>
<td>{$order->actual_amount} USDT<br><small class="us-mono text-muted us-truncate" title="{$order->receive_address|escape}">{$order->receive_address|escape}</small></td>
<td><span class="us-pill {if $order->status == 'paid'}is-paid{elseif $order->status == 'pending' || $order->status == 'expired'}is-pending{elseif $order->status == 'failed' || $order->status == 'review'}is-error{/if}">{$order->status|escape}</span></td>
<td>{date('Y-m-d H:i:s', $order->created_at)}</td>

@ -11,13 +11,14 @@
<div><h1>易支付</h1><p>管理支付宝、微信支付连接与本地入账订单。</p></div>
<span class="badge {if $yipay_config.yipay_enabled}bg-success{else}bg-secondary{/if}">{if $yipay_config.yipay_enabled}已启用{else}未启用{/if}</span>
</header>
<div><a class="btn btn-outline-primary btn-sm" href="/admin/payment-reconciliation?asset=CNY">支付汇率与对账</a></div>
<section class="yp-stats">
<article class="yp-stat"><span>全部订单</span><strong>{$yipay_summary.total}</strong></article>
<article class="yp-stat"><span>等待支付</span><strong>{$yipay_summary.pending}</strong></article>
<article class="yp-stat"><span>成功订单</span><strong>{$yipay_summary.paid}</strong></article>
<article class="yp-stat"><span>已退款</span><strong>{$yipay_summary.refunded}</strong></article>
<article class="yp-stat"><span>当前净入账</span><strong>¥ {$yipay_summary.paid_amount}</strong></article>
<article class="yp-stat"><span>已付款单原始面额</span><strong>{$yipay_summary.paid_amount} USD</strong></article>
</section>
<section class="yp-panel">
@ -69,17 +70,21 @@
<input class="form-control" id="ypOrderName" name="yipay_order_name" type="text" maxlength="127" value="{$yipay_config.yipay_order_name|escape}">
</div>
<div class="yp-field">
<label for="ypMinimum">最低充值金额</label>
<label for="ypMinimum">最低充值金额(USD)</label>
<input class="form-control" id="ypMinimum" name="yipay_min_amount" type="number" min="0.01" max="1000000" step="0.01" value="{$yipay_config.yipay_min_amount|escape}">
</div>
<div class="yp-field">
<label for="ypMaximum">最高充值金额</label>
<label for="ypMaximum">最高充值金额(USD)</label>
<input class="form-control" id="ypMaximum" name="yipay_max_amount" type="number" min="0.01" max="1000000" step="0.01" value="{$yipay_config.yipay_max_amount|escape}">
</div>
<div class="yp-field">
<label for="ypTimeout">请求超时(秒)</label>
<input class="form-control" id="ypTimeout" name="yipay_request_timeout_seconds" type="number" min="3" max="60" value="{$yipay_config.yipay_request_timeout_seconds|escape}">
</div>
<div class="yp-field">
<label for="ypQuoteMinutes">支付报价有效期(分钟)</label>
<input class="form-control" id="ypQuoteMinutes" name="yipay_quote_minutes" type="number" min="5" max="1440" value="{$yipay_config.yipay_quote_minutes|escape}">
</div>
</div>
<div class="yp-actions">
<button class="btn btn-primary" id="ypSave" type="submit" {if !$admin_can_manage|default:false}disabled{/if}><i class="mdi mdi-content-save-outline me-1"></i>保存配置</button>
@ -119,10 +124,22 @@
<tr>
<td><span>{$order->user_email|default:'已删除用户'|escape}</span><br><small class="text-muted">用户 ID {$order->user_id} · 记录 ID {$order->id}</small></td>
<td>{if $order->payment_type == 'wxpay'}微信支付{else}支付宝{/if}</td>
<td>¥ {$order->amount}</td>
<td>{$order->amount|escape} USD
{if $order->reconciliation.received|default:'' != ''}<br><small>实收 {$order->reconciliation.received|escape} CNY</small>{/if}
{if $order->reconciliation.credited|default:'' != ''}<br><small>入账 {$order->reconciliation.credited|escape} USD</small>{/if}
{if $order->reconciliation.status|default:'' == 'review'}<br><small>待核对</small>{/if}
</td>
<td><span class="yp-pill {if $order->status == 'paid'}is-paid{elseif $order->status == 'refunded'}is-refunded{elseif $order->status == 'pending' || $order->status == 'creating'}is-pending{elseif $order->status == 'failed'}is-failed{/if}">{if $order->status == 'creating'}创建中{elseif $order->status == 'pending'}待支付{elseif $order->status == 'paid'}已支付{elseif $order->status == 'refunded'}已退款{elseif $order->status == 'failed'}失败{else}{$order->status|escape}{/if}</span></td>
<td>{date('Y-m-d H:i:s', $order->created_at)}</td>
<td>{if $order->status == 'paid' && $yipay_refund_available}<button class="btn btn-sm btn-outline-danger yp-refund" type="button" data-refund-record="{$order->id}" data-refund-amount="{$order->amount|escape}" {if !$admin_can_manage|default:false}disabled aria-disabled="true"{/if}><i class="mdi mdi-cash-refund me-1"></i>退款</button>{else}<span class="text-muted">--</span>{/if}</td>
<td>{if $order->can_refund|default:false && $yipay_refund_available && $admin_can_manage}
<button class="btn btn-sm btn-outline-danger yp-refund" type="button" data-refund-record="{$order->id}"
data-refund-cny="{$order->reconciliation.received|escape}" data-refund-usd="{$order->reconciliation.credited|escape}"
data-refund-state="{$order->refund_state|escape}">{if $order->refund_state == 'gateway_accepted'}完成本地记账{else}退款{/if}</button>
{elseif $order->refund_state|default:'' == 'dispatching' || $order->refund_state|default:'' == 'uncertain'}<span class="text-muted">退款待核对</span>
{elseif $order->refund_state|default:'' == 'success' && $order->reconciliation.refund_cny|default:'' != ''}
已退 {$order->reconciliation.refund_cny|escape} CNY<br>已扣回 {$order->reconciliation.refund_usd|escape} USD
{else}<span class="text-muted">—</span>{/if}
</td>
</tr>
{foreachelse}
<tr><td colspan="6" class="yp-empty">暂无订单</td></tr>
@ -191,8 +208,12 @@
var button = event.target.closest('[data-refund-record]');
if (!button || button.disabled) return;
var recordId = button.getAttribute('data-refund-record');
var amount = button.getAttribute('data-refund-amount');
if (!window.confirm('确认将这笔充值全额退款 ¥' + amount + '?\n退款成功后会立即扣回用户余额和对应邀请返利,余额不足时将形成负余额。此操作不可撤销。')) return;
var cny = button.getAttribute('data-refund-cny');
var usd = button.getAttribute('data-refund-usd');
var confirmed = button.getAttribute('data-refund-state') === 'gateway_accepted';
var message = confirmed ? '渠道已退回 ' + cny + ' CNY。确认完成原单的 ' + usd + ' USD 余额及返利扣回?'
: '确认原路退回 ' + cny + ' CNY,并扣回 ' + usd + ' USD 余额及对应返利?此操作不可撤销。';
if (!window.confirm(message)) return;
button.disabled = true;
show('正在提交退款,请勿重复操作...', true);
request('/admin/yipay/refund', new URLSearchParams({record_id: recordId, confirm: 'REFUND'}).toString())

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

@ -41,7 +41,9 @@
<div class="vu-pay-dialog-backdrop" data-pay-close></div>
<div class="vu-pay-dialog-panel" role="dialog" aria-modal="true" aria-labelledby="vuPayTitle">
<button class="vu-modal-close" type="button" data-pay-close aria-label="{user_copy key='recharge.dialog.close'}"><i class="mdi mdi-close"></i></button>
<div class="vu-modal-mark"><i class="mdi mdi-qrcode-scan"></i></div><h2 id="vuPayTitle">{user_copy key='recharge.dialog.title'}</h2><p id="vuPayInfo">{user_copy key='recharge.dialog.info'}</p><div class="vu-pay-qrcode" id="qrcode"></div>
<div class="vu-modal-mark"><i class="mdi mdi-qrcode-scan"></i></div><h2 id="vuPayTitle">{user_copy key='recharge.dialog.title'}</h2>
<p id="vuPayQuote"></p><p id="vuPayExpiry"></p>
<p id="vuPayInfo">{user_copy key='recharge.dialog.info'}</p><div class="vu-pay-qrcode" id="qrcode"></div>
<div class="vu-pay-chain-details" id="vuPayChainDetails" hidden><div class="vu-pay-chain-summary"><span><small>{user_copy key='recharge.dialog.network'}</small><strong id="vuPayNetwork">--</strong></span><span><small>{user_copy key='recharge.dialog.amount'}</small><strong id="vuPayAmount">--</strong></span></div><div class="vu-pay-address"><small>{user_copy key='recharge.dialog.usdt_address'}</small><div><code id="vuPayAddress">--</code><button class="vu-icon-btn" id="vuPayAddressCopy" type="button" aria-label="{user_copy key='recharge.dialog.copy_address'}"><i class="mdi mdi-content-copy"></i></button></div></div></div>
<a class="vu-btn vu-btn-soft" id="vuPayOpen" href="#" target="_blank" rel="noopener"><i class="mdi mdi-open-in-new"></i><span id="vuPayOpenLabel">{user_copy key='recharge.dialog.open_link'}</span></a>
</div>

@ -1,12 +1,15 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
require __DIR__ . '/Support/PaymentCheckoutFixture.php';
$GLOBALS['System_Config'] = ['authDriver' => 'cookie'];
use App\Models\User;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudInvoiceDetailPageService;
use App\Services\Payment\PaymentCheckoutQuotes;
use App\Services\Payment\PaymentRateService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
@ -24,6 +27,19 @@ $capsule->addConnection([
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
createPaymentCheckoutFixture($schema);
$schema->create('configurations', static function (Blueprint $table): void {
$table->increments('id');
$table->string('name')->unique();
$table->text('value')->nullable();
});
$schema->create('paytaro_orders', static function (Blueprint $table): void {
$table->increments('id');
$table->string('order_no')->unique();
$table->integer('user_id');
$table->string('payment_kind');
$table->string('payment_value');
});
$schema->create('user', static function (Blueprint $table): void {
$table->increments('id');
@ -311,6 +327,34 @@ $assert(($latest['active_payment']['status'] ?? null) === 'pending'
&& ($latest['active_payment']['can_submit'] ?? false) === true,
'An older unknown task was merged into a newer provider payment.');
Capsule::table('paytaro_orders')->insert([
'order_no' => 'PT-RESUME-1', 'user_id' => 1, 'payment_kind' => 'payurl',
'payment_value' => 'https://payment.example.test/frozen-quote',
]);
Capsule::table('cloud_invoice_payments')->insert([
'id' => 43, 'invoice_id' => 21, 'user_id' => 1, 'provider' => 'paytaro',
'provider_order_no' => 'PT-RESUME-1', 'idempotency_key' => 'paytaro-resume-key-0001',
'amount' => '10.00', 'status' => 'pending', 'created_at' => $now, 'updated_at' => $now + 3,
]);
$legacy = CloudInvoiceDetailPageService::forUser(21, 1, $user);
$assert($legacy['active_payment']['status'] === 'review'
&& $legacy['presentation']['active_payment_key'] === 'billing.payment.fx_review'
&& !isset($legacy['active_payment']['payment']['payment_value'])
&& $legacy['balance_payment_allowed'], 'A stale legacy QR is still offered.');
PaymentRateService::override('USD/CNY', '7.20', $now + 2, 9, 'Short original source window', $now - 10);
$quote = PaymentCheckoutQuotes::prepare('paytaro', '10.00', $now - 10, $now + 1800);
PaymentCheckoutQuotes::persist($quote, 'PT-RESUME-1', 1);
Capsule::table('configurations')->delete();
$resumed = CloudInvoiceDetailPageService::statusForUser(21, 1)['active_payment'];
$assert($resumed['status'] === 'pending' && $resumed['payment']['amount'] === '10.00'
&& $resumed['payment']['charge_amount'] === '72.00' && $resumed['payment']['charge_currency'] === 'CNY'
&& $resumed['payment']['expires_at'] === $now + 1800,
'Reload depends on the live feed or changed the original amount or deadline.');
Capsule::table('payment_checkout_quotes')->where('order_no', 'PT-RESUME-1')->update(['pay_until' => $now - 1]);
$expiredQuote = CloudInvoiceDetailPageService::statusForUser(21, 1)['active_payment'];
$assert($expiredQuote['status'] === 'expired' && !isset($expiredQuote['payment']['payment_value']),
'An expired CNY quote regained its payment link.');
$foreignRejected = false;
try {
CloudInvoiceDetailPageService::forUser(21, 2, User::findOrFail(2));

@ -114,6 +114,8 @@ try {
'test.payment.active': '服务端待支付订单',
'test.payment.stale': '过期支付状态',
'billing.payment.usdt.amount': '请支付 {amount} USDT(TRC20)',
'billing.payment.quote': '账单 {usd} USD · 实际应付 {amount} {currency}',
'billing.payment.quote_deadline': '支付截止 {time}',
'billing.payment.task_accepted': '支付订单创建任务已接收。',
'billing.payment.task_accepted_short': '支付订单创建任务已接收。',
};
@ -224,6 +226,10 @@ try {
status: 'pending',
payment_kind: 'usdt',
actual_amount: '1.500001',
amount: '1.50',
charge_amount: '1.500001',
charge_currency: 'USDT',
checkout_state: 'payable',
receive_address: 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
label: 'USDT',
expires_at: now + 900,
@ -316,6 +322,8 @@ try {
await page.waitForFunction(() => document.querySelector(
'.cloud-payment-instructions strong'
)?.textContent?.includes('USDT'), null, { timeout: 5000 });
assert.match(await page.locator('.cloud-payment-instructions').textContent(),
/1\.50 USD.*1\.500001 USDT.*支付截止/);
await page.evaluate(oldStatus => {
window.__resolveOldStatus(oldStatus);

@ -5,6 +5,7 @@ require __DIR__ . '/Support/PaymentCheckoutFixture.php';
use App\Services\Payment\PaymentCheckoutQuotes;
use App\Services\Payment\PaymentRateService;
use App\Services\Payment\PaymentReconciliation;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
@ -27,6 +28,21 @@ $schema->create('configurations', function (Blueprint $table): void {
$table->text('value');
});
createPaymentCheckoutFixture($schema);
$schema->create('stripe_orders', static function (Blueprint $table): void {
$table->increments('id');
$table->string('order_no');
$table->string('payment_method');
$table->decimal('amount', 12, 2);
$table->string('status');
$table->integer('paid_at');
});
$schema->create('yipay_refunds', static function (Blueprint $table): void {
$table->increments('id');
$table->string('order_no');
$table->string('status');
$table->decimal('amount', 12, 2);
$table->decimal('gateway_amount', 12, 2);
});
$now = 1_770_000_000;
PaymentRateService::override('USD/CNY', '7.20', $now + 3600, 7, 'First acceptance quote', $now);
@ -58,4 +74,27 @@ checkCheckoutQuote($legacy->status === 'review' && $legacy->review_reason === 'l
checkCheckoutQuote($receipt('paytaro', 'PT-LEGACY', 7200, $now + 20, null)->received_at === $now + 10,
'Repeated legacy evidence changed the recorded settlement.');
Capsule::table('stripe_orders')->insert([
'order_no' => 'ST-USD', 'payment_method' => 'card', 'amount' => '20.00', 'status' => 'paid', 'paid_at' => $now,
]);
PaymentRateService::override('USDT/USD', '1.00', $now + 3600, 7, 'USDT reconciliation fixture', $now);
$usdt = PaymentCheckoutQuotes::prepare('usdt', '72.00', $now, $now + 900);
PaymentCheckoutQuotes::persist($usdt, 'USDT-EXPORT', 21, 72_000_001);
$receipt('usdt', 'USDT-EXPORT', 72_000_001, $now + 12, $now + 10);
$totals = PaymentReconciliation::totals();
checkCheckoutQuote($totals['CNY'] === ['received' => '525.60', 'credited' => '73.00', 'review' => 2]
&& $totals['USDT'] === ['received' => '72.000001', 'credited' => '72.00', 'review' => 0]
&& $totals['USD'] === ['received' => '20.00', 'credited' => '20.00', 'review' => 0],
'Reconciliation mixed currencies, excluded overpayment or counted unresolved receipts.');
$csvFile = tmpfile();
PaymentReconciliation::csv($csvFile, 'CNY', true);
rewind($csvFile);
$csv = stream_get_contents($csvFile);
fclose($csvFile);
checkCheckoutQuote(str_contains($csv, 'PT-LEGACY,paytaro,CNY,review,legacy_quote')
&& str_contains($csv, 'YP-QUOTE-B,yipay_wxpay,CNY,review,payment_time_unconfirmed')
&& !str_contains($csv, 'PT-QUOTE-A') && !str_contains($csv, 'USDT-EXPORT'),
'CSV did not respect the requested status and currency scopes.');
echo "Checkout quote persistence, old receipts and deadlines passed.\n";

@ -161,6 +161,7 @@ try {
(new PaytaroClient([
'paytaro_gateway_url' => PaytaroConfig::MAPI_GATEWAY_URL,
'paytaro_request_timeout_seconds' => 15,
'paytaro_quote_minutes' => 30,
PaytaroConfig::SECRET_KEY => 'merchant-secret',
], $httpClient))->createOrder($fixed);
fwrite(STDERR, 'Paytaro accepted a non-HTTPS payment URL.' . PHP_EOL);
@ -656,6 +657,7 @@ $smarty->assign([
'paytaro_min_amount' => '1.00',
'paytaro_max_amount' => '10000.00',
'paytaro_request_timeout_seconds' => 15,
'paytaro_quote_minutes' => 30,
],
'paytaro_orders' => null,
'paytaro_summary' => ['total' => 0, 'pending' => 0, 'paid' => 0, 'paid_amount' => '0.00'],
@ -677,6 +679,29 @@ if (strpos($adminHtml, 'action="/admin/paytaro/config"') === false
exit(1);
}
$smarty->assign([
'admin_can_manage' => true, 'admin_csrf_token' => str_repeat('c', 64),
'rate_saved' => false, 'table_error' => false, 'asset' => 'CNY', 'review' => true, 'orders' => null,
'rates' => ['USD/CNY' => [
'current' => ['source' => 'manual', 'rate' => '7.20'], 'feed' => 'wise',
'source_at_display' => '—', 'fetched_at_display' => '—', 'valid_until_display' => '1970-01-02 08:00:00',
'error' => 'missing_credentials', 'attempted_at' => null,
]],
'totals' => ['CNY' => ['received' => '720.00', 'credited' => '100.00', 'review' => 1]],
'quote_rows' => [[
'order' => 'PT-REVIEW', 'provider' => 'paytaro', 'status' => 'review', 'reason' => 'legacy_quote',
'quoted' => '', 'received' => '100.00', 'credited' => '', 'refund_status' => '',
]],
]);
$reconciliationHtml = $smarty->fetch('admin/payment-reconciliation/index.tpl');
if (!str_contains($reconciliationHtml, 'CNY')
|| !str_contains($reconciliationHtml, '720.00')
|| !str_contains($reconciliationHtml, 'legacy_quote')
|| !str_contains($reconciliationHtml, 'name="_admin_csrf"')
|| !str_contains($reconciliationHtml, '/admin/payment-reconciliation/export?asset=CNY&amp;review=1')) {
throw new RuntimeException('Admin reconciliation view did not render the currency, review and export controls.');
}
$rechargeTemplate = file_get_contents(dirname(__DIR__) . '/resources/views/venix/user/paytaro.tpl');
$userLayoutScripts = file_get_contents(dirname(__DIR__) . '/resources/views/venix/user/layout_scripts.tpl');
$rechargeScript = file_get_contents(dirname(__DIR__) . '/public/theme/venix/js/recharge.js');
@ -690,13 +715,14 @@ if ($rechargeTemplate === false
|| $userLayoutScripts === false
|| $rechargeScript === false
|| strpos($rechargeTemplate, 'src="/theme/venix/js/recharge.js?') === false
|| strpos($rechargeScript, 'definition.type === "paytaro" && isPaytaroMobileDevice()') === false
|| strpos($rechargeScript, 'isPaytaroMobileDevice() ? paytaroMobileUrl(data.url)') === false
|| strpos($rechargeScript, 'alipays://platformapi/startapp?appId=20000067') === false
|| strpos($rechargeScript, 'url.searchParams.get("method") === "alipay.trade.wap.pay"') === false
|| strpos($rechargeScript, 'host === "mclient.alipay.com"') === false
|| strpos($rechargeScript, 'function isPaytaroMobileDevice()') === false
|| strpos($rechargeScript, 'navigator.userAgentData.mobile') === false
|| strpos($rechargeScript, 'topWindow().location.assign(mobileUrl)') === false
|| strpos($rechargeScript, 'payOpen.setAttribute("href", directUrl)') === false
|| strpos($rechargeTemplate, 'id="vuPayQuote"') === false
|| strpos($rechargeScript, 'function renderPaymentQr(') === false
|| strpos($rechargeScript, 'content.length > 1200 ? levels.L : levels.M') === false
|| strpos($rechargeTemplate, 'data-recharge-time') === false
@ -706,7 +732,7 @@ if ($rechargeTemplate === false
'window.VenixUserCopy.date(date.getTime(), { hour12: false })') === false
|| $historyEpoch !== 1793606400
|| strpos($userLayoutScripts, 'src="{$cdn}/theme/venix/js/qrcode.min.js?v={$vu_asset_version}"') === false) {
fwrite(STDERR, 'Paytaro mobile redirect policy failed.' . PHP_EOL);
fwrite(STDERR, 'Paytaro mobile quote and checkout link contract failed.' . PHP_EOL);
exit(1);
}

Loading…
Cancel
Save