WalletService.php 30 KB

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