TronHelper.php 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400
  1. <?php
  2. namespace App\Helpers;
  3. use Mdanter\Ecc\EccFactory;
  4. use Mdanter\Ecc\Random\RandomGeneratorFactory;
  5. use Illuminate\Support\Facades\Cache;
  6. use Illuminate\Support\Facades\Crypt;
  7. use GuzzleHttp\Client;
  8. use GuzzleHttp\Exception\GuzzleException;
  9. use Illuminate\Support\Facades\Log;
  10. use TronTool\Credential;
  11. use TronTool\TronApi;
  12. use TronTool\TronKit;
  13. use kornrunner\Secp256k1;
  14. use kornrunner\Keccak;
  15. use App\Helpers\TronRawSerializer;
  16. use App\Http\Controllers\admin\Balance;
  17. use kornrunner\Signature\Signature;
  18. use Elliptic\EC;
  19. use kornrunner\Serializer\HexSignatureSerializer;
  20. class TronHelper
  21. {
  22. public static $isTest = true;
  23. public static $tronUrl = 'https://api.trongrid.io';
  24. public static $nileUrl = 'https://nile.trongrid.io'; // 测试网
  25. const CONFIRMED_NUMBER = 3; // 确认数
  26. const GLOBAL_TRON_RATE_LIMIT_KEY = 'tron_request_global_rate_limit';
  27. const GLOBAL_TRON_RATE_LIMIT_SECONDS = 1;
  28. const TRC20_TRANSFER_TOPIC = 'ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef';
  29. protected static $client;
  30. public static function init()
  31. {
  32. if(self::getTronNetwork()){
  33. $url = self::$nileUrl;
  34. }else{
  35. $url = self::$tronUrl;
  36. }
  37. if (!self::$client) {
  38. $headers = self::getTronRequestHeaders();
  39. self::$client = new Client([
  40. 'base_uri' => $url,
  41. 'timeout' => 10.0,
  42. 'headers' => $headers,
  43. 'verify' => false
  44. ]);
  45. }
  46. }
  47. public static function getTronRequestHeaders(): array
  48. {
  49. $headers = [
  50. 'Accept' => 'application/json',
  51. 'Content-Type' => 'application/json',
  52. ];
  53. $apiKey = self::getTronProApiKey();
  54. if ($apiKey) {
  55. $headers['TRON-PRO-API-KEY'] = $apiKey;
  56. }
  57. return $headers;
  58. }
  59. public static function getTronProApiKey(): string
  60. {
  61. return trim((string) config('app.tron_pro_api_key', ''));
  62. }
  63. public static function getUsdtTransferFeeLimitTrx(): float
  64. {
  65. $value = (float) config('app.tron_usdt_transfer_fee_limit', 30);
  66. return $value > 0 ? $value : 30.0;
  67. }
  68. public static function getUsdtTransferFeeLimitSun(): int
  69. {
  70. return (int) round(self::getUsdtTransferFeeLimitTrx() * 1000000);
  71. }
  72. public static function throttleTronRequest(int $seconds = self::GLOBAL_TRON_RATE_LIMIT_SECONDS, string $key = self::GLOBAL_TRON_RATE_LIMIT_KEY): void
  73. {
  74. $store = self::getTronRateLimitStore();
  75. $deadline = microtime(true) + max(3, $seconds + 2);
  76. while (!$store->add($key, microtime(true), $seconds)) {
  77. usleep(200000);
  78. if (microtime(true) >= $deadline) {
  79. break;
  80. }
  81. }
  82. }
  83. protected static function getTronRateLimitStore()
  84. {
  85. try {
  86. return Cache::store('redis');
  87. } catch (\Throwable $e) {
  88. return Cache::store(config('cache.default'));
  89. }
  90. }
  91. /**
  92. * @description: 获取网络
  93. * @return {*}
  94. */
  95. public static function getTronNetwork()
  96. {
  97. $netWork = config('app.tron_network'); // 默认是主网
  98. if($netWork == 'main'){
  99. return false;
  100. }else{
  101. return true;
  102. }
  103. }
  104. /**
  105. * @description: 创建钱包地址和私钥
  106. * @return {private_key,address}
  107. */
  108. public static function createAddress($memberId = ''): array
  109. {
  110. // 生成 TRC20 私钥
  111. $privateKey = self::makePrivateKey($memberId); // 默认不带 memberId
  112. // 从私钥生成地址
  113. $address = self::getAddressByPrivateKey($privateKey);
  114. // 记录日志
  115. Log::channel('wallet')->info('创建钱包地址', [
  116. 'member_id' => $memberId,
  117. 'address' => $address,
  118. 'private_key' => $privateKey,
  119. ]);
  120. return [
  121. 'address' => $address,
  122. 'private_key' => $privateKey,
  123. ];
  124. }
  125. /**
  126. * @description: 转账USDT
  127. * @param {*} $privateKey 转账秘钥
  128. * @param {*} $toAddress 接收地址
  129. * @param {*} $amount 转账金额
  130. * @return {*}
  131. */
  132. public static function transferUSDT($privateKey, $toAddress, $amount)
  133. {
  134. self::throttleTronRequest();
  135. $nodeScript = base_path('node/index.js'); // Laravel根目录下的路径
  136. $nodeBin = 'node'; // 用 which node 查看,或自定义
  137. if(self::getTronNetwork()){
  138. $fullNodeUrl = self::$nileUrl;
  139. }else{
  140. $fullNodeUrl = self::$tronUrl;
  141. }
  142. $contractAddress = self::getContractAddress('USDT');
  143. $apiKey = self::getTronProApiKey();
  144. $feeLimitSun = self::getUsdtTransferFeeLimitSun();
  145. $parts = [
  146. escapeshellcmd($nodeBin),
  147. escapeshellarg($nodeScript),
  148. escapeshellarg($privateKey),
  149. escapeshellarg($toAddress),
  150. escapeshellarg($contractAddress),
  151. escapeshellarg($fullNodeUrl),
  152. escapeshellarg($amount),
  153. escapeshellarg($feeLimitSun),
  154. ];
  155. if ($apiKey !== '') {
  156. $parts[] = escapeshellarg($apiKey);
  157. }
  158. $cmd = implode(' ', $parts) . ' 2>&1';
  159. exec($cmd, $outputLines, $status);
  160. $output = implode("\n", $outputLines);
  161. $result = json_decode($output, true);
  162. return $result;
  163. // self::init();
  164. // $contractAddress = self::getContractAddress('USDT');
  165. // $fromAddress = self::getAddressByPrivateKey($privateKey);
  166. // // 1. 构建转账交易
  167. // $transferData = [
  168. // 'owner_address' => self::base58check2HexString($fromAddress),
  169. // 'contract_address' => self::base58check2HexString($contractAddress),
  170. // 'function_selector' => 'transfer(address,uint256)',
  171. // 'parameter' => self::buildParameter($toAddress, $amount),
  172. // 'visible' => false
  173. // ];
  174. // $response = self::$client->post('/wallet/triggersmartcontract', [
  175. // 'json' => $transferData
  176. // ]);
  177. // $data = json_decode($response->getBody(), true);
  178. // var_dump($data);
  179. // if (empty($data['transaction'])) {
  180. // throw new \Exception('构建转账交易失败: ' . json_encode($data));
  181. // }
  182. // $txid = $data['transaction']['txID'];
  183. // // 2. 签名交易
  184. // // $rawData = $data['transaction']['raw_data'];
  185. // // $rawDataBytes = TronRawSerializer::serializeRawData($rawData); // 自定义函数,返回 Protobuf 序列化后的二进制
  186. // // $txHash = hash('sha256', $rawDataBytes); // Tron使用 SHA256,不是 Keccak256
  187. // // // 使用私钥签名
  188. // // $secp256k1 = new Secp256k1();
  189. // // $signature = $secp256k1->sign($txHash, $privateKey);
  190. // // $signatureHex = self::formatTronSignature($signature);
  191. // $signedTx = self::signTronTransaction($data['transaction'],$privateKey);
  192. // // var_dump($signatureHex);
  193. // // $signedTx['visible'] = true;
  194. // // 3. 广播交易
  195. // // 将 signature 转成 hex 字符串
  196. // // $signatureHex = bin2hex($signature);
  197. // // $signatureHex = $signature;
  198. // // var_dump($signatureHex);
  199. // // 构建签名交易
  200. // // $signedTx = [
  201. // // 'txID' => $data['transaction']['txID'],
  202. // // 'raw_data' => $data['transaction']['raw_data'],
  203. // // 'signature' => $signatureHex,
  204. // // ];
  205. // var_dump($signedTx);
  206. // $broadcast = self::$client->post('/wallet/broadcasttransaction', [
  207. // 'json' => $signedTx
  208. // ]);
  209. // $broadcastData = json_decode($broadcast->getBody(), true);
  210. // return $broadcastData;
  211. }
  212. public static function signTronTransaction(array $transaction, string $privateKey): array
  213. {
  214. $rawData = $transaction['raw_data'] ?? null;
  215. if (!$rawData) {
  216. throw new \Exception('交易中没有 raw_data');
  217. }
  218. $rawDataBytes = TronRawSerializer::serializeRawData($rawData);
  219. $txHash = hash('sha256', $rawDataBytes, true); // 二进制哈希
  220. $privateKeyHex = ltrim($privateKey, '0x');
  221. if (strlen($privateKeyHex) !== 64) {
  222. throw new \Exception('私钥格式不正确');
  223. }
  224. $privateKeyBin = hex2bin($privateKeyHex);
  225. $secp256k1 = new Secp256k1();
  226. $signatureObj = $secp256k1->sign($txHash, $privateKeyBin);
  227. // r, s 都是 GMP 对象,转成32字节二进制字符串
  228. $rBin = self::gmpToBin32($signatureObj->getR());
  229. $sBin = self::gmpToBin32($signatureObj->getS());
  230. $signatureBin = $rBin . $sBin; // 64字节二进制签名
  231. $transaction['signature'] = [$signatureBin];
  232. return $transaction;
  233. }
  234. private static function gmpToBin32($gmpNum): string
  235. {
  236. $hex = gmp_strval($gmpNum, 16);
  237. if (strlen($hex) % 2 !== 0) {
  238. $hex = '0' . $hex;
  239. }
  240. $bin = hex2bin($hex);
  241. return str_pad($bin, 32, "\0", STR_PAD_LEFT);
  242. }
  243. /**
  244. * 构建 parameter 字符串(目标地址 + 金额)
  245. */
  246. protected static function buildParameter($toAddress, $amount)
  247. {
  248. $hexAddress = self::base58check2HexString($toAddress);
  249. $addr = str_pad(substr($hexAddress, 2), 64, '0', STR_PAD_LEFT); // 去掉 '41' 开头的 Tron 前缀
  250. $amt = str_pad(bcdechex(bcmul($amount, '1000000')), 64, '0', STR_PAD_LEFT); // USDT 精度 6
  251. return $addr . $amt;
  252. }
  253. // /**
  254. // * @param Signature $signature
  255. // * @return string 65字节签名的十六进制字符串
  256. // */
  257. // public static function formatTronSignature(Signature $signature): string
  258. // {
  259. // $r = gmp_strval($signature->getR(), 16);
  260. // $s = gmp_strval($signature->getS(), 16);
  261. // $v = dechex($signature->getRecoveryParam()); // v 即 recoveryParam
  262. // // 补齐 r 和 s 为 64位长度(即32字节)
  263. // $r = str_pad($r, 64, '0', STR_PAD_LEFT);
  264. // $s = str_pad($s, 64, '0', STR_PAD_LEFT);
  265. // $v = str_pad($v, 2, '0', STR_PAD_LEFT); // 1字节 = 2个hex字符
  266. // $v_decimal = hexdec($v); // 0
  267. // $v_decimal += 27; // 27
  268. // $v_hex = dechex($v_decimal); // "1b"
  269. // return $r . $s . $v_hex; // 返回最终的签名字符串
  270. // }
  271. /**
  272. * @description: 获取地址的YRX余额
  273. * @param {*} $addressBase58
  274. * @return {*}
  275. */
  276. public static function getTrxBalance($addressBase58)
  277. {
  278. self::throttleTronRequest();
  279. $hexAddress = TronHelper::base58check2HexString($addressBase58);
  280. self::init();
  281. $response = self::$client->post('/wallet/getaccount', [
  282. 'json' => ['address' => $hexAddress]
  283. ]);
  284. $data = json_decode($response->getBody(), true);
  285. if (!empty($data['balance'])) {
  286. // TRX 的单位是 sun,1 TRX = 1_000_000 sun
  287. return $data['balance'] / 1_000_000;
  288. }
  289. return 0;
  290. }
  291. // /**
  292. // * @description: 向账户转TRX能量
  293. // * @param {*} $fromAddress
  294. // * @param {*} $privateKey
  295. // * @param {*} $toAddress
  296. // * @param {*} $amount
  297. // * @return {*}
  298. // */
  299. // public static function transferTRX($fromAddress, $privateKey, $toAddress, $amount)
  300. // {
  301. // self::init();
  302. // $ownerAddressHex = self::base58check2HexString($fromAddress);
  303. // $toAddressHex = self::base58check2HexString($toAddress);
  304. // $createData = [
  305. // 'owner_address' => $ownerAddressHex,
  306. // 'to_address' => $toAddressHex,
  307. // 'amount' => (int)($amount * 1_000_000), // TRX 精度为 6
  308. // ];
  309. // // 构建转账交易
  310. // $response = self::$client->post('/wallet/createtransaction', [
  311. // 'json' => $createData
  312. // ]);
  313. // $tx = json_decode($response->getBody(), true);
  314. // if (!isset($tx['txID'])) {
  315. // throw new \Exception('创建转账交易失败: ' . json_encode($tx));
  316. // }
  317. // // 签名交易
  318. // $signature = self::signTransaction($tx,$privateKey);
  319. // // 广播交易
  320. // $signedTx = [
  321. // 'txID' => $tx['txID'],
  322. // 'raw_data' => $tx['raw_data'],
  323. // 'raw_data_hex' => $tx['raw_data_hex'],
  324. // 'signature' => $signature,
  325. // ];
  326. // $response = self::$client->post('/wallet/broadcasttransaction', [
  327. // 'json' => $signedTx
  328. // ]);
  329. // var_dump($signedTx);
  330. // $result = json_decode($response->getBody(), true);
  331. // var_dump($result);
  332. // die();
  333. // // if (!isset($result['result']) || !$result['result']) {
  334. // // throw new \Exception('广播失败: ' . json_encode($result));
  335. // // }
  336. // return [
  337. // 'txID' => $tx['txID'],
  338. // 'result' => true
  339. // ];
  340. // }
  341. // /**
  342. // * @description: TRX签名
  343. // * @param {array} $transaction
  344. // * @param {string} $privateKey
  345. // * @return {*}
  346. // */
  347. // public static function signTransaction($tx, $privateKey)
  348. // {
  349. // if (empty($tx['raw_data_hex'])) {
  350. // throw new \Exception('原始交易数据为空,无法签名');
  351. // }
  352. // $rawDataHex = $tx['raw_data_hex'];
  353. // $rawDataBin = hex2bin($rawDataHex);
  354. // $hash = hash('sha256', $rawDataBin, true); // 原始数据做 SHA256
  355. // $signatureDer = self::ecdsaSignRaw($hash, $privateKey); // 返回 DER 格式签名
  356. // return [$signatureDer]; // Tron 要求是签名数组
  357. // }
  358. // public static function ecdsaSignRaw($hash, $privateKeyHex)
  359. // {
  360. // $ec = new EC('secp256k1');
  361. // $key = $ec->keyFromPrivate($privateKeyHex);
  362. // $signature = $key->sign(bin2hex($hash), ['canonical' => true]);
  363. // $r = str_pad($signature->r->toString('hex'), 64, '0', STR_PAD_LEFT);
  364. // $s = str_pad($signature->s->toString('hex'), 64, '0', STR_PAD_LEFT);
  365. // return hex2bin($r . $s); // 返回64字节的二进制字符串
  366. // }
  367. /**
  368. * 查询某地址的 TRX 充值记录
  369. * @param string $address 充值地址
  370. * @param int $limit 返回记录数
  371. * @return array
  372. */
  373. public static function getTrxTransactions(string $address, int $limit = 30): array
  374. {
  375. self::init();
  376. $response = self::$client->get("https://nile.trongrid.io/v1/accounts/{$address}/transactions", [
  377. 'query' => [
  378. 'limit' => $limit,
  379. 'only_confirmed' => 'true',
  380. 'order' => 'desc',
  381. ]
  382. ]);
  383. $data = json_decode($response->getBody()->getContents(), true);
  384. return $data;
  385. }
  386. /**
  387. * 查询某地址的 TRC20 USDT 充值记录
  388. * @param string $address 充值地址
  389. * @param int $limit 返回记录数
  390. * @return array
  391. */
  392. public static function getTrc20UsdtRecharges(string $address, int $limit = 30): array
  393. {
  394. self::throttleTronRequest();
  395. self::init();
  396. $usdtContract = self::getContractAddress('USDT');
  397. try {
  398. $response = self::$client->get("/v1/accounts/{$address}/transactions/trc20", [
  399. 'headers' => [
  400. 'Accept' => 'application/json',
  401. ],
  402. 'query' => [
  403. 'limit' => $limit,
  404. 'only_confirmed' => 'true',
  405. 'order_by' => 'block_timestamp,desc',
  406. ],
  407. 'timeout' => 10,
  408. ]);
  409. $data = json_decode($response->getBody()->getContents(), true);
  410. $recharges = [];
  411. foreach ($data['data'] ?? [] as $item) {
  412. $tokenAddress = $item['token_info']['address'] ?? '';
  413. if (strtolower($tokenAddress) !== strtolower($usdtContract)) {
  414. continue; // 不是USDT
  415. }
  416. $txid = $item['transaction_id'] ?? '';
  417. if (empty($txid)) {
  418. continue;
  419. }
  420. $transfer = self::getUsdtTransferByTxid($txid, $address);
  421. if (empty($transfer['success'])) {
  422. Log::warning('忽略非USDT Transfer充值记录', [
  423. 'address' => $address,
  424. 'txid' => $txid,
  425. 'message' => $transfer['message'] ?? '',
  426. ]);
  427. continue;
  428. }
  429. $recharges[] = [
  430. 'txid' => $txid,
  431. 'from_address' => $transfer['from_address'],
  432. 'to_address' => $transfer['to_address'],
  433. 'amount' => $transfer['amount'],
  434. 'coin' => 'USDT',
  435. 'block_time' => $transfer['block_time'],
  436. 'block_height' => $transfer['block_number'],
  437. ];
  438. }
  439. return $recharges;
  440. } catch (\Throwable $e) {
  441. Log::warning('获取TRC20 USDT充值记录失败', [
  442. 'address' => $address,
  443. 'error' => $e->getMessage(),
  444. ]);
  445. return [];
  446. }
  447. }
  448. /**
  449. * 查询并校验单笔交易是否为打到指定地址的 USDT Transfer 事件。
  450. */
  451. public static function getUsdtTransferByTxid(string $txid, ?string $expectedToAddress = null): array
  452. {
  453. self::throttleTronRequest();
  454. self::init();
  455. try {
  456. $txResp = self::$client->post('/wallet/gettransactioninfobyid', [
  457. 'json' => ['value' => $txid],
  458. 'headers' => ['Accept' => 'application/json'],
  459. ]);
  460. $txData = json_decode($txResp->getBody()->getContents(), true);
  461. $result = self::parseUsdtTransferEventFromTransactionInfo($txData, $expectedToAddress);
  462. if (empty($result['success'])) {
  463. return $result;
  464. }
  465. $result['txid'] = $txid;
  466. return $result;
  467. } catch (\Throwable $e) {
  468. return ['success' => false, 'message' => $e->getMessage()];
  469. }
  470. }
  471. /**
  472. * 查询确认数,同时强制校验交易必须是 USDT Transfer。
  473. */
  474. public static function getUsdtTransferConfirmation(string $txid, ?string $expectedToAddress = null): array
  475. {
  476. $transfer = self::getUsdtTransferByTxid($txid, $expectedToAddress);
  477. if (empty($transfer['success'])) {
  478. return $transfer;
  479. }
  480. try {
  481. $blockResp = self::$client->get('/wallet/getnowblock', [
  482. 'headers' => ['Accept' => 'application/json'],
  483. ]);
  484. $blockData = json_decode($blockResp->getBody()->getContents(), true);
  485. $latestBlock = $blockData['block_header']['raw_data']['number'] ?? 0;
  486. if ($latestBlock == 0) {
  487. return ['success' => false, 'message' => '无法获取最新区块'];
  488. }
  489. $confirmations = $latestBlock - $transfer['block_number'] + 1;
  490. return $transfer + [
  491. 'latest_block' => $latestBlock,
  492. 'confirmations' => $confirmations,
  493. ];
  494. } catch (\Throwable $e) {
  495. return ['success' => false, 'message' => $e->getMessage()];
  496. }
  497. }
  498. /**
  499. * 从 gettransactioninfobyid 返回值解析 USDT Transfer 事件。
  500. */
  501. public static function parseUsdtTransferEventFromTransactionInfo(array $txData, ?string $expectedToAddress = null, ?string $usdtContractAddress = null): array
  502. {
  503. if (empty($txData['blockNumber'])) {
  504. return ['success' => false, 'message' => '交易尚未被打包或无效'];
  505. }
  506. if (($txData['receipt']['result'] ?? 'SUCCESS') !== 'SUCCESS') {
  507. return ['success' => false, 'invalid' => true, 'message' => '交易执行失败'];
  508. }
  509. $usdtContractAddress = $usdtContractAddress ?: self::getContractAddress('USDT');
  510. $usdtLogAddress = self::normalizeTronLogAddress($usdtContractAddress);
  511. foreach ($txData['log'] ?? [] as $log) {
  512. $logAddress = self::normalizeTronLogAddress($log['address'] ?? '');
  513. if ($logAddress !== $usdtLogAddress) {
  514. continue;
  515. }
  516. $topics = $log['topics'] ?? [];
  517. if (count($topics) < 3 || self::stripHexPrefix($topics[0]) !== self::TRC20_TRANSFER_TOPIC) {
  518. continue;
  519. }
  520. $fromAddress = self::tronAddressFromEventTopic($topics[1]);
  521. $toAddress = self::tronAddressFromEventTopic($topics[2]);
  522. if (!$fromAddress || !$toAddress) {
  523. continue;
  524. }
  525. if ($expectedToAddress && !self::sameTronAddress($toAddress, $expectedToAddress)) {
  526. continue;
  527. }
  528. $amountRaw = self::hexToDecimalString($log['data'] ?? '0');
  529. if (bccomp($amountRaw, '0', 0) <= 0) {
  530. continue;
  531. }
  532. return [
  533. 'success' => true,
  534. 'from_address' => $fromAddress,
  535. 'to_address' => $toAddress,
  536. 'amount' => bcdiv($amountRaw, '1000000', 6),
  537. 'amount_raw' => $amountRaw,
  538. 'block_number' => $txData['blockNumber'],
  539. 'block_time' => isset($txData['blockTimeStamp']) ? intval($txData['blockTimeStamp'] / 1000) : null,
  540. ];
  541. }
  542. return ['success' => false, 'invalid' => true, 'message' => '未找到匹配的USDT Transfer事件'];
  543. }
  544. private static function normalizeTronLogAddress(string $address): string
  545. {
  546. $address = trim($address);
  547. if (strlen($address) === 34 && substr($address, 0, 1) === 'T') {
  548. try {
  549. $address = self::base58check2HexString($address);
  550. } catch (\Throwable $e) {
  551. return strtolower($address);
  552. }
  553. }
  554. $address = self::stripHexPrefix($address);
  555. if (strlen($address) === 42 && substr($address, 0, 2) === '41') {
  556. return substr($address, 2);
  557. }
  558. return $address;
  559. }
  560. private static function tronAddressFromEventTopic(string $topic): ?string
  561. {
  562. $topic = self::stripHexPrefix($topic);
  563. if (strlen($topic) < 40 || !ctype_xdigit($topic)) {
  564. return null;
  565. }
  566. try {
  567. return self::hexString2Base58check('41' . substr($topic, -40));
  568. } catch (\Throwable $e) {
  569. return null;
  570. }
  571. }
  572. private static function sameTronAddress(string $left, string $right): bool
  573. {
  574. return trim($left) === trim($right);
  575. }
  576. private static function hexToDecimalString(string $hex): string
  577. {
  578. $hex = self::stripHexPrefix($hex);
  579. if ($hex === '') {
  580. return '0';
  581. }
  582. if (!ctype_xdigit($hex)) {
  583. return '0';
  584. }
  585. $decimal = '0';
  586. foreach (str_split($hex) as $char) {
  587. $decimal = bcadd(bcmul($decimal, '16', 0), (string) hexdec($char), 0);
  588. }
  589. return $decimal;
  590. }
  591. private static function stripHexPrefix(string $hex): string
  592. {
  593. $hex = strtolower(trim($hex));
  594. if (substr($hex, 0, 2) === '0x') {
  595. return substr($hex, 2);
  596. }
  597. return $hex;
  598. }
  599. /**
  600. * @description: 获取TRC20账户余额
  601. * @param {*} $address
  602. * @return {*}
  603. */
  604. public static function getTrc20Balance($address)
  605. {
  606. self::throttleTronRequest();
  607. self::init();
  608. $contractAddress = self::getContractAddress('USDT');
  609. $hexAddress = self::base58check2HexString($address);
  610. $postData = [
  611. 'owner_address' => $hexAddress,
  612. 'contract_address' => self::base58check2HexString($contractAddress),
  613. 'function_selector' => 'balanceOf(address)',
  614. 'parameter' => str_pad(substr($hexAddress, 2), 64, '0', STR_PAD_LEFT),
  615. ];
  616. // try {
  617. $response = self::$client->post('/wallet/triggerconstantcontract', [
  618. 'headers' => [
  619. 'Content-Type' => 'application/json',
  620. ] + self::getTronRequestHeaders(),
  621. 'json' => $postData,
  622. ]);
  623. $body = $response->getBody()->getContents();
  624. $data = json_decode($body, true);
  625. $hexBalance = $data['constant_result'][0] ?? '0x0';
  626. return hexdec($hexBalance) / 1e6; // USDT 精度是 6 位
  627. // } catch (\Exception $e) {
  628. // // 可以记录日志或抛出异常
  629. // return 0;
  630. // }
  631. }
  632. /**
  633. * 查询交易确认数
  634. * @param string $txid 交易哈希
  635. * @return array
  636. */
  637. public static function getTransactionConfirmations(string $txid): array
  638. {
  639. // $client = new Client(['timeout' => 10]);
  640. self::throttleTronRequest();
  641. self::init();
  642. try {
  643. // 1. 获取交易信息
  644. $txResp = self::$client->post('/wallet/gettransactioninfobyid', [
  645. 'json' => ['value' => $txid],
  646. 'headers' => ['Accept' => 'application/json'],
  647. ]);
  648. $txData = json_decode($txResp->getBody()->getContents(), true);
  649. if (!isset($txData['blockNumber'])) {
  650. return ['success' => false, 'message' => '交易尚未被打包或无效'];
  651. }
  652. $txBlock = $txData['blockNumber'];
  653. // 2. 获取最新区块高度
  654. $blockResp = self::$client->get('/wallet/getnowblock', [
  655. 'headers' => ['Accept' => 'application/json'],
  656. ]);
  657. $blockData = json_decode($blockResp->getBody()->getContents(), true);
  658. $latestBlock = $blockData['block_header']['raw_data']['number'] ?? 0;
  659. if ($latestBlock == 0) {
  660. return ['success' => false, 'message' => '无法获取最新区块'];
  661. }
  662. // 3. 计算确认数
  663. $confirmations = $latestBlock - $txBlock + 1;
  664. return [
  665. 'success' => true,
  666. 'txid' => $txid,
  667. 'block_number' => $txBlock,
  668. 'latest_block' => $latestBlock,
  669. 'confirmations' => $confirmations,
  670. ];
  671. } catch (\Exception $e) {
  672. return ['success' => false, 'message' => $e->getMessage()];
  673. }
  674. }
  675. /**
  676. * 加密私钥
  677. */
  678. public static function encryptPrivateKey(string $privateKeyHex): string
  679. {
  680. return Crypt::encryptString($privateKeyHex);
  681. }
  682. /**
  683. * 解密私钥
  684. */
  685. public static function decryptPrivateKey(string $encrypted): string
  686. {
  687. return Crypt::decryptString($encrypted);
  688. }
  689. /**
  690. * 获取合约地址
  691. * @param $currency
  692. * @return string
  693. */
  694. public static function getContractAddress($currency)
  695. {
  696. $currency = strtoupper($currency);
  697. switch ($currency) {
  698. case 'USDT'://usdt
  699. if(self::getTronNetwork()){
  700. $contractAddress = 'TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf'; // nile测试地址
  701. }else{
  702. $contractAddress = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t';
  703. }
  704. break;
  705. case 'USDC'://usdc
  706. $contractAddress = 'TEkxiTehnzSmSe2XqrBj4w32RUN966rdz8';
  707. break;
  708. case 'USDJ'://USDJ
  709. $contractAddress = 'TMwFHYXLJaRUPeW6421aqXL4ZEzPRFGkGT';
  710. break;
  711. case 'TUSD'://TUSD
  712. $contractAddress = 'TUpMhErZL2fhh4sVNULAbNKLokS4GjC1F4';
  713. break;
  714. case 'BTC'://BTC
  715. $contractAddress = 'TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9';
  716. break;
  717. case 'ETH'://ETH
  718. $contractAddress = 'THb4CqiFdwNHsWsQCs4JhzwjMWys4aqCbF';
  719. break;
  720. case 'USDD'://USDD
  721. $contractAddress = 'TPYmHEhy5n8TCEfYGqW2rPxsghSfzghPDn';
  722. break;
  723. default:
  724. $contractAddress = '';
  725. }
  726. return $contractAddress;
  727. }
  728. public static function base58_encode($string)
  729. {
  730. if (is_string($string) === false) {
  731. return false;
  732. }
  733. if ($string === '') {
  734. return '';
  735. }
  736. $alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
  737. $base = strlen($alphabet);
  738. $bytes = array_values(unpack('C*', $string));
  739. $decimal = $bytes[0];
  740. for ($i = 1, $l = count($bytes); $i < $l; $i++) {
  741. $decimal = bcmul($decimal, 256);
  742. $decimal = bcadd($decimal, $bytes[$i]);
  743. }
  744. $output = '';
  745. while ($decimal >= $base) {
  746. $div = bcdiv($decimal, $base, 0);
  747. $mod = bcmod($decimal, $base);
  748. $output .= $alphabet[$mod];
  749. $decimal = $div;
  750. }
  751. if ($decimal > 0) {
  752. $output .= $alphabet[$decimal];
  753. }
  754. $output = strrev($output);
  755. foreach ($bytes as $byte) {
  756. if ($byte === 0) {
  757. $output = $alphabet[0].$output;
  758. continue;
  759. }
  760. break;
  761. }
  762. return $output;
  763. }
  764. public static function base58_decode($base58)
  765. {
  766. if (is_string($base58) === false) {
  767. return false;
  768. }
  769. if ($base58 === '') {
  770. return '';
  771. }
  772. $alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
  773. $base = strlen($alphabet);
  774. $indexes = array_flip(str_split($alphabet));
  775. $chars = str_split($base58);
  776. foreach ($chars as $char) {
  777. if (isset($indexes[$char]) === false) {
  778. return false;
  779. }
  780. }
  781. $decimal = $indexes[$chars[0]];
  782. for ($i = 1, $l = count($chars); $i < $l; $i++) {
  783. $decimal = bcmul($decimal, $base);
  784. $decimal = bcadd($decimal, $indexes[$chars[$i]]);
  785. }
  786. $output = '';
  787. while ($decimal > 0) {
  788. $byte = bcmod($decimal, 256);
  789. $output = pack('C', $byte).$output;
  790. $decimal = bcdiv($decimal, 256, 0);
  791. }
  792. foreach ($chars as $char) {
  793. if ($indexes[$char] === 0) {
  794. $output = "\x00".$output;
  795. continue;
  796. }
  797. break;
  798. }
  799. return $output;
  800. }
  801. //encode address from byte[] to base58check string
  802. public static function base58check_en($address)
  803. {
  804. $hash0 = hash("sha256", $address);
  805. $hash1 = hash("sha256", hex2bin($hash0));
  806. $checksum = substr($hash1, 0, 8);
  807. $address .= hex2bin($checksum);
  808. return self::base58_encode($address);
  809. }
  810. public static function base58check_de($base58add)
  811. {
  812. $address = self::base58_decode($base58add);
  813. $size = strlen($address);
  814. if ($size !== 25) {
  815. return false;
  816. }
  817. $checksum = substr($address, 21);
  818. $address = substr($address, 0, 21);
  819. $hash0 = hash("sha256", $address);
  820. $hash1 = hash("sha256", hex2bin($hash0));
  821. $checksum0 = substr($hash1, 0, 8);
  822. $checksum1 = bin2hex($checksum);
  823. if (strcmp($checksum0, $checksum1)) {
  824. return false;
  825. }
  826. return $address;
  827. }
  828. public static function hexString2Base58check($hexString)
  829. {
  830. $address = hex2bin($hexString);
  831. return self::base58check_en($address);
  832. }
  833. public static function base58check2HexString($base58add)
  834. {
  835. $address = self::base58check_de($base58add);
  836. return bin2hex($address);
  837. }
  838. public static function hexString2Base64($hexString)
  839. {
  840. $address = hex2bin($hexString);
  841. return base64_encode($address);
  842. }
  843. public static function base642HexString($base64)
  844. {
  845. $address = base64_decode($base64);
  846. return bin2hex($address);
  847. }
  848. public static function base58check2Base64($base58add)
  849. {
  850. $address =self::base58check_de($base58add);
  851. return base64_encode($address);
  852. }
  853. public static function base642Base58check($base64)
  854. {
  855. $address = base64_decode($base64);
  856. return self::base58check_en($address);
  857. }
  858. public static function getrandstr($length)
  859. {
  860. $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
  861. $randStr = str_shuffle($str);//打乱字符串
  862. return substr($randStr, 0, $length);
  863. }
  864. /**
  865. * 检测是否有效钱包地址
  866. * @param $address
  867. * @return bool
  868. */
  869. public static function isValidAddress($address)
  870. {
  871. if (empty($address)) {
  872. return false;
  873. }
  874. if (strlen($address) != 34) {
  875. return false;
  876. }
  877. if (substr($address, 0, 1) != 'T') {
  878. return false;
  879. }
  880. // 验证地址
  881. $client = new Client([
  882. 'verify' => false, // 关闭 SSL 验证
  883. ]);
  884. $response = $client->request('POST', 'https://api.shasta.trongrid.io/wallet/validateaddress', [
  885. 'body' => json_encode(["address" => $address]),
  886. 'headers' => [
  887. 'Accept' => 'application/json',
  888. 'Content-Type' => 'application/json',
  889. ],
  890. ]);
  891. $resp = $response->getBody()->getContents();
  892. $resp = json_decode($resp);
  893. // 失败提示错误
  894. if ($resp->result === false) {
  895. return false;
  896. }
  897. return true;
  898. }
  899. /**
  900. * 获取私钥,通过私钥可以拿到收款地址,各种权限
  901. * 注意:必须拿28位字符串来生成地址,否则无法生成正常的地址
  902. * @param $base64
  903. * @return string
  904. */
  905. public function getPrivateKey($base64)
  906. {
  907. return $this->base642HexString($base64);
  908. }
  909. /**
  910. * 生成波场key
  911. * @param $memberId
  912. * @return string
  913. */
  914. public static function makePrivateKey($memberId)
  915. {
  916. $fix = 'SSTGsstg';//固定8前缀,避免和其他人同地址
  917. $rand = TronHelper::getrandstr(20);//10位数随机,避免同地址
  918. $base64Sting = $fix.$rand.str_pad($memberId, 15, 0, STR_PAD_LEFT);
  919. $tronHelper = new TronHelper();
  920. return $tronHelper->getPrivateKey($base64Sting);
  921. }
  922. /**
  923. * 查询余额
  924. * @param $privateKey
  925. * @return int
  926. */
  927. public static function getBalance($address, $currency)
  928. {
  929. bcscale(6);
  930. $rate = 1000000;
  931. $currency = strtoupper($currency);
  932. if(self::getTronNetwork()){
  933. $api = TronApi::testNetNilo();
  934. }else{
  935. $api = TronApi::mainNet();
  936. }
  937. $privateKey = self::makePrivateKey(time());
  938. $credential = Credential::fromPrivateKey($privateKey);
  939. $kit = new TronKit($api, $credential);
  940. if ($currency == 'TRX') {
  941. try {
  942. $balance = $kit->getTrxBalance($address);
  943. return bcdiv($balance, $rate);
  944. } catch (\Exception $e) {
  945. return bcmul(0, 0);
  946. }
  947. }
  948. try {
  949. $contractAddress = self::getContractAddress($currency);
  950. $usdt = $kit->Trc20($contractAddress);
  951. $balance = $usdt->balanceOf($address);
  952. return bcdiv($balance, $rate);
  953. } catch (\Exception $e) {
  954. return bcmul(0, 0);
  955. }
  956. }
  957. /**
  958. * 获取转账信息
  959. * @param $txid
  960. */
  961. public static function getSendInfo($txid)
  962. {
  963. // $api = TronApi::mainNet();
  964. if(self::getTronNetwork()){
  965. $api = TronApi::testNetNilo();
  966. }else{
  967. $api = TronApi::mainNet();
  968. }
  969. $ret = $api->getTransaction($txid);
  970. $retArr = $ret->ret;
  971. if (isset($retArr[0]->contractRet)) {
  972. return $retArr[0]->contractRet;
  973. }
  974. return 'UNKNOWN';
  975. }
  976. /**
  977. * 完整交易详情,如果交易未完成或者不成功,返回空
  978. * @param $txid
  979. * @return string
  980. */
  981. public static function getTransactionInfoById($txid)
  982. {
  983. // $api = TronApi::mainNet();
  984. if(self::getTronNetwork()){
  985. $api = TronApi::testNetNilo();
  986. }else{
  987. $api = TronApi::mainNet();
  988. }
  989. $ret = $api->getTransactionInfoById($txid);
  990. return json_decode(json_encode($ret), true);
  991. }
  992. /**
  993. * 获取出款账户地址
  994. */
  995. public static function getWithdrawAddress()
  996. {
  997. // $privateKey = Yii::$app->params['withdraw_address_trx_key'];
  998. // $credential = Credential::fromPrivateKey($privateKey);
  999. // return $credential->address()->base58();
  1000. }
  1001. /**
  1002. * 获取地址
  1003. * @param $fromKey
  1004. */
  1005. public static function getAddressByPrivateKey($fromKey)
  1006. {
  1007. $credential = Credential::fromPrivateKey($fromKey);
  1008. return $credential->address()->base58();
  1009. }
  1010. /**
  1011. * 转账给指定地址
  1012. * @param $fromKey
  1013. * @param $toAddress
  1014. * @param $amount
  1015. * @throws \Exception
  1016. */
  1017. public static function sendTrx($fromKey, $toAddress, $amount)
  1018. {
  1019. if ($amount <= 0) {
  1020. throw new \Exception('不能低于 0 trx');
  1021. }
  1022. self::throttleTronRequest();
  1023. // from 初始化
  1024. if(self::getTronNetwork()){
  1025. $api = TronApi::testNetNilo();
  1026. }else{
  1027. $api = TronApi::mainNet();
  1028. }
  1029. $credential = Credential::fromPrivateKey($fromKey);
  1030. $kit = new TronKit($api, $credential);
  1031. // from 余额判断
  1032. $from = $credential->address()->base58();
  1033. $balance = self::getBalance($from, 'TRX');
  1034. $rate = 1000000;
  1035. if ($balance < $amount) {
  1036. return '余额不足';
  1037. }
  1038. // 发送
  1039. try {
  1040. return $kit->sendTrx($toAddress, 1 * bcmul($amount, $rate, 6));
  1041. } catch (\Exception $e) {
  1042. Log::error('转账错误,fromKey='.$fromKey.'toAddress='.$toAddress.'amount='.$amount);
  1043. Log::error('转账错误'.$e->getMessage());
  1044. return false;
  1045. }
  1046. }
  1047. /**usdt转账
  1048. * @param $fromKey
  1049. * @param $toAddress
  1050. * @param $amount
  1051. * @param $currency
  1052. * @return bool|object
  1053. * @throws \Exception
  1054. */
  1055. public static function sendTrc20($fromKey, $toAddress, $amount, $currency)
  1056. {
  1057. if ($amount <= 0) {
  1058. throw new \Exception('不能低于 0 USDT');
  1059. }
  1060. $credential = Credential::fromPrivateKey($fromKey);
  1061. $credential->address()->hex();
  1062. if(self::getTronNetwork()){
  1063. $api = TronApi::testNetNilo();
  1064. }else{
  1065. $api = TronApi::mainNet();
  1066. }
  1067. $kit = new TronKit($api, $credential);
  1068. $contractAddress = self::getContractAddress($currency);
  1069. $rate = 1000000;//换算汇率
  1070. // $balance = self::getBalance(self::getAddressByPrivateKey($fromKey), $currency); //查询Trc20代币余额
  1071. $balance = self::getTrc20Balance(self::getAddressByPrivateKey($fromKey)); //查询Trc20代币余额
  1072. if ($balance < $amount) {
  1073. throw new \Exception('余额不足');
  1074. }
  1075. $trc20 = $kit->Trc20($contractAddress); //创建Trc20代币合约实例
  1076. try {
  1077. $ret = $trc20->transfer($toAddress, (int) bcmul($amount, $rate)); //转账Trc20代币
  1078. return (object) [
  1079. 'txid' => $ret->tx->txID,
  1080. 'result' => $ret->result,
  1081. ];
  1082. } catch (\Exception $e) {
  1083. Log::error('Trc20转账错误,fromKey='.$fromKey.'toAddress='.$toAddress.'amount='.$amount);
  1084. Log::error('Trc20转账错误'.$e->getMessage());
  1085. return false;
  1086. }
  1087. }
  1088. /**
  1089. * 归集账户资金校验
  1090. * trade_status:
  1091. * - failed 转账失败
  1092. * - waiting 转账成功,尚未校验
  1093. * - closed waiting 之后,脚本查询时,交易验证成功
  1094. * - aborted waiting 之后,脚本查询时,交易验证失败
  1095. * @param $fromKey
  1096. * @param $toAddress
  1097. * @param $amount
  1098. * @param $memberId
  1099. * @param string $currency
  1100. * @param string $net
  1101. * @return bool
  1102. * @throws \Exception
  1103. */
  1104. public function actionFundsGather(
  1105. $fromKey,
  1106. $toAddress,
  1107. $amount,
  1108. $memberId,
  1109. $currency = 'TRX',
  1110. $net = 'TRC20'
  1111. ) {
  1112. // $currency = strtoupper($currency);
  1113. // if ($amount <= 0) {
  1114. // throw new \Exception('不能低于 0 trx');
  1115. // }
  1116. // if (empty($toAddress)) {
  1117. // throw new \Exception('收款地址不能为空');
  1118. // }
  1119. // $fromAddress = self::getAddressByPrivateKey($fromKey);
  1120. // $remainAmount = self::getBalance($fromAddress, $currency);
  1121. // if ($remainAmount < $amount) {
  1122. // throw new \Exception('余额不足,归集失败');
  1123. // }
  1124. // $min = MinRechargeEnum::getValue($currency);
  1125. // if ($currency == 'TRX') {
  1126. // $ret = self::sendTrx($fromKey, $toAddress, $amount);
  1127. // } else {
  1128. // // 发送
  1129. // //校验trx是否足够,不够就充值10燃烧费用进来
  1130. // if (self::getBalance($fromAddress, 'TRX') < 10) {
  1131. // $withdrawAddressTrxKey = Yii::$app->params['withdraw_address_trx_key'];
  1132. // self::sendTrx($withdrawAddressTrxKey, self::getAddressByPrivateKey($fromKey), 10);
  1133. // }
  1134. // $ret = self::sendTrc20($fromKey, $toAddress, $amount, $currency);
  1135. // }
  1136. // //少于最低可入款额度,不入账,只做归集
  1137. // if ($min > $remainAmount) {
  1138. // return false;
  1139. // }
  1140. // try {
  1141. // // 记录
  1142. // $fundsGather = new Recharge();
  1143. // $fundsGather->member_id = $memberId;
  1144. // $fundsGather->txid = $ret->txid;
  1145. // $fundsGather->amount = $amount;
  1146. // $fundsGather->address = $toAddress;
  1147. // $fundsGather->created_at = time();
  1148. // $fundsGather->currency = $currency;
  1149. // $fundsGather->usdt_balance = bcmul($amount, ExchangeRateService::getExchangeRate($currency),
  1150. // CommonEnum::DIGITS);
  1151. // $fundsGather->is_auto = 1;
  1152. // $fundsGather->count = Recharge::find()->where(['member_id' => $memberId])->count() + 1;
  1153. // $fundsGather->net = $net;
  1154. // $fundsGather->ordernum = StrHelper::createOrdernum();
  1155. // // 记录「充值请求次数」
  1156. // $member = Member::findOne($memberId);
  1157. // $member->recharge_request_count = $fundsGather->count;
  1158. // $member->save();
  1159. // if ($ret->result == 1) { // 成功
  1160. // $fundsGather->trade_status = 'waiting';
  1161. // if ($fundsGather->save()) {
  1162. // return true;
  1163. // }
  1164. // } else { // 失败
  1165. // $fundsGather->trade_status = 'failed';
  1166. // $fundsGather->save();
  1167. // }
  1168. // } catch (Exception $e) {
  1169. // throw new \Exception('转账异常'.$e->getMessage());
  1170. // }
  1171. return false;
  1172. }
  1173. }