WalletService.php 38 KB

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