RechargeService.php 19 KB

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