CollectService.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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. }
  339. $transferResult = TronHelper::transferUSDT($privateKey, $to_address, $v['amount']);
  340. $item['transfer_result'] = $transferResult;
  341. if (is_array($transferResult) && !empty($transferResult['success'])) {
  342. $data['to_address'] = $to_address;
  343. $data['txid'] = $transferResult['txid'] ?? '';
  344. $data['remark'] = 'success';
  345. $data['status'] = self::model()::STATUS_START;
  346. $item['status'] = 'success';
  347. $item['txid'] = $data['txid'];
  348. $result['success_count']++;
  349. Log::info('syncCollectStayByMember transfer success', $item + ['member_id' => $memberId]);
  350. } else {
  351. $error = is_array($transferResult)
  352. ? ($transferResult['error'] ?? 'USDT归集失败')
  353. : (is_string($transferResult) ? $transferResult : 'USDT归集失败');
  354. $data['status'] = self::model()::STATUS_STAY;
  355. $data['to_address'] = null;
  356. $data['txid'] = null;
  357. $data['remark'] = $error;
  358. $item['status'] = 'failed';
  359. $item['error'] = $error;
  360. $result['fail_count']++;
  361. Log::warning('syncCollectStayByMember transfer failed', $item + ['member_id' => $memberId]);
  362. }
  363. $data['updated_at'] = now();
  364. self::model()::where(self::getWhere(['id' => $v['id']]))->update($data);
  365. $result['handled_count']++;
  366. $result['items'][] = $item;
  367. }
  368. Log::info('syncCollectStayByMember finished', $result);
  369. return $result;
  370. }
  371. /**
  372. * @description: 处理待归集的
  373. * @return {*}
  374. */
  375. public static function syncCollectStay()
  376. {
  377. $result = [
  378. 'threshold' => self::$THRESHOLD,
  379. 'to_address' => null,
  380. 'pending_count' => 0,
  381. 'handled_count' => 0,
  382. 'success_count' => 0,
  383. 'fail_count' => 0,
  384. 'items' => [],
  385. ];
  386. $to_address = self::getUsdtAddress(); // 转账的接收地址
  387. $trx_private_key = self::getTrxPrivateKey(); // 获取TRX能量的秘钥
  388. $result['to_address'] = $to_address;
  389. Log::info('syncCollectStay start', [
  390. 'threshold' => self::$THRESHOLD,
  391. 'to_address' => $to_address,
  392. 'has_trx_private_key' => !empty($trx_private_key),
  393. ]);
  394. if (!$to_address || !$trx_private_key) {
  395. $result['message'] = '归集配置不完整';
  396. Log::warning('syncCollectStay skipped: missing config', [
  397. 'to_address' => $to_address,
  398. 'has_trx_private_key' => !empty($trx_private_key),
  399. ]);
  400. return $result;
  401. }
  402. $list = self::findAll(['status' => self::model()::STATUS_STAY ,'amount' => self::$THRESHOLD]);
  403. $result['pending_count'] = $list->count();
  404. if ($list->isEmpty()) {
  405. $result['message'] = '没有待归集记录';
  406. Log::info('syncCollectStay finished: no pending collects', $result);
  407. return $result;
  408. }
  409. foreach($list as $k => $v){
  410. $item = [
  411. 'id' => $v['id'],
  412. 'from_address' => $v['from_address'],
  413. 'amount' => $v['amount'],
  414. 'status' => 'pending',
  415. ];
  416. $data = [];
  417. $wallets = WalletService::findOne(['address' => $v['from_address']]);
  418. if (empty($wallets) || empty($wallets['private_key'])) {
  419. $item['status'] = 'wallet_not_found';
  420. $item['error'] = '未找到归集钱包私钥';
  421. $data['remark'] = $item['error'];
  422. $data['updated_at'] = now();
  423. self::model()::where(self::getWhere(['id' => $v['id']]))->update($data);
  424. $result['fail_count']++;
  425. $result['handled_count']++;
  426. $result['items'][] = $item;
  427. Log::warning('syncCollectStay wallet missing', $item);
  428. continue;
  429. }
  430. $privateKey = $wallets['private_key'];
  431. $trxBalance = TronHelper::getTrxBalance($v['from_address']);
  432. $item['trx_balance'] = $trxBalance;
  433. if($trxBalance < 10){
  434. $trxResult = TronHelper::sendTrx($trx_private_key,$v['from_address'],10);
  435. $item['trx_topup_result'] = $trxResult;
  436. Log::info('syncCollectStay topup trx', [
  437. 'from_address' => $v['from_address'],
  438. 'trx_balance' => $trxBalance,
  439. 'result' => $trxResult,
  440. ]);
  441. if ($trxResult === false || is_string($trxResult)) {
  442. $error = is_string($trxResult) ? $trxResult : 'TRX能量补充失败';
  443. $data['status'] = self::model()::STATUS_STAY;
  444. $data['to_address'] = null;
  445. $data['txid'] = null;
  446. $data['remark'] = $error;
  447. $data['updated_at'] = now();
  448. $item['status'] = 'trx_topup_failed';
  449. $item['error'] = $error;
  450. self::model()::where(self::getWhere(['id' => $v['id']]))->update($data);
  451. $result['fail_count']++;
  452. $result['handled_count']++;
  453. $result['items'][] = $item;
  454. Log::warning('syncCollectStay topup trx failed', $item);
  455. continue;
  456. }
  457. }
  458. $transferResult = TronHelper::transferUSDT($privateKey,$to_address,$v['amount']);
  459. $item['transfer_result'] = $transferResult;
  460. if(is_array($transferResult) && !empty($transferResult['success'])){
  461. $data['to_address'] = $to_address;
  462. $data['txid'] = $transferResult['txid'] ?? '';
  463. $data['remark'] = 'success';
  464. $data['status'] = self::model()::STATUS_START;
  465. $item['status'] = 'success';
  466. $item['txid'] = $data['txid'];
  467. $result['success_count']++;
  468. Log::info('syncCollectStay transfer success', $item);
  469. }else{
  470. $error = is_array($transferResult)
  471. ? ($transferResult['error'] ?? 'USDT归集失败')
  472. : (is_string($transferResult) ? $transferResult : 'USDT归集失败');
  473. $data['status'] = self::model()::STATUS_STAY;
  474. $data['to_address'] = null;
  475. $data['txid'] = null;
  476. $data['remark'] = $error;
  477. $item['status'] = 'failed';
  478. $item['error'] = $error;
  479. $result['fail_count']++;
  480. Log::warning('syncCollectStay transfer failed', $item);
  481. }
  482. $data['updated_at'] = now();
  483. self::model()::where(self::getWhere(['id' => $v['id']]))->update($data);
  484. $result['handled_count']++;
  485. $result['items'][] = $item;
  486. }
  487. Log::info('syncCollectStay finished', $result);
  488. return $result;
  489. }
  490. /**
  491. * @description: 获取归集平台的接收地址
  492. * @return {*}
  493. */
  494. public static function getUsdtAddress()
  495. {
  496. $usdt_address = config('app.usdt_address');
  497. return $usdt_address;
  498. }
  499. /**
  500. * @description: 获取TRX能量账号秘钥
  501. * @return {*}
  502. */
  503. public static function getTrxPrivateKey()
  504. {
  505. $str = config('app.trx_private_key');
  506. return $str;
  507. }
  508. }