开发者文档
PHP 集成
在 PHP 中使用 iexbase/tron-api 集成 TronEnergy 能量委托。Composer 安装,代码示例可直接复制。
API 付款地址
TFqUiCu1JwLHHnBNeaaVKH7Csm4aA3YhZx
向该地址发送 TRX。交易哈希用于领取能量委托。
使用 iexbase/tron-api 库的完整 PHP 集成。每一步都是可以直接复制进项目的独立代码块,兼容任何 PHP 框架,也可用于纯 PHP。
前置条件: PHP 7.4+、Composer、已启用 ext-gmp 与 ext-bcmath,以及一个有余额的波场钱包。
关于在 PHP 中签名: TronEnergy API 要求使用
tronWeb.trx.signMessageV2() 进行钱包签名。iexbase/tron-api 库没有暴露这个签名原语,所以本指南在签名这一步借助一个极小的 Node.js 辅助脚本。其余环节(发送 TRX、调用 API、发送 USDT)全部留在 PHP 中。如果您有能生成有效 signMessageV2 签名的纯 PHP 方案,直接替换这个辅助脚本即可,其他步骤不用动。
流程
无需 API 密钥,无需注册。您的代码向 TronEnergy 付款地址在链上发送 TRX,对一条消息签名以证明所有权,然后领取委托。能量约 3 秒到账。随后代码使用委托的能量发送 USDT。
1
发送 TRX
向付款地址在链上发送 4 TRX 或以上(最低 4,最高 1000)。
2
签名
对 tx_hash:delegate_to 签名,证明您是发送方。
3
领取
带上交易哈希和签名调用 POST /delegate。能量约 3 秒到账。
线性定价:每 TRX 兑换 16,250 能量。 最低订单 4 TRX(65,000 能量 — 一笔标准 USDT 转账),最高 1,000 TRX(1,625 万能量)。发送数量精确决定委托返还的能量,没有梯度或套餐。单笔标准转账用
$trxAmount = 4,新钱包转账用 8,批量任务用更多。下面的代码使用 $trxAmount 变量,改一处即可全局生效。
分步说明
1. 安装
composer
composer require iexbase/tron-api
2. 初始化
setup.php
require_once 'vendor/autoload.php';
use IEXBase\TronAPI\Tron;
$tron = new Tron();
$tron->setPrivateKey('YOUR_PRIVATE_KEY');
$tron->setAddress('YOUR_WALLET_ADDRESS');
$api = 'https://api.tronnrg.com';
$addr = 'TFqUiCu1JwLHHnBNeaaVKH7Csm4aA3YhZx'; // API payment address
$usdt = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'; // USDT contract
切勿硬编码凭证。 私钥请从环境变量或密钥管理器加载。任何密钥都不要提交到 git。
4. 发送 TRX
发送 TRX
// Send TRX to the API payment address — pricing is linear.
// 16,250 energy per TRX. Min 4 TRX, max 1,000 TRX.
// $trxAmount = 4 → 65,000 energy (standard USDT transfer)
// $trxAmount = 8 → 130,000 energy (new wallet transfer)
// $trxAmount = 40 → 650,000 energy (10 standard transfers)
// $trxAmount = 1000 → 16,250,000 energy (max)
$trxAmount = 4;
$payment = $tron->sendTrx($addr, $trxAmount);
if (!isset($payment['result']) || !$payment['result']) {
throw new Exception('TRX transfer failed');
}
$txHash = $payment['txid'];
echo "Payment sent: ${txHash}\n";
5. 对消息签名
API 要求一个签名,证明请求委托的正是发送 TRX 的那个钱包。我们用一个极小的 Node.js 辅助脚本来完成。把它保存为 sign.js,与您的 PHP 文件放在同一目录:
sign.js
// Usage: node sign.js <tx_hash> <delegate_to>
// Outputs the signature to stdout. Reads private key from TRON_PRIVATE_KEY env var.
const { TronWeb } = require('tronweb');
const [, , txHash, delegateTo] = process.argv;
const tronWeb = new TronWeb({
fullHost: 'https://api.trongrid.io',
privateKey: process.env.TRON_PRIVATE_KEY,
});
tronWeb.trx.signMessageV2(`${txHash}:${delegateTo}`)
.then(sig => process.stdout.write(sig))
.catch(e => { console.error(e.message); process.exit(1); });
在同一目录安装 TronWeb:npm install tronweb。然后从 PHP 中调用:
在 PHP 中签名
// Both the sender (in $tron) and the signer must be the SAME wallet.
// Make sure TRON_PRIVATE_KEY in your environment matches the wallet that sent the TRX.
$delegateTo = 'TWalletThatNeedsEnergy';
$signature = trim(shell_exec(
sprintf('node sign.js %s %s',
escapeshellarg($txHash),
escapeshellarg($delegateTo)
)
));
if (!$signature) {
throw new Exception('Signing failed. Check that node and tronweb are installed and TRON_PRIVATE_KEY is set.');
}
echo "Signed: " . substr($signature, 0, 20) . "...\n";
6. 领取委托
领取委托
// $txHash, $delegateTo, and $signature are all defined in the previous steps.
$ch = curl_init("${api}/delegate");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode([
'tx_hash' => $txHash,
'delegate_to' => $delegateTo,
'signature' => $signature,
]),
]);
$result = json_decode(curl_exec($ch), true);
curl_close($ch);
echo "Energy: " . $result['energy'] . "\n";
echo "Ref: " . $result['ref'] . "\n";
7. 发送 USDT
发送 USDT
// Energy is now delegated. Send USDT.
$contract = $tron->contract($usdt);
$transfer = $contract->transfer($delegateTo, 10 * pow(10, 6));
echo "USDT sent: " . $transfer . "\n";
错误处理
把领取调用包进一个小的重试函数。最常见的错误是交易尚未在链上被索引时出现的 payment_verification_failed,等几秒后重试一次即可。
错误处理
function claimDelegation($api, $txHash, $delegateTo, $signature, $retries = 3) {
for ($i = 0; $i < $retries; $i++) {
$ch = curl_init("${api}/delegate");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode([
'tx_hash' => $txHash,
'delegate_to' => $delegateTo,
'signature' => $signature,
]),
]);
$result = json_decode(curl_exec($ch), true);
curl_close($ch);
if (!isset($result['error'])) {
return $result; // Success
}
switch ($result['error']) {
case 'payment_verification_failed':
// Most common: tx not yet indexed. Wait and retry.
sleep(3);
continue 2;
case 'hash_already_used':
throw new Exception('This tx hash has already been claimed');
case 'signature_mismatch':
throw new Exception('Signer does not match payment sender. Sign with the same wallet that sent TRX.');
case 'delegation_failed':
// Refund queued automatically if payment was verified
throw new Exception('Delegation failed: ' . $result['message']);
default:
throw new Exception($result['message'] ?? 'Unknown error');
}
}
throw new Exception('Transaction not found after retries');
}
完整示例
delegate-energy.php
<?php
require_once 'vendor/autoload.php';
use IEXBase\TronAPI\Tron;
$tron = new Tron();
$tron->setPrivateKey(getenv('TRON_PRIVATE_KEY'));
$tron->setAddress(getenv('TRON_WALLET_ADDRESS'));
$api = 'https://api.tronnrg.com';
$addr = 'TFqUiCu1JwLHHnBNeaaVKH7Csm4aA3YhZx';
try {
$delegateTo = 'TRecipientWallet';
$trxAmount = 4; // min 4, max 1000 — energy = trxAmount × 16,250
// 1. Send TRX (linear pricing: 16,250 energy per TRX)
$payment = $tron->sendTrx($addr, $trxAmount);
$txHash = $payment['txid'];
echo "Payment: ${txHash}\n";
// 2. Sign via Node helper (see Step 5 above)
$signature = trim(shell_exec(
sprintf('node sign.js %s %s',
escapeshellarg($txHash),
escapeshellarg($delegateTo)
)
));
if (!$signature) throw new Exception('Signing failed');
// 3. Claim delegation (with retry)
$result = claimDelegation($api, $txHash, $delegateTo, $signature);
echo "Energy: " . $result['energy'] . "\n";
echo "Ref: " . $result['ref'] . "\n";
// 4. Send USDT (energy is now available)
$contract = $tron->contract('TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t');
$transfer = $contract->transfer($delegateTo, 10 * pow(10, 6));
echo "USDT sent: ${transfer}\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}