|
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace App\Services\Payment;
|
|
|
|
|
|
|
|
|
|
use App\Models\CloudInvoicePayment;
|
|
|
|
|
use App\Models\Paylist;
|
|
|
|
|
use App\Models\UsdtChainTransaction;
|
|
|
|
|
use App\Models\UsdtPaymentOrder;
|
|
|
|
|
use App\Models\UsdtWallet;
|
|
|
|
|
use App\Services\Cloud\CloudInvoicePaymentService;
|
|
|
|
|
|
|
|
|
|
class UsdtScannerService
|
|
|
|
|
{
|
|
|
|
|
private const RECOVERY_LOOKBACK_SECONDS = 86400;
|
|
|
|
|
|
|
|
|
|
public function run($walletLimit = 50)
|
|
|
|
|
{
|
|
|
|
|
$settings = UsdtConfig::runtime(false);
|
|
|
|
|
$walletLimit = max(1, min(100, (int) $walletLimit));
|
|
|
|
|
$now = time();
|
|
|
|
|
$stats = [
|
|
|
|
|
'wallets' => 0,
|
|
|
|
|
'transfers' => 0,
|
|
|
|
|
'credited' => 0,
|
|
|
|
|
'unmatched' => 0,
|
|
|
|
|
'duplicates' => 0,
|
|
|
|
|
'errors' => 0,
|
|
|
|
|
'expired' => 0,
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
$stats['expired'] = UsdtPaymentOrder::where('status', 'pending')
|
|
|
|
|
->where('business_type', 'recharge')
|
|
|
|
|
->where('expires_at', '<', $now)
|
|
|
|
|
->update(['status' => 'expired', 'updated_at' => $now]);
|
|
|
|
|
|
|
|
|
|
$walletIds = UsdtPaymentOrder::whereIn('status', ['pending', 'expired'])
|
|
|
|
|
->where('business_type', 'recharge')
|
|
|
|
|
->where('expires_at', '>=', $now - self::RECOVERY_LOOKBACK_SECONDS)
|
|
|
|
|
->distinct()
|
|
|
|
|
->limit($walletLimit)
|
|
|
|
|
->pluck('wallet_id')
|
|
|
|
|
->all();
|
|
|
|
|
if ($walletIds === []) {
|
|
|
|
|
return $stats;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$wallets = UsdtWallet::whereIn('id', $walletIds)
|
|
|
|
|
->orderBy('id', 'asc')
|
|
|
|
|
->get();
|
|
|
|
|
$client = $this->client($settings);
|
|
|
|
|
foreach ($wallets as $wallet) {
|
|
|
|
|
$stats['wallets']++;
|
|
|
|
|
try {
|
|
|
|
|
$this->retryStoredEvents($wallet, $settings, $stats);
|
|
|
|
|
$earliest = UsdtPaymentOrder::where('wallet_id', (int) $wallet->id)
|
|
|
|
|
->where('business_type', 'recharge')
|
|
|
|
|
->whereIn('status', ['pending', 'expired'])
|
|
|
|
|
->where('expires_at', '>=', $now - self::RECOVERY_LOOKBACK_SECONDS)
|
|
|
|
|
->min('created_at');
|
|
|
|
|
if ($earliest === null) {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$minimum = max(0, (int) $earliest - 120);
|
|
|
|
|
if ((int) $wallet->last_scanned_at > 0) {
|
|
|
|
|
$minimum = max($minimum, (int) $wallet->last_scanned_at - 300);
|
|
|
|
|
}
|
|
|
|
|
$transfers = $client->transfersTo(
|
|
|
|
|
(string) $wallet->address,
|
|
|
|
|
$minimum * 1000,
|
|
|
|
|
($now + 30) * 1000
|
|
|
|
|
);
|
|
|
|
|
foreach ($transfers as $rawTransfer) {
|
|
|
|
|
$stats['transfers']++;
|
|
|
|
|
try {
|
|
|
|
|
$event = $this->recordTransfer($wallet, $rawTransfer, $now);
|
|
|
|
|
if ($event === null) {
|
|
|
|
|
$stats['duplicates']++;
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
$this->settleEvent($wallet, $event, $settings, $stats);
|
|
|
|
|
} catch (\Throwable $exception) {
|
|
|
|
|
$stats['errors']++;
|
|
|
|
|
error_log('USDT transfer processing failed: ' . $exception->getMessage());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$wallet->last_scanned_at = $now;
|
|
|
|
|
$wallet->last_error = '';
|
|
|
|
|
$wallet->updated_at = $now;
|
|
|
|
|
$wallet->save();
|
|
|
|
|
} catch (\Throwable $exception) {
|
|
|
|
|
$stats['errors']++;
|
|
|
|
|
$wallet->last_error = mb_substr($exception->getMessage(), 0, 500);
|
|
|
|
|
$wallet->updated_at = time();
|
|
|
|
|
$wallet->save();
|
|
|
|
|
error_log('USDT wallet scan failed for ' . (string) $wallet->address . ': ' . $exception->getMessage());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return $stats;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected function client(array $settings)
|
|
|
|
|
{
|
|
|
|
|
return new TronGridClient($settings);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private function retryStoredEvents(UsdtWallet $wallet, array $settings, array &$stats)
|
|
|
|
|
{
|
|
|
|
|
$events = UsdtChainTransaction::where('to_address', (string) $wallet->address)
|
|
|
|
|
->whereIn('status', ['detected', 'error'])
|
|
|
|
|
->orderBy('id', 'asc')
|
|
|
|
|
->limit(100)
|
|
|
|
|
->get();
|
|
|
|
|
foreach ($events as $event) {
|
|
|
|
|
try {
|
|
|
|
|
$this->settleEvent($wallet, $event, $settings, $stats);
|
|
|
|
|
} catch (\Throwable $exception) {
|
|
|
|
|
$stats['errors']++;
|
|
|
|
|
error_log('USDT stored event retry failed: ' . $exception->getMessage());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private function recordTransfer(UsdtWallet $wallet, array $raw, $now)
|
|
|
|
|
{
|
|
|
|
|
$transfer = $this->normalizeTransfer($wallet, $raw);
|
|
|
|
|
$existing = UsdtChainTransaction::where('event_key', $transfer['event_key'])->first();
|
|
|
|
|
if ($existing !== null) {
|
|
|
|
|
if (in_array((string) $existing->status, ['detected', 'error'], true)) {
|
|
|
|
|
return $existing;
|
|
|
|
|
}
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$event = new UsdtChainTransaction();
|
|
|
|
|
$event->event_key = $transfer['event_key'];
|
|
|
|
|
$event->txid = $transfer['txid'];
|
|
|
|
|
$event->contract_address = UsdtConfig::CONTRACT_ADDRESS;
|
|
|
|
|
$event->from_address = $transfer['from_address'];
|
|
|
|
|
$event->to_address = $transfer['to_address'];
|
|
|
|
|
$event->amount_atomic = $transfer['amount_atomic'];
|
|
|
|
|
$event->block_number = $transfer['block_number'];
|
|
|
|
|
$event->block_timestamp = $transfer['block_timestamp'];
|
|
|
|
|
$event->payload = $transfer['payload'];
|
|
|
|
|
$event->status = 'detected';
|
|
|
|
|
$event->order_no = null;
|
|
|
|
|
$event->detected_at = $now;
|
|
|
|
|
$event->processed_at = 0;
|
|
|
|
|
$event->error_message = '';
|
|
|
|
|
try {
|
|
|
|
|
$event->save();
|
|
|
|
|
} catch (\Throwable $exception) {
|
|
|
|
|
$existing = UsdtChainTransaction::where('event_key', $transfer['event_key'])->first();
|
|
|
|
|
if ($existing !== null) {
|
|
|
|
|
return in_array((string) $existing->status, ['detected', 'error'], true) ? $existing : null;
|
|
|
|
|
}
|
|
|
|
|
throw $exception;
|
|
|
|
|
}
|
|
|
|
|
return $event;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private function normalizeTransfer(UsdtWallet $wallet, array $raw)
|
|
|
|
|
{
|
|
|
|
|
$txid = strtolower(trim((string) ($raw['transaction_id'] ?? '')));
|
|
|
|
|
$from = trim((string) ($raw['from'] ?? ''));
|
|
|
|
|
$to = trim((string) ($raw['to'] ?? ''));
|
|
|
|
|
$value = trim((string) ($raw['value'] ?? ''));
|
|
|
|
|
$timestamp = $raw['block_timestamp'] ?? null;
|
|
|
|
|
$contract = trim((string) ($raw['token_info']['address'] ?? ''));
|
|
|
|
|
$decimals = $raw['token_info']['decimals'] ?? null;
|
|
|
|
|
if (!preg_match('/^[a-f0-9]{64}$/', $txid)
|
|
|
|
|
|| !TronAddress::isValid($from)
|
|
|
|
|
|| $to !== (string) $wallet->address
|
|
|
|
|
|| $contract !== UsdtConfig::CONTRACT_ADDRESS
|
|
|
|
|
|| (int) $decimals !== 6
|
|
|
|
|
|| !ctype_digit($value)
|
|
|
|
|
|| strlen($value) > 18
|
|
|
|
|
|| !is_numeric($timestamp)) {
|
|
|
|
|
throw new \RuntimeException('TRON API 返回了不符合 USDT TRC20 规则的交易');
|
|
|
|
|
}
|
|
|
|
|
$amountAtomic = (int) $value;
|
|
|
|
|
$timestamp = (int) $timestamp;
|
|
|
|
|
if ($amountAtomic <= 0 || $timestamp <= 0) {
|
|
|
|
|
throw new \RuntimeException('TRON API 返回的交易金额或时间无效');
|
|
|
|
|
}
|
|
|
|
|
$payload = json_encode($raw, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE);
|
|
|
|
|
if (!is_string($payload) || strlen($payload) > 65535) {
|
|
|
|
|
throw new \RuntimeException('TRON API 交易记录无法安全保存');
|
|
|
|
|
}
|
|
|
|
|
return [
|
|
|
|
|
'event_key' => hash('sha256', implode('|', [$txid, $contract, $from, $to, $value, $timestamp])),
|
|
|
|
|
'txid' => $txid,
|
|
|
|
|
'from_address' => $from,
|
|
|
|
|
'to_address' => $to,
|
|
|
|
|
'amount_atomic' => $amountAtomic,
|
|
|
|
|
'block_number' => max(0, (int) ($raw['block_number'] ?? $raw['block'] ?? 0)),
|
|
|
|
|
'block_timestamp' => $timestamp,
|
|
|
|
|
'payload' => $payload,
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private function settleEvent(UsdtWallet $wallet, UsdtChainTransaction $event, array $settings, array &$stats)
|
|
|
|
|
{
|
|
|
|
|
if (!in_array((string) $event->status, ['detected', 'error'], true)) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
$blockTime = (int) floor((int) $event->block_timestamp / 1000);
|
|
|
|
|
$graceSeconds = (int) $settings['usdt_late_grace_minutes'] * 60;
|
|
|
|
|
$order = UsdtPaymentOrder::where('wallet_id', (int) $wallet->id)
|
|
|
|
|
->where('business_type', 'recharge')
|
|
|
|
|
->where('amount_atomic', (int) $event->amount_atomic)
|
|
|
|
|
->whereIn('status', ['pending', 'expired'])
|
|
|
|
|
->where('created_at', '<=', $blockTime + 30)
|
|
|
|
|
->where('expires_at', '>=', $blockTime - $graceSeconds)
|
|
|
|
|
->orderBy('id', 'desc')
|
|
|
|
|
->first();
|
|
|
|
|
if ($order === null) {
|
|
|
|
|
$event->status = 'unmatched';
|
|
|
|
|
$event->processed_at = time();
|
|
|
|
|
$event->error_message = '未找到地址、金额和支付时间窗均匹配的订单';
|
|
|
|
|
$event->save();
|
|
|
|
|
$stats['unmatched']++;
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
if ((string) $order->receive_address !== (string) $event->to_address
|
|
|
|
|
|| (string) $order->contract_address !== UsdtConfig::CONTRACT_ADDRESS) {
|
|
|
|
|
throw new \RuntimeException('USDT 订单的收款地址或代币合约与链上事件不一致');
|
|
|
|
|
}
|
|
|
|
|
if (UsdtPaymentOrder::where('txid', (string) $event->txid)
|
|
|
|
|
->where('id', '<>', (int) $order->id)
|
|
|
|
|
->exists()) {
|
|
|
|
|
throw new \RuntimeException('链上交易已绑定其他 USDT 订单');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
if ((string) $order->business_type === 'recharge') {
|
|
|
|
|
$outcome = $this->settleRecharge($order, $event);
|
|
|
|
|
$stats[match ($outcome) {
|
|
|
|
|
'credited' => 'credited',
|
|
|
|
|
'duplicate' => 'duplicates',
|
|
|
|
|
'unmatched' => 'unmatched',
|
|
|
|
|
default => throw new \RuntimeException('USDT 结算结果无效'),
|
|
|
|
|
}]++;
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
throw new \RuntimeException('USDT 订单业务类型无效');
|
|
|
|
|
} catch (\Throwable $exception) {
|
|
|
|
|
$event->status = 'error';
|
|
|
|
|
$event->error_message = mb_substr($exception->getMessage(), 0, 500);
|
|
|
|
|
$event->save();
|
|
|
|
|
throw $exception;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private function settleRecharge(UsdtPaymentOrder $sourceOrder, UsdtChainTransaction $sourceEvent)
|
|
|
|
|
{
|
|
|
|
|
$credited = false;
|
|
|
|
|
$connection = $sourceOrder->getConnection();
|
|
|
|
|
$connection->transaction(function () use ($sourceOrder, $sourceEvent, &$credited) {
|
|
|
|
|
$order = UsdtPaymentOrder::where('id', (int) $sourceOrder->id)->lockForUpdate()->first();
|
|
|
|
|
$event = UsdtChainTransaction::where('id', (int) $sourceEvent->id)->lockForUpdate()->first();
|
|
|
|
|
if ($order === null || $event === null) {
|
|
|
|
|
throw new \RuntimeException('USDT 充值订单或链上事件不存在');
|
|
|
|
|
}
|
|
|
|
|
if ((string) $order->status === 'paid') {
|
|
|
|
|
$sameTransaction = (string) $order->txid !== ''
|
|
|
|
|
&& hash_equals((string) $order->txid, (string) $event->txid);
|
|
|
|
|
$event->status = $sameTransaction ? 'credited' : 'unmatched';
|
|
|
|
|
$event->order_no = $sameTransaction ? (string) $order->order_no : null;
|
|
|
|
|
$event->processed_at = time();
|
|
|
|
|
$event->error_message = $sameTransaction ? ''
|
|
|
|
|
: '同额订单已由另一笔链上交易结算,请人工核对';
|
|
|
|
|
$event->save();
|
|
|
|
|
$credited = $sameTransaction ? 'duplicate' : 'unmatched';
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$paylist = Paylist::where('id', (int) $order->paylist_id)->lockForUpdate()->first();
|
|
|
|
|
if ($paylist === null
|
|
|
|
|
|| (string) $paylist->tradeno !== (string) $order->business_order_no
|
|
|
|
|
|| (int) $paylist->userid !== (int) $order->user_id) {
|
|
|
|
|
throw new \RuntimeException('USDT 关联充值订单无效');
|
|
|
|
|
}
|
|
|
|
|
$walletCredited = RechargeCreditService::creditLocked(
|
|
|
|
|
$paylist, UsdtPaymentService::LEDGER_TYPE);
|
|
|
|
|
if (CloudInvoicePayment::where('provider', 'usdt')
|
|
|
|
|
->where('provider_order_no', (string) $order->order_no)->exists()) {
|
|
|
|
|
CloudInvoicePaymentService::settleForProvider('usdt', (string) $order->order_no);
|
|
|
|
|
}
|
|
|
|
|
$this->applyChainResult($order, $event, 'paid', 'credited');
|
|
|
|
|
$credited = $walletCredited ? 'credited' : 'duplicate';
|
|
|
|
|
}, 3);
|
|
|
|
|
return $credited;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private function applyChainResult(UsdtPaymentOrder $order, UsdtChainTransaction $event, $orderStatus, $eventStatus)
|
|
|
|
|
{
|
|
|
|
|
$now = time();
|
|
|
|
|
$order->txid = (string) $event->txid;
|
|
|
|
|
$order->block_number = (int) $event->block_number;
|
|
|
|
|
$order->block_timestamp = (int) $event->block_timestamp;
|
|
|
|
|
$order->status = $orderStatus;
|
|
|
|
|
$order->paid_at = $now;
|
|
|
|
|
$order->updated_at = $now;
|
|
|
|
|
$order->error_message = '';
|
|
|
|
|
$order->save();
|
|
|
|
|
|
|
|
|
|
$event->status = $eventStatus;
|
|
|
|
|
$event->order_no = (string) $order->order_no;
|
|
|
|
|
$event->processed_at = $now;
|
|
|
|
|
$event->error_message = '';
|
|
|
|
|
$event->save();
|
|
|
|
|
}
|
|
|
|
|
}
|