Creare webhook blockchain per i depositi
Per ricevere notifiche di deposito da Chaingateway servono due parti: un endpoint ricevente sul tuo server e un webhook creato con POST /api/v2/{chain}/webhooks. Quando una transazione corrisponde al filtro, Chaingateway invia al tuo endpoint una richiesta HTTP POST con i dati della transazione. Il tutorial costruisce entrambe le parti per i depositi TRC20 su TRON. Gli stessi passaggi valgono per Ethereum, BNB Smart Chain, Polygon, Arbitrum e Bitcoin. Su Solana non esistono webhook.
Leggi prima Webhook se vuoi i concetti e il formato del payload. Serve un token API dalla Guida rapida.
Come scrivo un ricevente per i webhook?
Sezione intitolata “Come scrivo un ricevente per i webhook?”Un ricevente è un endpoint del server che accetta richieste HTTP POST con corpo JSON e risponde con lo status 200. Tieni breve il gestore: memorizza il payload, rispondi e svolgi il lavoro lento dopo, in una coda o in un job in background. Gli esempi seguenti registrano il payload e lo confermano.
const express = require('express');const app = express();const port = 3000;
app.use(express.json());
app.post('/webhook', (req, res) => { console.log('Received webhook:', req.body); res.status(200).send('Webhook received');});
app.listen(port, () => { console.log(`Webhook receiver listening at http://localhost:${port}`);});from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])def webhook(): data = request.get_json() print('Received webhook:', data) return jsonify({'status': 'Webhook received'}), 200
if __name__ == '__main__': app.run(port=3000)<?phpif ($_SERVER['REQUEST_METHOD'] === 'POST') { $data = file_get_contents('php://input'); $json = json_decode($data, true); file_put_contents('php://stderr', print_r($json, TRUE)); http_response_code(200); echo json_encode(['status' => 'Webhook received']);}<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class WebhookController extends Controller{ // Register the route in routes/api.php: // Route::post('/webhook', [WebhookController::class, 'handleWebhook']); public function handleWebhook(Request $request) { $data = $request->all(); file_put_contents('php://stderr', print_r($data, TRUE)); return response()->json(['status' => 'Webhook received'], 200); }}Chaingateway raggiunge solo un URL pubblico. Durante lo sviluppo, esponi la tua porta locale tramite un tunnel e usa l’indirizzo HTTPS del tunnel come url del webhook. Controlla la firma di ogni richiesta prima di agire, come descrive Verificare le firme dei webhook.
Come mi iscrivo a un evento blockchain?
Sezione intitolata “Come mi iscrivo a un evento blockchain?”Invia POST /api/v2/tron/webhooks con l’url del tuo ricevente e un filtro. Il filtro decide quali transazioni attivano una notifica.
url(obbligatorio): l’indirizzo del tuo ricevente. Deve essere un URL valido.frometo: l’indirizzo del mittente e del destinatario, in formato Tron. Almeno uno dei due è obbligatorio, a meno che tu non forniscacontractaddressetoken_id.contractaddress: il contratto del token da monitorare.token_id: l’ID di un token NFT.type: uno traTRX,TRC10,TRC20,TRC721.reference: una tua etichetta di al massimo 255 caratteri, ad esempio un numero d’ordine.
L’esempio monitora i trasferimenti TRC20 di un token verso un indirizzo di deposito.
curl --request POST \ --url https://app.chaingateway.io/api/v2/tron/webhooks \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer YOUR_API_TOKEN' \ --data '{ "url": "https://example.com/webhook", "to": "TUwmZghA7u2GxGxKaxM1mkCmsTF4wHs4vp", "contractaddress": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "type": "TRC20", "reference": "order-1042"}'import requests
url = "https://app.chaingateway.io/api/v2/tron/webhooks"payload = { "url": "https://example.com/webhook", "to": "TUwmZghA7u2GxGxKaxM1mkCmsTF4wHs4vp", "contractaddress": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "type": "TRC20", "reference": "order-1042"}headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer YOUR_API_TOKEN'}
response = requests.post(url, json=payload, headers=headers)print(response.json())const axios = require('axios');
const url = 'https://app.chaingateway.io/api/v2/tron/webhooks';const payload = { url: 'https://example.com/webhook', to: 'TUwmZghA7u2GxGxKaxM1mkCmsTF4wHs4vp', contractaddress: 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', type: 'TRC20', reference: 'order-1042'};const headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Bearer YOUR_API_TOKEN'};
axios.post(url, payload, { headers }) .then(response => { console.log(response.data); }) .catch(error => { console.error(error.response?.data ?? error); });<?phprequire 'vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client();$response = $client->post('https://app.chaingateway.io/api/v2/tron/webhooks', [ 'headers' => [ 'Accept' => 'application/json', 'Authorization' => 'Bearer YOUR_API_TOKEN', ], 'json' => [ 'url' => 'https://example.com/webhook', 'to' => 'TUwmZghA7u2GxGxKaxM1mkCmsTF4wHs4vp', 'contractaddress' => 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', 'type' => 'TRC20', 'reference' => 'order-1042' ]]);
echo $response->getBody();La risposta ha status 201 e l’ID del webhook in data.webhook. Conserva l’ID, perché serve per aggiornare o eliminare il webhook.
{ "status": 201, "ok": true, "message": "Webhook created", "data": { "webhook": "9b2b4dcc-1479-4bcd-9b8a-015673e80f46" }}Su altre chain cambiano il percorso e i valori di type. Ethereum e Arbitrum accettano ETH, ERC20 e ERC721, Polygon accetta MATIC, ERC20 e ERC721, BNB Smart Chain accetta BNB, BEP20 e BEP721, e Bitcoin accetta solo url, from e to. Gli indirizzi sulle chain EVM devono corrispondere a 0x seguito da 40 caratteri esadecimali. Per provare su una rete di test, aggiungi l’header X-Network: testnet alla richiesta di creazione.
Come provo il ricevente prima che arrivi un deposito reale?
Sezione intitolata “Come provo il ricevente prima che arrivi un deposito reale?”Invia una notifica di esempio al tuo endpoint con curl. Il corpo seguente ha gli stessi campi di una notifica reale. Se il ricevente la registra e risponde 200, l’endpoint funziona. Poi invia un piccolo trasferimento testnet all’indirizzo monitorato per vedere l’evento reale.
curl --request POST \ --url https://example.com/webhook \ --header 'Content-Type: application/json' \ --data '{ "id": "9d18457f-c71c-4be4-ae7c-ce04e48359ed", "webhook_id": "9b2b4dcc-1479-4bcd-9b8a-015673e80f46", "from": "TTd9qHyjqiUkfTxe3gotbuTMpjU8LEbpkN", "to": "TUwmZghA7u2GxGxKaxM1mkCmsTF4wHs4vp", "blocknumber": "65542464", "datetime": "2024-09-25 14:48:27", "tokenid": null, "type": "TRC20", "contractaddress": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "txid": "18f52f2a55b94a6e3705de4abb18e95dfce79970f27b29450705c561e12b6988", "amount": 108935}'Cosa faccio con le consegne fallite e con i vecchi webhook?
Sezione intitolata “Cosa faccio con le consegne fallite e con i vecchi webhook?”Chaingateway non ripete automaticamente le consegne fallite. GET /api/v2/tron/webhooks/notifications/failed le elenca, e POST /api/v2/tron/webhooks/notifications/{id}/retry ne invia di nuovo una. Usa GET /api/v2/tron/webhooks per elencare i tuoi webhook, PUT /api/v2/tron/webhooks/{id} per modificarne uno e DELETE /api/v2/tron/webhooks/{id} per rimuoverlo. Elimina un webhook quando ha svolto il suo compito, ad esempio dopo l’arrivo del pagamento di un ordine.
Informazioni importanti
Sezione intitolata “Informazioni importanti”- Il ricevente deve essere raggiungibile pubblicamente e accettare richieste HTTP POST.
- Verifica l’origine e l’integrità di ogni richiesta con l’header
X-Signature. - Rendi il ricevente idempotente. Usa il
txidper riconoscere una notifica già elaborata. - Conserva il tuo token API in un secrets store, non nel codice sorgente del ricevente.
- RFC 9110, HTTP Semantics definisce il metodo POST e gli status code usati dal ricevente.
- TRON TRC20 protocol interface definisce gli eventi dei token alla base delle notifiche TRC20.
- Ethereum token standard EIP-20 definisce lo stesso per ERC-20 sulle chain EVM.