WalletService.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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\ConfigModel;
  15. use App\Models\MemberModel;
  16. use App\Models\WalletLogModel;
  17. use App\Models\WalletModel;
  18. use App\Services\Api\FinanceService;
  19. use App\Services\Api\PledgeOrderService;
  20. use Illuminate\Support\Facades\DB;
  21. use Tighten\SolanaPhpSdk\Connection;
  22. use Tighten\SolanaPhpSdk\PublicKey;
  23. use Tighten\SolanaPhpSdk\SolanaRpcClient;
  24. /**
  25. * 钱包管理-服务类
  26. * @package App\Services
  27. */
  28. class WalletService extends BaseService
  29. {
  30. protected $apiUrl = '';
  31. protected $bianUrl = 'http://p2p.binance.com/bapi/c2c/v2/public/c2c/adv/quoted-price';
  32. protected $ouyiApi = 'https://okbs.dongerkj.com/priapi/v3/b2c/deposit/quotedPrice';
  33. // protected $ouyiApi = 'https://www.okx.com/priapi/v3/b2c/deposit/quotedPrice';
  34. protected $config = [];
  35. protected $tokenAddress = 'So11111111111111111111111111111111111111111'; // solana
  36. protected $usdtTokenAddress = 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB'; // solana-usdt
  37. // 静态对象
  38. protected static $instance = null;
  39. protected $apiUrls = [
  40. // 代币账号
  41. 'tokenAccount' => '/v2.0/account/token-accounts',
  42. // 账户交易记录
  43. 'accountTransfer' => '/v2.0/account/transfer?address=%s&activity_type[]=%s&block_time[]=%s&page=%s&page_size=%s',
  44. // 代币账户
  45. 'tokenAccounts'=>'/v2.0/account/token-accounts?address=%s&type=%s&hide_zero=true',
  46. // 交易详情
  47. 'transactionDetail'=>'/v1.0/transaction/%s',
  48. ];
  49. /**
  50. * 构造函数
  51. */
  52. public function __construct()
  53. {
  54. $this->config = ConfigService::make()->getConfigOptionByGroup(14);
  55. if (empty($this->config)) {
  56. return false;
  57. }
  58. }
  59. /**
  60. * 静态入口
  61. * @return static|null
  62. */
  63. public static function make()
  64. {
  65. if (!self::$instance) {
  66. self::$instance = (new static());
  67. }
  68. return self::$instance;
  69. }
  70. /**
  71. * 获取平台钱包地址
  72. * @param int $type 钱包类型:1-充值入账,2-提现出账,默认充值
  73. * @param int $amount 提币时,提币金额验证,充值钱包可忽略
  74. * @param int $coinType 币种:1-USDT
  75. * @param boolean $privateKey 是否返回解码的私钥
  76. * @return array|false|mixed、
  77. */
  78. public function getWallet($type = 1, $amount = 0, $coinType = 1, $privateKey = false)
  79. {
  80. $cacheKey = "caches:wallet:platform:{$type}";
  81. $wallets = RedisService::get($cacheKey);
  82. if (empty($wallets)) {
  83. $wallets = WalletModel::where(['type' => $type, 'status' => 1, 'mark' => 1])->select(['address', 'private_key'])->get();
  84. $wallets = $wallets ? $wallets->toArray() : [];
  85. if ($wallets) {
  86. RedisService::set($cacheKey, $wallets, rand(300, 600));
  87. }
  88. }
  89. if (empty($wallets)) {
  90. $this->error = $type == 1 ? 1036 : 1037;
  91. return false;
  92. }
  93. // 需要验证余额
  94. if ($amount > 0) {
  95. foreach ($wallets as $item) {
  96. $address = isset($item['address']) ? trim($item['address']) : '';
  97. $privateKey = isset($item['private_key']) ? trim($item['private_key']) : '';
  98. $privateKey = $this->getAddressPrivateKey($privateKey, $address, 2);
  99. if ($coinType == 1) {
  100. $accountData = $this->getUsdtBalance($address);
  101. $balance = isset($accountData['amount'])? $accountData['amount'] : 0;
  102. } else {
  103. $accountData = $this->getUsdtBalance($address);
  104. $balance = isset($accountData['amount'])? $accountData['amount'] : 0;
  105. }
  106. if ($balance >= $amount) {
  107. $tokenAccount = isset($accountData['tokenAccount'])? $accountData['tokenAccount'] : '';
  108. return ['address' => $address,'tokenAccount'=>$tokenAccount, 'private_key' => $privateKey];
  109. }
  110. }
  111. $this->error = 1038;
  112. return false;
  113. } else {
  114. $rand = rand(0, count($wallets) - 1);
  115. $wallet = $wallets[$rand];
  116. if ($privateKey) {
  117. $wallet['private_key'] = $this->getAddressPrivateKey($wallet['private_key'], $wallet['address'], 2);
  118. }
  119. return $wallet;
  120. }
  121. }
  122. /**
  123. * 获取所有钱包地址
  124. * @return array|mixed
  125. */
  126. public function getWalletList()
  127. {
  128. try {
  129. $cacheKey = "caches:wallet:platform:all";
  130. $wallets = RedisService::get($cacheKey);
  131. if ($wallets) {
  132. return $wallets;
  133. }
  134. $wallets = WalletModel::where(['status' => 1, 'mark' => 1])->select(['id', 'address', 'type'])->get();
  135. $wallets = $wallets ? $wallets->toArray() : [];
  136. if ($wallets) {
  137. RedisService::set($cacheKey, $wallets, rand(300, 600));
  138. }
  139. return $wallets;
  140. } catch (\Exception $exception){
  141. $this->error = $exception->getMessage();
  142. return false;
  143. }
  144. }
  145. /**
  146. * 加解密密钥
  147. * @param $key 密钥或加密密钥
  148. * @param $address 地址
  149. * @param $type 类型:1-加密,2-解密
  150. * @return mixed|string|string[]
  151. */
  152. public function getAddressPrivateKey($key, $address, $type)
  153. {
  154. // 加密
  155. if ($type == 1) {
  156. $baseStr = base64_encode($key);
  157. $baseStr = str_replace(['==', '='], ['-2', '-1'], $baseStr);
  158. $str = substr($baseStr, -6, 7) . substr(md5($address), 2, 6) . substr($baseStr, 0, -6);
  159. return $str;
  160. } // 解密
  161. else {
  162. $str1 = substr($key, 12) . substr($key, 0, 6);
  163. $str1 = str_replace(['-1', '-2'], ['=', '=='], $str1);
  164. return base64_decode($str1);
  165. }
  166. }
  167. /**
  168. * 验证地址
  169. * @param $address
  170. * @return string
  171. */
  172. public function checkAddress($address)
  173. {
  174. try{
  175. $publicKey = new PublicKey($address);
  176. return PublicKey::isOnCurve($publicKey);
  177. } catch (\Exception $exception){
  178. $this->error = $exception->getMessage();
  179. return false;
  180. }
  181. }
  182. /**
  183. * solana余额
  184. * @param $address
  185. * @return false|float|string
  186. */
  187. public function getBalance($address, $cache = false)
  188. {
  189. if (empty($address)) {
  190. $this->error = '1018';
  191. return false;
  192. }
  193. $cacheKey = "caches:wallet:balance:sol_{$address}";
  194. if ($data = RedisService::get($cacheKey) && $cache) {
  195. return $data;
  196. }
  197. if (RedisService::get($cacheKey . '_lock') && $cache) {
  198. return false;
  199. }
  200. try {
  201. $sdk = new Connection(new SolanaRpcClient(SolanaRpcClient::MAINNET_ENDPOINT));
  202. $publicKey = new PublicKey($address);
  203. $balance = $sdk->getBalance($publicKey);
  204. RedisService::set($cacheKey, $balance, rand(3, 5));
  205. RedisService::set($cacheKey . '_lock', true, rand(3, 5));
  206. return $balance;
  207. } catch (\Exception $exception) {
  208. $this->error = $exception->getMessage();
  209. return false;
  210. }
  211. }
  212. /**
  213. * TRC20-USDT余额
  214. * @param $address
  215. * @return false|float|string
  216. */
  217. public function getUsdtBalance($address, $cache = false)
  218. {
  219. if (empty($address)) {
  220. $this->error = 1018;
  221. return false;
  222. }
  223. $cacheKey = "caches:wallet:balance:trc_usdt_{$address}";
  224. $data = RedisService::get($cacheKey);
  225. if ($data && !$cache) {
  226. return $data;
  227. }
  228. try {
  229. $apiUrl = ConfigService::make()->getConfigByCode('solana_scan_api', '');
  230. if (empty($apiUrl)) {
  231. $this->error = 1040;
  232. return false;
  233. }
  234. $token = ConfigService::make()->getConfigByCode('solana_scan_api_key', '');
  235. if (empty($token)) {
  236. $this->error = 1039;
  237. return false;
  238. }
  239. $headers = [
  240. "token: {$token}",
  241. ];
  242. $url = $apiUrl . sprintf($this->apiUrls['tokenAccounts'],$address,'token');
  243. $result = curl_get($url, '', $headers, 5);
  244. $data = $result ? json_decode($result, true) : [];
  245. RedisService::set($cacheKey.'_result', ['url'=>$url,'address'=>$address,'data'=>$data,'result'=>$result,'headers'=>$headers], 600);
  246. $accounts = isset($data['data']) ? $data['data'] : [];
  247. if(empty($accounts)){
  248. $this->error = 2208;
  249. return false;
  250. }
  251. $balance = 0;
  252. $tokenAccount = '';
  253. foreach ($accounts as $item){
  254. if($item['token_address'] = $this->usdtTokenAddress){
  255. $tokenAccount = $item['token_account'];
  256. $balance = moneyFormat($item['amount']/pow(10, $item['token_decimals']), 2);
  257. }
  258. }
  259. RedisService::set($cacheKey, ['amount'=> $balance,'tokenAccount'=>$tokenAccount], rand(5, 10));
  260. return ['amount'=> $balance,'tokenAccount'=>$tokenAccount];
  261. } catch (\Exception $exception) {
  262. $this->error = $exception->getMessage();
  263. RedisService::set($cacheKey.'_error', ['error'=> $exception->getMessage(),'address'=>$address], 600);
  264. return false;
  265. }
  266. }
  267. /**
  268. * solana usdt 转账
  269. * @param $to 进账账户
  270. * @param $amount 转账金额
  271. */
  272. public function usdtTransfer($to, $amount, $from = '', $fromPrivateKey = '')
  273. {
  274. if ($amount <= 0) {
  275. $this->error = '2205';
  276. return false;
  277. }
  278. }
  279. /**
  280. * 查询交易详情
  281. * @param $txid
  282. * @return array|false|mixed
  283. */
  284. public function getTradeDetail($txid)
  285. {
  286. $cacheKey = "caches:wallet:tradeDetail_{$txid}";
  287. $data = RedisService::get($cacheKey);
  288. if($data){
  289. return $data;
  290. }
  291. try {
  292. $apiUrl = ConfigService::make()->getConfigByCode('solana_scan_api', '');
  293. if (empty($apiUrl)) {
  294. $this->error = 1040;
  295. return false;
  296. }
  297. $token = ConfigService::make()->getConfigByCode('solana_v1_api_key', '');
  298. if (empty($token)) {
  299. $this->error = 1039;
  300. return false;
  301. }
  302. $headers = [
  303. "token: {$token}",
  304. ];
  305. $url = $apiUrl . sprintf($this->apiUrls['transactionDetail'],$txid);
  306. $result = curl_get($url, '', $headers, 5);
  307. $data = $result ? json_decode($result, true) : [];
  308. RedisService::set($cacheKey.'_result', ['url'=>$url,'txid'=>$txid,'data'=>$data,'result'=>$result,'headers'=>$headers], 600);
  309. $tradeData = isset($data['tokenTransfers'][0]) ? $data['tokenTransfers'][0] : [];
  310. if(empty($tradeData)){
  311. $this->error = 2210;
  312. return false;
  313. }
  314. RedisService::set($cacheKey, $tradeData, rand(10, 20));
  315. return $tradeData;
  316. } catch (\Exception $exception) {
  317. $this->error = $exception->getMessage();
  318. RedisService::set($cacheKey.'_error', ['error'=> $exception->getMessage(),'txid'=>$txid], 600);
  319. return false;
  320. }
  321. }
  322. /**
  323. * 监听充值存币处理
  324. * @param $address 钱包地址
  325. * @param int $accountType 账户类型:1-USDT充值,2-USDT提现
  326. * @param int $page 分页:默认0-轮询分页20页,每页100条记录
  327. * @return array|false
  328. */
  329. public function listenWallet($address, $accountType = 1, $page = 0)
  330. {
  331. // 获取钱包参数
  332. try {
  333. $apiUrl = ConfigService::make()->getConfigByCode('solana_scan_api', '');
  334. if (empty($apiUrl)) {
  335. $this->error = 1040;
  336. return false;
  337. }
  338. $token = ConfigService::make()->getConfigByCode('solana_scan_api_key', '');
  339. if (empty($token)) {
  340. $this->error = 1039;
  341. return false;
  342. }
  343. $headers = [
  344. "token: {$token}",
  345. ];
  346. if ($page <= 0) {
  347. $page = RedisService::get('caches:wallet:listen_recharge_page_' . $address);
  348. $maxPage = ConfigService::make()->getConfigByCode('wallet_listen_max_page', 20);
  349. $page = $page > 0 && $page <= $maxPage ? $page : 1;
  350. }
  351. $limit = ConfigService::make()->getConfigByCode('wallet_listen_limit', 300);
  352. $limit = $limit > 10 && $limit <= 100 ? $limit : 100;
  353. $time = ConfigService::make()->getConfigByCode('wallet_listen_time', 48);
  354. $startTime = $time > 0 ? time() - $time * 3600 : time() - 7200;
  355. $url = $apiUrl . sprintf($this->apiUrls['accountTransfer'], $address, 'ACTIVITY_SPL_TRANSFER', $startTime, $page, $limit);
  356. $result = curl_get($url, [], $headers, 5);
  357. $result = $result ? json_decode($result, true) : [];
  358. $datas = isset($result['data']) && is_array($result['data']) ? $result['data'] : [];
  359. $status = isset($result['success']) ? $result['success'] : '';
  360. $error = isset($result['error_message']) ? $result['error_message'] : '';
  361. RedisService::set("caches:wallet:listen_{$address}", ['url' => $url, 'page' => $page, 'result' => $result], 7200);
  362. if ($status != true || empty($datas)) {
  363. $this->error = $error ? '第{$page}页接口错误-' . $error : "第{$page}页没有取到数据";
  364. return false;
  365. }
  366. RedisService::set('caches:wallet:listen_recharge_page', $page + 1, rand(3600, 7200));
  367. $coinInMin = ConfigService::make()->getConfigByCode('recharge_min_money');
  368. $coinInMin = $coinInMin > 0 ? $coinInMin : 0;
  369. $cacheKey = "caches:wallet:listen:{$address}_{$accountType}:";
  370. $dateTime = date('Y-m-d H:i:s');
  371. $success = 0;
  372. if ($datas) {
  373. foreach ($datas as $v) {
  374. $amount = isset($v['amount']) ? intval($v['amount']) : 0;
  375. $tokenDecimals = isset($v['token_decimals']) && $v['token_decimals'] ? intval($v['token_decimals']) : 6;
  376. $amount = moneyFormat($amount / pow(10, $tokenDecimals), 6);
  377. $time = isset($v['block_time']) ? intval($v['block_time']) : 0;
  378. $txid = isset($v['trans_id']) ? $v['trans_id'] : '';
  379. $ownerAddress = isset($v['from_address']) ? $v['from_address'] : '';
  380. $toAddress = isset($v['to_address']) ? $v['to_address'] : '';
  381. $tokenAddress = isset($v['token_address']) ? $v['token_address'] : '';
  382. $coinType = 0;
  383. $coinName = '';
  384. if ($tokenAddress == $this->tokenAddress) {
  385. $coinType = 2;
  386. $coinName = 'SOL';
  387. } else if ($tokenAddress == $this->usdtTokenAddress) {
  388. $coinType = 1;
  389. $coinName = 'USDT';
  390. }
  391. if($amount<=0){
  392. echo "【{$dateTime} wallet】账户[{$ownerAddress}]到钱包[{$toAddress}]记录[{$txid}]金额[{$amount}]{$coinName},金额较小不处理\n";
  393. RedisService::set($cacheKey . "{$txid}:error", ['error' => '金额较小不处理', 'data' => $v], 7200);
  394. continue;
  395. }
  396. // 处理交易记录
  397. if (!WalletLogModel::checkExists($txid)) {
  398. $log = [
  399. 'owner_address' => $ownerAddress,
  400. 'to_address' => $toAddress,
  401. 'token_address' => $tokenAddress,
  402. 'token_type' => $coinType,
  403. 'hash' => $txid,
  404. 'amount' => $amount,
  405. 'create_time' => $time ? $time : time(),
  406. 'update_time' => time(),
  407. 'status' => 1,
  408. 'mark' => 1,
  409. ];
  410. WalletLogModel::insert($log);
  411. }
  412. // 充值处理(solana-usdt)
  413. if ($toAddress == $address && $ownerAddress && $accountType != 2) {
  414. if ($amount < $coinInMin) {
  415. echo "【{$dateTime} wallet】账户[{$ownerAddress}]到钱包[{$toAddress}]记录[{$txid}]金额[{$amount}]{$coinName},金额较小不处理\n";
  416. RedisService::set($cacheKey . "{$txid}:error", ['error' => '金额较小不处理', 'data' => $v], 7200);
  417. continue;
  418. }
  419. if ($tokenAddress != $this->usdtTokenAddress) {
  420. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]{$coinName}币种不匹配\n";
  421. RedisService::set($cacheKey . "{$txid}:error", ['error' => '币种不匹配', 'data' => $v], 7200);
  422. continue;
  423. }
  424. if (BalanceLogModel::checkExists($txid)) {
  425. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]{$coinName}交易已处理过\n";
  426. RedisService::set($cacheKey . "{$txid}:error", ['error' => '交易已处理过', 'data' => $v], 7200);
  427. continue;
  428. }
  429. $memberInfo = MemberModel::where(['wallet_url' => $ownerAddress, 'mark' => 1])
  430. ->select(['id', 'nickname', 'wallet_url', 'usdt', 'sbt'])
  431. ->orderBy('id', 'asc')
  432. ->first();
  433. $trcUrl = isset($memberInfo['wallet_url']) ? trim($memberInfo['wallet_url']) : '';
  434. $usdt = isset($memberInfo['usdt']) ? floatval($memberInfo['usdt']) : 0;
  435. $userId = isset($memberInfo['id']) ? intval($memberInfo['id']) : 0;
  436. if (empty($memberInfo)) {
  437. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]{$coinName}未绑定用户\n";
  438. RedisService::set($cacheKey . "{$txid}:error", ['error' => '未绑定用户', 'data' => $v], 7200);
  439. continue;
  440. }
  441. // 入账
  442. try {
  443. DB::beginTransaction();
  444. $updateData = ['update_time' => time()];
  445. $total = $amount;
  446. $updateData['usdt'] = DB::raw("usdt + {$total}");
  447. if (!MemberModel::where(['id' => $userId])->update($updateData)) {
  448. DB::rollBack();
  449. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]入账处理失败\n";
  450. RedisService::set($cacheKey . "{$txid}:error", ['error' => '入账处理失败', 'update' => $updateData, 'member' => $memberInfo, 'data' => $v], 7200);
  451. continue;
  452. }
  453. // 充值明细
  454. $data = [
  455. 'user_id' => $userId,
  456. 'order_no' => get_order_num('SR'),
  457. 'type' => 1,
  458. 'coin_type' => 1,
  459. 'money' => $amount,
  460. 'actual_money' => $total,
  461. 'pay_type' => 20,
  462. 'pay_status' => 20,
  463. 'pay_at' => date('Y-m-d H:i:s', $time),
  464. 'hash' => $txid,
  465. 'wallet_url' => $trcUrl,
  466. 'pt_wallet_url' => $address,
  467. 'date' => date('Y-m-d'),
  468. 'create_time' => time(),
  469. 'update_time' => time(),
  470. 'status' => 2,
  471. 'mark' => 1,
  472. ];
  473. if (!BalanceLogModel::insert($data)) {
  474. DB::rollBack();
  475. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]充值明细处理失败\n";
  476. RedisService::set($cacheKey . "{$txid}:error", ['error' => '充值明细处理失败', 'log' => $data, 'member' => $memberInfo, 'data' => $v], 7200);
  477. continue;
  478. }
  479. // 用户账户明细
  480. $log = [
  481. 'user_id' => $userId,
  482. 'order_no' => $data['order_no'],
  483. 'user_type' => 1,
  484. 'type' => 3,
  485. 'coin_type' => 1,
  486. 'hash' => $txid,
  487. 'money' => $amount,
  488. 'before_money' => $usdt,
  489. 'create_time' => time(),
  490. 'update_time' => date('Y-m-d H:i:s'),
  491. 'remark' => 'USDT充值',
  492. 'status' => 1,
  493. 'mark' => 1,
  494. ];
  495. if (!AccountLogModel::insert($log)) {
  496. DB::rollBack();
  497. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]账户明细处理失败\n";
  498. RedisService::set($cacheKey . "{$txid}:error", ['error' => '账户明细处理失败', 'log' => $log, 'member' => $memberInfo, 'data' => $v], 7200);
  499. continue;
  500. }
  501. // 平台进账
  502. FinanceService::make()->saveLog(0, $amount, 1);
  503. DB::commit();
  504. $amount = moneyFormat($amount, 2);
  505. RedisService::set($cacheKey . "{$txid}:success", ['error' => '处理成功', 'log' => $data, 'member' => $memberInfo, 'data' => $v], 7200);
  506. echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]充值成功\n";
  507. RedisService::clear("caches:wallet:balanceLog:{$txid}");
  508. RedisService::keyDel("caches:balanceLog:total*");
  509. $success++;
  510. } catch (\Exception $exception) {
  511. DB::rollBack();
  512. RedisService::clear("caches:wallet:balanceLog:{$txid}");
  513. $this->error = "处理错误-" . $exception->getMessage();
  514. echo "处理错误-" . $exception->getMessage();
  515. continue;
  516. }
  517. } // 提现处理
  518. else if ($ownerAddress == $address && $toAddress && $accountType == 2) {
  519. // 处理锁跳过
  520. if (RedisService::get($cacheKey . "{$txid}:lock")) {
  521. echo "【{$dateTime} withdraw】提现记录[{$txid}]金额[{$amount}]间隔时间不处理\n";
  522. RedisService::set($cacheKey . "{$txid}:error", ['error' => '间隔时间内不处理', 'data' => $v], 600);
  523. continue;
  524. }
  525. $info = BalanceLogModel::checkExists($txid);
  526. $logId = isset($info['id']) ? $info['id'] : 0;
  527. $userId = isset($info['user_id']) ? $info['user_id'] : 0;
  528. $money = isset($info['money']) ? $info['money'] : 0;
  529. $actualMoney = isset($info['actual_money']) ? $info['actual_money'] : 0;
  530. $payStatus = isset($info['pay_status']) ? $info['pay_status'] : 0;
  531. $status = isset($info['status']) ? $info['status'] : 0;
  532. $trcUrl = isset($info['wallet_url']) ? trim($info['wallet_url']) : '';
  533. $walletUrl = isset($info['pt_wallet_url']) ? trim($info['pt_wallet_url']) : '';
  534. if (empty($info) || $logId <= 0 || $userId <= 0) {
  535. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}]提现记录不存在\n";
  536. RedisService::set($cacheKey . "{$txid}:error", ['error' => '提现记录不存在', 'data' => $v], 7200);
  537. RedisService::set($cacheKey . "{$txid}:lock", ['error' => '提现记录不存在', 'data' => $v], rand(30, 60));
  538. continue;
  539. }
  540. if ($status != 2) {
  541. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}]提现记录未审核\n";
  542. RedisService::set($cacheKey . "{$txid}:error", ['error' => '提现记录未审核', 'data' => $v], 7200);
  543. RedisService::set($cacheKey . "{$txid}:lock", ['error' => '提现记录未审核', 'data' => $v], rand(30, 60));
  544. continue;
  545. }
  546. if ($payStatus == 20) {
  547. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}]提现记录已打款\n";
  548. RedisService::set($cacheKey . "{$txid}:error", ['error' => '提现记录已打款', 'data' => $v], 7200);
  549. RedisService::set($cacheKey . "{$txid}:lock", ['error' => '提现记录已打款', 'data' => $v], rand(30, 60));
  550. continue;
  551. }
  552. if ($trcUrl != $toAddress || $walletUrl != $ownerAddress) {
  553. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],提现订单交易地址不匹配\n";
  554. RedisService::set($cacheKey . "{$txid}:error", ['error' => '提现订单交易地址不匹配', 'info' => $info, 'data' => $v], 7200);
  555. continue;
  556. }
  557. // 金额验证
  558. if (abs($actualMoney - $amount) > 1) {
  559. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],提现金额与交易金额不匹配\n";
  560. RedisService::set($cacheKey . "{$txid}:error", ['error' => '提现金额与交易金额不匹配', 'info' => $info, 'data' => $v], 7200);
  561. RedisService::set($cacheKey . "{$txid}:lock", ['error' => '提现金额与交易金额不匹配', 'data' => $v], rand(30, 60));
  562. continue;
  563. }
  564. // 更新状态
  565. try {
  566. DB::beginTransaction();
  567. if (!BalanceLogModel::where(['id' => $logId])->update(['pay_status' => 20, 'pay_at' => $dateTime, 'update_time' => time()])) {
  568. DB::rollBack();
  569. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],提现状态更新失败\n";
  570. RedisService::set($cacheKey . "{$txid}:error", ['error' => '提现状态更新失败', 'info' => $info, 'data' => $v], 7200);
  571. continue;
  572. }
  573. // 平台出账
  574. FinanceService::make()->saveLog(0, $amount, 2);
  575. DB::commit();
  576. $amount = moneyFormat($amount, 2);
  577. RedisService::set($cacheKey . "{$txid}:success", ['error' => '处理成功', 'log' => $log, 'info' => $info, 'data' => $v], 7200);
  578. echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],提现成功\n";
  579. RedisService::clear("caches:wallet:balanceLog:{$txid}");
  580. $success++;
  581. } catch (\Exception $exception) {
  582. DB::rollBack();
  583. RedisService::clear("caches:wallet:balanceLog:{$txid}");
  584. $this->error = "处理错误-" . $exception->getMessage();
  585. echo "处理错误-" . $exception->getMessage();
  586. continue;
  587. }
  588. }
  589. }
  590. }
  591. $this->error = 1010;
  592. return ['success' => $success, 'total' => count($datas)];
  593. } catch (\Exception $exception) {
  594. $message = $exception->getMessage();
  595. $this->error = $message;
  596. RedisService::set("caches:wallet:listen_error_{$address}", ['error' => $exception->getMessage(), 'trace' => $exception->getTrace()], 600);
  597. return false;
  598. }
  599. }
  600. /**
  601. * USDT 汇率CNY买/卖价格
  602. * @return string
  603. */
  604. public function getUsdtPrice($side='sell',$refresh = true)
  605. {
  606. // USDT价格
  607. $cacheKey ="caches:wallets:usdtPrice_{$side}";
  608. $price = RedisService::get($cacheKey);
  609. if($price && !$refresh){
  610. return $price;
  611. }
  612. $url = $this->ouyiApi.'?t=' . time() . "&side={$side}&quoteCurrency=CNY&baseCurrency=USDT";
  613. $result = httpRequest($url, '', 'get', '', 10);
  614. $datas = isset($result['data']) ? $result['data'] : [];
  615. $datas = isset($datas[0]) ? $datas[0] : [];
  616. $price = isset($datas['price']) ? $datas['price'] : 0;
  617. if($price<=0){
  618. $price = ConfigService::make()->getConfigByCode("usdt_cny_{$side}_price",7.2);
  619. }else{
  620. $price1 = ConfigService::make()->getConfigByCode("usdt_cny_{$side}_price",7.2);
  621. $rate = ConfigService::make()->getConfigByCode("usdt_{$side}_rate",1);
  622. $price= $rate? moneyFormat($price*(1-$rate/100), 3) : $price;
  623. ConfigModel::where(['code'=>"usdt_cny_{$side}_price"])->update(['value'=> $price,'options'=>$price1]);
  624. }
  625. RedisService::set($cacheKey, $price, rand(30,60));
  626. return $price>0? $price : 0;
  627. }
  628. }