WalletService.php 35 KB

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