CollectService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. * @return {*}
  211. */
  212. public static function syncCollectStay()
  213. {
  214. $result = [
  215. 'threshold' => self::$THRESHOLD,
  216. 'to_address' => null,
  217. 'pending_count' => 0,
  218. 'handled_count' => 0,
  219. 'success_count' => 0,
  220. 'fail_count' => 0,
  221. 'items' => [],
  222. ];
  223. $to_address = self::getUsdtAddress(); // 转账的接收地址
  224. $trx_private_key = self::getTrxPrivateKey(); // 获取TRX能量的秘钥
  225. $result['to_address'] = $to_address;
  226. Log::info('syncCollectStay start', [
  227. 'threshold' => self::$THRESHOLD,
  228. 'to_address' => $to_address,
  229. 'has_trx_private_key' => !empty($trx_private_key),
  230. ]);
  231. if (!$to_address || !$trx_private_key) {
  232. $result['message'] = '归集配置不完整';
  233. Log::warning('syncCollectStay skipped: missing config', [
  234. 'to_address' => $to_address,
  235. 'has_trx_private_key' => !empty($trx_private_key),
  236. ]);
  237. return $result;
  238. }
  239. $list = self::findAll(['status' => self::model()::STATUS_STAY ,'amount' => self::$THRESHOLD]);
  240. $result['pending_count'] = $list->count();
  241. if ($list->isEmpty()) {
  242. $result['message'] = '没有待归集记录';
  243. Log::info('syncCollectStay finished: no pending collects', $result);
  244. return $result;
  245. }
  246. foreach($list as $k => $v){
  247. $item = [
  248. 'id' => $v['id'],
  249. 'from_address' => $v['from_address'],
  250. 'amount' => $v['amount'],
  251. 'status' => 'pending',
  252. ];
  253. $data = [];
  254. $wallets = WalletService::findOne(['address' => $v['from_address']]);
  255. if (empty($wallets) || empty($wallets['private_key'])) {
  256. $item['status'] = 'wallet_not_found';
  257. $item['error'] = '未找到归集钱包私钥';
  258. $data['remark'] = $item['error'];
  259. $data['updated_at'] = now();
  260. self::model()::where(self::getWhere(['id' => $v['id']]))->update($data);
  261. $result['fail_count']++;
  262. $result['handled_count']++;
  263. $result['items'][] = $item;
  264. Log::warning('syncCollectStay wallet missing', $item);
  265. continue;
  266. }
  267. $privateKey = $wallets['private_key'];
  268. $trxBalance = TronHelper::getTrxBalance($v['from_address']);
  269. $item['trx_balance'] = $trxBalance;
  270. if($trxBalance < 10){
  271. $trxResult = TronHelper::sendTrx($trx_private_key,$v['from_address'],10);
  272. $item['trx_topup_result'] = $trxResult;
  273. Log::info('syncCollectStay topup trx', [
  274. 'from_address' => $v['from_address'],
  275. 'trx_balance' => $trxBalance,
  276. 'result' => $trxResult,
  277. ]);
  278. }
  279. $transferResult = TronHelper::transferUSDT($privateKey,$to_address,$v['amount']);
  280. $item['transfer_result'] = $transferResult;
  281. $data['to_address'] = $to_address;
  282. if(is_array($transferResult) && !empty($transferResult['success'])){
  283. $data['txid'] = $transferResult['txid'] ?? '';
  284. $data['remark'] = 'success';
  285. $data['status'] = self::model()::STATUS_START;
  286. $item['status'] = 'success';
  287. $item['txid'] = $data['txid'];
  288. $result['success_count']++;
  289. Log::info('syncCollectStay transfer success', $item);
  290. }else{
  291. $error = is_array($transferResult)
  292. ? ($transferResult['error'] ?? 'USDT归集失败')
  293. : (is_string($transferResult) ? $transferResult : 'USDT归集失败');
  294. $data['remark'] = $error;
  295. $item['status'] = 'failed';
  296. $item['error'] = $error;
  297. $result['fail_count']++;
  298. Log::warning('syncCollectStay transfer failed', $item);
  299. }
  300. $data['updated_at'] = now();
  301. self::model()::where(self::getWhere(['id' => $v['id']]))->update($data);
  302. $result['handled_count']++;
  303. $result['items'][] = $item;
  304. }
  305. Log::info('syncCollectStay finished', $result);
  306. return $result;
  307. }
  308. /**
  309. * @description: 获取归集平台的接收地址
  310. * @return {*}
  311. */
  312. public static function getUsdtAddress()
  313. {
  314. $usdt_address = config('app.usdt_address');
  315. return $usdt_address;
  316. }
  317. /**
  318. * @description: 获取TRX能量账号秘钥
  319. * @return {*}
  320. */
  321. public static function getTrxPrivateKey()
  322. {
  323. $str = config('app.trx_private_key');
  324. return $str;
  325. }
  326. }