Skip to content

Webhooks

Learn how the webhook feature of chaingateway can provide instant payment notifications to your server.

Introduction

Chaingateway's webhooks provide real time instant payment notifications to your systems endpoint. To do so, you should create a webhook right before the payment is done. This Webhooks has several filter options and provide you transaction information as soon as an transaction was setteled matching your filter criteria.

How Webhook works

Webhooks: Webhooks are a way for applications to send real-time notifications to other applications or services. In the context of blockchain, webhooks can be used to receive notifications about various events, such as new blocks being mined, transactions being confirmed, or smart contract events being triggered.

When you set up a webhook, you provide a URL endpoint in your application that will receive the notifications. Whenever the specified event occurs, the blockchain network will send an HTTP POST request to your webhook endpoint with relevant data. Your application can then process this data and take appropriate actions, such as updating a database, sending notifications, or triggering other processes.

Instant Payment Notifications (IPNs): IPNs are a specific type of webhook used in the context of payment systems, including blockchain-based payment systems. IPNs are typically used to receive notifications about payment-related events, such as successful payments, failed payments, or refunds.

When a payment is made on a blockchain network, an IPN can be triggered to notify your application about the payment status. This allows your application to update its internal records, provide instant feedback to users, or trigger further actions based on the payment status.

Both webhooks and IPNs are essential for building real-time and event-driven applications that interact with blockchain networks. They enable your application to stay updated with the latest events and take immediate actions based on those events.

Example Webhook Message

Our Webhook system will post messages in this format

json
{
    "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
}

Workflow

To create a webhook, you will need to process the following steps:

  • Create an receiver endpoint where we can send you the webhooks to
  • Create a webhook on chaingateway using the receiver endpoint
  • Wait for blockchain events
  • Consume the Request and send back the correct response code

Example receiver

Before you create an webhook, you first need to setup an receiver. A webhook receiver is a component or endpoint that listens for incoming webhook requests. It acts as a receiver or listener for events triggered by external systems or services. When a webhook event occurs, the sender system makes an HTTP request to the webhook receiver's URL, providing data related to the event.

The webhook receiver's role is to handle and process the incoming webhook requests. It typically performs actions based on the received data, such as updating a database, triggering a notification, or executing specific business logic.

To set up a webhook receiver, you need to define an endpoint in your application that can receive incoming HTTP requests. This endpoint should be publicly accessible so that the sender system can send webhook events to it. Once the receiver is set up, you can configure the sender system to send webhook events to the receiver's URL.

Important:

It is crucial that the webhook receivers are accessible from outside. This means that the endpoint URLs defined in the webhook receivers should be publicly accessible so that the sender systems can send webhook events to them. Make sure to configure your network settings, firewalls, and security measures accordingly to allow incoming HTTP requests to reach the webhook receivers.

bash
#!/bin/bash

# Define the endpoint URL
ENDPOINT_URL="https://example.com/webhook"

# Start a local server to receive the webhook
nc -l -p 8080 > webhook_payload.json &

# Print the server's PID
echo "Webhook receiver is running with PID: $!"

# Wait for the webhook payload to be received
sleep 5

# Read the received payload from the file
PAYLOAD=$(cat webhook_payload.json)

# Process the webhook data
# Update database, trigger notifications, execute business logic, etc.

# Send the response back to the sender
echo "Webhook received successfully" | curl -X POST -d @- $ENDPOINT_URL

# Clean up the temporary files
rm webhook_payload.json
python
from flask import Flask, request

app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook_receiver():
    data = request.webhook_json()
    # Process the webhook data
    # Update database, trigger notifications, execute business logic, etc.
    return 'Webhook received successfully'

if __name__ == '__main__':
    app.run()
javascript
const express = require('express');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());

app.post('/webhook', (req, res) => {
    const data = req.body;
    // Process the webhook data
    // Update database, trigger notifications, execute business logic, etc.
    res.send('Webhook received successfully');
});

app.listen(3000, () => {
    console.log('Webhook receiver is listening on port 3000');
});
php
<?php

$data = file_webhook_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
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class WebhookController extends Controller
{
    /*
    * you should register a route for it like 
    * Route::post('/webhook', [WebhookController::class, 'handle']);
    */
    public function handle(Request $request)
    {
        // Log the webhook payload for debugging
        \Log::info('Webhook received: ', $request->all());

        // Process the webhook payload
        $eventType = $request->header('X-Event-Type');
        $payload = $request->all();

       // Do something with this webhook receiver

        // Respond to the webhook sender
        return response()->json(['status' => 'success']);
    }
}

?>

Example creation

If you have created your public webhook receiver, we can now create the webhook.

For creating a webhook, you have several options to filter your relevant events.

  • from (string): The sender's address.
  • to (string): The receiver's address.
  • contractaddress (string): The address of a contract you want to track.
  • token_id (string): A NFT Token Id.
  • type (string enum): The type of asset to track. Possible values for ethereum are ETH, ERC20, or ERC721. Check the docs for other chains.

You also need to add the url parameter which needs to be a full qualified domain name or ip address with the route to your webhook receiver endpoint we've created before.

This leads to a required set of "url" and one of "from" or "to". The rest is optional.

examples:

shell
curl --request POST \
  --url https://api.chaingateway.io/api/v2/ethereum/webhooks \
  --header 'Authorization: YOUR_SECRET_TOKEN' \
  --header 'Content-Type: application/json' \
  --data '{
  "from": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE",
  "to": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE",
  "url": "http://vonrueden.com/",
  "contractaddress": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE",
  "token_id": null,
  "type": "ERC20"
}'
python
import requests

url = "https://api.chaingateway.io/api/v2/ethereum/webhooks"

payload = {
    "from": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE",
    "to": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE",
    "url": "http://vonrueden.com/",
    "contractaddress": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE",
    "token_id": None,
    "type": "ERC20"
}
headers = {
    "Content-Type": "application/json",
    "Authorization": "YOUR_SECRET_TOKEN"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
javascript
import axios from 'axios';

const options = {
  method: 'POST',
  url: 'https://api.chaingateway.io/api/v2/ethereum/webhooks',
  headers: {'Content-Type': 'application/json', Authorization: 'YOUR_SECRET_TOKEN'},
  data: {
    from: '0x922815dFbEa128eAeaAAa185508fe078bECeFBBE',
    to: '0x922815dFbEa128eAeaAAa185508fe078bECeFBBE',
    url: 'http://vonrueden.com/',
    contractaddress: '0x922815dFbEa128eAeaAAa185508fe078bECeFBBE',
    token_id: null,
    type: 'ERC20'
  }
};

try {
  const { data } = await axios.request(options);
  console.log(data);
} catch (error) {
  console.error(error);
}
php
<?php

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.chaingateway.io/api/v2/ethereum/webhooks', [
  'body' => '{
  "from": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE",
  "to": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE",
  "url": "http://vonrueden.com/",
  "contractaddress": "0x922815dFbEa128eAeaAAa185508fe078bECeFBBE",
  "token_id": null,
  "type": "ERC20"
}',
  'headers' => [
    'Authorization' => 'YOUR_SECRET_TOKEN',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
php
<?php

use Illuminate\Support\Facades\Http;

$response = Http::withHeaders([
    'Authorization' => 'YOUR_SECRET_TOKEN',
    'Content-Type' => 'application/json',
])->post('https://api.chaingateway.io/api/v2/ethereum/webhooks', [
    'from' => '0x922815dFbEa128eAeaAAa185508fe078bECeFBBE',
    'to' => '0x922815dFbEa128eAeaAAa185508fe078bECeFBBE',
    'url' => 'http://vonrueden.com/',
    'contractaddress' => '0x922815dFbEa128eAeaAAa185508fe078bECeFBBE',
    'token_id' => null,
    'type' => 'ERC20',
]);

echo $response->body();

The response would then looks like this:

json
{
  "status": 201,
  "ok": true,
  "message": "Webhook created",
  "data": {
    "webhook": "9b2b4dcc-1479-4bcd-9b8a-015673e80f46"
  }
}