DIRECCIÓN DE PAGO API
TFqUiCu1JwLHHnBNeaaVKH7Csm4aA3YhZx
Envía TRX a esta dirección. El hash de tu transacción se utiliza para reclamar la delegación de energía.

Integración completa de PHP mediante el iexbase/tron-api Biblioteca. Cada paso es un bloque de código independiente que puedes copiar en tu proyecto. Funciona con cualquier framework de PHP o con PHP puro.

Requisitos previos: PHP 7.4+, Composer, ext-gmp y ext-bcmath habilitados, una billetera Tron con fondos.
Acerca de la firma en PHP: La API TronEnergy requiere una firma de billetera que utilice tronWeb.trx.signMessageV2(). El iexbase/tron-api La biblioteca no expone esta primitiva de firma exacta, por lo que esta guía utiliza una pequeña función auxiliar de Node.js para el paso de firma. Todo lo demás (envío de TRX , llamada a la API , envío USDT ) se mantiene en PHP. Si dispone de una solución de firma puramente PHP que genere una firma signMessageV2 válida, puede reemplazar la función auxiliar sin modificar ningún otro paso.

El flujo

Sin clave API . Sin registro. Tu código envía TRX a la cadena de bloques a la dirección de pago TronEnergy , firma un mensaje que prueba la propiedad y luego reclama la delegación. Energy llega en aproximadamente 3 segundos. A continuación, tu código envía USDT utilizando la energía delegada.

1
Enviar TRX
Envía 4 o más TRX a la dirección de pago en la cadena de bloques (mínimo 4, máximo 1000).
2
Firmar
Firma tx_hash:delegate_to para demostrar que eres el remitente.
3
Afirmar
POST /delegate con el hash y la firma de la transacción. Energy llega en ~3s.
El precio es lineal: 16.250 Energy por TRX . Pedido mínimo 4 TRX (65.000 Energy — una transferencia USDT estándar), máximo 1.000 TRX (16,25 M Energy ). La cantidad que envíe determina exactamente cuánta Energy se delega de vuelta; no hay niveles ni paquetes. Para una única transferencia estándar, utilice $trxAmount = 4Para una transferencia a una nueva billetera, utilice 8Para el trabajo por lotes, utilice más. El código siguiente utiliza un $trxAmount variable para que puedas cambiarla en un solo lugar.

Paso a paso

1. Instalar

compositor
composer require iexbase/tron-api

2. Configuración

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
Nunca codifique las credenciales directamente en el código. Carga tu clave privada desde variables de entorno o un gestor de secretos. Nunca subas secretos a Git.

3. Obtener información de pago (opcional)

obtener información de pago
// 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. Enviar TRX

enviar 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. Firma el mensaje

La API requiere una firma que demuestre que la misma billetera que envió el TRX está solicitando la delegación. Hacemos esto con un pequeño auxiliar de Node.js. Guárdalo como sign.js junto a tu archivo 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); });

Instala TronWeb en la misma carpeta: npm install tronweb. Luego, llámalo desde PHP:

firmar desde 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. Reclamar la delegación

delegación de reclamaciones
// $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. Enviar USDT

enviar USDT
// Energy is now delegated. Send USDT. $contract = $tron->contract($usdt); $transfer = $contract->transfer($delegateTo, 10 * pow(10, 6)); echo "USDT sent: " . $transfer . "\n";

Manejo de errores

Envuelva la llamada de reclamación en una pequeña función auxiliar de reintento. El error más común es payment_verification_failed Cuando la transacción aún no esté indexada en la cadena de bloques, espere unos segundos e inténtelo de nuevo.

manejo de errores
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'); }

Ejemplo completo

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"; }
Telegram WhatsApp