RechargeService.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. <?php
  2. namespace App\Services;
  3. use App\Services\BaseService;
  4. use App\Models\Collect;
  5. use App\Models\Recharge;
  6. use App\Models\User;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Collection;
  9. use Illuminate\Support\Facades\Cache;
  10. use Illuminate\Support\Facades\Log;
  11. use App\Services\WalletService;
  12. use App\Services\CollectService;
  13. use App\Services\UserService;
  14. use App\Services\BalanceLogService;
  15. use App\Helpers\TronHelper;
  16. use App\Models\Config;
  17. use App\Services\AdminRealtime\AdminRealtime;
  18. use App\Support\MemberAccount;
  19. /**
  20. * 用户充值记录
  21. */
  22. class RechargeService extends BaseService
  23. {
  24. public static string $MODEL = Recharge::class;
  25. const PENDING_SYNC_CACHE_KEY = 'usdt_recharge_pending_sync_members';
  26. const RECENT_ACTIVE_SYNC_CACHE_KEY = 'usdt_recharge_recent_active_synced_at';
  27. const TRONGRID_SYNC_LOCK_KEY = 'usdt_recharge_trongrid_sync_lock';
  28. const ADDRESS_SYNC_CACHE_PREFIX = 'usdt_recharge_address_synced_at:';
  29. const PENDING_SYNC_TTL = 7200;
  30. const ADDRESS_SYNC_COOLDOWN = 60;
  31. const TRONGRID_SYNC_LOCK_SECONDS = 2;
  32. const SYNC_BATCH_SIZE = 1;
  33. const RECENT_ACTIVE_MINUTES = 30;
  34. const RECENT_ACTIVE_LIMIT = 20;
  35. const RECENT_ACTIVE_ENQUEUE_INTERVAL = 300;
  36. /**
  37. * @description: 模型
  38. * @return {string}
  39. */
  40. public static function model(): string
  41. {
  42. return Recharge::class;
  43. }
  44. /**
  45. * @description: 枚举
  46. * @return {*}
  47. */
  48. public static function enum(): string
  49. {
  50. return '';
  51. }
  52. /**
  53. * @description: 获取查询条件
  54. * @param {array} $search 查询内容
  55. * @return {array}
  56. */
  57. public static function getWhere(array $search = []): array
  58. {
  59. $where = [];
  60. if (isset($search['coin']) && !empty($search['coin'])) {
  61. $where[] = ['coin', '=', $search['coin']];
  62. }
  63. if (isset($search['net']) && !empty($search['net'])) {
  64. $where[] = ['net', '=', $search['net']];
  65. }
  66. if (isset($search['to_address']) && !empty($search['to_address'])) {
  67. $where[] = ['to_address', '=', $search['to_address']];
  68. }
  69. if (isset($search['id']) && !empty($search['id'])) {
  70. $where[] = ['id', '=', $search['id']];
  71. }
  72. if (isset($search['member_id']) && !empty($search['member_id'])) {
  73. $where[] = ['member_id', '=', $search['member_id']];
  74. }
  75. if (isset($search['txid']) && !empty($search['txid'])) {
  76. $where[] = ['txid', '=', $search['txid']];
  77. }
  78. if (isset($search['status']) && $search['status'] != '') {
  79. $where[] = ['status', '=', $search['status']];
  80. }
  81. if (isset($search['type']) && $search['type'] != '') {
  82. $where[] = ['type', '=', $search['type']];
  83. }
  84. return $where;
  85. }
  86. /**
  87. * @description: 查询单条数据
  88. * @param array $search
  89. * @return \App\Models\Coin|null
  90. */
  91. public static function findOne(array $search): ?Recharge
  92. {
  93. return static::$MODEL::where(self::getWhere($search))->first();
  94. }
  95. /**
  96. * @description: 查询所有数据
  97. * @param array $search
  98. * @return \Illuminate\Database\Eloquent\Collection
  99. */
  100. public static function findAll(array $search = [])
  101. {
  102. return static::$MODEL::where(self::getWhere($search))->get();
  103. }
  104. /**
  105. * @description: 分页查询
  106. * @param array $search
  107. * @return array
  108. */
  109. public static function paginate(array $search = [])
  110. {
  111. $limit = isset($search['limit']) ? $search['limit'] : 15;
  112. $first_name = $search['first_name'] ?? '';
  113. $paginator = static::$MODEL::where(self::getWhere($search))
  114. ->with(['member'])
  115. ->tap(fn($query) => MemberAccount::filter($query, $search['account'] ?? null))
  116. ->when($first_name, function ($query) use ($first_name) {
  117. $query->whereHas('member', function ($q) use ($first_name) {
  118. $q->where('first_name', 'like', "%{$first_name}%");
  119. });
  120. })
  121. ->orderBy("created_at", 'desc')
  122. ->paginate($limit);
  123. $list = $paginator->items();
  124. $totalAmount = 0;
  125. $totalSuccess = 0;
  126. $totalFail = 0;
  127. foreach ($list as $item) {
  128. $item['amount'] = floatval($item['amount']);
  129. $item['account'] = (string)($item->member->account ?? '');
  130. $totalAmount += $item['amount'];
  131. if ($item['status'] == 1) $totalSuccess += $item['amount'];
  132. if ($item['status'] == 2) $totalFail += $item['amount'];
  133. }
  134. return [
  135. 'total' => $paginator->total(),
  136. 'total_amount' => $totalAmount,
  137. 'total_success' => $totalSuccess,
  138. 'total_fail' => $totalFail,
  139. 'data' => $list];
  140. }
  141. /**
  142. * @description: 同步会员的USDT充值记录
  143. * @param {*} $memberId
  144. * @return {*}
  145. */
  146. public static function syncUsdtRechargeRecords($memberId, $walletInfo = null, $force = false)
  147. {
  148. $walletInfo = $walletInfo ?: WalletService::findOne(['member_id' => $memberId, 'coin' => 'USDT']);
  149. if (empty($walletInfo) || empty($walletInfo->address)) {
  150. return 0;
  151. }
  152. if (!$force && !self::canSyncAddress($walletInfo->address)) {
  153. return 0;
  154. }
  155. try {
  156. $data = TronHelper::getTrc20UsdtRecharges($walletInfo->address);
  157. } catch (\Throwable $e) {
  158. Log::warning('同步USDT充值记录失败', [
  159. 'member_id' => $memberId,
  160. 'address' => $walletInfo->address,
  161. 'error' => $e->getMessage(),
  162. ]);
  163. return 0;
  164. }
  165. if (empty($data)) {
  166. return 0;
  167. }
  168. foreach ($data as $k => $v) {
  169. $v['member_id'] = $walletInfo->member_id ?: $memberId;
  170. $v['net'] = $walletInfo->net;
  171. $v['type'] = static::$MODEL::TYPE_AUTO;
  172. $v['created_at'] = now();
  173. $v['updated_at'] = now();
  174. $data[$k] = $v;
  175. }
  176. $result = 0;
  177. foreach ($data as $record) $result += RechargeBonusService::registerChain($record);
  178. return $result;
  179. }
  180. /**
  181. * @description: 强制同步并确认单个会员的USDT充值记录
  182. * @param {*} $memberId
  183. * @param bool $syncChain 是否先拉链上新充值
  184. * @param bool $force 是否忽略地址同步节流
  185. * @return array
  186. */
  187. public static function syncAndConfirmMemberRecharge($memberId, $syncChain = true, $force = false)
  188. {
  189. $walletInfo = WalletService::findOne(['member_id' => $memberId, 'coin' => 'USDT']);
  190. if (empty($walletInfo) || empty($walletInfo->address)) {
  191. return [
  192. 'success' => false,
  193. 'message' => '未找到该用户的USDT钱包地址',
  194. 'member_id' => $memberId,
  195. ];
  196. }
  197. $synced = 0;
  198. if ($syncChain) {
  199. $synced = self::syncUsdtRechargeRecords($memberId, $walletInfo, $force);
  200. }
  201. $pendingList = self::model()::where(self::getWhere([
  202. 'member_id' => $memberId,
  203. 'status' => self::model()::STATUS_STAY,
  204. 'type' => self::model()::TYPE_AUTO,
  205. ]))->orderBy('id')->get();
  206. $checked = 0;
  207. $confirmed = 0;
  208. $confirmedTxids = [];
  209. foreach ($pendingList as $item) {
  210. $checked++;
  211. self::handleRechargeConfirmation($item->txid);
  212. $fresh = self::findOne(['id' => $item->id]);
  213. if ($fresh && intval($fresh->status) === self::model()::STATUS_SUCCESS) {
  214. $confirmed++;
  215. $confirmedTxids[] = $fresh->txid;
  216. }
  217. }
  218. $remainingPending = self::model()::where(self::getWhere([
  219. 'member_id' => $memberId,
  220. 'status' => self::model()::STATUS_STAY,
  221. 'type' => self::model()::TYPE_AUTO,
  222. ]))->count();
  223. $collectResult = self::ensureCollectRecordsForMember($memberId);
  224. return [
  225. 'success' => true,
  226. 'member_id' => $memberId,
  227. 'address' => $walletInfo->address,
  228. 'synced' => $synced,
  229. 'checked' => $checked,
  230. 'confirmed' => $confirmed,
  231. 'remaining_pending' => $remainingPending,
  232. 'confirmed_txids' => $confirmedTxids,
  233. 'collect_ensured' => $collectResult['ensured'],
  234. 'collect_addresses' => $collectResult['addresses'],
  235. ];
  236. }
  237. /**
  238. * @description: 为已确认充值补建待归集记录
  239. * @param {*} $memberId
  240. * @return array
  241. */
  242. public static function ensureCollectRecordsForMember($memberId)
  243. {
  244. $list = self::model()::where(self::getWhere([
  245. 'member_id' => $memberId,
  246. 'status' => self::model()::STATUS_SUCCESS,
  247. 'type' => self::model()::TYPE_AUTO,
  248. ]))->orderByDesc('id')->get();
  249. $ensured = 0;
  250. $addresses = [];
  251. $seen = [];
  252. foreach ($list as $item) {
  253. $address = $item->to_address;
  254. if (empty($address) || isset($seen[$address])) {
  255. continue;
  256. }
  257. $seen[$address] = true;
  258. $hasOpenCollect = Collect::where('from_address', $address)
  259. ->whereIn('status', [Collect::STATUS_STAY, Collect::STATUS_START])
  260. ->exists();
  261. if ($hasOpenCollect) {
  262. continue;
  263. }
  264. CollectService::createCollect($address, $item->coin, $item->net);
  265. $ensured++;
  266. $addresses[] = $address;
  267. }
  268. return [
  269. 'ensured' => $ensured,
  270. 'addresses' => $addresses,
  271. ];
  272. }
  273. /**
  274. * @description: 标记用户进入USDT充值同步队列
  275. * @param {*} $memberId
  276. * @return void
  277. */
  278. public static function markUsdtRechargePending($memberId)
  279. {
  280. if (empty($memberId)) {
  281. return;
  282. }
  283. $queue = self::getPendingSyncQueue();
  284. $key = strval($memberId);
  285. $now = time();
  286. $queue[$key] = [
  287. 'member_id' => $memberId,
  288. 'last_synced_at' => $queue[$key]['last_synced_at'] ?? 0,
  289. 'updated_at' => $now,
  290. 'expires_at' => $now + self::PENDING_SYNC_TTL,
  291. ];
  292. self::putPendingSyncQueue($queue);
  293. }
  294. /**
  295. * @description: 同步待处理队列中的USDT充值记录
  296. * @param int $limit
  297. * @return array
  298. */
  299. public static function syncPendingUsdtRechargeRecords($limit = self::SYNC_BATCH_SIZE)
  300. {
  301. self::markRecentActiveMembersPending();
  302. $queue = self::getPendingSyncQueue();
  303. uasort($queue, function ($a, $b) {
  304. return ($a['last_synced_at'] ?? 0) <=> ($b['last_synced_at'] ?? 0);
  305. });
  306. $synced = 0;
  307. $checked = 0;
  308. $now = time();
  309. foreach ($queue as $key => $item) {
  310. if ($checked >= $limit) {
  311. break;
  312. }
  313. if (!empty($item['last_synced_at']) && $now - $item['last_synced_at'] < self::ADDRESS_SYNC_COOLDOWN) {
  314. continue;
  315. }
  316. $walletInfo = WalletService::findOne(['member_id' => $item['member_id'] ?? 0, 'coin' => 'USDT']);
  317. if (empty($walletInfo) || empty($walletInfo->address)) {
  318. unset($queue[$key]);
  319. continue;
  320. }
  321. $synced += self::syncUsdtRechargeRecords($walletInfo->member_id, $walletInfo);
  322. $checked++;
  323. $queue[$key]['last_synced_at'] = time();
  324. $queue[$key]['updated_at'] = time();
  325. }
  326. self::putPendingSyncQueue($queue);
  327. return [
  328. 'synced' => $synced,
  329. 'checked' => $checked,
  330. 'queued' => count($queue),
  331. ];
  332. }
  333. /**
  334. * @description: 兼容旧调用,避免再次全量扫描钱包
  335. * @return array
  336. */
  337. public static function syncAllUsdtRechargeRecords()
  338. {
  339. return self::syncPendingUsdtRechargeRecords();
  340. }
  341. private static function canSyncAddress($address)
  342. {
  343. $addressKey = self::ADDRESS_SYNC_CACHE_PREFIX . $address;
  344. if (Cache::has($addressKey)) {
  345. return false;
  346. }
  347. if (!Cache::add(self::TRONGRID_SYNC_LOCK_KEY, time(), self::TRONGRID_SYNC_LOCK_SECONDS)) {
  348. return false;
  349. }
  350. Cache::put($addressKey, time(), self::ADDRESS_SYNC_COOLDOWN);
  351. return true;
  352. }
  353. private static function getPendingSyncQueue()
  354. {
  355. $queue = Cache::get(self::PENDING_SYNC_CACHE_KEY, []);
  356. if (!is_array($queue)) {
  357. return [];
  358. }
  359. $now = time();
  360. foreach ($queue as $key => $item) {
  361. if (!is_array($item) || empty($item['member_id']) || ($item['expires_at'] ?? 0) < $now) {
  362. unset($queue[$key]);
  363. }
  364. }
  365. return $queue;
  366. }
  367. private static function putPendingSyncQueue(array $queue)
  368. {
  369. Cache::put(self::PENDING_SYNC_CACHE_KEY, $queue, self::PENDING_SYNC_TTL);
  370. }
  371. private static function markRecentActiveMembersPending()
  372. {
  373. if (Cache::has(self::RECENT_ACTIVE_SYNC_CACHE_KEY)) {
  374. return;
  375. }
  376. Cache::put(self::RECENT_ACTIVE_SYNC_CACHE_KEY, time(), self::RECENT_ACTIVE_ENQUEUE_INTERVAL);
  377. $since = date('Y-m-d H:i:s', time() - self::RECENT_ACTIVE_MINUTES * 60);
  378. $members = User::whereNotNull('last_active_time')
  379. ->where('last_active_time', '>=', $since)
  380. ->orderByDesc('last_active_time')
  381. ->limit(self::RECENT_ACTIVE_LIMIT)
  382. ->pluck('member_id');
  383. foreach ($members as $memberId) {
  384. self::markUsdtRechargePending($memberId);
  385. }
  386. }
  387. /**
  388. * @description: 充值确认
  389. * @param {*} $txid
  390. * @return {*}
  391. */
  392. public static function handleRechargeConfirmation($txid)
  393. {
  394. $info = self::findOne(['txid' => $txid]); // 获取充值的信息
  395. if (empty($info)) {
  396. return;
  397. }
  398. // 汇率
  399. $rate = Config::where('field', 'exchange_rate_rmb')->first()->val ?? 1;
  400. // 待处理进行充值
  401. if ($info['status'] == static::$MODEL::STATUS_STAY) {
  402. $walletInfo = WalletService::findOne(['member_id' => $info->member_id, 'coin' => 'USDT']);
  403. $expectedToAddress = $walletInfo->address ?? '';
  404. if (empty($expectedToAddress) || $info->to_address !== $expectedToAddress) {
  405. self::ignoreInvalidAutoRecharge($info, '充值地址不是该会员系统分配的USDT地址', [
  406. 'expected_to_address' => $expectedToAddress,
  407. 'record_to_address' => $info->to_address,
  408. ]);
  409. return;
  410. }
  411. $result = TronHelper::getUsdtTransferConfirmation($txid, $expectedToAddress);
  412. if (empty($result['success'])) {
  413. if (!empty($result['invalid'])) {
  414. self::ignoreInvalidAutoRecharge($info, $result['message'] ?? '无效USDT充值交易');
  415. }
  416. return;
  417. }
  418. if (!empty($result['success'])) {
  419. $data = [];
  420. $data['block_height'] = $result['block_number'];
  421. $data['confirmations'] = $result['confirmations'];
  422. $data['from_address'] = $result['from_address'];
  423. $data['to_address'] = $result['to_address'];
  424. $data['amount'] = $result['amount'];
  425. $data['block_time'] = $result['block_time'];
  426. $data['exchange_rate'] = $rate;
  427. if ($data['confirmations'] >= TronHelper::CONFIRMED_NUMBER) {
  428. $data['status'] = static::$MODEL::STATUS_SUCCESS;
  429. $amount = (string)$result['amount'];
  430. $rate_amount = bcmul($amount, (string)$rate, 10);
  431. $recharge = self::creditConfirmedRecharge($info, $data, $rate_amount);
  432. // 更新成功,变动可用余额
  433. if ($recharge) {
  434. CollectService::createCollect($result['to_address'], $info->coin, $info->net);
  435. $text = "充值结果通知\n";
  436. $text .= "充值数量:{$amount} USDT\n";
  437. $text .= "充值地址:{$result['to_address']}\n";
  438. $text .= "汇率:1 USDT = {$rate} RMB\n";
  439. $text .= "折合金额:" . number_format($rate_amount, 2) . " RMB\n";
  440. $text .= "状态:成功\n";
  441. TopUpService::notifyTransferSuccess($info->member_id, $text);
  442. }
  443. } else {
  444. $ids = static::$MODEL::where(self::getWhere(['txid' => $txid, 'status' => static::$MODEL::STATUS_STAY]))->pluck('id')->all();
  445. static::$MODEL::where(self::getWhere(['txid' => $txid, 'status' => static::$MODEL::STATUS_STAY]))->update($data);
  446. AdminRealtime::record('recharges', $ids);
  447. }
  448. }
  449. }
  450. }
  451. /** Called only after the chain transfer has been verified. Deposit, log and first-deposit award commit together. */
  452. public static function creditConfirmedRecharge(Recharge $info, array $confirmed, string $amount): bool
  453. {
  454. return DB::transaction(function () use ($info, $confirmed, $amount) {
  455. $info = static::$MODEL::where('id', $info->id)->lockForUpdate()->first();
  456. if (!$info || (int)$info->status !== Recharge::STATUS_STAY) return false;
  457. if (!RechargeBonusService::chainCreditAllowed($info)) {
  458. $info->status = Recharge::STATUS_IGNORE; $info->save(); return false;
  459. }
  460. $wallet = \App\Models\Wallet::where('member_id', $info->member_id)->lockForUpdate()->first();
  461. if (!$wallet) throw new \RuntimeException('充值钱包不存在');
  462. $updated = static::$MODEL::where('id', $info->id)->where('status', Recharge::STATUS_STAY)->update($confirmed);
  463. if (!$updated) return false;
  464. AdminRealtime::record('recharges', $info->id);
  465. $before = (string)$wallet->available_balance;
  466. $wallet->available_balance = bcadd($before, $amount, 10); $wallet->save();
  467. $principal = BalanceLogService::addLog($info->member_id, $amount, $before, $wallet->available_balance, '充值', $info->id, '');
  468. RechargeBonusService::grant('recharge', $info, $principal);
  469. RechargeBonusService::markChainCredited($info, $principal);
  470. return true;
  471. }, 3);
  472. }
  473. private static function ignoreInvalidAutoRecharge(Recharge $info, string $reason, array $context = []): void
  474. {
  475. if (intval($info->type) !== static::$MODEL::TYPE_AUTO || intval($info->status) !== static::$MODEL::STATUS_STAY) {
  476. return;
  477. }
  478. static::$MODEL::where(self::getWhere([
  479. 'id' => $info->id,
  480. 'status' => static::$MODEL::STATUS_STAY,
  481. ]))->update([
  482. 'status' => static::$MODEL::STATUS_IGNORE,
  483. ]);
  484. AdminRealtime::record('recharges', $info->id);
  485. Log::warning('忽略无效USDT自动充值记录', array_merge([
  486. 'id' => $info->id,
  487. 'member_id' => $info->member_id,
  488. 'txid' => $info->txid,
  489. 'reason' => $reason,
  490. ], $context));
  491. }
  492. /**
  493. * @description: 同步待处理的充值记录
  494. * @return {*}
  495. */
  496. public static function syncRechargeStay()
  497. {
  498. $list = self::findAll(['status' => static::$MODEL::STATUS_STAY, 'type' => static::$MODEL::TYPE_AUTO]);
  499. foreach ($list as $k => $v) {
  500. self::handleRechargeConfirmation($v->txid);
  501. }
  502. }
  503. }