From 3c054cf5b37d6cfc783873ca2cf65dda5645ac2b Mon Sep 17 00:00:00 2001 From: codex Date: Sun, 22 Nov 2026 13:32:56 +0800 Subject: [PATCH] feat(payment): display charge and credit currencies --- .../Admin/PaymentReconciliationController.php | 98 +++++++++++++++++++ web/app/Controllers/Admin/YipayController.php | 16 +++ web/app/Controllers/CloudApiController.php | 12 ++- web/app/Controllers/PaytaroController.php | 31 ++++-- web/app/Controllers/UsdtController.php | 29 +++++- web/app/Controllers/YipayController.php | 31 ++++-- .../Cloud/CloudInvoiceDetailPageService.php | 3 + .../Cloud/CloudInvoicePaymentService.php | 23 ++++- .../Cloud/CloudInvoicePresentation.php | 4 + .../Payment/PaymentCheckoutQuotes.php | 31 +++++- .../Services/Payment/PaymentRateService.php | 1 + .../Payment/PaymentRateUnavailable.php | 13 +++ .../Payment/PaymentReconciliation.php | 91 +++++++++++++++++ web/config/routes.php | 3 + web/public/cloud/invoice-detail-runtime.js | 27 ++++- web/public/theme/venix/js/recharge.js | 71 +++++++++----- .../entries/account-commerce.entries.php | 8 +- .../user-copy/entries/billing.entries.php | 6 +- .../admin/payment-reconciliation/index.tpl | 85 ++++++++++++++++ .../views/venix/admin/paytaro/index.tpl | 6 +- .../views/venix/admin/stripe/index.tpl | 1 + .../views/venix/admin/usdt/index.tpl | 5 +- .../views/venix/admin/yipay/index.tpl | 35 +++++-- web/resources/views/venix/layout_assets.tpl | 2 +- web/resources/views/venix/user/paytaro.tpl | 4 +- web/tests/CloudInvoicePaymentResumeTest.php | 44 +++++++++ ...CloudInvoicePaymentRuntimeBehaviorTest.mjs | 8 ++ web/tests/PaymentCheckoutQuoteTest.php | 39 ++++++++ web/tests/PaytaroPaymentServiceTest.php | 32 +++++- 29 files changed, 684 insertions(+), 75 deletions(-) create mode 100644 web/app/Controllers/Admin/PaymentReconciliationController.php create mode 100644 web/app/Services/Payment/PaymentRateUnavailable.php create mode 100644 web/app/Services/Payment/PaymentReconciliation.php create mode 100644 web/resources/views/venix/admin/payment-reconciliation/index.tpl diff --git a/web/app/Controllers/Admin/PaymentReconciliationController.php b/web/app/Controllers/Admin/PaymentReconciliationController.php new file mode 100644 index 00000000..0a22115e --- /dev/null +++ b/web/app/Controllers/Admin/PaymentReconciliationController.php @@ -0,0 +1,98 @@ +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']; + } +} diff --git a/web/app/Controllers/Admin/YipayController.php b/web/app/Controllers/Admin/YipayController.php index 31a60879..6d605cf4 100644 --- a/web/app/Controllers/Admin/YipayController.php +++ b/web/app/Controllers/Admin/YipayController.php @@ -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(); diff --git a/web/app/Controllers/CloudApiController.php b/web/app/Controllers/CloudApiController.php index 3b599e76..35fd1777 100644 --- a/web/app/Controllers/CloudApiController.php +++ b/web/app/Controllers/CloudApiController.php @@ -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, diff --git a/web/app/Controllers/PaytaroController.php b/web/app/Controllers/PaytaroController.php index 550ef992..b567a860 100644 --- a/web/app/Controllers/PaytaroController.php +++ b/web/app/Controllers/PaytaroController.php @@ -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); diff --git a/web/app/Controllers/UsdtController.php b/web/app/Controllers/UsdtController.php index e38e3e6f..4342dd06 100644 --- a/web/app/Controllers/UsdtController.php +++ b/web/app/Controllers/UsdtController.php @@ -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, ]); diff --git a/web/app/Controllers/YipayController.php b/web/app/Controllers/YipayController.php index 7fc93162..fef62b14 100644 --- a/web/app/Controllers/YipayController.php +++ b/web/app/Controllers/YipayController.php @@ -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); diff --git a/web/app/Services/Cloud/CloudInvoiceDetailPageService.php b/web/app/Services/Cloud/CloudInvoiceDetailPageService.php index 00414131..68a9ebe2 100644 --- a/web/app/Services/Cloud/CloudInvoiceDetailPageService.php +++ b/web/app/Services/Cloud/CloudInvoiceDetailPageService.php @@ -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. diff --git a/web/app/Services/Cloud/CloudInvoicePaymentService.php b/web/app/Services/Cloud/CloudInvoicePaymentService.php index 4e0eadfa..babd8298 100644 --- a/web/app/Services/Cloud/CloudInvoicePaymentService.php +++ b/web/app/Services/Cloud/CloudInvoicePaymentService.php @@ -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 : []); } } diff --git a/web/app/Services/Cloud/CloudInvoicePresentation.php b/web/app/Services/Cloud/CloudInvoicePresentation.php index d3bdb854..9082d27c 100644 --- a/web/app/Services/Cloud/CloudInvoicePresentation.php +++ b/web/app/Services/Cloud/CloudInvoicePresentation.php @@ -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' diff --git a/web/app/Services/Payment/PaymentCheckoutQuotes.php b/web/app/Services/Payment/PaymentCheckoutQuotes.php index 5869589f..4fd5259a 100644 --- a/web/app/Services/Payment/PaymentCheckoutQuotes.php +++ b/web/app/Services/Payment/PaymentCheckoutQuotes.php @@ -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, diff --git a/web/app/Services/Payment/PaymentRateService.php b/web/app/Services/Payment/PaymentRateService.php index 3398112d..ada7688a 100644 --- a/web/app/Services/Payment/PaymentRateService.php +++ b/web/app/Services/Payment/PaymentRateService.php @@ -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, diff --git a/web/app/Services/Payment/PaymentRateUnavailable.php b/web/app/Services/Payment/PaymentRateUnavailable.php new file mode 100644 index 00000000..fdfa1271 --- /dev/null +++ b/web/app/Services/Payment/PaymentRateUnavailable.php @@ -0,0 +1,13 @@ +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'); + } +} diff --git a/web/config/routes.php b/web/config/routes.php index cf800c6c..6c932e56 100644 --- a/web/config/routes.php +++ b/web/config/routes.php @@ -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'); diff --git a/web/public/cloud/invoice-detail-runtime.js b/web/public/cloud/invoice-detail-runtime.js index 7a4fa5ed..f7d3fc31 100644 --- a/web/public/cloud/invoice-detail-runtime.js +++ b/web/public/cloud/invoice-detail-runtime.js @@ -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); } diff --git a/web/public/theme/venix/js/recharge.js b/web/public/theme/venix/js/recharge.js index f6ab12b8..28fcb749 100644 --- a/web/public/theme/venix/js/recharge.js +++ b/web/public/theme/venix/js/recharge.js @@ -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); } diff --git a/web/resources/user-copy/entries/account-commerce.entries.php b/web/resources/user-copy/entries/account-commerce.entries.php index d6547b67..8cf96480 100644 --- a/web/resources/user-copy/entries/account-commerce.entries.php +++ b/web/resources/user-copy/entries/account-commerce.entries.php @@ -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'), diff --git a/web/resources/user-copy/entries/billing.entries.php b/web/resources/user-copy/entries/billing.entries.php index 47a13dfc..358fbde3 100644 --- a/web/resources/user-copy/entries/billing.entries.php +++ b/web/resources/user-copy/entries/billing.entries.php @@ -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'), diff --git a/web/resources/views/venix/admin/payment-reconciliation/index.tpl b/web/resources/views/venix/admin/payment-reconciliation/index.tpl new file mode 100644 index 00000000..cdb9ecfd --- /dev/null +++ b/web/resources/views/venix/admin/payment-reconciliation/index.tpl @@ -0,0 +1,85 @@ +{assign var=admin_title value='支付汇率与对账'} +{include file='admin/static_header.tpl'} + +
+
+

支付汇率与对账

+

按应收币种查看实收金额、美元入账和待核对记录。

+
+ + {if $rate_saved}
应急报价已保存,应用于新建订单。
{/if} +
+

当前行情

+
+ + {foreach $rates as $pair => $rate} + + + + + + + + + + {/foreach} +
币对新单汇率来源源时间 UTC获取时间 UTC有效至 UTC刷新状态
{$pair|escape}{if $rate.current}{$rate.current.rate|escape}{else}暂停新单{/if}{$rate.feed|escape}{if $rate.current && $rate.current.source == 'manual'} · 应急报价{/if}{$rate.source_at_display|escape}{$rate.fetched_at_display|escape}{$rate.valid_until_display|escape}{$rate.error|default:'—'|escape}{if $rate.attempted_at}
{$rate.attempted_at_display|escape}{/if}
+ {if $admin_can_manage} +
+ 设置应急报价 +
+ + + + + +
+
+
+ {/if} +
+ +
+

按币种汇总

+

CNY 和 USDT 汇总新版已验证收款,USD 汇总 Stripe。入账为退款前金额,退款在明细中单列。

+ {if $table_error}
支付对账表不可用,请核对数据库迁移。
{else} +
+ + {foreach $totals as $currency => $total} + + {/foreach} +
收款币种实收入账 USD待核对
{$currency|escape}{$total.received|escape}{$total.credited|escape}{$total.review|escape}
+
+ + + + {if $admin_can_manage}导出 CSV{/if} +
+ {if $asset == 'USD'}

查看 Stripe 订单

{else} +
+ + {foreach $quote_rows as $order} + + + + + + + {foreachelse}{/foreach} +
订单渠道应付 {$asset|escape}实收 {$asset|escape}入账 USD状态退款
{if $admin_can_manage}{$order.order|escape}{else}—{/if}{$order.provider|escape}{$order.quoted|default:'—'|escape}{$order.received|default:'—'|escape}{$order.credited|default:'—'|escape}{if $order.status == 'review'}待核对 {$order.reason|escape} + {elseif $order.status == 'accepted'}已核实收款{else}已报价{/if}{if $order.refund_status != ''} + {$order.refund_status|escape} · {$order.refund_cny|default:'—'|escape} CNY / {$order.refund_usd|escape} USD + {else}—{/if}
暂无符合条件的记录
+ {if $orders}{$orders->links()}{/if} + {/if} + {/if} +
+
+ +{include file='admin/static_footer.tpl'} diff --git a/web/resources/views/venix/admin/paytaro/index.tpl b/web/resources/views/venix/admin/paytaro/index.tpl index c249fce4..2ec5bbde 100644 --- a/web/resources/views/venix/admin/paytaro/index.tpl +++ b/web/resources/views/venix/admin/paytaro/index.tpl @@ -11,12 +11,13 @@

Paytaro 支付

通过官方 MAPI 通道管理支付宝收款、固定回调和本地入账订单。

{if $paytaro_config.paytaro_enabled}已启用{else}未启用{/if} +
支付汇率与对账
全部订单{$paytaro_summary.total}
等待支付{$paytaro_summary.pending}
成功订单{$paytaro_summary.paid}
-
成功入账¥ {$paytaro_summary.paid_amount}
+
已付款单原始面额{$paytaro_summary.paid_amount} USD
@@ -33,6 +34,7 @@
+
@@ -43,7 +45,7 @@ {if $paytaro_table_error != ''}
{$paytaro_table_error|escape}
{/if}
- {if $paytaro_orders}
{foreach $paytaro_orders as $order}{foreachelse}{/foreach}
用户金额状态创建时间
{$order->user_email|default:'已删除用户'|escape}
用户 ID {$order->user_id} · 记录 ID {$order->id}
¥ {$order->amount}{if $order->status == 'creating'}创建中{elseif $order->status == 'pending'}待支付{elseif $order->status == 'paid'}已支付{elseif $order->status == 'failed'}失败{else}{$order->status|escape}{/if}{date('Y-m-d H:i:s', $order->created_at)}
暂无订单
{$paytaro_orders->links()}
{/if} + {if $paytaro_orders}
{foreach $paytaro_orders as $order}{foreachelse}{/foreach}
用户金额状态创建时间
{$order->user_email|default:'已删除用户'|escape}
用户 ID {$order->user_id} · 记录 ID {$order->id}
{$order->amount|escape} USD{if $order->status == 'creating'}创建中{elseif $order->status == 'pending'}待支付{elseif $order->status == 'paid'}已支付{elseif $order->status == 'failed'}失败{else}{$order->status|escape}{/if}{date('Y-m-d H:i:s', $order->created_at)}
暂无订单
{$paytaro_orders->links()}
{/if}
diff --git a/web/resources/views/venix/admin/stripe/index.tpl b/web/resources/views/venix/admin/stripe/index.tpl index 554665b9..fac149cd 100644 --- a/web/resources/views/venix/admin/stripe/index.tpl +++ b/web/resources/views/venix/admin/stripe/index.tpl @@ -11,6 +11,7 @@

Stripe 支付

使用 Stripe 托管 Checkout 收取银行卡和支付宝付款,面板不接触银行卡资料。

{if $stripe_config.stripe_enabled}已启用{else}未启用{/if} +
支付汇率与对账
全部订单{$stripe_summary.total}
diff --git a/web/resources/views/venix/admin/usdt/index.tpl b/web/resources/views/venix/admin/usdt/index.tpl index 027f15b6..daec7f4c 100644 --- a/web/resources/views/venix/admin/usdt/index.tpl +++ b/web/resources/views/venix/admin/usdt/index.tpl @@ -10,12 +10,13 @@

原生 USDT 收款

TRON 地址池、链上订单和到账扫描。

{if $usdt_config.usdt_enabled}已启用{else}未启用{/if} +
支付汇率与对账
全部订单{$usdt_summary.total}
等待到账{$usdt_summary.pending}
成功订单{$usdt_summary.paid}
-
成功入账¥ {$usdt_summary.paid_amount}
+
已付款单原始面额{$usdt_summary.paid_amount} USD
需人工处理的链上记录{$usdt_summary.attention}
@@ -112,7 +113,7 @@ 余额充值
记录 ID {$order->id} {if $order->user_email}{$order->user_email|escape}
用户 ID {$order->user_id}{else}-{/if} - ¥ {$order->amount} + {$order->amount|escape} USD {$order->actual_amount} USDT
{$order->receive_address|escape} {$order->status|escape} {date('Y-m-d H:i:s', $order->created_at)} diff --git a/web/resources/views/venix/admin/yipay/index.tpl b/web/resources/views/venix/admin/yipay/index.tpl index 92ace20e..56c9e66d 100644 --- a/web/resources/views/venix/admin/yipay/index.tpl +++ b/web/resources/views/venix/admin/yipay/index.tpl @@ -11,13 +11,14 @@

易支付

管理支付宝、微信支付连接与本地入账订单。

{if $yipay_config.yipay_enabled}已启用{else}未启用{/if} +
支付汇率与对账
全部订单{$yipay_summary.total}
等待支付{$yipay_summary.pending}
成功订单{$yipay_summary.paid}
已退款{$yipay_summary.refunded}
-
当前净入账¥ {$yipay_summary.paid_amount}
+
已付款单原始面额{$yipay_summary.paid_amount} USD
@@ -69,17 +70,21 @@
- +
- +
+
+ + +
@@ -119,10 +124,22 @@ {$order->user_email|default:'已删除用户'|escape}
用户 ID {$order->user_id} · 记录 ID {$order->id} {if $order->payment_type == 'wxpay'}微信支付{else}支付宝{/if} - ¥ {$order->amount} + {$order->amount|escape} USD + {if $order->reconciliation.received|default:'' != ''}
实收 {$order->reconciliation.received|escape} CNY{/if} + {if $order->reconciliation.credited|default:'' != ''}
入账 {$order->reconciliation.credited|escape} USD{/if} + {if $order->reconciliation.status|default:'' == 'review'}
待核对{/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} {date('Y-m-d H:i:s', $order->created_at)} - {if $order->status == 'paid' && $yipay_refund_available}{else}--{/if} + {if $order->can_refund|default:false && $yipay_refund_available && $admin_can_manage} + + {elseif $order->refund_state|default:'' == 'dispatching' || $order->refund_state|default:'' == 'uncertain'}退款待核对 + {elseif $order->refund_state|default:'' == 'success' && $order->reconciliation.refund_cny|default:'' != ''} + 已退 {$order->reconciliation.refund_cny|escape} CNY
已扣回 {$order->reconciliation.refund_usd|escape} USD + {else}—{/if} + {foreachelse} 暂无订单 @@ -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()) diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index 94125a87..62be36e3 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -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'} diff --git a/web/resources/views/venix/user/paytaro.tpl b/web/resources/views/venix/user/paytaro.tpl index e5415740..71a134d2 100644 --- a/web/resources/views/venix/user/paytaro.tpl +++ b/web/resources/views/venix/user/paytaro.tpl @@ -41,7 +41,9 @@
diff --git a/web/tests/CloudInvoicePaymentResumeTest.php b/web/tests/CloudInvoicePaymentResumeTest.php index 48e8e9e5..b02f6de4 100644 --- a/web/tests/CloudInvoicePaymentResumeTest.php +++ b/web/tests/CloudInvoicePaymentResumeTest.php @@ -1,12 +1,15 @@ '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)); diff --git a/web/tests/CloudInvoicePaymentRuntimeBehaviorTest.mjs b/web/tests/CloudInvoicePaymentRuntimeBehaviorTest.mjs index 21ea805b..592daf82 100644 --- a/web/tests/CloudInvoicePaymentRuntimeBehaviorTest.mjs +++ b/web/tests/CloudInvoicePaymentRuntimeBehaviorTest.mjs @@ -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); diff --git a/web/tests/PaymentCheckoutQuoteTest.php b/web/tests/PaymentCheckoutQuoteTest.php index 8d9427cc..06a4d091 100644 --- a/web/tests/PaymentCheckoutQuoteTest.php +++ b/web/tests/PaymentCheckoutQuoteTest.php @@ -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"; diff --git a/web/tests/PaytaroPaymentServiceTest.php b/web/tests/PaytaroPaymentServiceTest.php index ca352d50..cc64f265 100644 --- a/web/tests/PaytaroPaymentServiceTest.php +++ b/web/tests/PaytaroPaymentServiceTest.php @@ -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&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); }