WalletService.php 38 KB

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