WalletService.php 37 KB

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