CollectService.php 22 KB

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