개발자 문서
PHP INTEGRATION
PHP에서 iexbase/tron-api를 사용하여 TronEnergy Energy 기능을 통합하세요. Composer 설치가 가능하며, 복사하여 붙여넣기만 하면 되는 코드 예제가 포함되어 있습니다.
API 결제 주소
TFqUiCu1JwLHHnBNeaaVKH7Csm4aA3YhZx
이 주소로 TRX 보내주세요. 귀하의 거래 해시는 에너지 위임을 청구하는 데 사용됩니다.
PHP를 사용한 완벽한 통합 iexbase/tron-api 이 라이브러리는 각 단계가 독립적인 코드 블록으로 구성되어 있어 프로젝트에 복사하여 사용할 수 있습니다. 모든 PHP 프레임워크 또는 순수 PHP 코드와 호환됩니다.
필수 조건: PHP 7.4 이상, Composer, ext-gmp 및 ext-bcmath 활성화, 자금이 충전된 Tron 지갑이 필요합니다.
PHP 로그인에 관하여: TronEnergy API 사용하려면 지갑 서명이 필요합니다.
tronWeb.trx.signMessageV2(). 그 iexbase/tron-api 이 라이브러리는 정확한 서명 기본 기능을 제공하지 않으므로, 이 가이드에서는 서명 단계에 간단한 Node.js 헬퍼를 사용합니다. 나머지 부분( TRX 전송, API 호출, USDT 전송)은 모두 PHP로 작성됩니다. 유효한 signMessageV2 서명을 생성하는 순수 PHP 서명 솔루션이 있는 경우, 다른 단계를 변경하지 않고 헬퍼를 다른 함수로 대체할 수 있습니다.
흐름
API 키도 필요 없고, 가입 절차도 없습니다. 여러분의 코드는 온체인에서 TronEnergy 결제 주소로 TRX 전송하고, 소유권을 증명하는 메시지에 서명한 후 위임 권한을 획득합니다. Energy 약 3초 안에 도착합니다. 그런 다음, 여러분의 코드는 위임받은 에너지를 사용하여 USDT 전송합니다.
1
TRX 전송
온체인 결제 주소로 4 TRX 이상을 보내주세요 (최소 4, 최대 1000).
2
징후
발신자임을 증명하려면 tx_hash:delegate_to에 서명하십시오.
3
주장하다
POST /delegate 명령으로 트랜잭션 해시와 서명을 전송하세요. Energy 약 3초 후에 도착합니다.
가격은 선형적으로 책정됩니다: TRX 당 16,250 Energy . Minimum order 4 TRX (65,000 Energy — one standard USDT transfer), maximum 1,000 TRX (16.25M Energy). The amount you send determines exactly how much Energy is delegated back — no tiers, no packages. For a single standard transfer, use
$trxAmount = 4. For a new-wallet transfer, use 8. For batch work, use more. The code below uses a $trxAmount variable so you can change it in one place.
단계별
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
자격 증명을 절대 하드코딩하지 마세요. Use environment variables or a secrets manager. The example above is for illustration only.
3. 결제 정보 입력 (선택 사항)
get payment info
// Get pricing and payment address (optional, energy is always available)
$supply = json_decode(
file_get_contents("${api}/supply"),
true
);
echo "Pay to: " . $supply['pay_to'] . "\n";
echo "Energy per TRX: " . $supply['energy_per_trx'] . "\n";
4. TRX 전송
send 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 (run with node)
// 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에서 호출합니다.
sign from 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. 대표단을 확보하십시오
claim delegation
// $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,
]),
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$result = json_decode($response, true);
if (isset($result['error'])) {
throw new Exception("Delegation failed: " . $result['message']);
}
echo "Delegated: " . $result['energy'] . " energy\n";
echo "Ref: " . $result['ref'] . "\n";
7. USDT 보내세요
send USDT
// Send USDT using the delegated energy
$usdtContract = $tron->contract($usdt);
// Amount in smallest unit (6 decimals for USDT)
// 10 USDT = 10 * 1,000,000 = 10000000
$amount = 10 * pow(10, 6);
$recipient = 'TRecipientAddress';
$transfer = $usdtContract->transfer($recipient, $amount);
echo "USDT sent: " . $transfer . "\n";
오류 처리
클레임 호출을 간단한 재시도 도우미 함수로 감싸세요. 가장 흔한 오류는 다음과 같습니다. payment_verification_failed 거래가 아직 온체인에 인덱싱되지 않은 경우, 몇 초 기다렸다가 다시 시도하십시오.
error handling
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";
}