Skip to content

Creating Webhooks

This guide helps you create webhooks using the Chaingateway API. It includes details on writing a basic webhook receiver, subscribing to a webhook, and handling Chain-specific parameters.

How it works

Our webhook system works as an Instant Payment Notification system. It can be used to notify your software of an incoming payment or token receipt. It consists of two parts of code:

The Webhook: This is the endpoint URL where the webhook notifications will be sent. You need to provide this URL to the Chaingateway API when subscribing to the webhook. You also need to specify the filter parameters like sender, receiver, contractaddress, token_id and type (transaction type). If an event on the blockchain happens matching those criterias, we will send out a webhook to the url you specified.

The Webhook Receiver: This is the code that runs on your server and listens for incoming webhook notifications. It receives the webhook payload and performs the necessary actions in your software based on the received data.

To set up the webhook system, you need to implement the webhook receiver code on your server and configure the webhook URL in the Chaingateway API. Once set up, whenever a payment or token receipt occurs, the Chaingateway API will send a POST request to your webhook URL, triggering the webhook receiver code and allowing your software to take appropriate actions.

Writing a Basic Webhook Receiver

A webhook receiver is a server endpoint that listens for incoming HTTP POST requests from ChainGateway. Below are examples of basic webhook receivers in different programming languages.

Example Code

javascript
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}`);
});
python
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    data = request.json
    print('Received webhook:', data)
    return jsonify({'status': 'Webhook received'}), 200

if __name__ == '__main__':
    app.run(port=3000)
php
<?php
if ($_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
/*
* To integrate this code into a Laravel application, follow these steps:
* 
* 1. Create a new route in your `routes/web.php` file:
* Route::post('/webhook', [WebhookController::class, 'handleWebhook']);
* 
* php artisan make:controller WebhookController
* 
* This will create a new `WebhookController` class in the `app/Http/Controllers` directory.
* 
* 3. Open the newly created `WebhookController.php` file and replace its content with the code provided above.
* 
* Now, your Laravel application is ready to handle webhooks using the `WebhookController` class.
*
*/

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class WebhookController extends Controller
{
    public function handleWebhook(Request $request)
    {
        $data = $request->all();
        file_put_contents('php://stderr', print_r($data, TRUE));
        return response()->json(['status' => 'Webhook received'], 200);
    }
}

Create a Webhook to subscribe to a Blockchain Event

To subscribe to a webhook, you need to send a request to the ChainGateway API with the appropriate parameters.

Parameters

  • url (required): The URL of your webhook receiver endpoint. Must be a valid URL.
  • from: The sender address (optional, at least one of from or to is required).
  • to: The receiver address (optional, at least one of from or to is required).
  • contractaddress: The contract address of the token (optional).
  • token_id: Required when neither from nor to are present.
  • type: The type of transaction (optional). Possible values: TRX, TRC10, TRC20, TRC721.

Example Authorization Header

Replace YOUR_API_TOKEN with your actual API token.

Example Code

shell
curl --request POST \
  --url https://api.chaingateway.io/v2/webhooks \
  --header 'Accept: application/json' \
  --header 'content-type: application/json' \
  --header 'Authorization: YOUR_API_TOKEN' \
  --data '{
    "url": "http://yourdomain.com/webhook",
    "from": "TXSenderAddress",
    "to": "TXReceiverAddress",
    "contractaddress": "0xTokenContractAddress",
    "token_id": "12345",
    "type": "TRC20"
}'
python
import requests

url = "https://api.chaingateway.io/v2/webhooks"
payload = {
    "url": "http://yourdomain.com/webhook",
    "from": "TXSenderAddress",
    "to": "TXReceiverAddress",
    "contractaddress": "0xTokenContractAddress",
    "token_id": "12345",
    "type": "TRC20"
}
headers = {
    'Accept': 'application/json',
    'content-type': 'application/json',
    'Authorization': 'YOUR_API_TOKEN'
}

response = requests.post(url, json=payload, headers=headers)
print(response.json())
javascript
const axios = require('axios');

const url = 'https://api.chaingateway.io/v2/webhooks';
const payload = {
  url: 'http://yourdomain.com/webhook',
  from: 'TXSenderAddress',
  to: 'TXReceiverAddress',
  contractaddress: '0xTokenContractAddress',
  token_id: '12345',
  type: 'TRC20'
};
const headers = {
  'Accept': 'application/json',
  'content-type': 'application/json',
  'Authorization': 'YOUR_API_TOKEN'
};

axios.post(url, payload, { headers })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });
php
<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;

$client = new Client();
$response = $client->post('https://api.chaingateway.io/v2/webhooks', [
    'headers' => [
        'Accept' => 'application/json',
        'content-type' => 'application/json',
        'Authorization' => 'YOUR_API_TOKEN',
    ],
    'json' => [
        'url' => 'http://yourdomain.com/webhook',
        'from' => 'TXSenderAddress',
        'to' => 'TXReceiverAddress',
        'contractaddress' => '0xTokenContractAddress',
        'token_id' => '12345',
        'type' => 'TRC20'
    ]
]);

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

use Illuminate\Support\Facades\Http;

$response = Http::withHeaders([
    'Accept' => 'application/json',
    'content-type' => 'application/json',
    'Authorization' => 'YOUR_API_TOKEN',
])->post('https://api.chaingateway.io/v2/webhooks', [
    'url' => 'http://yourdomain.com/webhook',
    'from' => 'TXSenderAddress',
    'to' => 'TXReceiverAddress',
    'contractaddress' => '0xTokenContractAddress',
    'token_id' => '12345',
    'type' => 'TRC20'
]);

echo $response->body();

Important Information

  • Ensure that your webhook receiver endpoint is publicly accessible and can handle HTTP POST requests.
  • Secure your webhook endpoint by validating the source of incoming requests and ensuring the data integrity.
  • Chaingateway does not store sensitive information such as the token. Therefore, store this information securely.
  • For obtaining an API key and learning about authorization, please refer to the Getting Started section of the Chaingateway documentation.