CollectService.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. <?php
  2. namespace App\Services;
  3. use App\Services\BaseService;
  4. use App\Models\Collect;
  5. use App\Models\Recharge;
  6. use Illuminate\Support\Facades\DB;
  7. use Illuminate\Support\Collection;
  8. use Illuminate\Support\Facades\Cache;
  9. use Illuminate\Support\Facades\Log;
  10. use App\Helpers\TronHelper;
  11. use App\Services\WalletService;
  12. /**
  13. * 归集记录
  14. */
  15. class CollectService extends BaseService
  16. {
  17. public static string $MODEL = Collect::class;
  18. public static $THRESHOLD = 10; // 最小归集金额(USDT)
  19. public static function getRequiredTrxBalance(): float
  20. {
  21. $value = (float) config('app.collect_required_trx_balance', 15);
  22. return $value > 0 ? $value : 15.0;
  23. }
  24. /**
  25. * @description: 模型
  26. * @return {string}
  27. */
  28. public static function model() :string
  29. {
  30. return Collect::class;
  31. }
  32. /**
  33. * @description: 枚举
  34. * @return {*}
  35. */
  36. public static function enum() :string
  37. {
  38. return '';
  39. }
  40. /**
  41. * @description: 获取查询条件
  42. * @param {array} $search 查询内容
  43. * @return {array}
  44. */
  45. public static function getWhere(array $search = []) :array
  46. {
  47. $where = [];
  48. if(isset($search['coin']) && !empty($search['coin'])){
  49. $where[] = ['coin', '=', $search['coin']];
  50. }
  51. if(isset($search['net']) && !empty($search['net'])){
  52. $where[] = ['net', '=', $search['net']];
  53. }
  54. if(isset($search['to_address']) && !empty($search['to_address'])){
  55. $where[] = ['to_address', '=', $search['to_address']];
  56. }
  57. if(isset($search['from_address']) && !empty($search['from_address'])){
  58. $where[] = ['from_address', '=', $search['from_address']];
  59. }
  60. if(isset($search['id']) && !empty($search['id'])){
  61. $where[] = ['id', '=', $search['id']];
  62. }
  63. if(isset($search['txid']) && !empty($search['txid'])){
  64. $where[] = ['txid', '=', $search['txid']];
  65. }
  66. if(isset($search['status']) && $search['status'] != ''){
  67. $where[] = ['status', '=', $search['status']];
  68. }
  69. if (isset($search['amount']) && is_numeric($search['amount'])) {
  70. $where[] = ['amount', '>=', $search['amount']];
  71. }
  72. return $where;
  73. }
  74. /**
  75. * @description: 查询单条数据
  76. * @param array $search
  77. * @return \App\Models\Coin|null
  78. */
  79. public static function findOne(array $search): ?Collect
  80. {
  81. return self::model()::where(self::getWhere($search))->first();
  82. }
  83. /**
  84. * @description: 查询所有数据
  85. * @param array $search
  86. * @return \Illuminate\Database\Eloquent\Collection
  87. */
  88. public static function findAll(array $search = [])
  89. {
  90. return self::model()::where(self::getWhere($search))->get();
  91. }
  92. /**
  93. * @description: 分页查询
  94. * @param array $search
  95. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  96. */
  97. public static function paginate(array $search = [])
  98. {
  99. $limit = isset($search['limit'])?$search['limit']:15;
  100. $paginator = self::model()::where(self::getWhere($search))->paginate($limit);
  101. return ['total' => $paginator->total(), 'data' => $paginator->items()];
  102. }
  103. /**
  104. * @description: 生成归集记录
  105. * @param {*} $address
  106. * @param {*} $coin
  107. * @param {*} $net
  108. * @return {*}
  109. */
  110. public static function createCollect($address ,$coin ,$net)
  111. {
  112. $amount = TronHelper::getTrc20Balance($address); // 获取地址的余额
  113. $info = self::findOne(['from_address' => $address ,'status' => self::model()::STATUS_STAY]);
  114. if($amount >= 0 ){
  115. if(empty($info)){
  116. $data = [];
  117. $data['from_address'] = $address;
  118. $data['amount'] = $amount;
  119. $data['coin'] = $coin;
  120. $data['net'] = $net;
  121. self::model()::create($data);
  122. }else{
  123. $info->amount = $amount;
  124. $info->save();
  125. }
  126. }
  127. }
  128. /**
  129. * @description: 按会员补建或刷新待归集记录,不执行链上归集
  130. * @param {*} $memberId
  131. * @return array
  132. */
  133. public static function syncMemberCollectRecords($memberId)
  134. {
  135. $recharges = Recharge::where('member_id', $memberId)
  136. ->where('status', Recharge::STATUS_SUCCESS)
  137. ->where('type', Recharge::TYPE_AUTO)
  138. ->orderByDesc('id')
  139. ->get();
  140. $result = [
  141. 'success' => true,
  142. 'member_id' => $memberId,
  143. 'recharge_count' => $recharges->count(),
  144. 'processed_count' => 0,
  145. 'created_count' => 0,
  146. 'updated_count' => 0,
  147. 'skipped_count' => 0,
  148. 'failed_count' => 0,
  149. 'items' => [],
  150. ];
  151. if ($recharges->isEmpty()) {
  152. $result['success'] = false;
  153. $result['message'] = '未找到已确认的自动充值记录';
  154. return $result;
  155. }
  156. $seen = [];
  157. foreach ($recharges as $recharge) {
  158. $address = $recharge->to_address;
  159. if (empty($address) || isset($seen[$address])) {
  160. continue;
  161. }
  162. $seen[$address] = true;
  163. self::resetInvalidStartedCollectsByAddress($address);
  164. $item = [
  165. 'from_address' => $address,
  166. 'recharge_txid' => $recharge->txid,
  167. 'action' => 'pending',
  168. 'collect_id' => null,
  169. 'amount' => null,
  170. 'error' => null,
  171. ];
  172. $openCollect = self::model()::where('from_address', $address)
  173. ->whereIn('status', [self::model()::STATUS_STAY, self::model()::STATUS_START])
  174. ->orderByDesc('id')
  175. ->first();
  176. if ($openCollect && intval($openCollect->status) === self::model()::STATUS_START) {
  177. $item['action'] = 'skipped_started';
  178. $item['collect_id'] = $openCollect->id;
  179. $item['amount'] = $openCollect->amount;
  180. $result['skipped_count']++;
  181. $result['processed_count']++;
  182. $result['items'][] = $item;
  183. continue;
  184. }
  185. $hadPending = $openCollect && intval($openCollect->status) === self::model()::STATUS_STAY;
  186. try {
  187. self::createCollect($address, $recharge->coin, $recharge->net);
  188. $collect = self::model()::where('from_address', $address)
  189. ->where('status', self::model()::STATUS_STAY)
  190. ->orderByDesc('id')
  191. ->first();
  192. $item['action'] = $hadPending ? 'updated' : 'created';
  193. $item['collect_id'] = $collect->id ?? null;
  194. $item['amount'] = $collect->amount ?? null;
  195. if ($hadPending) {
  196. $result['updated_count']++;
  197. } else {
  198. $result['created_count']++;
  199. }
  200. } catch (\Throwable $e) {
  201. $item['action'] = 'failed';
  202. $item['error'] = $e->getMessage();
  203. $result['failed_count']++;
  204. }
  205. $result['processed_count']++;
  206. $result['items'][] = $item;
  207. }
  208. if ($result['processed_count'] === 0) {
  209. $result['success'] = false;
  210. $result['message'] = '未找到可处理的充值地址';
  211. }
  212. return $result;
  213. }
  214. private static function resetInvalidStartedCollectsByAddress($address)
  215. {
  216. $updated = self::model()::where('from_address', $address)
  217. ->where('status', self::model()::STATUS_START)
  218. ->where(function ($query) {
  219. $query->whereNull('txid')
  220. ->orWhere('txid', '');
  221. })
  222. ->update([
  223. 'status' => self::model()::STATUS_STAY,
  224. 'to_address' => null,
  225. 'remark' => 'reset invalid started collect',
  226. 'updated_at' => now(),
  227. ]);
  228. if ($updated > 0) {
  229. Log::warning('reset invalid started collects', [
  230. 'from_address' => $address,
  231. 'count' => $updated,
  232. ]);
  233. }
  234. return $updated;
  235. }
  236. /**
  237. * @description: 处理指定会员待归集记录,会执行链上归集
  238. * @param {*} $memberId
  239. * @return array
  240. */
  241. public static function syncCollectStayByMember($memberId)
  242. {
  243. $result = [
  244. 'member_id' => $memberId,
  245. 'threshold' => self::$THRESHOLD,
  246. 'from_address' => null,
  247. 'to_address' => null,
  248. 'pending_count' => 0,
  249. 'handled_count' => 0,
  250. 'success_count' => 0,
  251. 'fail_count' => 0,
  252. 'items' => [],
  253. ];
  254. $walletInfo = WalletService::findOne(['member_id' => $memberId, 'coin' => 'USDT']);
  255. if (empty($walletInfo) || empty($walletInfo->address)) {
  256. $result['message'] = '未找到该用户的USDT钱包地址';
  257. Log::warning('syncCollectStayByMember skipped: wallet missing', [
  258. 'member_id' => $memberId,
  259. ]);
  260. return $result;
  261. }
  262. $result['from_address'] = $walletInfo->address;
  263. self::resetInvalidStartedCollectsByAddress($walletInfo->address);
  264. $to_address = self::getUsdtAddress();
  265. $trx_private_key = self::getTrxPrivateKey();
  266. $result['to_address'] = $to_address;
  267. Log::info('syncCollectStayByMember start', [
  268. 'member_id' => $memberId,
  269. 'from_address' => $walletInfo->address,
  270. 'threshold' => self::$THRESHOLD,
  271. 'required_trx_balance' => self::getRequiredTrxBalance(),
  272. 'to_address' => $to_address,
  273. 'has_trx_private_key' => !empty($trx_private_key),
  274. ]);
  275. if (!$to_address || !$trx_private_key) {
  276. $result['message'] = '归集配置不完整';
  277. Log::warning('syncCollectStayByMember skipped: missing config', [
  278. 'member_id' => $memberId,
  279. 'to_address' => $to_address,
  280. 'has_trx_private_key' => !empty($trx_private_key),
  281. ]);
  282. return $result;
  283. }
  284. $list = self::findAll([
  285. 'status' => self::model()::STATUS_STAY,
  286. 'amount' => self::$THRESHOLD,
  287. 'from_address' => $walletInfo->address,
  288. ]);
  289. $result['pending_count'] = $list->count();
  290. if ($list->isEmpty()) {
  291. $result['message'] = '该用户没有待归集记录';
  292. Log::info('syncCollectStayByMember finished: no pending collects', $result);
  293. return $result;
  294. }
  295. foreach ($list as $v) {
  296. $item = [
  297. 'id' => $v['id'],
  298. 'from_address' => $v['from_address'],
  299. 'amount' => $v['amount'],
  300. 'status' => 'pending',
  301. ];
  302. $data = [];
  303. $wallets = WalletService::findOne(['address' => $v['from_address']]);
  304. if (empty($wallets) || empty($wallets['private_key'])) {
  305. $item['status'] = 'wallet_not_found';
  306. $item['error'] = '未找到归集钱包私钥';
  307. $data['remark'] = $item['error'];
  308. $data['updated_at'] = now();
  309. self::model()::where(self::getWhere(['id' => $v['id']]))->update($data);
  310. $result['fail_count']++;
  311. $result['handled_count']++;
  312. $result['items'][] = $item;
  313. Log::warning('syncCollectStayByMember wallet missing', $item + ['member_id' => $memberId]);
  314. continue;
  315. }
  316. $privateKey = $wallets['private_key'];
  317. $trxBalance = TronHelper::getTrxBalance($v['from_address']);
  318. $item['trx_balance'] = $trxBalance;
  319. $requiredTrxBalance = self::getRequiredTrxBalance();
  320. $item['required_trx_balance'] = $requiredTrxBalance;
  321. if ($trxBalance < $requiredTrxBalance) {
  322. $topupAmount = round($requiredTrxBalance - $trxBalance, 6);
  323. $item['trx_topup_amount'] = $topupAmount;
  324. $trxResult = TronHelper::sendTrx($trx_private_key, $v['from_address'], $topupAmount);
  325. $item['trx_topup_result'] = $trxResult;
  326. Log::info('syncCollectStayByMember topup trx', [
  327. 'member_id' => $memberId,
  328. 'from_address' => $v['from_address'],
  329. 'trx_balance' => $trxBalance,
  330. 'required_trx_balance' => $requiredTrxBalance,
  331. 'topup_amount' => $topupAmount,
  332. 'result' => $trxResult,
  333. ]);
  334. if ($trxResult === false || is_string($trxResult)) {
  335. $error = is_string($trxResult) ? $trxResult : 'TRX能量补充失败';
  336. $data['status'] = self::model()::STATUS_STAY;
  337. $data['to_address'] = null;
  338. $data['txid'] = null;
  339. $data['remark'] = $error;
  340. $data['updated_at'] = now();
  341. $item['status'] = 'trx_topup_failed';
  342. $item['error'] = $error;
  343. self::model()::where(self::getWhere(['id' => $v['id']]))->update($data);
  344. $result['fail_count']++;
  345. $result['handled_count']++;
  346. $result['items'][] = $item;
  347. Log::warning('syncCollectStayByMember topup trx failed', $item + ['member_id' => $memberId]);
  348. continue;
  349. }
  350. $trxBalance = TronHelper::getTrxBalance($v['from_address']);
  351. $item['trx_balance_after_topup'] = $trxBalance;
  352. if ($trxBalance < $requiredTrxBalance) {
  353. $error = 'TRX余额仍不足,停止归集';
  354. $data['status'] = self::model()::STATUS_STAY;
  355. $data['to_address'] = null;
  356. $data['txid'] = null;
  357. $data['remark'] = $error;
  358. $data['updated_at'] = now();
  359. $item['status'] = 'trx_balance_insufficient';
  360. $item['error'] = $error;
  361. self::model()::where(self::getWhere(['id' => $v['id']]))->update($data);
  362. $result['fail_count']++;
  363. $result['handled_count']++;
  364. $result['items'][] = $item;
  365. Log::warning('syncCollectStayByMember trx balance still insufficient', $item + ['member_id' => $memberId]);
  366. continue;
  367. }
  368. }
  369. $transferResult = TronHelper::transferUSDT($privateKey, $to_address, $v['amount']);
  370. $item['transfer_result'] = $transferResult;
  371. if (is_array($transferResult) && !empty($transferResult['success'])) {
  372. $data['to_address'] = $to_address;
  373. $data['txid'] = $transferResult['txid'] ?? '';
  374. $data['remark'] = 'success';
  375. $data['status'] = self::model()::STATUS_START;
  376. $item['status'] = 'success';
  377. $item['txid'] = $data['txid'];
  378. $result['success_count']++;
  379. Log::info('syncCollectStayByMember transfer success', $item + ['member_id' => $memberId]);
  380. } else {
  381. $error = is_array($transferResult)
  382. ? ($transferResult['error'] ?? 'USDT归集失败')
  383. : (is_string($transferResult) ? $transferResult : 'USDT归集失败');
  384. $data['status'] = self::model()::STATUS_STAY;
  385. $data['to_address'] = null;
  386. $data['txid'] = null;
  387. $data['remark'] = $error;
  388. $item['status'] = 'failed';
  389. $item['error'] = $error;
  390. $result['fail_count']++;
  391. Log::warning('syncCollectStayByMember transfer failed', $item + ['member_id' => $memberId]);
  392. }
  393. $data['updated_at'] = now();
  394. self::model()::where(self::getWhere(['id' => $v['id']]))->update($data);
  395. $result['handled_count']++;
  396. $result['items'][] = $item;
  397. }
  398. Log::info('syncCollectStayByMember finished', $result);
  399. return $result;
  400. }
  401. /**
  402. * @description: 处理待归集的
  403. * @return {*}
  404. */
  405. public static function syncCollectStay()
  406. {
  407. $result = [
  408. 'threshold' => self::$THRESHOLD,
  409. 'to_address' => null,
  410. 'pending_count' => 0,
  411. 'handled_count' => 0,
  412. 'success_count' => 0,
  413. 'fail_count' => 0,
  414. 'items' => [],
  415. ];
  416. $to_address = self::getUsdtAddress(); // 转账的接收地址
  417. $trx_private_key = self::getTrxPrivateKey(); // 获取TRX能量的秘钥
  418. $result['to_address'] = $to_address;
  419. Log::info('syncCollectStay start', [
  420. 'threshold' => self::$THRESHOLD,
  421. 'required_trx_balance' => self::getRequiredTrxBalance(),
  422. 'to_address' => $to_address,
  423. 'has_trx_private_key' => !empty($trx_private_key),
  424. ]);
  425. if (!$to_address || !$trx_private_key) {
  426. $result['message'] = '归集配置不完整';
  427. Log::warning('syncCollectStay skipped: missing config', [
  428. 'to_address' => $to_address,
  429. 'has_trx_private_key' => !empty($trx_private_key),
  430. ]);
  431. return $result;
  432. }
  433. $list = self::findAll(['status' => self::model()::STATUS_STAY ,'amount' => self::$THRESHOLD]);
  434. $result['pending_count'] = $list->count();
  435. if ($list->isEmpty()) {
  436. $result['message'] = '没有待归集记录';
  437. Log::info('syncCollectStay finished: no pending collects', $result);
  438. return $result;
  439. }
  440. foreach($list as $k => $v){
  441. $item = [
  442. 'id' => $v['id'],
  443. 'from_address' => $v['from_address'],
  444. 'amount' => $v['amount'],
  445. 'status' => 'pending',
  446. ];
  447. $data = [];
  448. $wallets = WalletService::findOne(['address' => $v['from_address']]);
  449. if (empty($wallets) || empty($wallets['private_key'])) {
  450. $item['status'] = 'wallet_not_found';
  451. $item['error'] = '未找到归集钱包私钥';
  452. $data['remark'] = $item['error'];
  453. $data['updated_at'] = now();
  454. self::model()::where(self::getWhere(['id' => $v['id']]))->update($data);
  455. $result['fail_count']++;
  456. $result['handled_count']++;
  457. $result['items'][] = $item;
  458. Log::warning('syncCollectStay wallet missing', $item);
  459. continue;
  460. }
  461. $privateKey = $wallets['private_key'];
  462. $trxBalance = TronHelper::getTrxBalance($v['from_address']);
  463. $item['trx_balance'] = $trxBalance;
  464. $requiredTrxBalance = self::getRequiredTrxBalance();
  465. $item['required_trx_balance'] = $requiredTrxBalance;
  466. if($trxBalance < $requiredTrxBalance){
  467. $topupAmount = round($requiredTrxBalance - $trxBalance, 6);
  468. $item['trx_topup_amount'] = $topupAmount;
  469. $trxResult = TronHelper::sendTrx($trx_private_key,$v['from_address'],$topupAmount);
  470. $item['trx_topup_result'] = $trxResult;
  471. Log::info('syncCollectStay topup trx', [
  472. 'from_address' => $v['from_address'],
  473. 'trx_balance' => $trxBalance,
  474. 'required_trx_balance' => $requiredTrxBalance,
  475. 'topup_amount' => $topupAmount,
  476. 'result' => $trxResult,
  477. ]);
  478. if ($trxResult === false || is_string($trxResult)) {
  479. $error = is_string($trxResult) ? $trxResult : 'TRX能量补充失败';
  480. $data['status'] = self::model()::STATUS_STAY;
  481. $data['to_address'] = null;
  482. $data['txid'] = null;
  483. $data['remark'] = $error;
  484. $data['updated_at'] = now();
  485. $item['status'] = 'trx_topup_failed';
  486. $item['error'] = $error;
  487. self::model()::where(self::getWhere(['id' => $v['id']]))->update($data);
  488. $result['fail_count']++;
  489. $result['handled_count']++;
  490. $result['items'][] = $item;
  491. Log::warning('syncCollectStay topup trx failed', $item);
  492. continue;
  493. }
  494. $trxBalance = TronHelper::getTrxBalance($v['from_address']);
  495. $item['trx_balance_after_topup'] = $trxBalance;
  496. if ($trxBalance < $requiredTrxBalance) {
  497. $error = 'TRX余额仍不足,停止归集';
  498. $data['status'] = self::model()::STATUS_STAY;
  499. $data['to_address'] = null;
  500. $data['txid'] = null;
  501. $data['remark'] = $error;
  502. $data['updated_at'] = now();
  503. $item['status'] = 'trx_balance_insufficient';
  504. $item['error'] = $error;
  505. self::model()::where(self::getWhere(['id' => $v['id']]))->update($data);
  506. $result['fail_count']++;
  507. $result['handled_count']++;
  508. $result['items'][] = $item;
  509. Log::warning('syncCollectStay trx balance still insufficient', $item);
  510. continue;
  511. }
  512. }
  513. $transferResult = TronHelper::transferUSDT($privateKey,$to_address,$v['amount']);
  514. $item['transfer_result'] = $transferResult;
  515. if(is_array($transferResult) && !empty($transferResult['success'])){
  516. $data['to_address'] = $to_address;
  517. $data['txid'] = $transferResult['txid'] ?? '';
  518. $data['remark'] = 'success';
  519. $data['status'] = self::model()::STATUS_START;
  520. $item['status'] = 'success';
  521. $item['txid'] = $data['txid'];
  522. $result['success_count']++;
  523. Log::info('syncCollectStay transfer success', $item);
  524. }else{
  525. $error = is_array($transferResult)
  526. ? ($transferResult['error'] ?? 'USDT归集失败')
  527. : (is_string($transferResult) ? $transferResult : 'USDT归集失败');
  528. $data['status'] = self::model()::STATUS_STAY;
  529. $data['to_address'] = null;
  530. $data['txid'] = null;
  531. $data['remark'] = $error;
  532. $item['status'] = 'failed';
  533. $item['error'] = $error;
  534. $result['fail_count']++;
  535. Log::warning('syncCollectStay transfer failed', $item);
  536. }
  537. $data['updated_at'] = now();
  538. self::model()::where(self::getWhere(['id' => $v['id']]))->update($data);
  539. $result['handled_count']++;
  540. $result['items'][] = $item;
  541. }
  542. Log::info('syncCollectStay finished', $result);
  543. return $result;
  544. }
  545. /**
  546. * @description: 获取归集平台的接收地址
  547. * @return {*}
  548. */
  549. public static function getUsdtAddress()
  550. {
  551. $usdt_address = config('app.usdt_address');
  552. return $usdt_address;
  553. }
  554. /**
  555. * @description: 获取TRX能量账号秘钥
  556. * @return {*}
  557. */
  558. public static function getTrxPrivateKey()
  559. {
  560. $str = config('app.trx_private_key');
  561. return $str;
  562. }
  563. }