WalletService.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  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. var_dump($result);
  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;
  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)) {
  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. RedisService::set("caches:wallet:transfer:temp_usdt_{$to}", ['to' => $to, 'out' => $outAddress, 'amount' => $amount], 7200);
  379. $fromAddress = new \Tron\Address($outAddressData['base58'], $outAddressPrivate, $outAddressData['hex']);
  380. $toAddress = new \Tron\Address($toAddress['base58'], '', $toAddress['hex']);
  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, 'result' => $result], 7200);
  385. if ($txID) {
  386. return $txID;
  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. 'remark'=> 'USDT充值',
  498. 'status'=> 2,
  499. 'mark'=>1,
  500. ];
  501. if(!BalanceLogModel::insert($data)){
  502. DB::rollBack();
  503. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]充值明细处理失败\n";
  504. RedisService::set($cacheKey."{$txid}:error", ['error'=>'充值明细处理失败','log'=> $data,'member'=> $memberInfo,'data'=> $v], 7200);
  505. continue;
  506. }
  507. /*
  508. // 用户账户明细
  509. $log = [
  510. 'user_id'=> $userId,
  511. 'source_order_no'=> $data['order_no'],
  512. 'user_type'=> 1,
  513. 'type'=> 5,
  514. 'coin_type'=> $accountType==1? 1 : 2,
  515. 'hash'=> $txid,
  516. 'money'=> $amount,
  517. 'actual_money'=> $total,
  518. 'balance'=> $accountType==1? $usdt : $balance,
  519. 'date'=> date('Y-m-d'),
  520. 'create_time'=> time(),
  521. 'update_time'=> time(),
  522. 'status'=> 1,
  523. 'mark'=>1,
  524. ];
  525. if(!AccountLogModel::insert($log)){
  526. DB::rollBack();
  527. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]账户明细处理失败\n";
  528. RedisService::set($cacheKey."{$txid}:error", ['error'=>'账户明细处理失败','log'=>$log,'member'=> $memberInfo,'data'=> $v], 7200);
  529. continue;
  530. }*/
  531. // 平台进账
  532. FinanceService::make()->saveLog(0, $amount, 1);
  533. // 平台账户明细
  534. $log = [
  535. 'user_id'=> 0,
  536. 'source_id'=> $userId,
  537. 'source_order_no'=> $data['order_no'],
  538. 'user_type'=> 4,
  539. 'type'=> 5,
  540. 'coin_type'=> 1,
  541. 'hash'=> $txid,
  542. 'money'=> $amount,
  543. 'actual_money'=> $amount,
  544. 'balance'=> 0,
  545. 'date'=> date('Y-m-d'),
  546. 'create_time'=> time(),
  547. 'update_time'=> time(),
  548. 'remark'=> 'USD充值',
  549. 'status'=> 1,
  550. 'mark'=>1,
  551. ];
  552. if(!AccountLogModel::insert($log)){
  553. DB::rollBack();
  554. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]平台账户明细处理失败\n";
  555. RedisService::set($cacheKey."{$txid}:error", ['error'=>'平台账户明细处理失败','log'=>$log,'member'=> $memberInfo,'data'=> $v], 7200);
  556. continue;
  557. }
  558. // 邮件消息
  559. DB::commit();
  560. $total = moneyFormat($total,2);
  561. $amount = moneyFormat($amount,2);
  562. $coinName = $accountType==1?'USDT':'星豆';
  563. $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>";
  564. EmailService::make()->sendUserEmail($userId, $message, $coinName.'充值到账通知',3);
  565. RedisService::set($cacheKey."{$txid}:success", ['error'=>'处理成功','log'=>$data,'member'=> $memberInfo,'data'=> $v], 7200);
  566. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]充值成功\n";
  567. RedisService::clear("caches:wallet:balanceLog:{$txid}");
  568. $success++;
  569. }
  570. // 提现处理
  571. else if($ownerAddress == $address && $toAddress && $accountType == 2){
  572. // 处理锁跳过
  573. if(RedisService::get($cacheKey."{$txid}:lock")){
  574. echo "【{$dateTime} withdraw】提现记录[{$txid}]金额[{$amount}]间隔时间不处理\n";
  575. RedisService::set($cacheKey."{$txid}:error", ['error'=>'间隔时间内不处理','data'=> $v], 600);
  576. continue;
  577. }
  578. $info = BalanceLogModel::checkExists($txid);
  579. $logId = isset($info['id'])? $info['id'] : 0;
  580. $userId = isset($info['user_id'])? $info['user_id'] : 0;
  581. $money = isset($info['money'])? $info['money'] : 0;
  582. $actualMoney = isset($info['actual_money'])? $info['actual_money'] : 0;
  583. $coinType = isset($info['coin_type'])? $info['coin_type'] : 1;
  584. $payStatus = isset($info['pay_status'])? $info['pay_status'] : 0;
  585. $status = isset($info['status'])? $info['status'] : 0;
  586. $trcUrl = isset($info['trc_url'])? trim($info['trc_url']) : '';
  587. $walletUrl = isset($info['wallet_url'])? trim($info['wallet_url']) : '';
  588. if (empty($info) || $logId<=0 || $userId<=0) {
  589. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}]提现记录不存在\n";
  590. RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现记录不存在','data'=> $v], 7200);
  591. RedisService::set($cacheKey."{$txid}:lock", ['error'=>'提现记录不存在','data'=> $v], rand(30,60));
  592. continue;
  593. }
  594. if($status != 2){
  595. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}]提现记录未审核\n";
  596. RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现记录未审核','data'=> $v], 7200);
  597. RedisService::set($cacheKey."{$txid}:lock", ['error'=>'提现记录未审核','data'=> $v], rand(30,60));
  598. continue;
  599. }
  600. if($payStatus == 20){
  601. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}]提现记录已打款\n";
  602. RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现记录已打款','data'=> $v], 7200);
  603. RedisService::set($cacheKey."{$txid}:lock", ['error'=>'提现记录已打款','data'=> $v], rand(30,60));
  604. continue;
  605. }
  606. if ($trcUrl != $toAddress || $walletUrl != $ownerAddress) {
  607. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],提现订单交易地址不匹配\n";
  608. RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现订单交易地址不匹配','info'=>$info,'data'=> $v], 7200);
  609. continue;
  610. }
  611. // 金额验证
  612. if(abs($actualMoney - $amount) > 1){
  613. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],提现金额与交易金额不匹配\n";
  614. RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现金额与交易金额不匹配','info'=>$info,'data'=> $v], 7200);
  615. RedisService::set($cacheKey."{$txid}:lock", ['error'=>'提现金额与交易金额不匹配','data'=> $v], rand(30,60));
  616. continue;
  617. }
  618. // 更新状态
  619. DB::beginTransaction();
  620. if(!BalanceLogModel::where(['id'=> $logId])->update(['pay_status'=> 20,'pay_at'=>$dateTime, 'update_time'=>time()])){
  621. DB::rollBack();
  622. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],提现状态更新失败\n";
  623. RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现状态更新失败','info'=>$info,'data'=> $v], 7200);
  624. continue;
  625. }
  626. // 平台出账
  627. FinanceService::make()->saveLog(0, $amount, 2);
  628. // 平台账户明细
  629. $orderNo = isset($info['order_no'])? $info['order_no'] : '';
  630. $log = [
  631. 'user_id'=> 0,
  632. 'source_id'=> $userId,
  633. 'source_order_no'=> $orderNo,
  634. 'user_type'=> 4,
  635. 'type'=> 5,
  636. 'coin_type'=> 1,
  637. 'hash'=> $txid,
  638. 'money'=> $money,
  639. 'actual_money'=> -$amount,
  640. 'balance'=> 0,
  641. 'date'=> date('Y-m-d'),
  642. 'create_time'=> time(),
  643. 'update_time'=> time(),
  644. 'status'=> 1,
  645. 'mark'=>1,
  646. ];
  647. if(!AccountLogModel::insert($log)){
  648. DB::rollBack();
  649. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],平台账户明细处理失败\n";
  650. RedisService::set($cacheKey."{$txid}:error", ['error'=>'平台账户明细处理失败','log'=>$log,'info'=> $info,'data'=> $v], 7200);
  651. continue;
  652. }
  653. // 邮件消息
  654. DB::commit();
  655. $amount = moneyFormat($amount,2);
  656. $accounts = [1=>'USDT',2=>'星豆',3=>'C2C额度',4=>'佣金',5=>'商户余额'];
  657. $coinName = isset($accounts[$coinType])? $accounts[$coinType] : '余额';
  658. $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>";
  659. EmailService::make()->sendUserEmail($userId, $message, $coinName.'提现到账通知', 3);
  660. RedisService::set($cacheKey."{$txid}:success", ['error'=>'处理成功','log'=>$log,'info'=>$info,'data'=> $v], 7200);
  661. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],提现成功\n";
  662. RedisService::clear("caches:wallet:balanceLog:{$txid}");
  663. $success++;
  664. }
  665. // 处理交易记录
  666. if (!WalletLogModel::checkExists($txid)) {
  667. $log = [
  668. 'owner_address' => $ownerAddress,
  669. 'to_address' => $toAddress,
  670. 'hash' => $txid,
  671. 'amount' => $amount,
  672. 'create_time' => $time ? $time : time(),
  673. 'update_time' => time(),
  674. 'status' => 1,
  675. 'mark' => 1,
  676. ];
  677. WalletLogModel::insert($log);
  678. }
  679. }
  680. }
  681. $this->error = 1010;
  682. return ['success'=> $success, 'total'=> count($datas)];
  683. } catch (\Exception $exception) {
  684. $message = $exception->getMessage();
  685. $this->error = $message;
  686. RedisService::set("caches:wallet:listen_error_{$address}", ['error' => $exception->getMessage(), 'trace' => $exception->getTrace()], 600);
  687. return false;
  688. }
  689. }
  690. }