How Blockchain Payment Webhooks Work
A webhook in Chaingateway is a subscription that makes our servers send an HTTP POST request to your URL when a transaction matches the filter you set, for example an incoming transfer to one of your addresses. This is how you receive instant payment notifications without polling. Webhooks exist for Ethereum, BNB Smart Chain, Polygon, Arbitrum, TRON and Bitcoin, but not for Solana.
How does a webhook work?
Section titled “How does a webhook work?”You provide a public URL and a filter, and Chaingateway calls the URL once for each matching transaction. The call is an HTTP POST with a JSON body. Your application reads the body and acts on it, for example by marking an order as paid. The pattern is also called an Instant Payment Notification, or IPN, when it is used for payments.
Create the webhook shortly before you expect the payment, with the address that will receive it. Each notification carries the data below. The type is the asset type, here a TRC20 token transfer.
{ "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}What do I need before I create a webhook?
Section titled “What do I need before I create a webhook?”You need a receiver, which is an endpoint on your server that accepts POST requests from the internet. The workflow has four steps:
- Build a receiver endpoint that Chaingateway can reach.
- Create a webhook that points to the receiver.
- Wait for a matching blockchain event.
- Read the request body and answer with HTTP status 200.
The receiver has to be publicly reachable. Check firewalls, reverse proxies and network rules, because a private address or a blocked port makes every delivery fail. If you have set a personal secret, verify the signature of each request before you trust it, as described in Webhooks Security. The receivers below only read the body and answer.
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']); }}How do I create a webhook?
Section titled “How do I create a webhook?”Send a POST request to /api/v2/{chain}/webhooks. The body needs the url of your receiver and a filter. The filter fields are the following.
| Field | Meaning |
|---|---|
url | Required. The full URL of your receiver, including the path. |
from | Sender address to watch. |
to | Receiver address to watch. |
contractaddress | Contract address of a token you want to track. Not available on Bitcoin. |
token_id | NFT token id. |
type | Asset type. Ethereum and Arbitrum: ETH, ERC20, ERC721. Polygon: MATIC, ERC20, ERC721. BNB Smart Chain: BNB, BEP20, BEP721. TRON: TRX, TRC10, TRC20, TRC721. |
reference | Your own label, up to 255 characters. |
Provide from or to. If you provide neither, the API requires contractaddress and token_id. Bitcoin webhooks accept only url, from and to. Address formats are validated, and an address that does not match returns status 422 with the field name 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();A successful call returns status 201 and the id of the webhook:
{ "status": 201, "ok": true, "message": "Webhook created", "data": { "webhook": "9b2b4dcc-1479-4bcd-9b8a-015673e80f46" }}You manage existing webhooks with GET /api/v2/{chain}/webhooks to list them, GET .../webhooks/{id} to read one, PUT .../webhooks/{id} to change it and DELETE .../webhooks/{id} to remove it. Delete a webhook once the payment has arrived, so it does not keep matching later transfers. PUT answers with status 404 and the message Webhook not found when the id does not exist.
What happens when a delivery fails?
Section titled “What happens when a delivery fails?”Chaingateway does not retry a failed delivery on its own. Failed notifications are stored, and you read them and send them again yourself. The two endpoints are GET /api/v2/{chain}/webhooks/notifications/failed and POST /api/v2/{chain}/webhooks/notifications/{id}/retry. The list is paginated with the page query parameter.
Each entry shows the txid, the target url, the stored response of your server and the number of attempts. After you start a retry, the notification leaves the failed list. If the retry fails as well, it returns to the list. GET /api/v2/{chain}/webhooks/notifications lists all notifications, successful ones included. Run a small job that checks the failed list at an interval and retries what is there, and make the receiver idempotent by using txid as the key, so a repeated notification does no harm.
How do I detect deposits on Solana?
Section titled “How do I detect deposits on Solana?”Solana has no webhook endpoints. The OpenAPI file defines them for Ethereum, BNB Smart Chain, Polygon, Arbitrum, TRON and Bitcoin only. For Solana, read the balance of the receiving address or list transactions at a fixed interval and compare the result with your records.
Sources
Section titled “Sources”- RFC 9110, HTTP Semantics defines the POST method and the 2xx status codes that a receiver answers with.
- Ethereum transactions describes the transaction fields that appear in notifications on the EVM chains.
- TRON transaction documentation describes the transaction types behind the TRON
typevalues.