WalletService.php 39 KB

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