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/Payment/UsdtPaymentService.php

223 lines
8.4 KiB
PHP

<?php
namespace App\Services\Payment;
use App\Models\Paylist;
use App\Models\User;
use App\Models\UsdtPaymentOrder;
use App\Models\UsdtWallet;
use App\Services\Cloud\CloudInvoicePaymentService;
class UsdtPaymentService
{
public const LEDGER_TYPE = 10006;
private const UNIQUE_AMOUNT_VARIANTS = 50000;
public function createRechargeOrder(User $user, $rawAmount)
{
$this->assertSchemaReady();
$settings = UsdtConfig::runtimeForUser($user);
$amount = $this->validateAmount($rawAmount, $settings['usdt_min_amount']);
$orderNo = $this->orderNo();
return $this->createOrder($orderNo, (int) $user->id, $amount, $settings, []);
}
public function createInvoiceOrder(User $user, $rawAmount, array $businessContext)
{
$this->assertSchemaReady();
$settings = UsdtConfig::runtimeForUser($user);
$amount = $this->validateAmount($rawAmount, $settings['usdt_min_amount']);
$orderNo = $this->orderNo();
return $this->createOrder(
$orderNo, (int) $user->id, $amount, $settings, $businessContext
);
}
public function expire(UsdtPaymentOrder $order)
{
if ((string) $order->status === 'pending' && (int) $order->expires_at < time()) {
$order->status = 'expired';
$order->updated_at = time();
$order->save();
}
return $order;
}
public function details(UsdtPaymentOrder $order)
{
return [
'order_no' => (string) $order->order_no,
'amount' => number_format((float) $order->amount, 2, '.', ''),
'actual_amount' => (string) $order->actual_amount,
'token' => 'USDT',
'network' => 'tron',
'receive_address' => (string) $order->receive_address,
'expires_at' => (int) $order->expires_at,
];
}
private function createOrder($businessOrderNo, $userId, $amount, array $settings,
array $businessContext)
{
$now = time();
$result = null;
$connection = (new UsdtPaymentOrder())->getConnection();
$connection->transaction(function () use (
$businessOrderNo, $userId, $amount, $settings, $businessContext, $now, &$result
) {
$lockedUser = User::where('id', (int) $userId)->lockForUpdate()->first();
if ($lockedUser === null) {
throw new \RuntimeException('支付账户不存在');
}
if ($businessContext !== []) {
CloudInvoicePaymentService::assertInvoicePaymentAllowed($lockedUser);
}
$existing = UsdtPaymentOrder::where('business_type', 'recharge')
->where('business_order_no', $businessOrderNo)
->lockForUpdate()
->first();
if ($existing !== null) {
$result = $existing;
return;
}
$wallet = UsdtWallet::where('enabled', 1)
->orderBy('last_assigned_at', 'asc')
->orderBy('sort', 'asc')
->orderBy('id', 'asc')
->lockForUpdate()
->first();
if ($wallet === null) {
throw new \RuntimeException('USDT 收款地址池没有可用地址');
}
$baseAtomic = $this->amountAtomic($amount, $settings['usdt_cny_per_token']);
[$amountAtomic, $cursor] = $this->allocateAmount($wallet, $baseAtomic);
$paylist = new Paylist();
$paylist->userid = (int) $userId;
$paylist->total = $amount;
$paylist->status = 0;
$paylist->tradeno = $businessOrderNo;
$paylist->datetime = $now;
$paylist->save();
$order = new UsdtPaymentOrder();
$order->order_no = $businessOrderNo;
$order->business_type = 'recharge';
$order->business_order_no = $businessOrderNo;
$order->paylist_id = (int) $paylist->id;
$order->user_id = $userId;
$order->wallet_id = (int) $wallet->id;
$order->amount = $amount;
$order->exchange_rate = $settings['usdt_cny_per_token'];
$order->actual_amount = $this->formatAtomic($amountAtomic);
$order->amount_atomic = $amountAtomic;
$order->currency = 'CNY';
$order->token = 'USDT';
$order->network = 'tron';
$order->contract_address = UsdtConfig::CONTRACT_ADDRESS;
$order->receive_address = (string) $wallet->address;
$order->status = 'pending';
$order->txid = null;
$order->block_number = 0;
$order->block_timestamp = 0;
$order->expires_at = $now + (int) $settings['usdt_order_expire_minutes'] * 60;
$order->paid_at = 0;
$order->created_at = $now;
$order->updated_at = $now;
$order->error_message = '';
$order->save();
CloudInvoicePaymentService::recordAttempt(
$businessContext, $businessOrderNo, $amount, (int) $userId, $now
);
$wallet->allocation_cursor = $cursor;
$wallet->last_assigned_at = $now;
$wallet->updated_at = $now;
$wallet->save();
$result = $order;
}, 3);
return $result;
}
private function allocateAmount(UsdtWallet $wallet, $baseAtomic)
{
$minimum = $baseAtomic + 1;
$maximum = $baseAtomic + self::UNIQUE_AMOUNT_VARIANTS;
$used = UsdtPaymentOrder::where('wallet_id', (int) $wallet->id)
->whereBetween('amount_atomic', [$minimum, $maximum])
->pluck('amount_atomic')
->mapWithKeys(function ($value) {
return [(string) $value => true];
})
->all();
$cursor = max(0, (int) $wallet->allocation_cursor) % self::UNIQUE_AMOUNT_VARIANTS;
for ($attempt = 0; $attempt < self::UNIQUE_AMOUNT_VARIANTS; $attempt++) {
$offset = (($cursor + $attempt) % self::UNIQUE_AMOUNT_VARIANTS) + 1;
$candidate = $baseAtomic + $offset;
if (!isset($used[(string) $candidate])) {
return [$candidate, $offset];
}
}
throw new \RuntimeException('当前收款地址的订单金额编号已用尽,请在地址池中增加新地址');
}
private function amountAtomic($amount, $rate)
{
$cents = $this->scaledInteger($amount, 2);
$rateScaled = $this->scaledInteger($rate, 4);
if ($cents <= 0 || $rateScaled <= 0) {
throw new \InvalidArgumentException('USDT 订单金额或汇率无效');
}
$numerator = $cents * 100000000;
return intdiv($numerator + $rateScaled - 1, $rateScaled);
}
private function scaledInteger($value, $scale)
{
$value = trim((string) $value);
if (!preg_match('/^(\d+)(?:\.(\d+))?$/', $value, $matches)) {
return 0;
}
$fraction = substr(str_pad($matches[2] ?? '', $scale, '0'), 0, $scale);
return (int) $matches[1] * (10 ** $scale) + (int) $fraction;
}
private function formatAtomic($atomic)
{
return intdiv((int) $atomic, 1000000) . '.' . str_pad((string) ((int) $atomic % 1000000), 6, '0', STR_PAD_LEFT);
}
private function validateAmount($rawAmount, $minimum)
{
$rawAmount = trim((string) $rawAmount);
if (!preg_match('/^\d{1,7}(?:\.\d{1,2})?$/', $rawAmount)) {
throw new \InvalidArgumentException('请输入正确的充值金额,最多保留两位小数');
}
$amount = UsdtConfig::money($rawAmount);
if ((float) $amount < (float) $minimum) {
throw new \InvalidArgumentException('最低充值金额为 $' . UsdtConfig::money($minimum));
}
if ((float) $amount > 9999999.99) {
throw new \InvalidArgumentException('充值金额超过允许范围');
}
return $amount;
}
private function orderNo()
{
return 'US' . date('YmdHis') . strtoupper(bin2hex(random_bytes(8)));
}
private function assertSchemaReady()
{
$connection = (new UsdtPaymentOrder())->getConnection();
foreach (['usdt_wallets', 'usdt_payment_orders', 'usdt_chain_transactions'] as $table) {
if (!$connection->getSchemaBuilder()->hasTable($table)) {
throw new \RuntimeException('请先导入 sql/usdt_native_payment.sql');
}
}
}
}