CollectService.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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. $item = [
  159. 'from_address' => $address,
  160. 'recharge_txid' => $recharge->txid,
  161. 'action' => 'pending',
  162. 'collect_id' => null,
  163. 'amount' => null,
  164. 'error' => null,
  165. ];
  166. $openCollect = self::model()::where('from_address', $address)
  167. ->whereIn('status', [self::model()::STATUS_STAY, self::model()::STATUS_START])
  168. ->orderByDesc('id')
  169. ->first();
  170. if ($openCollect && intval($openCollect->status) === self::model()::STATUS_START) {
  171. $item['action'] = 'skipped_started';
  172. $item['collect_id'] = $openCollect->id;
  173. $item['amount'] = $openCollect->amount;
  174. $result['skipped_count']++;
  175. $result['processed_count']++;
  176. $result['items'][] = $item;
  177. continue;
  178. }
  179. $hadPending = $openCollect && intval($openCollect->status) === self::model()::STATUS_STAY;
  180. try {
  181. self::createCollect($address, $recharge->coin, $recharge->net);
  182. $collect = self::model()::where('from_address', $address)
  183. ->where('status', self::model()::STATUS_STAY)
  184. ->orderByDesc('id')
  185. ->first();
  186. $item['action'] = $hadPending ? 'updated' : 'created';
  187. $item['collect_id'] = $collect->id ?? null;
  188. $item['amount'] = $collect->amount ?? null;
  189. if ($hadPending) {
  190. $result['updated_count']++;
  191. } else {
  192. $result['created_count']++;
  193. }
  194. } catch (\Throwable $e) {
  195. $item['action'] = 'failed';
  196. $item['error'] = $e->getMessage();
  197. $result['failed_count']++;
  198. }
  199. $result['processed_count']++;
  200. $result['items'][] = $item;
  201. }
  202. if ($result['processed_count'] === 0) {
  203. $result['success'] = false;
  204. $result['message'] = '未找到可处理的充值地址';
  205. }
  206. return $result;
  207. }
  208. /**
  209. * @description: 处理指定会员待归集记录,会执行链上归集
  210. * @param {*} $memberId
  211. * @return array
  212. */
  213. public static function syncCollectStayByMember($memberId)
  214. {
  215. $result = [
  216. 'member_id' => $memberId,
  217. 'threshold' => self::$THRESHOLD,
  218. 'from_address' => null,
  219. 'to_address' => null,
  220. 'pending_count' => 0,
  221. 'handled_count' => 0,
  222. 'success_count' => 0,
  223. 'fail_count' => 0,
  224. 'items' => [],
  225. ];
  226. $walletInfo = WalletService::findOne(['member_id' => $memberId, 'coin' => 'USDT']);
  227. if (empty($walletInfo) || empty($walletInfo->address)) {
  228. $result['message'] = '未找到该用户的USDT钱包地址';
  229. Log::warning('syncCollectStayByMember skipped: wallet missing', [
  230. 'member_id' => $memberId,
  231. ]);
  232. return $result;
  233. }
  234. $result['from_address'] = $walletInfo->address;
  235. $to_address = self::getUsdtAddress();
  236. $trx_private_key = self::getTrxPrivateKey();
  237. $result['to_address'] = $to_address;
  238. Log::info('syncCollectStayByMember start', [
  239. 'member_id' => $memberId,
  240. 'from_address' => $walletInfo->address,
  241. 'threshold' => self::$THRESHOLD,
  242. 'to_address' => $to_address,
  243. 'has_trx_private_key' => !empty($trx_private_key),
  244. ]);
  245. if (!$to_address || !$trx_private_key) {
  246. $result['message'] = '归集配置不完整';
  247. Log::warning('syncCollectStayByMember skipped: missing config', [
  248. 'member_id' => $memberId,
  249. 'to_address' => $to_address,
  250. 'has_trx_private_key' => !empty($trx_private_key),
  251. ]);
  252. return $result;
  253. }
  254. $list = self::findAll([
  255. 'status' => self::model()::STATUS_STAY,
  256. 'amount' => self::$THRESHOLD,
  257. 'from_address' => $walletInfo->address,
  258. ]);
  259. $result['pending_count'] = $list->count();
  260. if ($list->isEmpty()) {
  261. $result['message'] = '该用户没有待归集记录';
  262. Log::info('syncCollectStayByMember finished: no pending collects', $result);
  263. return $result;
  264. }
  265. foreach ($list as $v) {
  266. $item = [
  267. 'id' => $v['id'],
  268. 'from_address' => $v['from_address'],
  269. 'amount' => $v['amount'],
  270. 'status' => 'pending',
  271. ];
  272. $data = [];
  273. $wallets = WalletService::findOne(['address' => $v['from_address']]);
  274. if (empty($wallets) || empty($wallets['private_key'])) {
  275. $item['status'] = 'wallet_not_found';
  276. $item['error'] = '未找到归集钱包私钥';
  277. $data['remark'] = $item['error'];
  278. $data['updated_at'] = now();
  279. self::model()::where(self::getWhere(['id' => $v['id']]))->update($data);
  280. $result['fail_count']++;
  281. $result['handled_count']++;
  282. $result['items'][] = $item;
  283. Log::warning('syncCollectStayByMember wallet missing', $item + ['member_id' => $memberId]);
  284. continue;
  285. }
  286. $privateKey = $wallets['private_key'];
  287. $trxBalance = TronHelper::getTrxBalance($v['from_address']);
  288. $item['trx_balance'] = $trxBalance;
  289. if ($trxBalance < 10) {
  290. $trxResult = TronHelper::sendTrx($trx_private_key, $v['from_address'], 10);
  291. $item['trx_topup_result'] = $trxResult;
  292. Log::info('syncCollectStayByMember topup trx', [
  293. 'member_id' => $memberId,
  294. 'from_address' => $v['from_address'],
  295. 'trx_balance' => $trxBalance,
  296. 'result' => $trxResult,
  297. ]);
  298. }
  299. $transferResult = TronHelper::transferUSDT($privateKey, $to_address, $v['amount']);
  300. $item['transfer_result'] = $transferResult;
  301. $data['to_address'] = $to_address;
  302. if (is_array($transferResult) && !empty($transferResult['success'])) {
  303. $data['txid'] = $transferResult['txid'] ?? '';
  304. $data['remark'] = 'success';
  305. $data['status'] = self::model()::STATUS_START;
  306. $item['status'] = 'success';
  307. $item['txid'] = $data['txid'];
  308. $result['success_count']++;
  309. Log::info('syncCollectStayByMember transfer success', $item + ['member_id' => $memberId]);
  310. } else {
  311. $error = is_array($transferResult)
  312. ? ($transferResult['error'] ?? 'USDT归集失败')
  313. : (is_string($transferResult) ? $transferResult : 'USDT归集失败');
  314. $data['remark'] = $error;
  315. $item['status'] = 'failed';
  316. $item['error'] = $error;
  317. $result['fail_count']++;
  318. Log::warning('syncCollectStayByMember transfer failed', $item + ['member_id' => $memberId]);
  319. }
  320. $data['updated_at'] = now();
  321. self::model()::where(self::getWhere(['id' => $v['id']]))->update($data);
  322. $result['handled_count']++;
  323. $result['items'][] = $item;
  324. }
  325. Log::info('syncCollectStayByMember finished', $result);
  326. return $result;
  327. }
  328. /**
  329. * @description: 处理待归集的
  330. * @return {*}
  331. */
  332. public static function syncCollectStay()
  333. {
  334. $result = [
  335. 'threshold' => self::$THRESHOLD,
  336. 'to_address' => null,
  337. 'pending_count' => 0,
  338. 'handled_count' => 0,
  339. 'success_count' => 0,
  340. 'fail_count' => 0,
  341. 'items' => [],
  342. ];
  343. $to_address = self::getUsdtAddress(); // 转账的接收地址
  344. $trx_private_key = self::getTrxPrivateKey(); // 获取TRX能量的秘钥
  345. $result['to_address'] = $to_address;
  346. Log::info('syncCollectStay start', [
  347. 'threshold' => self::$THRESHOLD,
  348. 'to_address' => $to_address,
  349. 'has_trx_private_key' => !empty($trx_private_key),
  350. ]);
  351. if (!$to_address || !$trx_private_key) {
  352. $result['message'] = '归集配置不完整';
  353. Log::warning('syncCollectStay skipped: missing config', [
  354. 'to_address' => $to_address,
  355. 'has_trx_private_key' => !empty($trx_private_key),
  356. ]);
  357. return $result;
  358. }
  359. $list = self::findAll(['status' => self::model()::STATUS_STAY ,'amount' => self::$THRESHOLD]);
  360. $result['pending_count'] = $list->count();
  361. if ($list->isEmpty()) {
  362. $result['message'] = '没有待归集记录';
  363. Log::info('syncCollectStay finished: no pending collects', $result);
  364. return $result;
  365. }
  366. foreach($list as $k => $v){
  367. $item = [
  368. 'id' => $v['id'],
  369. 'from_address' => $v['from_address'],
  370. 'amount' => $v['amount'],
  371. 'status' => 'pending',
  372. ];
  373. $data = [];
  374. $wallets = WalletService::findOne(['address' => $v['from_address']]);
  375. if (empty($wallets) || empty($wallets['private_key'])) {
  376. $item['status'] = 'wallet_not_found';
  377. $item['error'] = '未找到归集钱包私钥';
  378. $data['remark'] = $item['error'];
  379. $data['updated_at'] = now();
  380. self::model()::where(self::getWhere(['id' => $v['id']]))->update($data);
  381. $result['fail_count']++;
  382. $result['handled_count']++;
  383. $result['items'][] = $item;
  384. Log::warning('syncCollectStay wallet missing', $item);
  385. continue;
  386. }
  387. $privateKey = $wallets['private_key'];
  388. $trxBalance = TronHelper::getTrxBalance($v['from_address']);
  389. $item['trx_balance'] = $trxBalance;
  390. if($trxBalance < 10){
  391. $trxResult = TronHelper::sendTrx($trx_private_key,$v['from_address'],10);
  392. $item['trx_topup_result'] = $trxResult;
  393. Log::info('syncCollectStay topup trx', [
  394. 'from_address' => $v['from_address'],
  395. 'trx_balance' => $trxBalance,
  396. 'result' => $trxResult,
  397. ]);
  398. }
  399. $transferResult = TronHelper::transferUSDT($privateKey,$to_address,$v['amount']);
  400. $item['transfer_result'] = $transferResult;
  401. $data['to_address'] = $to_address;
  402. if(is_array($transferResult) && !empty($transferResult['success'])){
  403. $data['txid'] = $transferResult['txid'] ?? '';
  404. $data['remark'] = 'success';
  405. $data['status'] = self::model()::STATUS_START;
  406. $item['status'] = 'success';
  407. $item['txid'] = $data['txid'];
  408. $result['success_count']++;
  409. Log::info('syncCollectStay transfer success', $item);
  410. }else{
  411. $error = is_array($transferResult)
  412. ? ($transferResult['error'] ?? 'USDT归集失败')
  413. : (is_string($transferResult) ? $transferResult : 'USDT归集失败');
  414. $data['remark'] = $error;
  415. $item['status'] = 'failed';
  416. $item['error'] = $error;
  417. $result['fail_count']++;
  418. Log::warning('syncCollectStay transfer failed', $item);
  419. }
  420. $data['updated_at'] = now();
  421. self::model()::where(self::getWhere(['id' => $v['id']]))->update($data);
  422. $result['handled_count']++;
  423. $result['items'][] = $item;
  424. }
  425. Log::info('syncCollectStay finished', $result);
  426. return $result;
  427. }
  428. /**
  429. * @description: 获取归集平台的接收地址
  430. * @return {*}
  431. */
  432. public static function getUsdtAddress()
  433. {
  434. $usdt_address = config('app.usdt_address');
  435. return $usdt_address;
  436. }
  437. /**
  438. * @description: 获取TRX能量账号秘钥
  439. * @return {*}
  440. */
  441. public static function getTrxPrivateKey()
  442. {
  443. $str = config('app.trx_private_key');
  444. return $str;
  445. }
  446. }