← Blog
10 min di lettura
|
Pubblicato
|
Aggiornato

Ricevere pagamenti crypto in Laravel (Tron)

Un gateway di pagamento Laravel per TRX e token TRC20: un indirizzo per sessione, un webhook Chaingateway, verifica della firma e della transazione.

Capitoli
C
Chaingateway Team
Esperti di blockchain

Verificato da Maurice Sobiera

Un gateway di pagamento crypto per Laravel crea un indirizzo blockchain per ogni sessione di pagamento, registra un webhook su quell’indirizzo e segna la sessione come pagata quando arriva una notifica verificata. Questo tutorial costruisce questo flusso per TRX e il token JST (TRC20) su Tron con l’API di Chaingateway. Il codice è una demo, non un sistema di produzione.

Lo stesso schema funziona per Bitcoin, Ethereum, BNB Smart Chain e Polygon con piccole modifiche agli endpoint. Il codice della demo è disponibile nel repository chaingateway-crypto-payment-demo-laravel.

Non usi questo codice in produzione. La demo memorizza le chiavi private in chiaro, cosa che non deve mai accadere in un ambiente di produzione. Chaingateway può anche creare indirizzi protetti da password, dove Lei invia una password invece di memorizzare una chiave privata.

Che cosa costruisce il tutorial?

Il risultato è un piccolo gateway di pagamento con queste parti:

  1. Un modulo che avvia una sessione di pagamento con un importo e una valuta (TRX o JST).
  2. Un nuovo indirizzo wallet per ogni sessione.
  3. Una pagina di sessione che mostra l’indirizzo, lo stato, l’importo atteso e l’importo ricevuto.
  4. Un endpoint webhook che verifica la firma, controlla la transazione, aggiorna la sessione e, facoltativamente, inoltra i fondi a un cold wallet.

Come ottengo una chiave API?

Crea un token API nel pannello dell’account Chaingateway. Acceda a app.chaingateway.io, apra le impostazioni utente e selezioni API Tokens. Clicchi su Create Token, gli dia un nome (ad esempio “Payment Gateway”) e copi il valore. Ogni richiesta lo invia come bearer token. Il portale per sviluppatori e la documentazione API descrivono nel dettaglio gli endpoint.

Serve anche un progetto Laravel con un database configurato. Segua la guida all’installazione di Laravel se parte da zero. Bastano le nozioni di base su modelli, migrazioni, controller e route.

Passo 1: come configuro il client API?

Aggiunga l’URL base, il token, la rete e l’indirizzo del cold wallet in config/app.php. L’header X-Network seleziona la rete: testnet per lo sviluppo e mainnet per la produzione.

'Chaingateway' => [
'api_url' => env('Chaingateway_API_URL', 'https://app.chaingateway.io/api/v2'),
'api_key' => env('Chaingateway_API_KEY'),
'network' => env('Chaingateway_NETWORK', 'testnet'), // Use 'mainnet' for production
'cold_wallet' => env('COLD_WALLET'),
'webhook_secret' => env('Chaingateway_WEBHOOK_SECRET'),
],

Poi aggiunga i valori al file .env:

Chaingateway_API_URL=https://app.chaingateway.io/api/v2
Chaingateway_API_KEY=your_api_key_here
Chaingateway_NETWORK=testnet
COLD_WALLET=your_cold_wallet_address
Chaingateway_WEBHOOK_SECRET=your_personal_secret

Il webhook secret è il segreto personale delle impostazioni del profilo Chaingateway. Una volta impostato, ogni webhook porta l’header X-Signature, che il passo 4 verifica.

Passo 2: come definisco le route?

Quattro route coprono il flusso: la pagina di pagamento, l’avvio di una sessione, la vista della sessione e il ricevitore del webhook. Le aggiunga a routes/web.php. La route del webhook deve avere un nome, perché il controller costruisce il suo URL con route('handleWebhook').

use App\Http\Controllers\PaymentController;
Route::get('/payment', [PaymentController::class, 'showPaymentPage']);
Route::post('/start-payment-session', [PaymentController::class, 'startPaymentSession']);
Route::get('/payment-session/{id}', [PaymentController::class, 'showPaymentSession'])->name('showPaymentSession');
Route::post('/webhook', [PaymentController::class, 'handleWebhook'])->name('handleWebhook');

Laravel rifiuta le richieste POST senza un token CSRF, e Chaingateway non può inviarne uno. Escluda la route del webhook in bootstrap/app.php. La documentazione Laravel sul CSRF descrive la stessa impostazione per le versioni precedenti.

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
// Exclude the webhook route from CSRF protection
$middleware->validateCsrfTokens(except: [
'webhook',
]);
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();

L’URL del webhook deve essere raggiungibile da internet pubblico. Durante lo sviluppo in locale, esponga il server di sviluppo tramite un tunnel.

Passo 3: di quali modelli e migrazioni ho bisogno?

Servono due tabelle: wallet con le loro chiavi, e sessioni di pagamento con il loro stato. Generi entrambi i modelli con le migrazioni.

Terminal window
php artisan make:model Wallet -m
php artisan make:model PaymentSession -m

In database/migrations/<timestamp>_create_wallets_table.php:

Schema::create('wallets', function (Blueprint $table) {
$table->id();
$table->string('address')->unique(); // Wallet address
$table->string('private_key'); // Demo only: never store keys in plain text
$table->timestamps();
});

In database/migrations/<timestamp>_create_payment_sessions_table.php:

Schema::create('payment_sessions', function (Blueprint $table) {
$table->id();
$table->string('status')->default('Pending'); // Pending, Completed, Failed, overpaid, underpaid
$table->foreignId('wallet_id')->constrained()->onDelete('cascade');
$table->decimal('amount', 18, 8)->nullable(); // Amount the customer should send
$table->string('currency')->default('TRX');
$table->decimal('received_amount', 18, 8)->nullable(); // Amount that arrived
$table->string('webhook_id')->nullable();
$table->timestamps();
});

Esegua php artisan migrate, poi renda i campi assegnabili e definisca le relazioni.

app/Models/Wallet.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Wallet extends Model
{
protected $fillable = ['address', 'private_key'];
public function paymentSessions()
{
return $this->hasMany(PaymentSession::class);
}
}
app/Models/PaymentSession.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class PaymentSession extends Model
{
protected $fillable = ['wallet_id', 'status', 'amount', 'currency', 'received_amount', 'webhook_id'];
public function wallet()
{
return $this->belongsTo(Wallet::class);
}
}

Passo 4: come funziona il PaymentController?

Il controller crea il wallet, registra il webhook e gestisce le notifiche in arrivo. Lo generi con php artisan make:controller PaymentController.

La creazione di una sessione effettua due chiamate API. POST /api/v2/tron/addresses restituisce un nuovo indirizzo e, senza password, la sua chiave privata. POST /api/v2/tron/webhooks registra un webhook per le transazioni in entrata verso quell’indirizzo e restituisce l’ID del webhook in data.webhook.

Il gestore del webhook fa quattro cose in ordine. Verifica l’header X-Signature. Cerca la sessione tramite l’indirizzo ricevente. Chiede all’API la transazione e controlla che ret[0].contractRet sia SUCCESS. Solo allora aggiorna la sessione.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use App\Models\PaymentSession;
use App\Models\Wallet;
class PaymentController extends Controller
{
private $apiUrl;
private $apiKey;
private $network;
private $coldWallet;
private $webhookSecret;
public function __construct()
{
$this->apiUrl = config('app.Chaingateway.api_url');
$this->apiKey = config('app.Chaingateway.api_key');
$this->network = config('app.Chaingateway.network');
$this->coldWallet = config('app.Chaingateway.cold_wallet');
$this->webhookSecret = config('app.Chaingateway.webhook_secret');
}
private function api(): PendingRequest
{
return Http::withHeaders([
'Authorization' => "Bearer {$this->apiKey}",
'Content-Type' => 'application/json',
'X-Network' => $this->network,
]);
}
public function showPaymentPage()
{
return view('payment');
}
/**
* Creates a wallet address and a webhook for it, then stores the session.
*/
public function startPaymentSession(Request $request)
{
$validated = $request->validate([
'amount' => 'required|numeric|gt:0',
'currency' => 'required|in:TRX,JST',
]);
$response = $this->api()->post("{$this->apiUrl}/tron/addresses");
if (! $response->successful()) {
return back()->withErrors(['error' => 'Failed to create payment session.']);
}
$walletData = $response->json()['data'];
$wallet = Wallet::create([
'address' => $walletData['address'],
'private_key' => $walletData['privateKey'],
]);
$webhookResponse = $this->api()->post("{$this->apiUrl}/tron/webhooks", [
'to' => $wallet->address,
'url' => route('handleWebhook'),
]);
if (! $webhookResponse->successful()) {
return back()->withErrors(['error' => 'Failed to create webhook.']);
}
$paymentSession = PaymentSession::create([
'wallet_id' => $wallet->id,
'webhook_id' => $webhookResponse->json()['data']['webhook'],
'amount' => $validated['amount'],
'currency' => $validated['currency'],
'status' => 'Pending',
]);
return redirect()->route('showPaymentSession', ['id' => $paymentSession->id]);
}
public function showPaymentSession($id)
{
$paymentSession = PaymentSession::with('wallet')->findOrFail($id);
return view('payment-session', compact('paymentSession'));
}
public function handleWebhook(Request $request)
{
$transactionData = $request->all();
// 1. Verify that Chaingateway sent the notification (see the signature section)
if (! $this->signatureIsValid($transactionData['txid'] ?? '', $request->header('X-Signature', ''))) {
return response()->json(['error' => 'Invalid signature'], 401);
}
// 2. Find the session for the receiving address
$wallet = Wallet::where('address', $transactionData['to'])->first();
if (! $wallet) {
return response()->json(['error' => 'Wallet not found'], 404);
}
$paymentSession = PaymentSession::where('wallet_id', $wallet->id)->first();
if (! $paymentSession) {
return response()->json(['error' => 'Payment session not found'], 404);
}
// A notification can arrive twice. Acknowledge it without processing it again.
if ($paymentSession->status !== 'Pending') {
return response()->json(['status' => 'already processed']);
}
// 3. Check on chain that the transaction succeeded
$txResponse = $this->api()->get("{$this->apiUrl}/tron/transactions/{$transactionData['txid']}");
$contractRet = $txResponse->json('data.transaction.ret.0.contractRet');
if ($txResponse->successful() && $contractRet === 'SUCCESS') {
$paymentSession->status = 'Completed';
$paymentSession->received_amount = $transactionData['amount'];
// Compare the received amount with the expected one and allow a margin.
// Check in a test notification whether `amount` is in the token's smallest unit
// or already a decimal value, and convert before you compare.
$allowedDifference = $paymentSession->amount * 0.10;
if (abs($paymentSession->amount - $transactionData['amount']) >= $allowedDifference) {
$paymentSession->status = $transactionData['amount'] > $paymentSession->amount
? 'overpaid'
: 'underpaid';
}
// For tokens, check that the contract is the one you expect (JST on Tron mainnet)
if ($paymentSession->currency == 'JST'
&& ($transactionData['contractaddress'] ?? null) != 'TF17BgPaZYbz8oxbjhriubPDsA7ArKoLX3') {
$paymentSession->status = 'Wrong currency received';
}
/**
* Optional: forward the funds to a cold wallet.
* A TRC20 transfer needs Energy, so the address must hold TRX or staked resources.
* Chaingateway's Tron Paymaster is deprecated. Use TronFuel (https://tronfuel.dev)
* if you do not want to handle the fees yourself.
*
* $endpoint = $transactionData['contractaddress']
* ? "{$this->apiUrl}/tron/transactions/trc20"
* : "{$this->apiUrl}/tron/transactions";
*
* $this->api()->post($endpoint, [
* 'amount' => $transactionData['amount'],
* 'privatekey' => $wallet->private_key,
* 'to' => $this->coldWallet,
* 'from' => $transactionData['to'],
* 'contractaddress' => $transactionData['contractaddress'],
* ]);
*/
} else {
$paymentSession->status = 'Failed';
}
// Delete the webhook if you will not reuse the address
$this->api()->delete("{$this->apiUrl}/tron/webhooks/{$paymentSession->webhook_id}");
$paymentSession->save();
return response()->json(['status' => 'success']);
}
private function signatureIsValid(string $txid, string $received): bool
{
if (! $this->webhookSecret) {
return false;
}
$expected = base64_encode(hash_hmac('sha256', $txid, $this->webhookSecret, true));
return hash_equals($expected, $received);
}
}

Il controllo sullo stato Pending La protegge da una notifica ripetuta, che può accadere quando si reinvia una notifica fallita. Una notifica che il server non accetta non viene ritentata in automatico. Compare nell’elenco delle notifiche fallite su GET /api/v2/tron/webhooks/notifications/failed, e può essere reinviata con POST /api/v2/tron/webhooks/notifications/{id}/retry.

Come verifico la firma del webhook?

Calcoli un HMAC-SHA256 sul txid con il Suo segreto personale e lo confronti con l’header X-Signature. L’header contiene il risultato codificato in Base64. L’HMAC è specificato nella RFC 2104. Il metodo signatureIsValid qui sopra lo implementa con hash_hmac e confronta con hash_equals, che richiede tempo costante. La documentazione sulla firma elenca lo stesso controllo in altri linguaggi.

La demo rifiuta ogni notifica se non è configurato alcun segreto. Una richiesta senza firma valida potrebbe provenire da chiunque conosca l’URL del Suo webhook, quindi non deve saltare il controllo.

Passo 5: come costruisco le viste?

Bastano due viste Blade: un modulo per avviare una sessione e una pagina che ne mostra lo stato. In resources/views/payment.blade.php:

<!DOCTYPE html>
<html>
<head>
<title>Start Payment Session</title>
</head>
<body>
<h2>Start a New Payment Session</h2>
<form action="/start-payment-session" method="POST">
@csrf
<label for="amount">Amount:</label>
<input type="number" step="0.01" name="amount" id="amount" required />
<br />
<label for="currency">Currency:</label>
<select name="currency" id="currency" required>
<option value="TRX">TRX</option>
<option value="JST">JST (TRC20)</option>
</select>
<br />
<button type="submit">Start Payment Session</button>
</form>
</body>
</html>

In un negozio reale, la sessione viene avviata dal processo di checkout, non da un modulo. La pagina di sessione qui sotto mostra l’indirizzo e lo stato. Una pagina reale aggiornerebbe lo stato tramite polling o websocket. In resources/views/payment-session.blade.php:

<!DOCTYPE html>
<html>
<head>
<title>Payment Session</title>
</head>
<body>
<h2>Payment Session</h2>
<p>
Send <strong>{{ $paymentSession->amount }} {{ $paymentSession->currency }}</strong>
to the address below:
</p>
<p><strong>{{ $paymentSession->wallet->address }}</strong></p>
<p>Status: <strong>{{ $paymentSession->status }}</strong></p>
<p>
Received:
<strong>{{ $paymentSession->received_amount }} {{ $paymentSession->currency }}</strong>
</p>
</body>
</html>

Passo 6: come provo il flusso?

Provi prima sulla testnet. Avvii il server con php artisan serve, poi segua questi passi.

  1. Apra /payment e avvii una nuova sessione.
  2. Invii fondi di testnet all’indirizzo del wallet mostrato nella pagina di sessione.
  3. Attenda il webhook, oppure invii Lei stesso una notifica firmata a /webhook.
  4. Ricarichi la pagina di sessione e verifichi che lo stato sia cambiato.

Per simulare una notifica, invii un payload simile a quello della documentazione dei webhook con un header X-Signature valido. Ricordi che il controllo della transazione chiama l’API per il txid, quindi un ID di transazione inventato finisce nello stato Failed.

Che cosa devo aggiungere prima della produzione?

Sostituisca le scorciatoie della demo prima di accettare pagamenti reali.

  • Crei gli indirizzi con una password, così nel database non viene memorizzata alcuna chiave privata.
  • Accrediti un pagamento solo dopo il numero di conferme richiesto dalla Sua policy di rischio.
  • Confronti gli importi nell’unità più piccola del token e verifichi l’indirizzo del contratto per ogni token.
  • Riconcili regolarmente le sessioni aperte con l’API, perché un webhook può andare perso.

Per il flusso di deposito in dettaglio, legga come funzionano i webhook per i pagamenti crypto e le garanzie di consegna dei webhook. Per domande, veda la pagina di supporto.

Come scriviamo questi articoli

Pronto a costruirlo da solo? Ottieni la tua API key — prova di 7 giorni, senza carta — oppure consulta API Tron per il riferimento completo degli endpoint.

C
Chaingateway Team
Esperti di blockchain

Il team di Chaingateway si impegna a semplificare l'integrazione blockchain per sviluppatori di tutto il mondo.