WalletService.php 36 KB

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