Webhooks
GTRADE sends a signed HTTPS POST to your server whenever a payment changes status, so you can fulfil orders without polling.
#Overview
- You register an HTTPS endpoint, for example
https://shop.example.com/webhooks/gtrade. - When one of your payments changes, GTRADE sends an event to every endpoint registered on your account.
- Your endpoint verifies the
X-Gtrade-Signatureheader against the raw request body, processes the event and answers2xxwithin 10 seconds. - If delivery fails, GTRADE retries for about 23 hours.
#Event types
| Type | Sent when | Payment status in data |
|---|---|---|
payment.updated | The payment is still open, or a deposit was detected and is confirming. | open or pending |
payment.partially_paid | Less than the requested amount was received. | partially_paid |
payment.paid | The full amount (or more) was received and confirmed. Fulfil the order. | paid |
payment.cancelled | The link expired or the payment was replaced. | cancelled |
payment.expired | Reserved for future use. Expiry is currently reported as payment.cancelled. | expired |
payment.test | You sent a test event (see Testing). | paid (sample data) |
Handle the types you need and answer 2xx to the others; new types may be added.
#Event payload
Each event is a JSON object. data is the Payment as it was at the moment of the event, plus confirmation and transaction details:
{
"id": "evt_d574ee67c881dd5b2d0b0fd8",
"object": "event",
"type": "payment.paid",
"created_at": "2026-11-17T16:40:35.199Z",
"data": {
"id": "9f439f25-f403-446c-9c6a-ecd4aab265e3",
"object": "payment",
"status": "paid",
"amount_usd": 25,
"amount_paid_usd": 25,
"currency": "USDC",
"network": "BASE",
"customer_email": "[email protected]",
"customer_id": "cust_1042",
"checkout_url": "https://checkout.gtradegateway.io/payments?reference_id=9f439f25-f403-446c-9c6a-ecd4aab265e3",
"metadata": { "order_id": "ORD-1042" },
"created_at": "2026-11-17T16:34:38.052139Z",
"updated_at": "2026-11-17T16:34:38.052139Z",
"confirmations": { "current": 12, "required": 12 },
"transactions": [
{ "tx_hash": "0x5c50…e1f3", "from_address": "0x8f3a…21c0", "to_address": "0x2b71…9d44", "block_number": 22874132 }
]
}
}| Field | Description |
|---|---|
id | Unique event id (evt_…). |
type | One of the event types. |
created_at | When the event was created (ISO-8601 UTC). |
data | The Payment. Relayed payment events also include confirmations ({current, required}) and transactions ([{tx_hash, from_address, to_address, block_number}]). |
#Request headers
POST /webhooks/gtrade HTTP/1.1
Content-Type: application/json
User-Agent: GTRADE-Webhooks/1.0
X-Gtrade-Signature: sha256=05816508f83e193bd7fd66dec2dedc5603ad5350919923d6569f9ba4ffee7fed
X-Gtrade-Event: payment.paid
X-Gtrade-Delivery: dlv_1b0c0563a03ccd454eafcc95X-Gtrade-Delivery identifies one delivery (it stays the same across retries of that delivery). X-Gtrade-Event repeats the event type.
#Verifying signatures
X-Gtrade-Signature is sha256= followed by the lowercase hex HMAC-SHA256 of the raw request body, keyed with your API key (the key used to register the endpoint; see key rotation).
Important: Compute the HMAC over the exact bytes you received, before parsing the JSON. Parsing and re-serializing changes whitespace and key order and breaks the signature. Compare in constant time. Reject the request with 400 if the signature doesn't match.
#Without an SDK
Complete, runnable handlers that listen on http://localhost:3000/webhooks/gtrade:
// webhook-server.js — node webhook-server.js
const http = require('node:http');
const crypto = require('node:crypto');
const API_KEY = process.env.GTRADE_API_KEY;
function verifySignature(rawBody, header, apiKey) {
const expected = 'sha256=' + crypto.createHmac('sha256', apiKey).update(rawBody).digest('hex');
return typeof header === 'string' && header.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(header), Buffer.from(expected));
}
http.createServer((req, res) => {
if (req.method !== 'POST' || req.url !== '/webhooks/gtrade') {
res.writeHead(404);
return res.end();
}
const chunks = [];
req.on('data', (chunk) => chunks.push(chunk));
req.on('end', () => {
const rawBody = Buffer.concat(chunks); // the exact bytes received
if (!verifySignature(rawBody, req.headers['x-gtrade-signature'], API_KEY)) {
res.writeHead(400);
return res.end('invalid signature');
}
const event = JSON.parse(rawBody.toString('utf8'));
if (event.type === 'payment.paid') {
console.log('Paid:', event.data.id, event.data.metadata.order_id); // fulfil the order here
} else {
console.log('Event:', event.type, event.data.id, event.data.status);
}
res.writeHead(200);
res.end('ok');
});
}).listen(process.env.PORT || 3000);// npm install express
const express = require('express');
const crypto = require('node:crypto');
const app = express();
const API_KEY = process.env.GTRADE_API_KEY;
// express.raw() keeps the body as a Buffer. Don't use express.json() on this route.
app.post('/webhooks/gtrade', express.raw({ type: 'application/json' }), (req, res) => {
const expected = 'sha256=' + crypto.createHmac('sha256', API_KEY).update(req.body).digest('hex');
const header = req.get('X-Gtrade-Signature') || '';
if (header.length !== expected.length ||
!crypto.timingSafeEqual(Buffer.from(header), Buffer.from(expected))) {
return res.status(400).send('invalid signature');
}
const event = JSON.parse(req.body.toString('utf8'));
if (event.type === 'payment.paid') {
console.log('Paid:', event.data.id, event.data.metadata.order_id); // fulfil the order here
}
res.sendStatus(200);
});
app.listen(process.env.PORT || 3000);# pip install flask — flask --app webhook_server run --port 3000
import hashlib
import hmac
import json
import os
from flask import Flask, request
app = Flask(__name__)
API_KEY = os.environ["GTRADE_API_KEY"]
def verify_signature(raw_body: bytes, header: str, api_key: str) -> bool:
expected = "sha256=" + hmac.new(api_key.encode(), raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, header or "")
@app.post("/webhooks/gtrade")
def gtrade_webhook():
raw_body = request.get_data() # the exact bytes received
if not verify_signature(raw_body, request.headers.get("X-Gtrade-Signature", ""), API_KEY):
return "invalid signature", 400
event = json.loads(raw_body)
if event["type"] == "payment.paid":
print("Paid:", event["data"]["id"], event["data"]["metadata"].get("order_id")) # fulfil the order here
return "ok", 200<?php
// webhook.php — php -S localhost:3000 webhook.php
$apiKey = getenv('GTRADE_API_KEY');
$rawBody = file_get_contents('php://input'); // the exact bytes received
$header = $_SERVER['HTTP_X_GTRADE_SIGNATURE'] ?? '';
$expected = 'sha256=' . hash_hmac('sha256', $rawBody, $apiKey);
if (!hash_equals($expected, $header)) {
http_response_code(400);
exit('invalid signature');
}
$event = json_decode($rawBody, true);
if ($event['type'] === 'payment.paid') {
error_log('Paid: ' . $event['data']['id'] . ' ' . ($event['data']['metadata']['order_id'] ?? '')); // fulfil the order here
}
http_response_code(200);
echo 'ok';#With an SDK
The SDKs verify the signature and parse the event in one call. They raise an error when the signature is wrong.
const express = require('express');
const { Webhook } = require('gtrade-payments');
const app = express();
app.post('/webhooks/gtrade', express.raw({ type: 'application/json' }), (req, res) => {
let event;
try {
event = Webhook.constructEvent(req.body, req.get('X-Gtrade-Signature'), process.env.GTRADE_API_KEY);
} catch (err) {
return res.status(400).send('invalid signature');
}
if (event.type === 'payment.paid') {
console.log('Paid:', event.data.id); // fulfil the order here
}
res.sendStatus(200);
});
app.listen(process.env.PORT || 3000);import os
from flask import Flask, request
from gtrade_payments import SignatureVerificationError, Webhook
app = Flask(__name__)
@app.post("/webhooks/gtrade")
def gtrade_webhook():
try:
event = Webhook.construct_event(
request.get_data(), request.headers.get("X-Gtrade-Signature"), os.environ["GTRADE_API_KEY"]
)
except SignatureVerificationError:
return "invalid signature", 400
if event.type == "payment.paid":
print("Paid:", event.data.id) # fulfil the order here
return "ok", 200<?php
require __DIR__ . '/vendor/autoload.php';
try {
$event = \Gtrade\Webhook::constructEvent(
file_get_contents('php://input'),
$_SERVER['HTTP_X_GTRADE_SIGNATURE'] ?? null,
getenv('GTRADE_API_KEY')
);
} catch (\Gtrade\Exception\SignatureVerificationError $e) {
http_response_code(400);
exit('invalid signature');
}
if ($event->type === 'payment.paid') {
error_log('Paid: ' . $event->data->id); // fulfil the order here
}
http_response_code(200);
echo 'ok';Note: Frameworks that parse JSON automatically (Express express.json(), Laravel, Django REST framework and others) give you a parsed object, not the raw bytes. Read the raw body for this route (for example express.raw(), request.get_data() in Flask, request.body in Django, $request->getContent() in Laravel).
#Handling events reliably
- Answer fast. Return
2xxwithin 10 seconds, then do slow work (emails, fulfilment) in a background job. Any other status, a timeout or a connection error counts as a failure and is retried. - Expect duplicates. You can receive the same status more than once. Make your handler idempotent: key it on
data.id+data.status(for example, only mark an order paid if it isn't already). - Don't rely on order. Events can arrive out of order. If in doubt, fetch the current state with
GET /v1/payments/{id}; it's always authoritative. - Fulfil on
payment.paidonly.payment.updatedwith statuspendingmeans "seen, not yet confirmed". - Match the order with
data.metadata(your order id) or thedata.idyou stored when creating the payment.
#Retries
A failed delivery is retried with increasing delays: 10 attempts in total, immediately and then after 10 s, 30 s, 2 min, 10 min, 30 min, 1 h, 3 h, 6 h and 12 h (about 23 hours in all). After the last attempt the delivery is marked failed. Retries survive restarts on our side.
If your endpoint was down for longer, reconcile with GET /v1/payments (for example, list status=paid and compare with your orders).
#Managing endpoints
You can register up to 10 endpoints per account. Every endpoint receives every event of your account.
Endpoint URL rules: it must use https://, must not contain a username or password, and must resolve to a public address (no localhost, private or link-local IPs). This is checked when you register the endpoint and again on every delivery. An invalid URL returns 422 parameter_invalid; an 11th endpoint returns 422 webhook_limit_reached.
#Register an endpoint
curl https://api.gtradegateway.io/v1/webhooks \
-H "Authorization: Bearer $GTRADE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://shop.example.com/webhooks/gtrade"}'const { Gtrade } = require('gtrade-payments');
const gtrade = new Gtrade({ apiKey: process.env.GTRADE_API_KEY, baseUrl: 'https://api.gtradegateway.io' });
gtrade.webhooks.create('https://shop.example.com/webhooks/gtrade')
.then((endpoint) => console.log(endpoint.id));import os
from gtrade_payments import Gtrade
gtrade = Gtrade(api_key=os.environ["GTRADE_API_KEY"], base_url="https://api.gtradegateway.io")
endpoint = gtrade.webhooks.create("https://shop.example.com/webhooks/gtrade")
print(endpoint.id)<?php
require __DIR__ . '/vendor/autoload.php';
$gtrade = new \Gtrade\Client(getenv('GTRADE_API_KEY'), ['base_url' => 'https://api.gtradegateway.io']);
$endpoint = $gtrade->webhooks->create('https://shop.example.com/webhooks/gtrade');
echo $endpoint->id, PHP_EOL;{
"id": "wh_3d2879879510976a9ad3a82b",
"object": "webhook_endpoint",
"url": "https://shop.example.com/webhooks/gtrade",
"created_at": "2026-11-17T16:34:38.542Z"
}#List endpoints
curl https://api.gtradegateway.io/v1/webhooks \
-H "Authorization: Bearer $GTRADE_API_KEY"const { Gtrade } = require('gtrade-payments');
const gtrade = new Gtrade({ apiKey: process.env.GTRADE_API_KEY, baseUrl: 'https://api.gtradegateway.io' });
gtrade.webhooks.list().then((list) => {
for (const w of list.data) console.log(w.id, w.url);
});import os
from gtrade_payments import Gtrade
gtrade = Gtrade(api_key=os.environ["GTRADE_API_KEY"], base_url="https://api.gtradegateway.io")
for w in gtrade.webhooks.list().data:
print(w.id, w.url)<?php
require __DIR__ . '/vendor/autoload.php';
$gtrade = new \Gtrade\Client(getenv('GTRADE_API_KEY'), ['base_url' => 'https://api.gtradegateway.io']);
foreach ($gtrade->webhooks->list()->data as $w) {
echo $w->id, ' ', $w->url, PHP_EOL;
}{
"object": "list",
"data": [
{ "id": "wh_3d2879879510976a9ad3a82b", "object": "webhook_endpoint", "url": "https://shop.example.com/webhooks/gtrade", "created_at": "2026-11-17T16:34:38.542Z" }
]
}#Send a test event
Sends a signed payment.test event to that endpoint right away and reports the first attempt.
curl -X POST https://api.gtradegateway.io/v1/webhooks/wh_3d2879879510976a9ad3a82b/test \
-H "Authorization: Bearer $GTRADE_API_KEY"const { Gtrade } = require('gtrade-payments');
const gtrade = new Gtrade({ apiKey: process.env.GTRADE_API_KEY, baseUrl: 'https://api.gtradegateway.io' });
gtrade.webhooks.test('wh_3d2879879510976a9ad3a82b')
.then((delivery) => console.log(delivery.status, delivery.response_status));import os
from gtrade_payments import Gtrade
gtrade = Gtrade(api_key=os.environ["GTRADE_API_KEY"], base_url="https://api.gtradegateway.io")
delivery = gtrade.webhooks.test("wh_3d2879879510976a9ad3a82b")
print(delivery.status, delivery.response_status)<?php
require __DIR__ . '/vendor/autoload.php';
$gtrade = new \Gtrade\Client(getenv('GTRADE_API_KEY'), ['base_url' => 'https://api.gtradegateway.io']);
$delivery = $gtrade->webhooks->test('wh_3d2879879510976a9ad3a82b');
echo $delivery->status, ' ', var_export($delivery->response_status, true), PHP_EOL;{
"id": "dlv_ddbb6e88b7e8e4c2ce111d2c",
"object": "webhook_delivery",
"webhook_id": "wh_3d2879879510976a9ad3a82b",
"event_id": "evt_f1e8d1a24482804e3652ad47",
"event_type": "payment.test",
"status": "succeeded",
"response_status": 200
}status is succeeded, or pending when the first attempt failed and a retry is scheduled. response_status is the HTTP status your endpoint returned, or null when it couldn't be reached (DNS, TLS, connection or timeout error).
The test event uses sample data (data.id is 00000000-0000-0000-0000-000000000000, metadata is {"test": true}), so make sure your handler doesn't try to fulfil a real order for it.
#Delete an endpoint
curl -X DELETE https://api.gtradegateway.io/v1/webhooks/wh_3d2879879510976a9ad3a82b \
-H "Authorization: Bearer $GTRADE_API_KEY"const { Gtrade } = require('gtrade-payments');
const gtrade = new Gtrade({ apiKey: process.env.GTRADE_API_KEY, baseUrl: 'https://api.gtradegateway.io' });
gtrade.webhooks.delete('wh_3d2879879510976a9ad3a82b').then(() => console.log('deleted'));import os
from gtrade_payments import Gtrade
gtrade = Gtrade(api_key=os.environ["GTRADE_API_KEY"], base_url="https://api.gtradegateway.io")
gtrade.webhooks.delete("wh_3d2879879510976a9ad3a82b")<?php
require __DIR__ . '/vendor/autoload.php';
$gtrade = new \Gtrade\Client(getenv('GTRADE_API_KEY'), ['base_url' => 'https://api.gtradegateway.io']);
$gtrade->webhooks->delete('wh_3d2879879510976a9ad3a82b');The API answers 204 No Content. Pending retries to that endpoint are cancelled. An unknown id returns 404 webhook_not_found.
Note: Manage your endpoints with this API. The webhook settings page in the dashboard is managed by GTRADE; leave its entries unchanged.
#Testing your endpoint
#1. Test locally with a signed sample event
Webhook endpoints must be public, so GTRADE can't call localhost. While developing, sign a sample event yourself with your API key and send it to your local handler. This is exactly what GTRADE does:
BODY='{"id":"evt_local_test","object":"event","type":"payment.test","created_at":"2026-11-17T16:22:13.980Z","data":{"id":"00000000-0000-0000-0000-000000000000","object":"payment","status":"paid","amount_usd":1,"amount_paid_usd":1,"currency":"USDT","network":"ETH","customer_email":"[email protected]","customer_id":"test_customer","checkout_url":"https://checkout.gtradegateway.io/payments?reference_id=00000000-0000-0000-0000-000000000000","metadata":{"test":true},"created_at":"2026-11-17T16:22:13.979Z","updated_at":"2026-11-17T16:22:13.979Z"}}'
SIG="sha256=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$GTRADE_API_KEY" | sed 's/^.*= //')"
curl -i http://localhost:3000/webhooks/gtrade \
-H "Content-Type: application/json" \
-H "X-Gtrade-Event: payment.test" \
-H "X-Gtrade-Signature: $SIG" \
--data-binary "$BODY"Your handler should answer 200. Change one character of BODY after computing SIG, and it should answer 400.
#2. Test end to end
- Deploy your handler on a public HTTPS URL. For a development machine, a tunnelling tool that gives you a public HTTPS URL forwarding to
localhost:3000works too. - Register that URL.
- Send a test event and check that
statusissucceededandresponse_statusis200. - Create a small real payment (for example USD 1), pay it, and watch
payment.updatedandpayment.paidarrive. - Delete endpoints you no longer use.
#Troubleshooting
| Symptom | Likely cause |
|---|---|
| Signature never matches | The body was parsed or re-encoded before hashing; the wrong API key is used (the key that registered the endpoint, see key rotation); or the sha256= prefix is missing from your comparison. |
response_status is null | Your URL isn't reachable from the internet: DNS, firewall, TLS certificate or a timeout over 10 seconds. |
response_status is 3xx | Redirects are not followed. Register the final URL. |
| Same event twice | Expected occasionally. Make the handler idempotent. |