Come funzionano i webhook di pagamento
Un webhook in Chaingateway è un’iscrizione: i nostri server inviano una richiesta HTTP POST al tuo URL quando una transazione corrisponde al filtro impostato, ad esempio un trasferimento in entrata verso uno dei tuoi indirizzi. Ricevi così notifiche di pagamento istantanee senza polling. I webhook esistono per Ethereum, BNB Smart Chain, Polygon, Arbitrum, TRON e Bitcoin, ma non per Solana.
Come funziona un webhook?
Sezione intitolata “Come funziona un webhook?”Fornisci un URL pubblico e un filtro, e Chaingateway chiama l’URL una volta per ogni transazione corrispondente. La chiamata è una richiesta HTTP POST con un corpo JSON. La tua applicazione legge il corpo e agisce di conseguenza, ad esempio segnando un ordine come pagato. Quando è usato per i pagamenti, lo schema si chiama anche Instant Payment Notification, o IPN.
Crea il webhook poco prima del pagamento atteso, con l’indirizzo che lo riceverà. Ogni notifica contiene i dati seguenti. Il type è il tipo di asset, qui un trasferimento di token TRC20.
{ "id": "9d18457f-c71c-4be4-ae7c-ce04e48359ed", "webhook_id": "9ced86a9-b8d9-4bc2-bbd8-5ffe5b456bc8", "from": "TTd9qHyjqiUkfTxe3gotbuTMpjU8LEbpkN", "to": "DScWVXehzWdV2YS8fA2ryNsiHpKiLgAxM", "blocknumber": "65542464", "datetime": "2024-09-25 14:48:27", "tokenid": null, "type": "TRC20", "contractaddress": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "txid": "18f52f2a55b94a6e3705de4abb18e95dfce79970f27b29450705c561e12b6988", "amount": 108935}Cosa mi serve prima di creare un webhook?
Sezione intitolata “Cosa mi serve prima di creare un webhook?”Ti serve un ricevente, cioè un endpoint sul tuo server che accetta richieste POST da internet. Il flusso di lavoro ha quattro passaggi:
- Crea un endpoint ricevente raggiungibile da Chaingateway.
- Crea un webhook che punta al ricevente.
- Attendi un evento blockchain corrispondente.
- Leggi il corpo della richiesta e rispondi con lo stato HTTP 200.
Il ricevente deve essere raggiungibile pubblicamente. Controlla firewall, reverse proxy e regole di rete, perché un indirizzo privato o una porta bloccata fa fallire ogni consegna. Se hai impostato un personal secret, verifica la firma di ogni richiesta prima di fidarti, come descritto in Sicurezza dei webhook. I riceventi seguenti leggono solo il corpo e rispondono.
from flask import Flask, request
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])def webhook_receiver(): data = request.get_json() # Process the webhook data # Update database, trigger notifications, execute business logic, etc. return 'Webhook received successfully', 200
if __name__ == '__main__': app.run()const express = require('express');
const app = express();app.use(express.json());
app.post('/webhook', (req, res) => { const data = req.body; // Process the webhook data // Update database, trigger notifications, execute business logic, etc. res.status(200).send('Webhook received successfully');});
app.listen(3000, () => { console.log('Webhook receiver is listening on port 3000');});<?php
$data = file_get_contents('php://input');$payload = json_decode($data, true);
// Process the webhook data// Update database, trigger notifications, execute business logic, etc.
http_response_code(200);echo 'Webhook received successfully';<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class WebhookController extends Controller{ /* * Register a route for it, for example: * Route::post('/webhook', [WebhookController::class, 'handle']); */ public function handle(Request $request) { $payload = $request->all();
// Process the webhook payload \Log::info('Webhook received: ', $payload);
return response()->json(['status' => 'success']); }}Come creo un webhook?
Sezione intitolata “Come creo un webhook?”Invia una richiesta POST a /api/v2/{chain}/webhooks. Il corpo richiede l’url del tuo ricevente e un filtro. I campi del filtro sono i seguenti.
| Campo | Significato |
|---|---|
url | Obbligatorio. L’URL completo del tuo ricevente, incluso il percorso. |
from | Indirizzo del mittente da osservare. |
to | Indirizzo del destinatario da osservare. |
contractaddress | Indirizzo del contratto di un token che vuoi tracciare. Non disponibile su Bitcoin. |
token_id | ID del token NFT. |
type | Tipo di asset. Ethereum e Arbitrum: ETH, ERC20, ERC721. Polygon: MATIC, ERC20, ERC721. BNB Smart Chain: BNB, BEP20, BEP721. TRON: TRX, TRC10, TRC20, TRC721. |
reference | Un’etichetta tua, fino a 255 caratteri. |
Indica from o to. Se non indichi nessuno dei due, l’API richiede contractaddress e token_id. I webhook Bitcoin accettano solo url, from e to. I formati degli indirizzi vengono validati, e un indirizzo che non corrisponde restituisce lo stato 422 con il nome del campo in errors.
curl --request POST \ --url https://app.chaingateway.io/api/v2/ethereum/webhooks \ --header 'Authorization: Bearer YOUR_API_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "to": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE", "url": "https://example.com/webhook", "contractaddress": "0xdac17f958d2ee523a2206206994597c13d831ec7", "type": "ERC20", "reference": "order-1042"}'import requests
url = "https://app.chaingateway.io/api/v2/ethereum/webhooks"
payload = { "to": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE", "url": "https://example.com/webhook", "contractaddress": "0xdac17f958d2ee523a2206206994597c13d831ec7", "type": "ERC20", "reference": "order-1042"}headers = { "Content-Type": "application/json", "Authorization": "Bearer YOUR_API_TOKEN"}
response = requests.post(url, json=payload, headers=headers)print(response.json())import axios from 'axios';
const options = { method: 'POST', url: 'https://app.chaingateway.io/api/v2/ethereum/webhooks', headers: {'Content-Type': 'application/json', Authorization: 'Bearer YOUR_API_TOKEN'}, data: { to: '0x922815dFbEa128eAeaAAa185508fe078bECeFBBE', url: 'https://example.com/webhook', contractaddress: '0xdac17f958d2ee523a2206206994597c13d831ec7', type: 'ERC20', reference: 'order-1042' }};
try { const { data } = await axios.request(options); console.log(data);} catch (error) { console.error(error.response?.data ?? error);}<?php
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'https://app.chaingateway.io/api/v2/ethereum/webhooks', [ 'json' => [ 'to' => '0x922815dFbEa128eAeaAAa185508fe078bECeFBBE', 'url' => 'https://example.com/webhook', 'contractaddress' => '0xdac17f958d2ee523a2206206994597c13d831ec7', 'type' => 'ERC20', 'reference' => 'order-1042', ], 'headers' => [ 'Authorization' => 'Bearer YOUR_API_TOKEN', ],]);
echo $response->getBody();Una chiamata riuscita restituisce lo stato 201 e l’id del webhook:
{ "status": 201, "ok": true, "message": "Webhook created", "data": { "webhook": "9b2b4dcc-1479-4bcd-9b8a-015673e80f46" }}Gestisci i webhook esistenti con GET /api/v2/{chain}/webhooks per elencarli, GET .../webhooks/{id} per leggerne uno, PUT .../webhooks/{id} per modificarlo e DELETE .../webhooks/{id} per rimuoverlo. Elimina un webhook quando il pagamento è arrivato, così non continua a corrispondere a trasferimenti successivi. PUT risponde con lo stato 404 e il messaggio Webhook not found quando l’id non esiste.
Cosa succede quando una consegna fallisce?
Sezione intitolata “Cosa succede quando una consegna fallisce?”Chaingateway non ritenta da solo una consegna fallita. Le notifiche fallite vengono memorizzate, e sei tu a leggerle e a reinviarle. I due endpoint sono GET /api/v2/{chain}/webhooks/notifications/failed e POST /api/v2/{chain}/webhooks/notifications/{id}/retry. L’elenco è paginato con il parametro di query page.
Ogni voce mostra il txid, l’url di destinazione, la response memorizzata del tuo server e il numero di attempts. Dopo aver avviato un nuovo tentativo, la notifica esce dall’elenco delle fallite. Se anche il nuovo tentativo fallisce, torna nell’elenco. GET /api/v2/{chain}/webhooks/notifications elenca tutte le notifiche, comprese quelle riuscite. Esegui un piccolo job che controlla a intervalli l’elenco delle fallite e ritenta ciò che trova, e rendi il ricevente idempotente usando txid come chiave, così una notifica ripetuta non causa danni.
Come rilevo i depositi su Solana?
Sezione intitolata “Come rilevo i depositi su Solana?”Solana non ha endpoint webhook. Il file OpenAPI li definisce solo per Ethereum, BNB Smart Chain, Polygon, Arbitrum, TRON e Bitcoin. Per Solana, leggi il saldo dell’indirizzo ricevente oppure elenca le transazioni a intervalli fissi e confronta il risultato con i tuoi registri.
- RFC 9110, HTTP Semantics definisce il metodo POST e i codici di stato 2xx con cui risponde un ricevente.
- Transazioni Ethereum descrive i campi di transazione che compaiono nelle notifiche sulle chain EVM.
- Documentazione delle transazioni TRON descrive i tipi di transazione dietro i valori
typedi TRON.