123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790 |
- <?php
- // +----------------------------------------------------------------------
- // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
- // +----------------------------------------------------------------------
- // | 版权所有 2017~2021 LARAVEL研发中心
- // +----------------------------------------------------------------------
- // | 官方网站: http://www.laravel.cn
- // +----------------------------------------------------------------------
- // | Author: laravel开发员 <laravel.qq.com>
- // +----------------------------------------------------------------------
- namespace App\Services;
- use App\Models\AccountLogModel;
- use App\Models\BalanceLogModel;
- use App\Models\MemberModel;
- use App\Models\WalletLogModel;
- use App\Models\WalletModel;
- use App\Services\Api\FinanceService;
- use App\Services\Api\TaskService;
- use GuzzleHttp\Client;
- use IEXBase\TronAPI\Tron;
- use Illuminate\Support\Facades\DB;
- use PHPUnit\TestFixture\issue4498test;
- use Tron\Api;
- use Tron\TRC20;
- use Tron\TRX;
- /**
- * 钱包管理-服务类
- * @package App\Services
- */
- class WalletService extends BaseService
- {
- protected $apiUrl = '';
- protected $config = [];
- // 静态对象
- protected static $instance = null;
- protected $apiUrls = [
- 'transactions' => '/v1/accounts/%s/transactions/trc20?limit=%s&only_to=%s&only_from=%s&only_confirmed=true&contract_address=TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
- ];
- /**
- * 构造函数
- * UsdtWalletService constructor.
- */
- public function __construct()
- {
- $this->config = ConfigService::make()->getConfigOptionByGroup(14);
- if (empty($this->config)) {
- return false;
- }
- }
- /**
- * 静态入口
- * @return static|null
- */
- public static function make()
- {
- if (!self::$instance) {
- self::$instance = (new static());
- }
- return self::$instance;
- }
- /**
- * 获取平台钱包地址
- * @param int $type
- */
- public function getWallet($type = 1, $amount = 0, $coinType = 1)
- {
- $cacheKey = "caches:wallet:platform:{$type}";
- $wallets = RedisService::get($cacheKey);
- if (empty($wallets)) {
- $wallets = WalletModel::where(['type' => $type, 'status' => 1, 'mark' => 1])->select(['address', 'private_key'])->get();
- $wallets = $wallets ? $wallets->toArray() : [];
- if ($wallets) {
- RedisService::set($cacheKey, $wallets, rand(300, 600));
- }
- }
- if (empty($wallets)) {
- $this->error = $type == 1 ? 1036 : 1037;
- return false;
- }
- // 需要验证余额
- if ($amount > 0) {
- foreach ($wallets as $item) {
- $address = isset($item['address']) ? trim($item['address']) : '';
- $privateKey = isset($item['private_key']) ? trim($item['private_key']) : '';
- $privateKey = $this->getAddressPrivateKey($privateKey, $address, 2);
- if ($coinType == 1) {
- $balance = $this->getTrcUsdtBalance($address);
- } else {
- $balance = $this->getTrcUsdtBalance($address);
- }
- if ($balance >= $amount) {
- return ['address' => $address, 'private_key' => $privateKey];
- }
- }
- $this->error = 1038;
- EmailService::make()->sendPlatformEmail('您的出账钱包地址' . ($coinType == 1 ? 'USDT' : 'TRX') . '余额不足,将会影响到提现打款,请及时登录系统后台查看钱包并充值');
- return false;
- } else {
- $rand = rand(0, count($wallets) - 1);
- $wallet = $wallets[$rand];
- $wallet['private_key'] = $this->getAddressPrivateKey($wallet['private_key'], $wallet['address'], 2);
- return $wallet;
- }
- }
- /**
- * 获取所有钱包地址
- * @return array|mixed
- */
- public function getWalletList()
- {
- $cacheKey = "caches:wallet:platform:all";
- $wallets = RedisService::get($cacheKey);
- if ($wallets) {
- return $wallets;
- }
- $wallets = WalletModel::where(['status' => 1, 'mark' => 1])->select(['id','address','type'])->get();
- $wallets = $wallets ? $wallets->toArray() : [];
- if ($wallets) {
- RedisService::set($cacheKey, $wallets, rand(300, 600));
- }
- return $wallets;
- }
- /**
- * 加解密密钥
- * @param $key 密钥或加密密钥
- * @param $address 地址
- * @param $type 类型:1-加密,2-解密
- * @return mixed|string|string[]
- */
- public function getAddressPrivateKey($key, $address, $type)
- {
- // 加密
- if ($type == 1) {
- $baseStr = base64_encode($key);
- $str = substr($baseStr, -6, 7) . substr(md5($address), 2, 6) . substr($baseStr, 0, -6);
- return str_replace(['==', '='], ['-2', '-1'], $str);
- } // 解密
- else {
- $str1 = substr($key, 12) . substr($key, 0, 6);
- $str1 = str_replace(['-1', '-2'], ['=', '=='], $str1);
- return base64_decode($str1);
- }
- }
- /**
- * 获取接口密钥
- * @return false|mixed|string
- */
- public function getApiKey()
- {
- $keys = $this->config['tron_api_keys'];
- $keys = $keys ? explode("\n", $keys) : [];
- if (empty($keys)) {
- $this->error = 1035;
- return false;
- }
- $len = rand(0, count($keys) - 1);
- $key = $keys[$len];
- return trim($key);
- }
- /**
- * 获取TRC2.0钱包地址
- * @throws \Tron\Exceptions\TronErrorException
- */
- public function getTrcAddress()
- {
- try {
- if (!$apiKey = $this->getApiKey()) {
- return false;
- }
- $headers = ["TRON-PRO-API-KEY" => $apiKey];
- $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], $headers]));
- $trxWallet = new TRX($api);
- $addressData = $trxWallet->generateAddress();
- $addressData = (array)$addressData;
- return ['wif' => $addressData['privateKey'], 'hexAddress' => $addressData['hexAddress'], 'address' => $addressData['address']];
- } catch (\Exception $exception) {
- $this->error = $exception->getMessage();
- return false;
- }
- }
- /**
- * USDT-TRC20余额
- * @param $address
- * @return false|float|string
- */
- public function getTrcUsdtBalance($address, $cache = false)
- {
- if (empty($address)) {
- $this->error = '1018';
- return false;
- }
- if (empty($this->config['tron_api_url'])) {
- $this->error = '2206';
- return false;
- }
- $cacheKey = "caches:wallet:balance:usdt_{$address}";
- if ($data = RedisService::get($cacheKey) && $cache) {
- return $data;
- }
- if (RedisService::get($cacheKey . '_lock') && $cache) {
- return false;
- }
- try {
- if (!$apiKey = $this->getApiKey()) {
- return false;
- }
- $headers = ["TRON-PRO-API-KEY" => $apiKey];
- $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
- $trxWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
- $tron = new Tron();
- $tron->setAddress($address);
- $address = $tron->getAddress();
- $address = new \Tron\Address($address['base58'], '', $address['hex']);
- $result = $trxWallet->balance($address);
- $result = $result ? floatval($result) : '0.00';
- RedisService::set($cacheKey, $result, rand(3, 5));
- RedisService::set($cacheKey . '_lock', true, rand(3, 5));
- return $result;
- } catch (\Exception $exception) {
- $this->error = $exception->getMessage();
- return false;
- }
- }
- /**
- * TRX余额
- * @param $address
- * @return false|float|string
- */
- public function getTrxBalance($address, $cache = false)
- {
- if (empty($address)) {
- $this->error = '1018';
- return false;
- }
- if (empty($this->config['tron_api_url'])) {
- $this->error = '2206';
- return false;
- }
- $cacheKey = "caches:wallet:balance:trx_{$address}";
- if ($data = RedisService::get($cacheKey) && $cache) {
- return $data;
- }
- if (RedisService::get($cacheKey . '_lock') && $cache) {
- return false;
- }
- try {
- if (!$apiKey = $this->getApiKey()) {
- return false;
- }
- $headers = ["TRON-PRO-API-KEY" => $apiKey];
- $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
- $trxWallet = new TRX($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
- $tron = new Tron();
- $tron->setAddress($address);
- $address = $tron->getAddress();
- $address = new \Tron\Address($address['base58'], '', $address['hex']);
- $result = $trxWallet->balance($address);
- $result = $result ? formatScientific($result) : '0.00';
- RedisService::set($cacheKey, $result, rand(3, 5));
- RedisService::set($cacheKey . '_lock', true, rand(3, 5));
- return $result;
- } catch (\Exception $exception) {
- $this->error = $exception->getMessage();
- return false;
- }
- }
- /**
- * trx 转账
- * @param $to 进账账户
- * @param $amount 转账金额
- * @throws \Tron\Exceptions\TransactionException
- * @throws \Tron\Exceptions\TronErrorException
- */
- public function trxTransfer($to, $amount, $from = '', $fromPrivateKey = '')
- {
- if ($amount <= 0) {
- $this->error = '2205';
- return false;
- }
- if (empty($this->config['tron_api_url'])) {
- $this->error = '2206';
- return false;
- }
- // 获取钱包参数
- try {
- if (!$apiKey = $this->getApiKey()) {
- return false;
- }
- $headers = ["TRON-PRO-API-KEY" => $apiKey];
- $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
- $trcWallet = new TRX($api);
- if ($from && $fromPrivateKey) {
- $outAddress = [
- 'address' => $from,
- 'private_key' => $fromPrivateKey,
- ];
- } else if (!$outAddress = $this->getWallet(2)) {
- return false;
- }
- $outAddressPrivate = isset($outAddress['private_key']) ? $outAddress['private_key'] : '';
- $outAddress = isset($outAddress['address']) ? $outAddress['address'] : '';
- if (empty($outAddress) || empty($outAddressPrivate)) {
- $this->error = '2203';
- return false;
- }
- $tron = new Tron();
- // 获取平台钱包hex
- $tron->setAddress($outAddress);
- $outAddressData = $tron->getAddress();
- $tron->setAddress($to);
- $toAddress = $tron->getAddress();
- RedisService::set("caches:wallet:transfer:temp_trx_{$to}", ['to' => $to, 'out' => $outAddress, 'amount' => $amount], 7200);
- $fromAddress = new \Tron\Address($outAddressData['base58'], $outAddressPrivate, $outAddressData['hex']);
- $toAddress = new \Tron\Address($toAddress['base58'], '', $toAddress['hex']);
- $result = $trcWallet->transfer($fromAddress, $toAddress, $amount);
- $result = (array)$result;
- $txID = isset($result['txID']) ? $result['txID'] : '';
- RedisService::set("caches:wallet:transfer:result_trx_{$to}", ['to' => $to, 'out' => $outAddress, 'result' => $result], 7200);
- if ($txID) {
- return ['txId'=> $txID,'address'=> $outAddress];
- }
- return false;
- } catch (\Exception $exception) {
- $message = $exception->getMessage();
- $this->error = $message;
- RedisService::set("caches:wallet:transfer:error_trx_{$to}", ['error' => $exception->getTrace()], 600);
- return false;
- }
- }
- /**
- * usdt-trc2.0 转账
- * @param $to 进账账户
- * @param $amount 转账金额
- * @param $from 转账账户
- * @param $fromPrivate 转账账户私钥
- * @throws \Tron\Exceptions\TransactionException
- * @throws \Tron\Exceptions\TronErrorException
- */
- public function usdtTrcTransfer($to, $amount, $from = '', $fromPrivateKey = '')
- {
- if ($amount <= 0) {
- $this->error = '2205';
- return false;
- }
- if (empty($this->config['tron_api_url'])) {
- $this->error = '2206';
- return false;
- }
- // 获取钱包参数
- try {
- if (!$apiKey = $this->getApiKey()) {
- return false;
- }
- $headers = ["TRON-PRO-API-KEY" => $apiKey];
- $api = new Api(new Client(['base_uri' => $this->config['tron_api_url'], 'headers' => $headers]));
- $trcWallet = new TRC20($api, ['contract_address' => $this->config['tron_contract_address'], 'decimals' => 6]);
- if ($from && $fromPrivateKey) {
- $outAddress = [
- 'address' => $from,
- 'private_key' => $fromPrivateKey,
- ];
- } else if (!$outAddress = $this->getWallet(2, $amount)) {
- return false;
- }
- $outAddressPrivate = isset($outAddress['private_key']) ? $outAddress['private_key'] : '';
- $outAddress = isset($outAddress['address']) ? $outAddress['address'] : '';
- if (empty($outAddress) || empty($outAddressPrivate)) {
- $this->error = '2203';
- return false;
- }
- $tron = new Tron();
- // 获取平台钱包hex
- $tron->setAddress($outAddress);
- $outAddressData = $tron->getAddress();
- // 获取收款钱包hex
- $tron->setAddress($to);
- $toAddress = $tron->getAddress();
- $fromAddress = new \Tron\Address($outAddressData['base58'], $outAddressPrivate, $outAddressData['hex']);
- $toAddress = new \Tron\Address($toAddress['base58'], '', $toAddress['hex']);
- RedisService::set("caches:wallet:transfer:temp_usdt_{$to}", ['to' => $to, 'out' => $outAddress,'private'=>$outAddressPrivate, 'amount' => $amount], 7200);
- $result = $trcWallet->transfer($fromAddress, $toAddress, $amount);
- $result = (array)$result;
- $txID = isset($result['txID']) ? $result['txID'] : '';
- RedisService::set("caches:wallet:transfer:result_usdt_{$to}", ['to' => $to, 'out' => $outAddress,'private'=>$outAddressPrivate, 'result' => $result], 7200);
- if ($txID) {
- return ['txId'=> $txID, 'address'=>$outAddress];
- }
- return false;
- } catch (\Exception $exception) {
- $message = $exception->getMessage();
- $this->error = $message;
- RedisService::set("caches:wallet:transfer:error_usdt_{$to}", ['error' => $exception->getTrace()], 600);
- return false;
- }
- }
- /**
- * 监听USDT-TRC2.0用户子钱包充值存币处理
- * @param $address 钱包地址
- * @param int $accountType 账户类型:1-USDT充值,2-USDT提现,3-星豆充值
- * @return array|false
- */
- public function listenTrcWallet($address, $accountType=1)
- {
- // 获取钱包参数
- try {
- if (!$apiKey = $this->getApiKey()) {
- return false;
- }
- $headers = ["TRON-PRO-API-KEY" => $apiKey];
- $limit = ConfigService::make()->getConfigByCode('wallet_listen_limit', 300);
- $limit = $limit>10 && $limit <=500? $limit : 200;
- $url = sprintf($this->apiUrls['transactions'], $address, $limit, $accountType==2? 'false': 'true', $accountType==2?'true':'false');
- $result = curl_get($this->config['tron_api_url'] . $url, [], $headers, 5);
- $result = $result ? json_decode($result, true) : [];
- $datas = isset($result['data']) && is_array($result['data'])? $result['data'] : [];
- $status = isset($result['success']) ? $result['success'] : '';
- RedisService::set("caches:wallets:listen_{$address}", ['url' => $this->config['tron_api_url'] . $url, 'result' => $result], 7200);
- if ($status != true || empty($datas)) {
- $this->error = '2207';
- return false;
- }
- $coinInMin = ConfigService::make()->getConfigByCode('trc_in_limit');
- $coinInMin = $coinInMin > 0 ? $coinInMin : 0;
- $cacheKey = "caches:wallet:listen:{$address}_{$accountType}:";
- $dateTime = date('Y-m-d H:i:s');
- $success = 0;
- if ($datas) {
- foreach ($datas as $v) {
- $amount = isset($v['value']) ? intval($v['value']) : 0;
- $amount = moneyFormat($amount / 1000000, 6);
- $time = isset($v['block_timestamp']) ? intval($v['block_timestamp'] / 1000) : 0;
- $txid = isset($v['transaction_id']) ? $v['transaction_id'] : '';
- $ownerAddress = isset($v['from']) ? $v['from'] : '';
- $toAddress = isset($v['to']) ? $v['to'] : '';
- if($amount < $coinInMin) {
- echo "【{$dateTime} wallet】账户[{$ownerAddress}]到钱包[{$toAddress}]记录[{$txid}]金额[{$amount}],金额较小不处理\n";
- RedisService::set($cacheKey."{$txid}:error", ['error'=>'金额较小不处理','data'=> $v], 7200);
- continue;
- }
- // 充值处理
- if($toAddress == $address && $ownerAddress && $accountType != 2){
- if (BalanceLogModel::checkExists($txid)) {
- echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]交易已处理过\n";
- RedisService::set($cacheKey."{$txid}:error", ['error'=>'交易已处理过','data'=> $v], 7200);
- continue;
- }
- $memberInfo = MemberModel::where(['trc_url' => $ownerAddress,'mark'=>1])
- ->select(['id','email','trc_url','usdt','balance'])
- ->orderBy('id','asc')
- ->first();
- $trcUrl = isset($memberInfo['trc_url'])? trim($memberInfo['trc_url']) : '';
- $usdt = isset($memberInfo['usdt'])? floatval($memberInfo['usdt']) : 0;
- $balance = isset($memberInfo['balance'])? floatval($memberInfo['balance']) : 0;
- $userId = isset($memberInfo['id'])? intval($memberInfo['id']) : 0;
- if(empty($memberInfo)){
- echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]未绑定用户\n";
- RedisService::set($cacheKey."{$txid}:error", ['error'=>'未绑定用户','data'=> $v], 7200);
- continue;
- }
- // 充值汇率
- $rate = ConfigService::make()->getConfigByCode('xd_price',0.01);
- $rate = $rate>0 && $rate <= 10000? $rate : 0.01;
- // 入账
- DB::beginTransaction();
- $updateData = ['update_time'=> time()];
- $total = $amount;
- if($accountType == 1){
- $updateData['usdt'] = DB::raw("usdt + {$total}");
- }else if($accountType == 3){
- $total = moneyFormat($rate * $amount, 6);
- $updateData['balance'] = DB::raw("balance + {$total}");
- }
- if(!MemberModel::where(['id'=> $userId])->update($updateData)){
- DB::rollBack();
- echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]入账处理失败\n";
- RedisService::set($cacheKey."{$txid}:error", ['error'=>'入账处理失败','update'=>$updateData,'member'=> $memberInfo,'data'=> $v], 7200);
- continue;
- }
- // 充值明细
- $data = [
- 'user_id'=> $userId,
- 'order_no'=> get_order_num('XC'),
- 'type'=> 1,
- 'user_type'=> 1,
- 'coin_type'=> $accountType==1? 1 : 2,
- 'money'=> $amount,
- 'actual_money'=> $total,
- 'pay_type'=> 20,
- 'pay_status'=> 20,
- 'pay_at'=> date('Y-m-d H:i:s', $time),
- 'hash'=> $txid,
- 'trc_url'=> $trcUrl,
- 'wallet_url'=> $address,
- 'date'=> date('Y-m-d'),
- 'create_time'=> time(),
- 'update_time'=> time(),
- 'status'=> 2,
- 'mark'=>1,
- ];
- if(!BalanceLogModel::insert($data)){
- DB::rollBack();
- echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]充值明细处理失败\n";
- RedisService::set($cacheKey."{$txid}:error", ['error'=>'充值明细处理失败','log'=> $data,'member'=> $memberInfo,'data'=> $v], 7200);
- continue;
- }
- // 用户账户明细
- $log = [
- 'user_id'=> $userId,
- 'source_order_no'=> $data['order_no'],
- 'user_type'=> 1,
- 'type'=> 5,
- 'coin_type'=> $accountType==1? 1 : 2,
- 'hash'=> $txid,
- 'money'=> $amount,
- 'actual_money'=> $total,
- 'balance'=> $accountType==1? $usdt : $balance,
- 'date'=> date('Y-m-d'),
- 'create_time'=> time(),
- 'update_time'=> time(),
- 'remark'=> $accountType==1? 'USDT余额充值':'星豆余额充值',
- 'status'=> 1,
- 'mark'=>1,
- ];
- if(!AccountLogModel::insert($log)){
- DB::rollBack();
- echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]账户明细处理失败\n";
- RedisService::set($cacheKey."{$txid}:error", ['error'=>'账户明细处理失败','log'=>$log,'member'=> $memberInfo,'data'=> $v], 7200);
- continue;
- }
- // 平台进账
- FinanceService::make()->saveLog(0, $amount, 1);
- // 平台账户明细
- $log = [
- 'user_id'=> 0,
- 'source_id'=> $userId,
- 'source_order_no'=> $data['order_no'],
- 'user_type'=> 4,
- 'type'=> 5,
- 'coin_type'=> 1,
- 'hash'=> $txid,
- 'money'=> $amount,
- 'actual_money'=> $amount,
- 'balance'=> 0,
- 'date'=> date('Y-m-d'),
- 'create_time'=> time(),
- 'update_time'=> time(),
- 'remark'=> 'USD充值',
- 'status'=> 1,
- 'mark'=>1,
- ];
- if(!AccountLogModel::insert($log)){
- DB::rollBack();
- echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]平台账户明细处理失败\n";
- RedisService::set($cacheKey."{$txid}:error", ['error'=>'平台账户明细处理失败','log'=>$log,'member'=> $memberInfo,'data'=> $v], 7200);
- continue;
- }
- // 邮件消息
- DB::commit();
- // 充值星豆/USDT任务
- TaskService::make()->updateTask($userId,$accountType==1?10:9, 0);
- $total = moneyFormat($total,2);
- $amount = moneyFormat($amount,2);
- $coinName = $accountType==1?'USDT':'星豆';
- $message = "您在 {$dateTime} (UTC+8) 充值{$total}到星链".($accountType==1?'USDT':'星豆')."账户成功,明细如下:<br>充值账户:{$trcUrl}<br>充值:{$amount} USDT<br>到账:{$total} {$coinName}<br>单号:{$data['order_no']}<br>交易单号:<a href='https://tronscan.org/#/transaction/{$txid}'>{$txid}</a>";
- EmailService::make()->sendUserEmail($userId, $message, $coinName.'充值到账通知',3);
- RedisService::set($cacheKey."{$txid}:success", ['error'=>'处理成功','log'=>$data,'member'=> $memberInfo,'data'=> $v], 7200);
- echo "【{$dateTime} recharge】账户[{$ownerAddress}]充值到钱包[{$address}]记录[{$txid}]金额[{$amount}]充值成功\n";
- RedisService::clear("caches:wallet:balanceLog:{$txid}");
- $success++;
- }
- // 提现处理
- else if($ownerAddress == $address && $toAddress && $accountType == 2){
- // 处理锁跳过
- if(RedisService::get($cacheKey."{$txid}:lock")){
- echo "【{$dateTime} withdraw】提现记录[{$txid}]金额[{$amount}]间隔时间不处理\n";
- RedisService::set($cacheKey."{$txid}:error", ['error'=>'间隔时间内不处理','data'=> $v], 600);
- continue;
- }
- $info = BalanceLogModel::checkExists($txid);
- $logId = isset($info['id'])? $info['id'] : 0;
- $userId = isset($info['user_id'])? $info['user_id'] : 0;
- $money = isset($info['money'])? $info['money'] : 0;
- $actualMoney = isset($info['actual_money'])? $info['actual_money'] : 0;
- $coinType = isset($info['coin_type'])? $info['coin_type'] : 1;
- $payStatus = isset($info['pay_status'])? $info['pay_status'] : 0;
- $status = isset($info['status'])? $info['status'] : 0;
- $trcUrl = isset($info['trc_url'])? trim($info['trc_url']) : '';
- $walletUrl = isset($info['wallet_url'])? trim($info['wallet_url']) : '';
- if (empty($info) || $logId<=0 || $userId<=0) {
- echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}]提现记录不存在\n";
- RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现记录不存在','data'=> $v], 7200);
- RedisService::set($cacheKey."{$txid}:lock", ['error'=>'提现记录不存在','data'=> $v], rand(30,60));
- continue;
- }
- if($status != 2){
- echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}]提现记录未审核\n";
- RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现记录未审核','data'=> $v], 7200);
- RedisService::set($cacheKey."{$txid}:lock", ['error'=>'提现记录未审核','data'=> $v], rand(30,60));
- continue;
- }
- if($payStatus == 20){
- echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}]提现记录已打款\n";
- RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现记录已打款','data'=> $v], 7200);
- RedisService::set($cacheKey."{$txid}:lock", ['error'=>'提现记录已打款','data'=> $v], rand(30,60));
- continue;
- }
- if ($trcUrl != $toAddress || $walletUrl != $ownerAddress) {
- echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],提现订单交易地址不匹配\n";
- RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现订单交易地址不匹配','info'=>$info,'data'=> $v], 7200);
- continue;
- }
- // 金额验证
- if(abs($actualMoney - $amount) > 1){
- echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],提现金额与交易金额不匹配\n";
- RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现金额与交易金额不匹配','info'=>$info,'data'=> $v], 7200);
- RedisService::set($cacheKey."{$txid}:lock", ['error'=>'提现金额与交易金额不匹配','data'=> $v], rand(30,60));
- continue;
- }
- // 更新状态
- DB::beginTransaction();
- if(!BalanceLogModel::where(['id'=> $logId])->update(['pay_status'=> 20,'pay_at'=>$dateTime, 'update_time'=>time()])){
- DB::rollBack();
- echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],提现状态更新失败\n";
- RedisService::set($cacheKey."{$txid}:error", ['error'=>'提现状态更新失败','info'=>$info,'data'=> $v], 7200);
- continue;
- }
- // 平台出账
- FinanceService::make()->saveLog(0, $amount, 2);
- // 平台账户明细
- $orderNo = isset($info['order_no'])? $info['order_no'] : '';
- $log = [
- 'user_id'=> 0,
- 'source_id'=> $userId,
- 'source_order_no'=> $orderNo,
- 'user_type'=> 4,
- 'type'=> 5,
- 'coin_type'=> 1,
- 'hash'=> $txid,
- 'money'=> $money,
- 'actual_money'=> -$amount,
- 'balance'=> 0,
- 'date'=> date('Y-m-d'),
- 'create_time'=> time(),
- 'update_time'=> time(),
- 'status'=> 1,
- 'mark'=>1,
- ];
- if(!AccountLogModel::insert($log)){
- DB::rollBack();
- echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],平台账户明细处理失败\n";
- RedisService::set($cacheKey."{$txid}:error", ['error'=>'平台账户明细处理失败','log'=>$log,'info'=> $info,'data'=> $v], 7200);
- continue;
- }
- // 邮件消息
- DB::commit();
- $amount = moneyFormat($amount,2);
- $accounts = [1=>'USDT',2=>'星豆',3=>'C2C额度',4=>'佣金',5=>'商户余额'];
- $coinName = isset($accounts[$coinType])? $accounts[$coinType] : '余额';
- $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>";
- EmailService::make()->sendUserEmail($userId, $message, $coinName.'提现到账通知', 3);
- RedisService::set($cacheKey."{$txid}:success", ['error'=>'处理成功','log'=>$log,'info'=>$info,'data'=> $v], 7200);
- echo "【{$dateTime} withdraw】账户[{$toAddress}]从[{$address}]提现记录[{$txid}]金额[{$amount}],提现成功\n";
- RedisService::clear("caches:wallet:balanceLog:{$txid}");
- $success++;
- }
- // 处理交易记录
- if (!WalletLogModel::checkExists($txid)) {
- $log = [
- 'owner_address' => $ownerAddress,
- 'to_address' => $toAddress,
- 'hash' => $txid,
- 'amount' => $amount,
- 'create_time' => $time ? $time : time(),
- 'update_time' => time(),
- 'status' => 1,
- 'mark' => 1,
- ];
- WalletLogModel::insert($log);
- }
- }
- }
- $this->error = 1010;
- return ['success'=> $success, 'total'=> count($datas)];
- } catch (\Exception $exception) {
- $message = $exception->getMessage();
- $this->error = $message;
- RedisService::set("caches:wallet:listen_error_{$address}", ['error' => $exception->getMessage(), 'trace' => $exception->getTrace()], 600);
- return false;
- }
- }
- }
|