WalletService.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2017~2021 LARAVEL研发中心
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://www.laravel.cn
  8. // +----------------------------------------------------------------------
  9. // | Author: laravel开发员 <laravel.qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace App\Services;
  12. use App\Models\AccountLogModel;
  13. use App\Models\BalanceLogModel;
  14. use App\Models\MemberModel;
  15. use App\Models\WalletLogModel;
  16. use App\Models\WalletModel;
  17. use App\Services\Api\FinanceService;
  18. use App\Services\Api\TaskService;
  19. use GuzzleHttp\Client;
  20. use IEXBase\TronAPI\Tron;
  21. use Illuminate\Support\Facades\DB;
  22. use PHPUnit\TestFixture\issue4498test;
  23. use Tron\Api;
  24. use Tron\TRC20;
  25. use Tron\TRX;
  26. /**
  27. * 钱包管理-服务类
  28. * @package App\Services
  29. */
  30. class WalletService extends BaseService
  31. {
  32. protected $apiUrl = '';
  33. protected $config = [];
  34. // 静态对象
  35. protected static $instance = null;
  36. protected $apiUrls = [
  37. 'transactions' => '/v1/accounts/%s/transactions/trc20?limit=%s&only_to=%s&only_from=%s&only_confirmed=true&contract_address=TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
  38. ];
  39. /**
  40. * 构造函数
  41. * UsdtWalletService constructor.
  42. */
  43. public function __construct()
  44. {
  45. $this->config = ConfigService::make()->getConfigOptionByGroup(14);
  46. if (empty($this->config)) {
  47. return false;
  48. }
  49. }
  50. /**
  51. * 静态入口
  52. * @return static|null
  53. */
  54. public static function make()
  55. {
  56. if (!self::$instance) {
  57. self::$instance = (new static());
  58. }
  59. return self::$instance;
  60. }
  61. /**
  62. * 获取平台钱包地址
  63. * @param int $type
  64. */
  65. public function getWallet($type = 1, $amount = 0, $coinType = 1)
  66. {
  67. $cacheKey = "caches:wallet:platform:{$type}";
  68. $wallets = RedisService::get($cacheKey);
  69. if (empty($wallets)) {
  70. $wallets = WalletModel::where(['type' => $type, 'status' => 1, 'mark' => 1])->select(['address', 'private_key'])->get();
  71. $wallets = $wallets ? $wallets->toArray() : [];
  72. if ($wallets) {
  73. RedisService::set($cacheKey, $wallets, rand(300, 600));
  74. }
  75. }
  76. if (empty($wallets)) {
  77. $this->error = $type == 1 ? 1036 : 1037;
  78. return false;
  79. }
  80. // 需要验证余额
  81. if ($amount > 0) {
  82. foreach ($wallets as $item) {
  83. $address = isset($item['address']) ? trim($item['address']) : '';
  84. $privateKey = isset($item['private_key']) ? trim($item['private_key']) : '';
  85. $privateKey = $this->getAddressPrivateKey($privateKey, $address, 2);
  86. if ($coinType == 1) {
  87. $balance = $this->getTrcUsdtBalance($address);
  88. } else {
  89. $balance = $this->getTrcUsdtBalance($address);
  90. }
  91. if ($balance >= $amount) {
  92. return ['address' => $address, 'private_key' => $privateKey];
  93. }
  94. }
  95. $this->error = 1038;
  96. EmailService::make()->sendPlatformEmail('您的出账钱包地址' . ($coinType == 1 ? 'USDT' : 'TRX') . '余额不足,将会影响到提现打款,请及时登录系统后台查看钱包并充值');
  97. return false;
  98. } else {
  99. $rand = rand(0, count($wallets) - 1);
  100. $wallet = $wallets[$rand];
  101. $wallet['private_key'] = $this->getAddressPrivateKey($wallet['private_key'], $wallet['address'], 2);
  102. return $wallet;
  103. }
  104. }
  105. /**
  106. * 获取所有钱包地址
  107. * @return array|mixed
  108. */
  109. public function getWalletList()
  110. {
  111. $cacheKey = "caches:wallet:platform:all";
  112. $wallets = RedisService::get($cacheKey);
  113. if ($wallets) {
  114. return $wallets;
  115. }
  116. $wallets = WalletModel::where(['status' => 1, 'mark' => 1])->select(['id','address','type'])->get();
  117. $wallets = $wallets ? $wallets->toArray() : [];
  118. if ($wallets) {
  119. RedisService::set($cacheKey, $wallets, rand(300, 600));
  120. }
  121. return $wallets;
  122. }
  123. /**
  124. * 加解密密钥
  125. * @param $key 密钥或加密密钥
  126. * @param $address 地址
  127. * @param $type 类型:1-加密,2-解密
  128. * @return mixed|string|string[]
  129. */
  130. public function getAddressPrivateKey($key, $address, $type)
  131. {
  132. // 加密
  133. if ($type == 1) {
  134. $baseStr = base64_encode($key);
  135. $str = substr($baseStr, -6, 7) . substr(md5($address), 2, 6) . substr($baseStr, 0, -6);
  136. return str_replace(['==', '='], ['-2', '-1'], $str);
  137. } // 解密
  138. else {
  139. $str1 = substr($key, 12) . substr($key, 0, 6);
  140. $str1 = str_replace(['-1', '-2'], ['=', '=='], $str1);
  141. return base64_decode($str1);
  142. }
  143. }
  144. /**
  145. * 获取接口密钥
  146. * @return false|mixed|string
  147. */
  148. public function getApiKey()
  149. {
  150. $keys = $this->config['tron_api_keys'];
  151. $keys = $keys ? explode("\n", $keys) : [];
  152. if (empty($keys)) {
  153. $this->error = 1035;
  154. return false;
  155. }
  156. $len = rand(0, count($keys) - 1);
  157. $key = $keys[$len];
  158. return trim($key);
  159. }
  160. /**
  161. * 获取TRC2.0钱包地址
  162. * @throws \Tron\Exceptions\TronErrorException
  163. */
  164. public function getTrcAddress()
  165. {
  166. try {
  167. if (!$apiKey = $this->getApiKey()) {
  168. return false;
  169. }
  170. $headers = ["TRON-PRO-API-KEY" => $apiKey];
  171. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], $headers]));
  172. $trxWallet = new TRX($api);
  173. $addressData = $trxWallet->generateAddress();
  174. $addressData = (array)$addressData;
  175. return ['wif' => $addressData['privateKey'], 'hexAddress' => $addressData['hexAddress'], 'address' => $addressData['address']];
  176. } catch (\Exception $exception) {
  177. $this->error = $exception->getMessage();
  178. return false;
  179. }
  180. }
  181. /**
  182. * USDT-TRC20余额
  183. * @param $address
  184. * @return false|float|string
  185. */
  186. public function getTrcUsdtBalance($address, $cache = false)
  187. {
  188. if (empty($address)) {
  189. $this->error = '1018';
  190. return false;
  191. }
  192. if (empty($this->config['tron_api_url'])) {
  193. $this->error = '2206';
  194. return false;
  195. }
  196. $cacheKey = "caches:wallet:balance:usdt_{$address}";
  197. if ($data = RedisService::get($cacheKey) && $cache) {
  198. return $data;
  199. }
  200. if (RedisService::get($cacheKey . '_lock') && $cache) {
  201. return false;
  202. }
  203. try {
  204. if (!$apiKey = $this->getApiKey()) {
  205. return false;
  206. }
  207. $headers = ["TRON-PRO-API-KEY" => $apiKey];
  208. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  209. $trxWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  210. $tron = new Tron();
  211. $tron->setAddress($address);
  212. $address = $tron->getAddress();
  213. $address = new \Tron\Address($address['base58'], '', $address['hex']);
  214. $result = $trxWallet->balance($address);
  215. $result = $result ? floatval($result) : '0.00';
  216. RedisService::set($cacheKey, $result, rand(3, 5));
  217. RedisService::set($cacheKey . '_lock', true, rand(3, 5));
  218. return $result;
  219. } catch (\Exception $exception) {
  220. $this->error = $exception->getMessage();
  221. return false;
  222. }
  223. }
  224. /**
  225. * TRX余额
  226. * @param $address
  227. * @return false|float|string
  228. */
  229. public function getTrxBalance($address, $cache = false)
  230. {
  231. if (empty($address)) {
  232. $this->error = '1018';
  233. return false;
  234. }
  235. if (empty($this->config['tron_api_url'])) {
  236. $this->error = '2206';
  237. return false;
  238. }
  239. $cacheKey = "caches:wallet:balance:trx_{$address}";
  240. if ($data = RedisService::get($cacheKey) && $cache) {
  241. return $data;
  242. }
  243. if (RedisService::get($cacheKey . '_lock') && $cache) {
  244. return false;
  245. }
  246. try {
  247. if (!$apiKey = $this->getApiKey()) {
  248. return false;
  249. }
  250. $headers = ["TRON-PRO-API-KEY" => $apiKey];
  251. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  252. $trxWallet = new TRX($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  253. $tron = new Tron();
  254. $tron->setAddress($address);
  255. $address = $tron->getAddress();
  256. $address = new \Tron\Address($address['base58'], '', $address['hex']);
  257. $result = $trxWallet->balance($address);
  258. $result = $result ? formatScientific($result) : '0.00';
  259. RedisService::set($cacheKey, $result, rand(3, 5));
  260. RedisService::set($cacheKey . '_lock', true, rand(3, 5));
  261. return $result;
  262. } catch (\Exception $exception) {
  263. $this->error = $exception->getMessage();
  264. return false;
  265. }
  266. }
  267. /**
  268. * trx 转账
  269. * @param $to 进账账户
  270. * @param $amount 转账金额
  271. * @throws \Tron\Exceptions\TransactionException
  272. * @throws \Tron\Exceptions\TronErrorException
  273. */
  274. public function trxTransfer($to, $amount, $from = '', $fromPrivateKey = '')
  275. {
  276. if ($amount <= 0) {
  277. $this->error = '2205';
  278. return false;
  279. }
  280. if (empty($this->config['tron_api_url'])) {
  281. $this->error = '2206';
  282. return false;
  283. }
  284. // 获取钱包参数
  285. try {
  286. if (!$apiKey = $this->getApiKey()) {
  287. return false;
  288. }
  289. $headers = ["TRON-PRO-API-KEY" => $apiKey];
  290. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  291. $trcWallet = new TRX($api);
  292. if ($from && $fromPrivateKey) {
  293. $outAddress = [
  294. 'address' => $from,
  295. 'private_key' => $fromPrivateKey,
  296. ];
  297. } else if (!$outAddress = $this->getWallet(2)) {
  298. return false;
  299. }
  300. $outAddressPrivate = isset($outAddress['private_key']) ? $outAddress['private_key'] : '';
  301. $outAddress = isset($outAddress['address']) ? $outAddress['address'] : '';
  302. if (empty($outAddress) || empty($outAddressPrivate)) {
  303. $this->error = '2203';
  304. return false;
  305. }
  306. $tron = new Tron();
  307. // 获取平台钱包hex
  308. $tron->setAddress($outAddress);
  309. $outAddressData = $tron->getAddress();
  310. $tron->setAddress($to);
  311. $toAddress = $tron->getAddress();
  312. RedisService::set("caches:wallet:transfer:temp_trx_{$to}", ['to' => $to, 'out' => $outAddress, 'amount' => $amount], 7200);
  313. $fromAddress = new \Tron\Address($outAddressData['base58'], $outAddressPrivate, $outAddressData['hex']);
  314. $toAddress = new \Tron\Address($toAddress['base58'], '', $toAddress['hex']);
  315. $result = $trcWallet->transfer($fromAddress, $toAddress, $amount);
  316. $result = (array)$result;
  317. $txID = isset($result['txID']) ? $result['txID'] : '';
  318. RedisService::set("caches:wallet:transfer:result_trx_{$to}", ['to' => $to, 'out' => $outAddress, 'result' => $result], 7200);
  319. if ($txID) {
  320. return ['txId'=> $txID,'address'=> $outAddress];
  321. }
  322. return false;
  323. } catch (\Exception $exception) {
  324. $message = $exception->getMessage();
  325. $this->error = $message;
  326. RedisService::set("caches:wallet:transfer:error_trx_{$to}", ['error' => $exception->getTrace()], 600);
  327. return false;
  328. }
  329. }
  330. /**
  331. * usdt-trc2.0 转账
  332. * @param $to 进账账户
  333. * @param $amount 转账金额
  334. * @param $from 转账账户
  335. * @param $fromPrivate 转账账户私钥
  336. * @throws \Tron\Exceptions\TransactionException
  337. * @throws \Tron\Exceptions\TronErrorException
  338. */
  339. public function usdtTrcTransfer($to, $amount, $from = '', $fromPrivateKey = '')
  340. {
  341. if ($amount <= 0) {
  342. $this->error = '2205';
  343. return false;
  344. }
  345. if (empty($this->config['tron_api_url'])) {
  346. $this->error = '2206';
  347. return false;
  348. }
  349. // 获取钱包参数
  350. try {
  351. if (!$apiKey = $this->getApiKey()) {
  352. return false;
  353. }
  354. $headers = ["TRON-PRO-API-KEY" => $apiKey];
  355. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  356. $trcWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  357. if ($from && $fromPrivateKey) {
  358. $outAddress = [
  359. 'address' => $from,
  360. 'private_key' => $fromPrivateKey,
  361. ];
  362. } else if (!$outAddress = $this->getWallet(2, $amount)) {
  363. return false;
  364. }
  365. $outAddressPrivate = isset($outAddress['private_key']) ? $outAddress['private_key'] : '';
  366. $outAddress = isset($outAddress['address']) ? $outAddress['address'] : '';
  367. if (empty($outAddress) || empty($outAddressPrivate)) {
  368. $this->error = '2203';
  369. return false;
  370. }
  371. $tron = new Tron();
  372. // 获取平台钱包hex
  373. $tron->setAddress($outAddress);
  374. $outAddressData = $tron->getAddress();
  375. // 获取收款钱包hex
  376. $tron->setAddress($to);
  377. $toAddress = $tron->getAddress();
  378. $fromAddress = new \Tron\Address($outAddressData['base58'], $outAddressPrivate, $outAddressData['hex']);
  379. $toAddress = new \Tron\Address($toAddress['base58'], '', $toAddress['hex']);
  380. RedisService::set("caches:wallet:transfer:temp_usdt_{$to}", ['to' => $to, 'out' => $outAddress,'private'=>$outAddressPrivate, 'amount' => $amount], 7200);
  381. $result = $trcWallet->transfer($fromAddress, $toAddress, $amount);
  382. $result = (array)$result;
  383. $txID = isset($result['txID']) ? $result['txID'] : '';
  384. RedisService::set("caches:wallet:transfer:result_usdt_{$to}", ['to' => $to, 'out' => $outAddress,'private'=>$outAddressPrivate, 'result' => $result], 7200);
  385. if ($txID) {
  386. return ['txId'=> $txID, 'address'=>$outAddress];
  387. }
  388. return false;
  389. } catch (\Exception $exception) {
  390. $message = $exception->getMessage();
  391. $this->error = $message;
  392. RedisService::set("caches:wallet:transfer:error_usdt_{$to}", ['error' => $exception->getTrace()], 600);
  393. return false;
  394. }
  395. }
  396. /**
  397. * 监听USDT-TRC2.0用户子钱包充值存币处理
  398. * @param $address 钱包地址
  399. * @param int $accountType 账户类型:1-USDT充值,2-USDT提现,3-星豆充值
  400. * @return array|false
  401. */
  402. public function listenTrcWallet($address, $accountType=1)
  403. {
  404. // 获取钱包参数
  405. try {
  406. if (!$apiKey = $this->getApiKey()) {
  407. return false;
  408. }
  409. $headers = ["TRON-PRO-API-KEY" => $apiKey];
  410. $limit = ConfigService::make()->getConfigByCode('wallet_listen_limit', 300);
  411. $limit = $limit>10 && $limit <=500? $limit : 200;
  412. $url = sprintf($this->apiUrls['transactions'], $address, $limit, $accountType==2? 'false': 'true', $accountType==2?'true':'false');
  413. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 5);
  414. $result = $result ? json_decode($result, true) : [];
  415. $datas = isset($result['data']) && is_array($result['data'])? $result['data'] : [];
  416. $status = isset($result['success']) ? $result['success'] : '';
  417. RedisService::set("caches:wallets:listen_{$address}", ['url' => $this->config['tron_api_url'] . $url, 'result' => $result], 7200);
  418. if ($status != true || empty($datas)) {
  419. $this->error = '2207';
  420. return false;
  421. }
  422. $coinInMin = ConfigService::make()->getConfigByCode('trc_in_limit');
  423. $coinInMin = $coinInMin > 0 ? $coinInMin : 0;
  424. $cacheKey = "caches:wallet:listen:{$address}_{$accountType}:";
  425. $dateTime = date('Y-m-d H:i:s');
  426. $success = 0;
  427. if ($datas) {
  428. foreach ($datas as $v) {
  429. $amount = isset($v['value']) ? intval($v['value']) : 0;
  430. $amount = moneyFormat($amount / 1000000, 6);
  431. $time = isset($v['block_timestamp']) ? intval($v['block_timestamp'] / 1000) : 0;
  432. $txid = isset($v['transaction_id']) ? $v['transaction_id'] : '';
  433. $ownerAddress = isset($v['from']) ? $v['from'] : '';
  434. $toAddress = isset($v['to']) ? $v['to'] : '';
  435. if($amount < $coinInMin) {
  436. echo "【{$dateTime} wallet】账户[{$ownerAddress}]到钱包[{$toAddress}]记录[{$txid}]金额[{$amount}],金额较小不处理\n";
  437. RedisService::set($cacheKey."{$txid}:error", ['error'=>'金额较小不处理','data'=> $v], 7200);
  438. continue;
  439. }
  440. // 充值处理
  441. if($toAddress == $address && $ownerAddress && $accountType != 2){
  442. if (BalanceLogModel::checkExists($txid)) {
  443. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]交易已处理过\n";
  444. RedisService::set($cacheKey."{$txid}:error", ['error'=>'交易已处理过','data'=> $v], 7200);
  445. continue;
  446. }
  447. $memberInfo = MemberModel::where(['trc_url' => $ownerAddress,'mark'=>1])
  448. ->select(['id','email','trc_url','usdt','balance'])
  449. ->orderBy('id','asc')
  450. ->first();
  451. $trcUrl = isset($memberInfo['trc_url'])? trim($memberInfo['trc_url']) : '';
  452. $usdt = isset($memberInfo['usdt'])? floatval($memberInfo['usdt']) : 0;
  453. $balance = isset($memberInfo['balance'])? floatval($memberInfo['balance']) : 0;
  454. $userId = isset($memberInfo['id'])? intval($memberInfo['id']) : 0;
  455. if(empty($memberInfo)){
  456. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]未绑定用户\n";
  457. RedisService::set($cacheKey."{$txid}:error", ['error'=>'未绑定用户','data'=> $v], 7200);
  458. continue;
  459. }
  460. // 充值汇率
  461. $rate = ConfigService::make()->getConfigByCode('xd_price',0.01);
  462. $rate = $rate>0 && $rate <= 10000? $rate : 0.01;
  463. // 入账
  464. DB::beginTransaction();
  465. $updateData = ['update_time'=> time()];
  466. $total = $amount;
  467. if($accountType == 1){
  468. $updateData['usdt'] = DB::raw("usdt + {$total}");
  469. }else if($accountType == 3){
  470. $total = moneyFormat($rate * $amount, 6);
  471. $updateData['balance'] = DB::raw("balance + {$total}");
  472. }
  473. if(!MemberModel::where(['id'=> $userId])->update($updateData)){
  474. DB::rollBack();
  475. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]入账处理失败\n";
  476. RedisService::set($cacheKey."{$txid}:error", ['error'=>'入账处理失败','update'=>$updateData,'member'=> $memberInfo,'data'=> $v], 7200);
  477. continue;
  478. }
  479. // 充值明细
  480. $data = [
  481. 'user_id'=> $userId,
  482. 'order_no'=> get_order_num('XC'),
  483. 'type'=> 1,
  484. 'user_type'=> 1,
  485. 'coin_type'=> $accountType==1? 1 : 2,
  486. 'money'=> $amount,
  487. 'actual_money'=> $total,
  488. 'pay_type'=> 20,
  489. 'pay_status'=> 20,
  490. 'pay_at'=> date('Y-m-d H:i:s', $time),
  491. 'hash'=> $txid,
  492. 'trc_url'=> $trcUrl,
  493. 'wallet_url'=> $address,
  494. 'date'=> date('Y-m-d'),
  495. 'create_time'=> time(),
  496. 'update_time'=> time(),
  497. 'status'=> 2,
  498. 'mark'=>1,
  499. ];
  500. if(!BalanceLogModel::insert($data)){
  501. DB::rollBack();
  502. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]充值明细处理失败\n";
  503. RedisService::set($cacheKey."{$txid}:error", ['error'=>'充值明细处理失败','log'=> $data,'member'=> $memberInfo,'data'=> $v], 7200);
  504. continue;
  505. }
  506. // 用户账户明细
  507. $log = [
  508. 'user_id'=> $userId,
  509. 'source_order_no'=> $data['order_no'],
  510. 'user_type'=> 1,
  511. 'type'=> 5,
  512. 'coin_type'=> $accountType==1? 1 : 2,
  513. 'hash'=> $txid,
  514. 'money'=> $amount,
  515. 'actual_money'=> $total,
  516. 'balance'=> $accountType==1? $usdt : $balance,
  517. 'date'=> date('Y-m-d'),
  518. 'create_time'=> time(),
  519. 'update_time'=> time(),
  520. 'remark'=> $accountType==1? 'USDT余额充值':'星豆余额充值',
  521. 'status'=> 1,
  522. 'mark'=>1,
  523. ];
  524. if(!AccountLogModel::insert($log)){
  525. DB::rollBack();
  526. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]账户明细处理失败\n";
  527. RedisService::set($cacheKey."{$txid}:error", ['error'=>'账户明细处理失败','log'=>$log,'member'=> $memberInfo,'data'=> $v], 7200);
  528. continue;
  529. }
  530. // 平台进账
  531. FinanceService::make()->saveLog(0, $amount, 1);
  532. // 平台账户明细
  533. $log = [
  534. 'user_id'=> 0,
  535. 'source_id'=> $userId,
  536. 'source_order_no'=> $data['order_no'],
  537. 'user_type'=> 4,
  538. 'type'=> 5,
  539. 'coin_type'=> 1,
  540. 'hash'=> $txid,
  541. 'money'=> $amount,
  542. 'actual_money'=> $amount,
  543. 'balance'=> 0,
  544. 'date'=> date('Y-m-d'),
  545. 'create_time'=> time(),
  546. 'update_time'=> time(),
  547. 'remark'=> 'USD充值',
  548. 'status'=> 1,
  549. 'mark'=>1,
  550. ];
  551. if(!AccountLogModel::insert($log)){
  552. DB::rollBack();
  553. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]平台账户明细处理失败\n";
  554. RedisService::set($cacheKey."{$txid}:error", ['error'=>'平台账户明细处理失败','log'=>$log,'member'=> $memberInfo,'data'=> $v], 7200);
  555. continue;
  556. }
  557. // 邮件消息
  558. DB::commit();
  559. // 充值星豆/USDT任务
  560. TaskService::make()->updateTask($userId,$accountType==1?10:9, 0);
  561. $total = moneyFormat($total,2);
  562. $amount = moneyFormat($amount,2);
  563. $coinName = $accountType==1?'USDT':'星豆';
  564. $message = "您在 {$dateTime} (UTC+8) 充值{$total}到星链".($accountType==1?'USDT':'星豆')."账户成功,明细如下:<br>充值账户:{$trcUrl}<br>充值:{$amount} USDT<br>到账:{$total} {$coinName}<br>单号:{$data['order_no']}<br>交易单号:<a href='https://tronscan.org/#/transaction/{$txid}'>{$txid}</a>";
  565. EmailService::make()->sendUserEmail($userId, $message, $coinName.'充值到账通知',3);
  566. RedisService::set($cacheKey."{$txid}:success", ['error'=>'处理成功','log'=>$data,'member'=> $memberInfo,'data'=> $v], 7200);
  567. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]充值成功\n";
  568. RedisService::clear("caches:wallet:balanceLog:{$txid}");
  569. $success++;
  570. }
  571. // 提现处理
  572. else if($ownerAddress == $address && $toAddress && $accountType == 2){
  573. // 处理锁跳过
  574. if(RedisService::get($cacheKey."{$txid}:lock")){
  575. echo "【{$dateTime} withdraw】提现记录[{$txid}]金额[{$amount}]间隔时间不处理\n";
  576. RedisService::set($cacheKey."{$txid}:error", ['error'=>'间隔时间内不处理','data'=> $v], 600);
  577. continue;
  578. }
  579. $info = BalanceLogModel::checkExists($txid);
  580. $logId = isset($info['id'])? $info['id'] : 0;
  581. $userId = isset($info['user_id'])? $info['user_id'] : 0;
  582. $money = isset($info['money'])? $info['money'] : 0;
  583. $actualMoney = isset($info['actual_money'])? $info['actual_money'] : 0;
  584. $coinType = isset($info['coin_type'])? $info['coin_type'] : 1;
  585. $payStatus = isset($info['pay_status'])? $info['pay_status'] : 0;
  586. $status = isset($info['status'])? $info['status'] : 0;
  587. $trcUrl = isset($info['trc_url'])? trim($info['trc_url']) : '';
  588. $walletUrl = isset($info['wallet_url'])? trim($info['wallet_url']) : '';
  589. if (empty($info) || $logId<=0 || $userId<=0) {
  590. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}]提现记录不存在\n";
  591. RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现记录不存在','data'=> $v], 7200);
  592. RedisService::set($cacheKey."{$txid}:lock", ['error'=>'提现记录不存在','data'=> $v], rand(30,60));
  593. continue;
  594. }
  595. if($status != 2){
  596. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}]提现记录未审核\n";
  597. RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现记录未审核','data'=> $v], 7200);
  598. RedisService::set($cacheKey."{$txid}:lock", ['error'=>'提现记录未审核','data'=> $v], rand(30,60));
  599. continue;
  600. }
  601. if($payStatus == 20){
  602. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}]提现记录已打款\n";
  603. RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现记录已打款','data'=> $v], 7200);
  604. RedisService::set($cacheKey."{$txid}:lock", ['error'=>'提现记录已打款','data'=> $v], rand(30,60));
  605. continue;
  606. }
  607. if ($trcUrl != $toAddress || $walletUrl != $ownerAddress) {
  608. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],提现订单交易地址不匹配\n";
  609. RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现订单交易地址不匹配','info'=>$info,'data'=> $v], 7200);
  610. continue;
  611. }
  612. // 金额验证
  613. if(abs($actualMoney - $amount) > 1){
  614. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],提现金额与交易金额不匹配\n";
  615. RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现金额与交易金额不匹配','info'=>$info,'data'=> $v], 7200);
  616. RedisService::set($cacheKey."{$txid}:lock", ['error'=>'提现金额与交易金额不匹配','data'=> $v], rand(30,60));
  617. continue;
  618. }
  619. // 更新状态
  620. DB::beginTransaction();
  621. if(!BalanceLogModel::where(['id'=> $logId])->update(['pay_status'=> 20,'pay_at'=>$dateTime, 'update_time'=>time()])){
  622. DB::rollBack();
  623. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],提现状态更新失败\n";
  624. RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现状态更新失败','info'=>$info,'data'=> $v], 7200);
  625. continue;
  626. }
  627. // 平台出账
  628. FinanceService::make()->saveLog(0, $amount, 2);
  629. // 平台账户明细
  630. $orderNo = isset($info['order_no'])? $info['order_no'] : '';
  631. $log = [
  632. 'user_id'=> 0,
  633. 'source_id'=> $userId,
  634. 'source_order_no'=> $orderNo,
  635. 'user_type'=> 4,
  636. 'type'=> 5,
  637. 'coin_type'=> 1,
  638. 'hash'=> $txid,
  639. 'money'=> $money,
  640. 'actual_money'=> -$amount,
  641. 'balance'=> 0,
  642. 'date'=> date('Y-m-d'),
  643. 'create_time'=> time(),
  644. 'update_time'=> time(),
  645. 'status'=> 1,
  646. 'mark'=>1,
  647. ];
  648. if(!AccountLogModel::insert($log)){
  649. DB::rollBack();
  650. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],平台账户明细处理失败\n";
  651. RedisService::set($cacheKey."{$txid}:error", ['error'=>'平台账户明细处理失败','log'=>$log,'info'=> $info,'data'=> $v], 7200);
  652. continue;
  653. }
  654. // 邮件消息
  655. DB::commit();
  656. $amount = moneyFormat($amount,2);
  657. $accounts = [1=>'USDT',2=>'星豆',3=>'C2C额度',4=>'佣金',5=>'商户余额'];
  658. $coinName = isset($accounts[$coinType])? $accounts[$coinType] : '余额';
  659. $message = "您在 {$dateTime} (UTC+8) 从星链平台{$coinName}账户提现{$amount}成功,明细如下:<br>提现账户:{$trcUrl}<br>提现数量:{$money}<br>到账:{$amount} USDT<br>单号:{$orderNo}<br>交易单号:{$txid} <a href='https://tronscan.org/#/transaction/{$txid}'>查看交易详情</a>";
  660. EmailService::make()->sendUserEmail($userId, $message, $coinName.'提现到账通知', 3);
  661. RedisService::set($cacheKey."{$txid}:success", ['error'=>'处理成功','log'=>$log,'info'=>$info,'data'=> $v], 7200);
  662. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],提现成功\n";
  663. RedisService::clear("caches:wallet:balanceLog:{$txid}");
  664. $success++;
  665. }
  666. // 处理交易记录
  667. if (!WalletLogModel::checkExists($txid)) {
  668. $log = [
  669. 'owner_address' => $ownerAddress,
  670. 'to_address' => $toAddress,
  671. 'hash' => $txid,
  672. 'amount' => $amount,
  673. 'create_time' => $time ? $time : time(),
  674. 'update_time' => time(),
  675. 'status' => 1,
  676. 'mark' => 1,
  677. ];
  678. WalletLogModel::insert($log);
  679. }
  680. }
  681. }
  682. $this->error = 1010;
  683. return ['success'=> $success, 'total'=> count($datas)];
  684. } catch (\Exception $exception) {
  685. $message = $exception->getMessage();
  686. $this->error = $message;
  687. RedisService::set("caches:wallet:listen_error_{$address}", ['error' => $exception->getMessage(), 'trace' => $exception->getTrace()], 600);
  688. return false;
  689. }
  690. }
  691. }