WalletService.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  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:wallet: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. * USDT-TRC20余额
  184. * @param $address
  185. * @return false|float|string
  186. */
  187. public function getTrcUsdtBalance($address, $cache = false)
  188. {
  189. if (empty($address)) {
  190. $this->error = '1018';
  191. return false;
  192. }
  193. if (empty($this->config['tron_api_url'])) {
  194. $this->error = '2206';
  195. return false;
  196. }
  197. $cacheKey = "caches:wallet:balance:usdt_{$address}";
  198. if ($data = RedisService::get($cacheKey) && $cache) {
  199. return $data;
  200. }
  201. if (RedisService::get($cacheKey . '_lock') && $cache) {
  202. return false;
  203. }
  204. try {
  205. if (!$apiKey = $this->getApiKey()) {
  206. return false;
  207. }
  208. $headers = ["TRON-PRO-API-KEY" => $apiKey];
  209. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  210. $trxWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  211. $tron = new Tron();
  212. $tron->setAddress($address);
  213. $address = $tron->getAddress();
  214. $address = new \Tron\Address($address['base58'], '', $address['hex']);
  215. $result = $trxWallet->balance($address);
  216. $result = $result ? floatval($result) : '0.00';
  217. RedisService::set($cacheKey, $result, rand(3, 5));
  218. RedisService::set($cacheKey . '_lock', true, rand(3, 5));
  219. return $result;
  220. } catch (\Exception $exception) {
  221. $this->error = $exception->getMessage();
  222. return false;
  223. }
  224. }
  225. /**
  226. * TRX余额
  227. * @param $address
  228. * @return false|float|string
  229. */
  230. public function getTrxBalance($address, $cache = false)
  231. {
  232. if (empty($address)) {
  233. $this->error = '1018';
  234. return false;
  235. }
  236. if (empty($this->config['tron_api_url'])) {
  237. $this->error = '2206';
  238. return false;
  239. }
  240. $cacheKey = "caches:wallet:balance:trx_{$address}";
  241. if ($data = RedisService::get($cacheKey) && $cache) {
  242. return $data;
  243. }
  244. if (RedisService::get($cacheKey . '_lock') && $cache) {
  245. return false;
  246. }
  247. try {
  248. if (!$apiKey = $this->getApiKey()) {
  249. return false;
  250. }
  251. $headers = ["TRON-PRO-API-KEY" => $apiKey];
  252. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  253. $trxWallet = new TRX($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  254. $tron = new Tron();
  255. $tron->setAddress($address);
  256. $address = $tron->getAddress();
  257. $address = new \Tron\Address($address['base58'], '', $address['hex']);
  258. $result = $trxWallet->balance($address);
  259. $result = $result ? formatScientific($result) : '0.00';
  260. RedisService::set($cacheKey, $result, rand(3, 5));
  261. RedisService::set($cacheKey . '_lock', true, rand(3, 5));
  262. return $result;
  263. } catch (\Exception $exception) {
  264. $this->error = $exception->getMessage();
  265. return false;
  266. }
  267. }
  268. /**
  269. * trx 转账
  270. * @param $to 进账账户
  271. * @param $amount 转账金额
  272. * @throws \Tron\Exceptions\TransactionException
  273. * @throws \Tron\Exceptions\TronErrorException
  274. */
  275. public function trxTransfer($to, $amount, $from = '', $fromPrivateKey = '')
  276. {
  277. if ($amount <= 0) {
  278. $this->error = '2205';
  279. return false;
  280. }
  281. if (empty($this->config['tron_api_url'])) {
  282. $this->error = '2206';
  283. return false;
  284. }
  285. // 获取钱包参数
  286. try {
  287. if (!$apiKey = $this->getApiKey()) {
  288. return false;
  289. }
  290. $headers = ["TRON-PRO-API-KEY" => $apiKey];
  291. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  292. $trcWallet = new TRX($api);
  293. if ($from && $fromPrivateKey) {
  294. $outAddress = [
  295. 'address' => $from,
  296. 'private_key' => $fromPrivateKey,
  297. ];
  298. } else if (!$outAddress = $this->getWallet(2)) {
  299. return false;
  300. }
  301. $outAddressPrivate = isset($outAddress['private_key']) ? $outAddress['private_key'] : '';
  302. $outAddress = isset($outAddress['address']) ? $outAddress['address'] : '';
  303. if (empty($outAddress) || empty($outAddressPrivate)) {
  304. $this->error = '2203';
  305. return false;
  306. }
  307. $tron = new Tron();
  308. // 获取平台钱包hex
  309. $tron->setAddress($outAddress);
  310. $outAddressData = $tron->getAddress();
  311. $tron->setAddress($to);
  312. $toAddress = $tron->getAddress();
  313. RedisService::set("caches:wallet:transfer:temp_trx_{$to}", ['to' => $to, 'out' => $outAddress, 'amount' => $amount], 7200);
  314. $fromAddress = new \Tron\Address($outAddressData['base58'], $outAddressPrivate, $outAddressData['hex']);
  315. $toAddress = new \Tron\Address($toAddress['base58'], '', $toAddress['hex']);
  316. $result = $trcWallet->transfer($fromAddress, $toAddress, $amount);
  317. $result = (array)$result;
  318. $txID = isset($result['txID']) ? $result['txID'] : '';
  319. RedisService::set("caches:wallet:transfer:result_trx_{$to}", ['to' => $to, 'out' => $outAddress, 'result' => $result], 7200);
  320. if ($txID) {
  321. return ['txId'=> $txID,'address'=> $outAddress];
  322. }
  323. return false;
  324. } catch (\Exception $exception) {
  325. $message = $exception->getMessage();
  326. $this->error = $message;
  327. RedisService::set("caches:wallet:transfer:error_trx_{$to}", ['error' => $exception->getTrace()], 600);
  328. return false;
  329. }
  330. }
  331. /**
  332. * usdt-trc2.0 转账
  333. * @param $to 进账账户
  334. * @param $amount 转账金额
  335. * @param $from 转账账户
  336. * @param $fromPrivate 转账账户私钥
  337. * @throws \Tron\Exceptions\TransactionException
  338. * @throws \Tron\Exceptions\TronErrorException
  339. */
  340. public function usdtTrcTransfer($to, $amount, $from = '', $fromPrivateKey = '')
  341. {
  342. if ($amount <= 0) {
  343. $this->error = '2205';
  344. return false;
  345. }
  346. if (empty($this->config['tron_api_url'])) {
  347. $this->error = '2206';
  348. return false;
  349. }
  350. // 获取钱包参数
  351. try {
  352. if (!$apiKey = $this->getApiKey()) {
  353. return false;
  354. }
  355. $headers = ["TRON-PRO-API-KEY" => $apiKey];
  356. $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
  357. $trcWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
  358. if ($from && $fromPrivateKey) {
  359. $outAddress = [
  360. 'address' => $from,
  361. 'private_key' => $fromPrivateKey,
  362. ];
  363. } else if (!$outAddress = $this->getWallet(2, $amount)) {
  364. return false;
  365. }
  366. $outAddressPrivate = isset($outAddress['private_key']) ? $outAddress['private_key'] : '';
  367. $outAddress = isset($outAddress['address']) ? $outAddress['address'] : '';
  368. if (empty($outAddress) || empty($outAddressPrivate)) {
  369. $this->error = '2203';
  370. return false;
  371. }
  372. $tron = new Tron();
  373. // 获取平台钱包hex
  374. $tron->setAddress($outAddress);
  375. $outAddressData = $tron->getAddress();
  376. // 获取收款钱包hex
  377. $tron->setAddress($to);
  378. $toAddress = $tron->getAddress();
  379. $fromAddress = new \Tron\Address($outAddressData['base58'], $outAddressPrivate, $outAddressData['hex']);
  380. $toAddress = new \Tron\Address($toAddress['base58'], '', $toAddress['hex']);
  381. RedisService::set("caches:wallet:transfer:temp_usdt_{$to}", ['to' => $to, 'out' => $outAddress,'private'=>$outAddressPrivate, 'amount' => $amount], 7200);
  382. $result = $trcWallet->transfer($fromAddress, $toAddress, $amount);
  383. $result = (array)$result;
  384. $txID = isset($result['txID']) ? $result['txID'] : '';
  385. RedisService::set("caches:wallet:transfer:result_usdt_{$to}", ['to' => $to, 'out' => $outAddress,'private'=>$outAddressPrivate, 'result' => $result], 7200);
  386. if ($txID) {
  387. return ['txId'=> $txID, 'address'=>$outAddress];
  388. }
  389. return false;
  390. } catch (\Exception $exception) {
  391. $message = $exception->getMessage();
  392. $this->error = $message;
  393. RedisService::set("caches:wallet:transfer:error_usdt_{$to}", ['error' => $exception->getTrace()], 600);
  394. return false;
  395. }
  396. }
  397. /**
  398. * 监听USDT-TRC2.0用户子钱包充值存币处理
  399. * @param $address 钱包地址
  400. * @param int $accountType 账户类型:1-USDT充值,2-USDT提现,3-星豆充值
  401. * @return array|false
  402. */
  403. public function listenTrcWallet($address, $accountType=1)
  404. {
  405. // 获取钱包参数
  406. try {
  407. if (!$apiKey = $this->getApiKey()) {
  408. return false;
  409. }
  410. $headers = ["TRON-PRO-API-KEY" => $apiKey];
  411. $limit = ConfigService::make()->getConfigByCode('wallet_listen_limit', 300);
  412. $limit = $limit>10 && $limit <=500? $limit : 200;
  413. $url = sprintf($this->apiUrls['transactions'], $address, $limit, $accountType==2? 'false': 'true', $accountType==2?'true':'false');
  414. $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 5);
  415. $result = $result ? json_decode($result, true) : [];
  416. $datas = isset($result['data']) && is_array($result['data'])? $result['data'] : [];
  417. $status = isset($result['success']) ? $result['success'] : '';
  418. RedisService::set("caches:wallets:listen_{$address}", ['url' => $this->config['tron_api_url'] . $url, 'result' => $result], 7200);
  419. if ($status != true || empty($datas)) {
  420. $this->error = '2207';
  421. return false;
  422. }
  423. $coinInMin = ConfigService::make()->getConfigByCode('trc_in_limit');
  424. $coinInMin = $coinInMin > 0 ? $coinInMin : 0;
  425. $cacheKey = "caches:wallet:listen:{$address}_{$accountType}:";
  426. $dateTime = date('Y-m-d H:i:s');
  427. $success = 0;
  428. if ($datas) {
  429. foreach ($datas as $v) {
  430. $amount = isset($v['value']) ? intval($v['value']) : 0;
  431. $amount = moneyFormat($amount / 1000000, 6);
  432. $time = isset($v['block_timestamp']) ? intval($v['block_timestamp'] / 1000) : 0;
  433. $txid = isset($v['transaction_id']) ? $v['transaction_id'] : '';
  434. $ownerAddress = isset($v['from']) ? $v['from'] : '';
  435. $toAddress = isset($v['to']) ? $v['to'] : '';
  436. if($amount < $coinInMin) {
  437. echo "【{$dateTime} wallet】账户[{$ownerAddress}]到钱包[{$toAddress}]记录[{$txid}]金额[{$amount}],金额较小不处理\n";
  438. RedisService::set($cacheKey."{$txid}:error", ['error'=>'金额较小不处理','data'=> $v], 7200);
  439. continue;
  440. }
  441. // 充值处理
  442. if($toAddress == $address && $ownerAddress && $accountType != 2){
  443. if (BalanceLogModel::checkExists($txid)) {
  444. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]交易已处理过\n";
  445. RedisService::set($cacheKey."{$txid}:error", ['error'=>'交易已处理过','data'=> $v], 7200);
  446. continue;
  447. }
  448. $memberInfo = MemberModel::where(['trc_url' => $ownerAddress,'mark'=>1])
  449. ->select(['id','email','trc_url','usdt','balance'])
  450. ->orderBy('id','asc')
  451. ->first();
  452. $trcUrl = isset($memberInfo['trc_url'])? trim($memberInfo['trc_url']) : '';
  453. $usdt = isset($memberInfo['usdt'])? floatval($memberInfo['usdt']) : 0;
  454. $balance = isset($memberInfo['balance'])? floatval($memberInfo['balance']) : 0;
  455. $userId = isset($memberInfo['id'])? intval($memberInfo['id']) : 0;
  456. if(empty($memberInfo)){
  457. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]未绑定用户\n";
  458. RedisService::set($cacheKey."{$txid}:error", ['error'=>'未绑定用户','data'=> $v], 7200);
  459. continue;
  460. }
  461. // 充值汇率
  462. $rate = ConfigService::make()->getConfigByCode('xd_price',0.01);
  463. $rate = $rate>0 && $rate <= 10000? $rate : 0.01;
  464. // 入账
  465. DB::beginTransaction();
  466. $updateData = ['update_time'=> time()];
  467. $total = $amount;
  468. if($accountType == 1){
  469. $updateData['usdt'] = DB::raw("usdt + {$total}");
  470. }else if($accountType == 3){
  471. $total = moneyFormat($rate * $amount, 6);
  472. $updateData['balance'] = DB::raw("balance + {$total}");
  473. }
  474. if(!MemberModel::where(['id'=> $userId])->update($updateData)){
  475. DB::rollBack();
  476. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]入账处理失败\n";
  477. RedisService::set($cacheKey."{$txid}:error", ['error'=>'入账处理失败','update'=>$updateData,'member'=> $memberInfo,'data'=> $v], 7200);
  478. continue;
  479. }
  480. // 充值明细
  481. $data = [
  482. 'user_id'=> $userId,
  483. 'order_no'=> get_order_num('XC'),
  484. 'type'=> 1,
  485. 'user_type'=> 1,
  486. 'coin_type'=> $accountType==1? 1 : 2,
  487. 'money'=> $amount,
  488. 'actual_money'=> $total,
  489. 'pay_type'=> 20,
  490. 'pay_status'=> 20,
  491. 'pay_at'=> date('Y-m-d H:i:s', $time),
  492. 'hash'=> $txid,
  493. 'trc_url'=> $trcUrl,
  494. 'wallet_url'=> $address,
  495. 'date'=> date('Y-m-d'),
  496. 'create_time'=> time(),
  497. 'update_time'=> time(),
  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. $log = [
  509. 'user_id'=> $userId,
  510. 'source_order_no'=> $data['order_no'],
  511. 'user_type'=> 1,
  512. 'type'=> 5,
  513. 'coin_type'=> $accountType==1? 1 : 2,
  514. 'hash'=> $txid,
  515. 'money'=> $amount,
  516. 'actual_money'=> $total,
  517. 'balance'=> $accountType==1? $usdt : $balance,
  518. 'date'=> date('Y-m-d'),
  519. 'create_time'=> time(),
  520. 'update_time'=> time(),
  521. 'remark'=> $accountType==1? 'USDT余额充值':'星豆余额充值',
  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. // 充值星豆/USDT任务
  561. TaskService::make()->updateTask($userId,$accountType==1?10:9, 0);
  562. $total = moneyFormat($total,2);
  563. $amount = moneyFormat($amount,2);
  564. $coinName = $accountType==1?'USDT':'星豆';
  565. $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>";
  566. EmailService::make()->sendUserEmail($userId, $message, $coinName.'充值到账通知',3);
  567. RedisService::set($cacheKey."{$txid}:success", ['error'=>'处理成功','log'=>$data,'member'=> $memberInfo,'data'=> $v], 7200);
  568. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]充值成功\n";
  569. RedisService::clear("caches:wallet:balanceLog:{$txid}");
  570. $success++;
  571. }
  572. // 提现处理
  573. else if($ownerAddress == $address && $toAddress && $accountType == 2){
  574. // 处理锁跳过
  575. if(RedisService::get($cacheKey."{$txid}:lock")){
  576. echo "【{$dateTime} withdraw】提现记录[{$txid}]金额[{$amount}]间隔时间不处理\n";
  577. RedisService::set($cacheKey."{$txid}:error", ['error'=>'间隔时间内不处理','data'=> $v], 600);
  578. continue;
  579. }
  580. $info = BalanceLogModel::checkExists($txid);
  581. $logId = isset($info['id'])? $info['id'] : 0;
  582. $userId = isset($info['user_id'])? $info['user_id'] : 0;
  583. $money = isset($info['money'])? $info['money'] : 0;
  584. $actualMoney = isset($info['actual_money'])? $info['actual_money'] : 0;
  585. $coinType = isset($info['coin_type'])? $info['coin_type'] : 1;
  586. $payStatus = isset($info['pay_status'])? $info['pay_status'] : 0;
  587. $status = isset($info['status'])? $info['status'] : 0;
  588. $trcUrl = isset($info['trc_url'])? trim($info['trc_url']) : '';
  589. $walletUrl = isset($info['wallet_url'])? trim($info['wallet_url']) : '';
  590. if (empty($info) || $logId<=0 || $userId<=0) {
  591. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}]提现记录不存在\n";
  592. RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现记录不存在','data'=> $v], 7200);
  593. RedisService::set($cacheKey."{$txid}:lock", ['error'=>'提现记录不存在','data'=> $v], rand(30,60));
  594. continue;
  595. }
  596. if($status != 2){
  597. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}]提现记录未审核\n";
  598. RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现记录未审核','data'=> $v], 7200);
  599. RedisService::set($cacheKey."{$txid}:lock", ['error'=>'提现记录未审核','data'=> $v], rand(30,60));
  600. continue;
  601. }
  602. if($payStatus == 20){
  603. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}]提现记录已打款\n";
  604. RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现记录已打款','data'=> $v], 7200);
  605. RedisService::set($cacheKey."{$txid}:lock", ['error'=>'提现记录已打款','data'=> $v], rand(30,60));
  606. continue;
  607. }
  608. if ($trcUrl != $toAddress || $walletUrl != $ownerAddress) {
  609. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],提现订单交易地址不匹配\n";
  610. RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现订单交易地址不匹配','info'=>$info,'data'=> $v], 7200);
  611. continue;
  612. }
  613. // 金额验证
  614. if(abs($actualMoney - $amount) > 1){
  615. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],提现金额与交易金额不匹配\n";
  616. RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现金额与交易金额不匹配','info'=>$info,'data'=> $v], 7200);
  617. RedisService::set($cacheKey."{$txid}:lock", ['error'=>'提现金额与交易金额不匹配','data'=> $v], rand(30,60));
  618. continue;
  619. }
  620. // 更新状态
  621. DB::beginTransaction();
  622. if(!BalanceLogModel::where(['id'=> $logId])->update(['pay_status'=> 20,'pay_at'=>$dateTime, 'update_time'=>time()])){
  623. DB::rollBack();
  624. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],提现状态更新失败\n";
  625. RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现状态更新失败','info'=>$info,'data'=> $v], 7200);
  626. continue;
  627. }
  628. // 平台出账
  629. FinanceService::make()->saveLog(0, $amount, 2);
  630. // 平台账户明细
  631. $orderNo = isset($info['order_no'])? $info['order_no'] : '';
  632. $log = [
  633. 'user_id'=> 0,
  634. 'source_id'=> $userId,
  635. 'source_order_no'=> $orderNo,
  636. 'user_type'=> 4,
  637. 'type'=> 5,
  638. 'coin_type'=> 1,
  639. 'hash'=> $txid,
  640. 'money'=> $money,
  641. 'actual_money'=> -$amount,
  642. 'balance'=> 0,
  643. 'date'=> date('Y-m-d'),
  644. 'create_time'=> time(),
  645. 'update_time'=> time(),
  646. 'status'=> 1,
  647. 'mark'=>1,
  648. ];
  649. if(!AccountLogModel::insert($log)){
  650. DB::rollBack();
  651. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],平台账户明细处理失败\n";
  652. RedisService::set($cacheKey."{$txid}:error", ['error'=>'平台账户明细处理失败','log'=>$log,'info'=> $info,'data'=> $v], 7200);
  653. continue;
  654. }
  655. // 邮件消息
  656. DB::commit();
  657. $amount = moneyFormat($amount,2);
  658. $accounts = [1=>'USDT',2=>'星豆',3=>'C2C额度',4=>'佣金',5=>'商户余额'];
  659. $coinName = isset($accounts[$coinType])? $accounts[$coinType] : '余额';
  660. $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>";
  661. EmailService::make()->sendUserEmail($userId, $message, $coinName.'提现到账通知', 3);
  662. RedisService::set($cacheKey."{$txid}:success", ['error'=>'处理成功','log'=>$log,'info'=>$info,'data'=> $v], 7200);
  663. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],提现成功\n";
  664. RedisService::clear("caches:wallet:balanceLog:{$txid}");
  665. $success++;
  666. }
  667. // 处理交易记录
  668. if (!WalletLogModel::checkExists($txid)) {
  669. $log = [
  670. 'owner_address' => $ownerAddress,
  671. 'to_address' => $toAddress,
  672. 'hash' => $txid,
  673. 'amount' => $amount,
  674. 'create_time' => $time ? $time : time(),
  675. 'update_time' => time(),
  676. 'status' => 1,
  677. 'mark' => 1,
  678. ];
  679. WalletLogModel::insert($log);
  680. }
  681. }
  682. }
  683. $this->error = 1010;
  684. return ['success'=> $success, 'total'=> count($datas)];
  685. } catch (\Exception $exception) {
  686. $message = $exception->getMessage();
  687. $this->error = $message;
  688. RedisService::set("caches:wallet:listen_error_{$address}", ['error' => $exception->getMessage(), 'trace' => $exception->getTrace()], 600);
  689. return false;
  690. }
  691. }
  692. /**
  693. * USDT 币安汇率
  694. * @return string
  695. */
  696. public function getBianRatePrice()
  697. {
  698. // 币安买价
  699. $cacheKey ="caches:wallet:usdt_rate";
  700. $price = RedisService::get($cacheKey);
  701. if($price){
  702. return $price;
  703. }
  704. $headers = ["Content-Type: application/json; charset=utf-8"];
  705. $result = httpRequest(self::$bianUrl, json_encode(['fromUserRole'=>'USER','assets'=>['USDT'],'fiatCurrency'=>'CNY','tradeType'=>'BUY']), 'post', '',5,$headers);
  706. $datas = isset($result['data']) ? $result['data'] : [];
  707. $data = isset($datas[0]) ? $datas[0] : [];
  708. $price = isset($data['referencePrice']) ? moneyFormat($data['referencePrice'],2) : '0.00';
  709. RedisService::set("caches:wallet:usdt_buy_result", ['result' => $result,'rates'=>$price,'data'=>$data], 7200);
  710. if($price){
  711. RedisService::set($cacheKey, $price, rand(5,10));
  712. }
  713. return $price>0? $price : 0;
  714. }
  715. }