You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Cloud/CloudInvoicePaymentService.php

398 lines
19 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudInvoice;
use App\Models\CloudInvoicePayment;
use App\Models\CloudInstance;
use App\Models\CloudOrder;
use App\Models\PaytaroOrder;
use App\Models\UsdtPaymentOrder;
use App\Models\User;
use App\Models\YipayOrder;
use App\Services\Config;
use App\Services\Payment\PaytaroConfig;
use App\Services\Payment\PaytaroPaymentService;
use App\Services\Payment\UsdtConfig;
use App\Services\Payment\UsdtPaymentService;
use App\Services\Payment\YipayConfig;
use App\Services\Payment\YipayPaymentService;
use App\Services\UserFeatureRestrictionService;
final class CloudInvoicePaymentService
{
/**
* Recheck the account at the final, row-locked provider-order boundary.
*
* The controller performs the same validation for a useful early error,
* but an administrator can change account restrictions before the payment
* provider's transaction begins. Each provider calls this method after it
* locks the user row so a disabled account cannot still receive a real
* external payment order through that race window.
*/
public static function assertInvoicePaymentAllowed(User $user): void
{
if ((int) $user->enable !== 1) {
throw new CloudError('账户不存在或不可用', 403);
}
if (UserFeatureRestrictionService::isBalancePurchaseRestricted($user)) {
throw new CloudError(UserFeatureRestrictionService::PURCHASE_MESSAGE, 403);
}
if (UserFeatureRestrictionService::isRechargeRestricted($user)) {
throw new CloudError(UserFeatureRestrictionService::RECHARGE_MESSAGE, 403);
}
}
public static function methods(User $user): array
{
if (UserFeatureRestrictionService::isRechargeRestricted($user)
|| UserFeatureRestrictionService::isBalancePurchaseRestricted($user)) {
return [];
}
$methods = [];
foreach (YipayConfig::visibleMethods($user) as $method) {
$methods[] = ['id' => 'yipay_' . $method,
'name' => $method === 'wxpay' ? '易支付 · 微信' : '易支付 · 支付宝'];
}
if (PaytaroConfig::isUserVisible($user)) {
$methods[] = ['id' => 'paytaro', 'name' => 'Paytaro · 支付宝'];
}
if (UsdtConfig::isUserVisible($user)) {
$methods[] = ['id' => 'usdt', 'name' => 'USDT-TRC20'];
}
return $methods;
}
public static function create(CloudInvoice $invoice, User $user, array $input,
string $clientIp, string $userAgent): array
{
CloudInput::only($input, ['method', 'idempotency_key']);
if (UserFeatureRestrictionService::isBalancePurchaseRestricted($user)) {
throw new CloudError(UserFeatureRestrictionService::PURCHASE_MESSAGE, 403);
}
if (UserFeatureRestrictionService::isRechargeRestricted($user)) {
throw new CloudError(UserFeatureRestrictionService::RECHARGE_MESSAGE, 403);
}
$validated = (new CloudInstance())->getConnection()->transaction(
function () use ($invoice, $user) {
$lockedUser = User::where('id', $user->id)->lockForUpdate()->first();
if ($lockedUser === null || (int) $lockedUser->enable !== 1) {
return ['error' => '账户不存在或不可用', 'status' => 403];
}
if (UserFeatureRestrictionService::isBalancePurchaseRestricted($lockedUser)) {
return ['error' => UserFeatureRestrictionService::PURCHASE_MESSAGE,
'status' => 403];
}
if (UserFeatureRestrictionService::isRechargeRestricted($lockedUser)) {
return ['error' => UserFeatureRestrictionService::RECHARGE_MESSAGE,
'status' => 403];
}
if ((string) ($invoice->purpose ?: 'renewal') === 'provision') {
$current = CloudInvoice::where('id', $invoice->id)
->where('user_id', $user->id)->lockForUpdate()->first();
if ($current === null) {
return ['error' => '账单不存在', 'status' => 404];
}
$order = CloudOrder::where('id', $current->order_id)
->where('user_id', $user->id)->lockForUpdate()->first();
if (!in_array((string) $current->status, ['open', 'overdue'], true)
|| self::provisionUnavailable($current, $order)) {
return ['error' => '账单已失效,请重新提交开通请求',
'status' => 409];
}
return ['invoice' => $current];
}
// Lock in the same instance -> invoice order as lifecycle. If
// the three-day cutoff wins, no new provider order is opened;
// if payment validation wins, final settlement still rechecks
// the cutoff before consuming credited wallet funds.
$instance = CloudInstance::where('id', $invoice->instance_id)
->where('user_id', $user->id)->lockForUpdate()->first();
$current = CloudInvoice::where('id', $invoice->id)
->where('user_id', $user->id)->lockForUpdate()->first();
if ($current === null) {
return ['error' => '账单不存在', 'status' => 404];
}
if (!in_array((string) $current->status, ['open', 'overdue'], true)) {
return ['error' => '账单已结清或不可支付', 'status' => 409];
}
if ($instance === null || CloudInvoiceService::instanceDeleting($instance)
|| CloudInvoiceService::paymentDeadlinePassed($current)) {
$current->status = 'expired';
$current->updated_at = time();
$current->save();
return ['error' => '账单已超过支付宽限期,实例正在删除',
'status' => 409];
}
if ($instance->expires_at === null
|| (int) $instance->expires_at !== (int) $current->renews_expires_at
|| $instance->renewal_price === null
|| CloudMoney::cents((string) $instance->renewal_price)
!== CloudMoney::cents((string) $current->amount)
|| (int) $instance->renewal_days !== (int) $current->validity_days
|| (int) $instance->renewal_traffic_bytes
!== (int) $current->traffic_quota_bytes) {
$current->status = 'void';
$current->updated_at = time();
$current->save();
return ['error' => '账单已失效,请刷新账单列表',
'status' => 409];
}
return ['invoice' => $current];
}, 3);
if (isset($validated['error'])) {
throw new CloudError($validated['error'], (int) $validated['status']);
}
$invoice = $validated['invoice'];
$method = strtolower(trim((string) ($input['method'] ?? '')));
$allowed = array_column(self::methods($user), 'id');
if (!in_array($method, $allowed, true)) {
throw new CloudError('所选在线支付方式不可用', 409);
}
$idempotency = trim((string) ($input['idempotency_key'] ?? ''));
if (preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $idempotency) !== 1) {
throw new CloudError('支付请求标识无效');
}
$existing = CloudInvoicePayment::where('user_id', $user->id)
->where('idempotency_key', $idempotency)->first();
if ($existing !== null) {
if ((int) $existing->invoice_id !== (int) $invoice->id
|| (string) $existing->provider !== $method) {
throw new CloudError('同一支付请求标识不能用于其他账单或渠道', 409);
}
$existing = self::recoverCreatingAttempt($existing);
if ((string) $existing->status === 'creating') {
throw new CloudError('支付订单正在创建,请稍后刷新账单再试', 409);
}
if ((string) $existing->status === 'failed') {
throw new CloudError('上次支付订单创建失败,请重新发起支付', 409);
}
return self::display($existing);
}
$baseUrl = rtrim((string) Config::get('baseUrl', ''), '/');
if (filter_var($baseUrl, FILTER_VALIDATE_URL) === false
|| preg_match('#^https://#i', $baseUrl) !== 1) {
throw new CloudError('站点 HTTPS 地址未正确配置,不能创建在线支付', 409);
}
$context = ['invoice_id' => (int) $invoice->id,
'idempotency_key' => $idempotency, 'provider' => $method];
try {
if (str_starts_with($method, 'yipay_')) {
$order = (new YipayPaymentService())->createOrder($user, (string) $invoice->amount,
substr($method, 6), $clientIp, $userAgent, $baseUrl, $context);
} elseif ($method === 'paytaro') {
$order = (new PaytaroPaymentService())->createOrder($user, (string) $invoice->amount,
$clientIp, $userAgent, $baseUrl, $context);
} else {
$order = (new UsdtPaymentService())->createInvoiceOrder(
$user, (string) $invoice->amount, $context);
}
CloudInvoicePayment::where('user_id', $user->id)
->where('idempotency_key', $idempotency)->where('status', 'creating')
->update(['status' => 'pending', 'updated_at' => time()]);
} catch (\Throwable $error) {
// A concurrent request with the same idempotency key may have won
// the unique insert. Never mutate that request's attempt here.
$winner = CloudInvoicePayment::where('user_id', $user->id)
->where('idempotency_key', $idempotency)->first();
if ($winner !== null) {
if ((int) $winner->invoice_id !== (int) $invoice->id
|| (string) $winner->provider !== $method) {
throw new CloudError('同一支付请求标识不能用于其他账单或渠道', 409);
}
$winner = self::recoverCreatingAttempt($winner);
if (!in_array((string) $winner->status, ['creating', 'failed'], true)) {
return self::display($winner);
}
if ((string) $winner->status === 'creating') {
throw new CloudError('支付订单正在创建,请稍后刷新账单再试', 409);
}
}
throw $error;
}
$payment = CloudInvoicePayment::where('user_id', $user->id)
->where('idempotency_key', $idempotency)->first();
if ($payment === null) {
throw new \RuntimeException('在线支付关联记录创建失败');
}
return self::display($payment);
}
private static function provisionUnavailable(CloudInvoice $invoice,
?CloudOrder $order): bool
{
return $order === null
|| (string) $order->status !== 'awaiting_payment'
|| CloudInvoiceService::paymentDeadlinePassed($invoice)
|| (int) $order->plan_id !== (int) $invoice->plan_id
|| CloudMoney::cents((string) $order->amount)
!== CloudMoney::cents((string) $invoice->amount);
}
private static function recoverCreatingAttempt(
CloudInvoicePayment $payment
): CloudInvoicePayment {
if (!in_array((string) $payment->status, ['creating', 'pending'], true)) {
return $payment;
}
$provider = (string) $payment->provider;
if (str_starts_with($provider, 'yipay_')) {
$providerStatus = YipayOrder::where(
'order_no', $payment->provider_order_no
)->value('status');
} elseif ($provider === 'paytaro') {
$providerStatus = PaytaroOrder::where(
'order_no', $payment->provider_order_no
)->value('status');
} else {
$providerStatus = UsdtPaymentOrder::where(
'order_no', $payment->provider_order_no
)->value('status');
}
if (in_array((string) $providerStatus, ['pending', 'paid'], true)) {
CloudInvoicePayment::where('id', $payment->id)
->where('status', 'creating')
->update(['status' => 'pending', 'updated_at' => time()]);
} elseif (in_array((string) $providerStatus, ['failed', 'expired'], true)) {
CloudInvoicePayment::where('id', $payment->id)
->whereIn('status', ['creating', 'pending'])
->update(['status' => 'failed', 'updated_at' => time()]);
}
return $payment->fresh() ?? $payment;
}
public static function recordAttempt(array $context, string $orderNo, string $amount,
int $userId, int $now): void
{
if ($context === []) {
return;
}
$provider = (string) ($context['provider'] ?? '');
$idempotency = (string) ($context['idempotency_key'] ?? '');
$invoiceId = (int) ($context['invoice_id'] ?? 0);
if ($invoiceId < 1 || !in_array($provider,
['yipay_alipay', 'yipay_wxpay', 'paytaro', 'usdt'], true)
|| preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $idempotency) !== 1) {
throw new \RuntimeException('账单支付上下文无效');
}
// The gateway services call this inside the same transaction that
// persists their local order, immediately before any remote request.
// Re-lock the billing state here so lifecycle cannot cross the grace
// cutoff between the controller's early validation and creation of a
// real provider order.
$source = CloudInvoice::where('id', $invoiceId)
->where('user_id', $userId)->first();
if ($source === null) {
throw new CloudError('账单不存在', 404);
}
if ((string) ($source->purpose ?: 'renewal') === 'provision') {
$invoice = CloudInvoice::where('id', $invoiceId)
->where('user_id', $userId)->lockForUpdate()->first();
$order = $invoice === null ? null : CloudOrder::where('id', $invoice->order_id)
->where('user_id', $userId)->lockForUpdate()->first();
if ($invoice === null || !in_array((string) $invoice->status,
['open', 'overdue'], true)) {
throw new CloudError('账单已结清或不可支付', 409);
}
if (self::provisionUnavailable($invoice, $order)) {
throw new CloudError('账单已失效,请重新提交开通请求', 409);
}
self::saveAttempt($invoiceId, $provider, $orderNo, $idempotency,
$amount, $userId, $now);
return;
}
$instance = CloudInstance::where('id', (int) $source->instance_id)
->where('user_id', $userId)->lockForUpdate()->first();
$invoice = CloudInvoice::where('id', $invoiceId)
->where('user_id', $userId)->lockForUpdate()->first();
if ($invoice === null || !in_array((string) $invoice->status,
['open', 'overdue'], true)) {
throw new CloudError('账单已结清或不可支付', 409);
}
if ($instance === null || CloudInvoiceService::instanceDeleting($instance)
|| CloudInvoiceService::paymentDeadlinePassed($invoice)
|| $instance->expires_at === null
|| (int) $instance->expires_at !== (int) $invoice->renews_expires_at
|| $instance->renewal_price === null
|| CloudMoney::cents((string) $instance->renewal_price)
!== CloudMoney::cents((string) $invoice->amount)
|| (int) $instance->renewal_days !== (int) $invoice->validity_days
|| (int) $instance->renewal_traffic_bytes
!== (int) $invoice->traffic_quota_bytes) {
throw new CloudError('账单已失效,请刷新账单列表', 409);
}
self::saveAttempt($invoiceId, $provider, $orderNo, $idempotency,
$amount, $userId, $now);
}
private static function saveAttempt(int $invoiceId, string $provider,
string $orderNo, string $idempotency, string $amount, int $userId,
int $now): void
{
$payment = new CloudInvoicePayment();
$payment->invoice_id = $invoiceId;
$payment->user_id = $userId;
$payment->provider = $provider;
$payment->provider_order_no = $orderNo;
$payment->idempotency_key = $idempotency;
$payment->amount = $amount;
$payment->status = 'creating';
$payment->created_at = $payment->updated_at = $now;
$payment->save();
}
public static function settleForProvider(string $provider, string $orderNo): ?string
{
$payment = CloudInvoicePayment::where('provider', $provider)
->where('provider_order_no', $orderNo)->lockForUpdate()->first();
if ($payment === null) {
return null;
}
if (in_array((string) $payment->status, ['paid_invoice', 'credited_balance'], true)) {
return (string) $payment->status;
}
return CloudInvoiceService::settleCreditedPayment($payment);
}
public static function display(CloudInvoicePayment $payment): array
{
$provider = (string) $payment->provider;
$result = [
'id' => (string) $payment->id,
'invoice_id' => (string) $payment->invoice_id,
'method' => $provider,
'status' => (string) $payment->status,
'amount' => (string) $payment->amount,
'poll_url' => '/api/v1/invoices/' . (int) $payment->invoice_id,
];
if (str_starts_with($provider, 'yipay_')) {
$order = YipayOrder::where('order_no', $payment->provider_order_no)->first();
if ($order === null) {
throw new CloudError('在线支付订单不存在', 404);
}
return array_merge($result, ['payment_kind' => (string) $order->payment_kind,
'payment_value' => (string) $order->payment_value,
'label' => $provider === 'yipay_wxpay'
? '易支付 · 微信' : '易支付 · 支付宝']);
}
if ($provider === 'paytaro') {
$order = PaytaroOrder::where('order_no', $payment->provider_order_no)->first();
if ($order === null) {
throw new CloudError('在线支付订单不存在', 404);
}
return array_merge($result, ['payment_kind' => (string) $order->payment_kind,
'payment_value' => (string) $order->payment_value,
'label' => 'Paytaro · 支付宝']);
}
$order = UsdtPaymentOrder::where('order_no', $payment->provider_order_no)->first();
if ($order === null) {
throw new CloudError('USDT 支付订单不存在', 404);
}
return array_merge($result, ['payment_kind' => 'usdt', 'label' => 'USDT-TRC20',
'actual_amount' => (string) $order->actual_amount,
'receive_address' => (string) $order->receive_address,
'expires_at' => (int) $order->expires_at]);
}
}