WalletService.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  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. * @param $key 密钥或加密密钥
  107. * @param $address 地址
  108. * @param $type 类型:1-加密,2-解密
  109. * @return mixed|string|string[]
  110. */
  111. public function getAddressPrivateKey($key, $address, $type)
  112. {
  113. // 加密
  114. if ($type == 1) {
  115. $baseStr = base64_encode($key);
  116. $str = substr($baseStr, -6, 7) . substr(md5($address), 2, 6) . substr($baseStr, 0, -6);
  117. return str_replace(['==', '='], ['-2', '-1'], $str);
  118. } // 解密
  119. else {
  120. $str1 = substr($key, 12) . substr($key, 0, 6);
  121. $str1 = str_replace(['-1', '-2'], ['=', '=='], $str1);
  122. return base64_decode($str1);
  123. }
  124. }
  125. /**
  126. * 获取接口密钥
  127. * @return false|mixed|string
  128. */
  129. public function getApiKey()
  130. {
  131. $keys = $this->config['tron_api_keys'];
  132. $keys = $keys ? explode("\n", $keys) : [];
  133. if (empty($keys)) {
  134. $this->error = 1035;
  135. return false;
  136. }
  137. $len = rand(0, count($keys) - 1);
  138. $key = $keys[$len];
  139. return trim($key);
  140. }
  141. /**
  142. * 获取TRC2.0钱包地址
  143. * @throws \Tron\Exceptions\TronErrorException
  144. */
  145. public function getTrcAddress()
  146. {
  147. try {
  148. if (!$apiKey = $this->getApiKey()) {
  149. return false;
  150. }
  151. $headers = ["TRON-PRO-API-KEY" => $apiKey];
  152. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], $headers]));
  153. $trxWallet = new TRX($api);
  154. $addressData = $trxWallet->generateAddress();
  155. $addressData = (array)$addressData;
  156. return ['wif' => $addressData['privateKey'], 'hexAddress' => $addressData['hexAddress'], 'address' => $addressData['address']];
  157. } catch (\Exception $exception) {
  158. $this->error = $exception->getMessage();
  159. return false;
  160. }
  161. }
  162. /**
  163. * USDT-TRC20余额
  164. * @param $address
  165. * @return false|float|string
  166. */
  167. public function getTrcUsdtBalance($address, $cache = false)
  168. {
  169. if (empty($address)) {
  170. $this->error = '1018';
  171. return false;
  172. }
  173. if (empty($this->config['tron_api_url'])) {
  174. $this->error = '2206';
  175. return false;
  176. }
  177. $cacheKey = "caches:wallet:balance:usdt_{$address}";
  178. if ($data = RedisService::get($cacheKey) && $cache) {
  179. return $data;
  180. }
  181. if (RedisService::get($cacheKey . '_lock') && $cache) {
  182. return false;
  183. }
  184. try {
  185. if (!$apiKey = $this->getApiKey()) {
  186. return false;
  187. }
  188. $headers = ["TRON-PRO-API-KEY" => $apiKey];
  189. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  190. $trxWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  191. $tron = new Tron();
  192. $tron->setAddress($address);
  193. $address = $tron->getAddress();
  194. $address = new \Tron\Address($address['base58'], '', $address['hex']);
  195. $result = $trxWallet->balance($address);
  196. var_dump($result);
  197. $result = $result ? floatval($result) : '0.00';
  198. RedisService::set($cacheKey, $result, rand(3, 5));
  199. RedisService::set($cacheKey . '_lock', true, rand(3, 5));
  200. return $result;
  201. } catch (\Exception $exception) {
  202. $this->error = $exception->getMessage();
  203. return false;
  204. }
  205. }
  206. /**
  207. * TRX余额
  208. * @param $address
  209. * @return false|float|string
  210. */
  211. public function getTrxBalance($address, $cache = false)
  212. {
  213. if (empty($address)) {
  214. $this->error = '1018';
  215. return false;
  216. }
  217. if (empty($this->config['tron_api_url'])) {
  218. $this->error = '2206';
  219. return false;
  220. }
  221. $cacheKey = "caches:wallet:balance:trx_{$address}";
  222. if ($data = RedisService::get($cacheKey) && $cache) {
  223. return $data;
  224. }
  225. if (RedisService::get($cacheKey . '_lock') && $cache) {
  226. return false;
  227. }
  228. try {
  229. if (!$apiKey = $this->getApiKey()) {
  230. return false;
  231. }
  232. $headers = ["TRON-PRO-API-KEY" => $apiKey];
  233. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  234. $trxWallet = new TRX($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  235. $tron = new Tron();
  236. $tron->setAddress($address);
  237. $address = $tron->getAddress();
  238. $address = new \Tron\Address($address['base58'], '', $address['hex']);
  239. $result = $trxWallet->balance($address);
  240. $result = $result ? formatScientific($result) : '0.00';
  241. RedisService::set($cacheKey, $result, rand(3, 5));
  242. RedisService::set($cacheKey . '_lock', true, rand(3, 5));
  243. return $result;
  244. } catch (\Exception $exception) {
  245. $this->error = $exception->getMessage();
  246. return false;
  247. }
  248. }
  249. /**
  250. * trx 转账
  251. * @param $to 进账账户
  252. * @param $amount 转账金额
  253. * @throws \Tron\Exceptions\TransactionException
  254. * @throws \Tron\Exceptions\TronErrorException
  255. */
  256. public function trxTransfer($to, $amount, $from = '', $fromPrivateKey = '')
  257. {
  258. if ($amount <= 0) {
  259. $this->error = '2205';
  260. return false;
  261. }
  262. if (empty($this->config['tron_api_url'])) {
  263. $this->error = '2206';
  264. return false;
  265. }
  266. // 获取钱包参数
  267. try {
  268. if (!$apiKey = $this->getApiKey()) {
  269. return false;
  270. }
  271. $headers = ["TRON-PRO-API-KEY" => $apiKey];
  272. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  273. $trcWallet = new TRX($api);
  274. if ($from && $fromPrivateKey) {
  275. $outAddress = [
  276. 'address' => $from,
  277. 'private_key' => $fromPrivateKey,
  278. ];
  279. } else if (!$outAddress = $this->getWallet(2)) {
  280. return false;
  281. }
  282. $outAddressPrivate = isset($outAddress['private_key']) ? $outAddress['private_key'] : '';
  283. $outAddress = isset($outAddress['address']) ? $outAddress['address'] : '';
  284. if (empty($outAddress) || empty($outAddressPrivate)) {
  285. $this->error = '2203';
  286. return false;
  287. }
  288. $tron = new Tron();
  289. // 获取平台钱包hex
  290. $tron->setAddress($outAddress);
  291. $outAddressData = $tron->getAddress();
  292. $tron->setAddress($to);
  293. $toAddress = $tron->getAddress();
  294. RedisService::set("caches:wallet:transfer:temp_trx_{$to}", ['to' => $to, 'out' => $outAddress, 'amount' => $amount], 7200);
  295. $fromAddress = new \Tron\Address($outAddressData['base58'], $outAddressPrivate, $outAddressData['hex']);
  296. $toAddress = new \Tron\Address($toAddress['base58'], '', $toAddress['hex']);
  297. $result = $trcWallet->transfer($fromAddress, $toAddress, $amount);
  298. $result = (array)$result;
  299. $txID = isset($result['txID']) ? $result['txID'] : '';
  300. RedisService::set("caches:wallet:transfer:result_trx_{$to}", ['to' => $to, 'out' => $outAddress, 'result' => $result], 7200);
  301. if ($txID) {
  302. return $txID;
  303. }
  304. return false;
  305. } catch (\Exception $exception) {
  306. $message = $exception->getMessage();
  307. $this->error = $message;
  308. RedisService::set("caches:wallet:transfer:error_trx_{$to}", ['error' => $exception->getTrace()], 600);
  309. return false;
  310. }
  311. }
  312. /**
  313. * usdt-trc2.0 转账
  314. * @param $to 进账账户
  315. * @param $amount 转账金额
  316. * @param $from 转账账户
  317. * @param $fromPrivate 转账账户私钥
  318. * @throws \Tron\Exceptions\TransactionException
  319. * @throws \Tron\Exceptions\TronErrorException
  320. */
  321. public function usdtTrcTransfer($to, $amount, $from = '', $fromPrivateKey = '')
  322. {
  323. if ($amount <= 0) {
  324. $this->error = '2205';
  325. return false;
  326. }
  327. if (empty($this->config['tron_api_url'])) {
  328. $this->error = '2206';
  329. return false;
  330. }
  331. // 获取钱包参数
  332. try {
  333. if (!$apiKey = $this->getApiKey()) {
  334. return false;
  335. }
  336. $headers = ["TRON-PRO-API-KEY" => $apiKey];
  337. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  338. $trcWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  339. if ($from && $fromPrivateKey) {
  340. $outAddress = [
  341. 'address' => $from,
  342. 'private_key' => $fromPrivateKey,
  343. ];
  344. } else if (!$outAddress = $this->getWallet(2)) {
  345. return false;
  346. }
  347. $outAddressPrivate = isset($outAddress['private_key']) ? $outAddress['private_key'] : '';
  348. $outAddress = isset($outAddress['address']) ? $outAddress['address'] : '';
  349. if (empty($outAddress) || empty($outAddressPrivate)) {
  350. $this->error = '2203';
  351. return false;
  352. }
  353. $tron = new Tron();
  354. // 获取平台钱包hex
  355. $tron->setAddress($outAddress);
  356. $outAddressData = $tron->getAddress();
  357. // 获取收款钱包hex
  358. $tron->setAddress($to);
  359. $toAddress = $tron->getAddress();
  360. RedisService::set("caches:wallet:transfer:temp_usdt_{$to}", ['to' => $to, 'out' => $outAddress, 'amount' => $amount], 7200);
  361. $fromAddress = new \Tron\Address($outAddressData['base58'], $outAddressPrivate, $outAddressData['hex']);
  362. $toAddress = new \Tron\Address($toAddress['base58'], '', $toAddress['hex']);
  363. $result = $trcWallet->transfer($fromAddress, $toAddress, $amount);
  364. $result = (array)$result;
  365. $txID = isset($result['txID']) ? $result['txID'] : '';
  366. RedisService::set("caches:wallet:transfer:result_usdt_{$to}", ['to' => $to, 'out' => $outAddress, 'result' => $result], 7200);
  367. if ($txID) {
  368. return $txID;
  369. }
  370. return false;
  371. } catch (\Exception $exception) {
  372. $message = $exception->getMessage();
  373. $this->error = $message;
  374. RedisService::set("caches:wallet:transfer:error_usdt_{$to}", ['error' => $exception->getTrace()], 600);
  375. return false;
  376. }
  377. }
  378. /**
  379. * 监听USDT-TRC2.0用户子钱包充值存币处理
  380. * @param $address 钱包地址
  381. * @param int $accountType 账户类型:1-USDT充值,2-USDT提现,3-星豆充值
  382. * @return array|false
  383. */
  384. public function listenTrcWallet($address, $accountType=1)
  385. {
  386. // 获取钱包参数
  387. try {
  388. if (!$apiKey = $this->getApiKey()) {
  389. return false;
  390. }
  391. $headers = ["TRON-PRO-API-KEY" => $apiKey];
  392. $limit = ConfigService::make()->getConfigByCode('wallet_listen_limit', 300);
  393. $limit = $limit>10 && $limit <=500? $limit : 200;
  394. $url = sprintf($this->apiUrls['transactions'], $address, $limit, $accountType==2? 'false': 'true', $accountType==2?'true':'false');
  395. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 5);
  396. $result = $result ? json_decode($result, true) : [];
  397. $datas = isset($result['data']) ? $result['data'] : [];
  398. $status = isset($result['success']) ? $result['success'] : '';
  399. RedisService::set("caches:wallets:listen_{$address}", ['url' => $this->config['tron_api_url'] . $url, 'result' => $result], 7200);
  400. if ($status != true || empty($datas)) {
  401. $this->error = '2207';
  402. return false;
  403. }
  404. $coinInMin = ConfigService::make()->getConfigByCode('trc_in_limit');
  405. $coinInMin = $coinInMin > 0 ? $coinInMin : 0;
  406. $cacheKey = "caches:wallet:listen:{$address}_{$accountType}:";
  407. $dateTime = date('Y-m-d H:i:s');
  408. if ($datas) {
  409. foreach ($datas as $v) {
  410. $amount = isset($v['value']) ? intval($v['value']) : 0;
  411. $amount = moneyFormat($amount / 1000000, 6);
  412. $time = isset($v['block_timestamp']) ? intval($v['block_timestamp'] / 1000) : 0;
  413. $txid = isset($v['transaction_id']) ? $v['transaction_id'] : '';
  414. $ownerAddress = isset($v['ownerAddress']) ? $v['ownerAddress'] : '';
  415. $toAddress = isset($v['toAddress']) ? $v['toAddress'] : '';
  416. if($amount < $coinInMin) {
  417. echo "【{$dateTime} wallet】账户[{$ownerAddress}]到钱包[{$toAddress}]记录[{$txid}]金额较小不处理\n";
  418. RedisService::set($cacheKey.'error', ['error'=>'金额较小不处理','data'=> $v], 7200);
  419. continue;
  420. }
  421. // 充值处理
  422. if($toAddress == $address && $ownerAddress && $accountType != 2){
  423. if (BalanceLogModel::checkExists($txid)) {
  424. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]已处理\n";
  425. RedisService::set($cacheKey.'error', ['error'=>'记录已处理','data'=> $v], 7200);
  426. continue;
  427. }
  428. $memberInfo = MemberModel::where(['trc_url' => $ownerAddress,'mark'=>1])->selct(['id','email','trc_url','usdt','balance'])->orderBy('id','asc')->first();
  429. $email = isset($memberInfo['email'])? trim($memberInfo['email']) : '';
  430. $trcUrl = isset($memberInfo['trc_url'])? trim($memberInfo['trc_url']) : '';
  431. $usdt = isset($memberInfo['usdt'])? floatval($memberInfo['usdt']) : 0;
  432. $balance = isset($memberInfo['balance'])? floatval($memberInfo['balance']) : 0;
  433. $userId = isset($memberInfo['id'])? intval($memberInfo['id']) : 0;
  434. if(empty($memberInfo)){
  435. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]未绑定用户\n";
  436. RedisService::set($cacheKey.'error', ['error'=>'用户不存在','data'=> $v], 7200);
  437. continue;
  438. }
  439. // 充值汇率
  440. $rate = ConfigService::make()->getConfigByCode('xd_price',0.01);
  441. $rate = $rate>0 && $rate <= 10000? $rate : 0.01;
  442. // 入账
  443. DB::beginTransaction();
  444. $updateData = ['update_time'=> time()];
  445. $total = $amount;
  446. if($accountType == 1){
  447. $updateData['usdt'] = DB::raw("usdt + {$total}");
  448. }else if($accountType == 3){
  449. $total = moneyFormat($rate * $amount, 6);
  450. $updateData['balance'] = DB::raw("balance + {$total}");
  451. }
  452. if(!MemberModel::where(['id'=> $userId])->update($updateData)){
  453. DB::rollBack();
  454. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]入账处理失败\n";
  455. RedisService::set($cacheKey.'error', ['error'=>'入账处理失败','update'=>$updateData,'member'=> $memberInfo,'data'=> $v], 7200);
  456. continue;
  457. }
  458. // 充值明细
  459. $data = [
  460. 'user_id'=> $userId,
  461. 'order_no'=> get_order_num('XC'),
  462. 'type'=> 1,
  463. 'user_type'=> 1,
  464. 'coin_type'=> $accountType==1? 1 : 2,
  465. 'money'=> $amount,
  466. 'actual_money'=> $total,
  467. 'pay_type'=> 20,
  468. 'pay_status'=> 20,
  469. 'pay_at'=> date('Y-m-d H:i:s', $time),
  470. 'hash'=> $txid,
  471. 'trc_url'=> $trcUrl,
  472. 'wallet_url'=> $address,
  473. 'date'=> date('Y-m-d'),
  474. 'create_time'=> time(),
  475. 'update_time'=> time(),
  476. 'status'=> 2,
  477. 'mark'=>1,
  478. ];
  479. if(!BalanceLogModel::insert($data)){
  480. DB::rollBack();
  481. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]充值明细处理失败\n";
  482. RedisService::set($cacheKey.'error', ['error'=>'充值明细处理失败','log'=> $data,'member'=> $memberInfo,'data'=> $v], 7200);
  483. continue;
  484. }
  485. /*
  486. // 用户账户明细
  487. $log = [
  488. 'user_id'=> $userId,
  489. 'source_order_no'=> $data['order_no'],
  490. 'user_type'=> 1,
  491. 'type'=> 5,
  492. 'coin_type'=> $accountType==1? 1 : 2,
  493. 'money'=> $amount,
  494. 'actual_money'=> $total,
  495. 'balance'=> $accountType==1? $usdt : $balance,
  496. 'date'=> date('Y-m-d'),
  497. 'create_time'=> time(),
  498. 'update_time'=> time(),
  499. 'status'=> 1,
  500. 'mark'=>1,
  501. ];
  502. if(!AccountLogModel::insert($log)){
  503. DB::rollBack();
  504. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]账户明细处理失败\n";
  505. RedisService::set($cacheKey.'error', ['error'=>'账户明细处理失败','log'=>$log,'member'=> $memberInfo,'data'=> $v], 7200);
  506. continue;
  507. }*/
  508. // 平台进账
  509. FinanceService::make()->saveLog(0, $amount, 1);
  510. // 平台账户明细
  511. $log = [
  512. 'user_id'=> 0,
  513. 'source_id'=> $userId,
  514. 'source_order_no'=> $data['order_no'],
  515. 'user_type'=> 4,
  516. 'type'=> 5,
  517. 'coin_type'=> 1,
  518. 'money'=> $amount,
  519. 'actual_money'=> $amount,
  520. 'balance'=> 0,
  521. 'date'=> date('Y-m-d'),
  522. 'create_time'=> time(),
  523. 'update_time'=> time(),
  524. 'status'=> 1,
  525. 'mark'=>1,
  526. ];
  527. if(!AccountLogModel::insert($log)){
  528. DB::rollBack();
  529. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]平台账户明细处理失败\n";
  530. RedisService::set($cacheKey.'error', ['error'=>'平台账户明细处理失败','log'=>$log,'member'=> $memberInfo,'data'=> $v], 7200);
  531. continue;
  532. }
  533. // 邮件消息
  534. $coinName = $accountType==1?'USDT':'星豆';
  535. $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>";
  536. EmailService::make()->sendUserEmail($userId, $message, $coinName.'充值到账通知',3);
  537. }
  538. // 提现处理
  539. else if($ownerAddress == $address && $toAddress && $accountType == 2){
  540. $info = BalanceLogModel::checkExists($txid);
  541. $logId = isset($info['id'])? $info['id'] : 0;
  542. $userId = isset($info['user_id'])? $info['user_id'] : 0;
  543. $money = isset($info['money'])? $info['money'] : 0;
  544. $actualMoney = isset($info['actual_money'])? $info['actual_money'] : 0;
  545. $coinType = isset($info['coin_type'])? $info['coin_type'] : 1;
  546. $trcUrl = isset($info['trc_url'])? trim($info['trc_url']) : '';
  547. $walletUrl = isset($info['wallet_url'])? trim($info['wallet_url']) : '';
  548. if (empty($info) || $logId<=0 || $userId<=0) {
  549. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]不存在\n";
  550. RedisService::set($cacheKey.'error', ['error'=>'提现记录不存在','data'=> $v], 7200);
  551. continue;
  552. }
  553. if ($trcUrl != $toAddress || $walletUrl != $ownerAddress) {
  554. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}],提现订单交易地址不匹配\n";
  555. RedisService::set($cacheKey.'error', ['error'=>'提现订单交易地址不匹配','info'=>$info,'data'=> $v], 7200);
  556. continue;
  557. }
  558. // 金额验证
  559. if(abs($actualMoney - $amount) > 1){
  560. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}],提现金额与交易金额不匹配\n";
  561. RedisService::set($cacheKey.'error', ['error'=>'提现金额与交易金额不匹配','info'=>$info,'data'=> $v], 7200);
  562. continue;
  563. }
  564. // 更新状态
  565. DB::beginTransaction();
  566. if(!BalanceLogModel::where(['id'=> $logId])->update(['status'=> 2, 'update_time'=>time()])){
  567. DB::rollBack();
  568. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}],提现状态更新失败\n";
  569. RedisService::set($cacheKey.'error', ['error'=>'提现状态更新失败','info'=>$info,'data'=> $v], 7200);
  570. continue;
  571. }
  572. // 平台出账
  573. FinanceService::make()->saveLog(0, $amount, 2);
  574. // 平台账户明细
  575. $orderNo = isset($info['order_no'])? $info['order_no'] : '';
  576. $log = [
  577. 'user_id'=> 0,
  578. 'source_id'=> $userId,
  579. 'source_order_no'=> $orderNo,
  580. 'user_type'=> 4,
  581. 'type'=> 5,
  582. 'coin_type'=> 1,
  583. 'money'=> $money,
  584. 'actual_money'=> -$amount,
  585. 'balance'=> 0,
  586. 'date'=> date('Y-m-d'),
  587. 'create_time'=> time(),
  588. 'update_time'=> time(),
  589. 'status'=> 1,
  590. 'mark'=>1,
  591. ];
  592. if(!AccountLogModel::insert($log)){
  593. DB::rollBack();
  594. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}],平台账户明细处理失败\n";
  595. RedisService::set($cacheKey.'error', ['error'=>'平台账户明细处理失败','log'=>$log,'info'=> $info,'data'=> $v], 7200);
  596. continue;
  597. }
  598. // 邮件消息
  599. $accounts = [1=>'USDT',2=>'星豆',3=>'C2C额度',4=>'佣金',5=>'商户余额'];
  600. $coinName = isset($accounts[$coinType])? $accounts[$coinType] : '余额';
  601. $message = "您在 {$dateTime} (UTC+8) 从星链平台{$coinName}账户提现{$amount}成功,明细如下:<br>提现账户:{$trcUrl}<br>提现数量:{$money}<br>到账:{$total} USDT<br>单号:{$orderNo}<br>交易单号:{$txid} <a href='https://tronscan.org/#/transaction/{$txid}'>查看交易详情</a>";
  602. EmailService::make()->sendUserEmail($userId, $message, $coinName.'提现到账通知', 3);
  603. }
  604. if (!WalletLogModel::checkExists($txid)) {
  605. $log = [
  606. 'address' => $address,
  607. 'hash' => $txid,
  608. 'amount' => $amount,
  609. 'create_time' => $time ? $time : time(),
  610. 'update_time' => time(),
  611. 'status' => 1,
  612. 'mark' => 1,
  613. ];
  614. WalletLogModel::insert($log);
  615. }
  616. }
  617. }
  618. return $result;
  619. } catch (\Exception $exception) {
  620. $message = $exception->getMessage();
  621. $this->error = $message;
  622. RedisService::set("caches:wallet:listen_error_{$address}", ['error' => $exception->getMessage(), 'trace' => $exception->getTrace()], 600);
  623. return false;
  624. }
  625. }
  626. }