개발자 문서
PHP 통합
PHP에서 iexbase/tron-api를 사용하여 TronEnergy 에너지 위임을 통합합니다. Composer 설치, 복사-붙여넣기 준비 완료 코드 예제.
API 결제 주소
TFqUiCu1JwLHHnBNeaaVKH7Csm4aA3YhZx
이 주소로 TRX를 전송합니다. 에너지 위임을 청구하는 데 tx 해시가 사용됩니다.
다음을 사용하는 완전한 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를 전송하고, 소유권을 증명하는 메시지에 서명한 다음, 위임을 청구합니다. 에너지는 약 3초 내에 도착합니다. 그런 다음 코드는 위임된 에너지를 사용하여 USDT를 전송합니다.
1
TRX 전송
온체인에서 결제 주소로 4개 이상의 TRX를 전송합니다(최소 4, 최대 1000).
2
서명
발신자임을 증명하기 위해 tx_hash:delegate_to에 서명합니다.
3
청구
tx 해시와 서명으로 POST /delegate를 실행합니다. 에너지는 약 3초 내에 도착합니다.
가격은 선형입니다: TRX당 16,250 에너지. 최소 주문 4 TRX(65,000 에너지 — 표준 USDT 전송 1회), 최대 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 헬퍼로 이를 수행합니다. PHP 파일 옆에 sign.js로 저장하세요:
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";
}