๐Ÿ“– Tronsell Wiki

Gateway Webhooks and Callbacks Setup

A step-by-step guide to setting up webhooks and callbacks for crypto payment gateways โ€” configure endpoints, verify signatures, and automate order fulfillment.

๐Ÿ”” Webhooks โ€” Quick Facts
DefinitionHTTP callbacks for payment events
Key Eventspayment.confirmed, payment.expired, refund.completed
SecurityHMAC signature verification
Retry MechanismExponential backoff for failures
Best PracticeIdempotent processing
TestingUse sandbox environment

๐Ÿ”” Introduction: What are Webhooks?

Webhooks are HTTP callbacks that a payment gateway sends to your server to notify you about payment events. They are the essential mechanism for automating order fulfillment, updating order statuses, and integrating payment confirmations into your application workflow.

Unlike polling (repeatedly calling the API to check status), webhooks provide real-time notifications and reduce API load. When a payment is confirmed, expired, or refunded, the gateway instantly sends a structured payload to your configured webhook URL.

๐Ÿ’ก Webhooks vs. Polling

Webhooks are push-based โ€” the gateway sends data to you. Polling is pull-based โ€” you repeatedly request data. Webhooks are more efficient, faster, and reduce server load.

๐Ÿ“‹ Step-by-Step Setup Guide

Step 1: Create Your Webhook Endpoint

Create an endpoint on your server that accepts POST requests. This is the URL where the gateway will send webhook notifications.

  • URL format โ€” https://yoursite.com/api/webhooks/payment
  • Method โ€” POST
  • Content-Type โ€” application/json (typically)
  • Response โ€” return HTTP 200 OK (2xx) to acknowledge receipt

Step 2: Configure Webhook in Gateway Dashboard

Log in to your payment gateway dashboard and navigate to the webhook configuration section:

  • Endpoint URL โ€” paste your server endpoint URL
  • Event Selection โ€” choose which events to subscribe to:
EventDescriptionAction
payment.createdPayment request createdLog transaction
payment.receivedTransaction detected on blockchainUpdate order status (pending)
payment.confirmedSufficient confirmations reachedFulfill order (ship, grant access)
payment.expiredPayment request expiredCancel order, notify customer
payment.underpaidAmount received is less than expectedNotify customer, request additional
payment.overpaidAmount received is more than expectedManual review or automatic refund
refund.completedRefund processedUpdate order status

Step 3: Implement Signature Verification

To prevent forged webhook requests, most gateways sign webhook payloads with a secret key. Here's how to verify:

// Node.js example: Verify webhook signature
const crypto = require('crypto');

function verifyWebhook(payload, signature, secret) {
    const expected = crypto
        .createHmac('sha256', secret)
        .update(JSON.stringify(payload))
        .digest('hex');
    return crypto.timingSafeEqual(
        Buffer.from(signature),
        Buffer.from(expected)
    );
}

// In your webhook handler:
const payload = req.body;
const signature = req.headers['x-webhook-signature'];
const isValid = verifyWebhook(payload, signature, WEBHOOK_SECRET);
if (!isValid) {
    return res.status(401).send('Invalid signature');
}
                    

Step 4: Handle Events

Process the webhook payload based on the event type:

// Example webhook handler
app.post('/webhooks/payment', (req, res) => {
    const event = req.body;
    switch (event.type) {
        case 'payment.confirmed':
            // Fulfill the order
            const orderId = event.data.order_id;
            updateOrderStatus(orderId, 'paid');
            sendConfirmationEmail(orderId);
            break;
        case 'payment.expired':
            // Cancel the order
            cancelOrder(event.data.order_id);
            break;
        case 'refund.completed':
            // Update refund status
            updateRefundStatus(event.data.refund_id, 'completed');
            break;
        default:
            // Log unknown event type
            console.log('Unhandled event:', event.type);
    }
    res.status(200).send('OK');
});
                    

Step 5: Test in Sandbox Environment

Before going live, test your webhook implementation in the gateway's sandbox environment:

  • Simulate events โ€” most gateways allow you to manually trigger webhook events from the dashboard.
  • Check responses โ€” verify that your endpoint returns 2xx status codes.
  • Monitor logs โ€” check your server logs to confirm payload receipt and processing.
  • Test failure scenarios โ€” simulate endpoint failure to verify gateway retry behavior.

๐Ÿ›ก๏ธ Webhook Security Best Practices

Implement these security measures to protect your webhook endpoint:

๐Ÿ”
Signature Verification

Always verify the webhook signature using the gateway's secret key. This ensures the request is genuinely from the gateway.

๐Ÿ”„
Idempotency

Handle duplicate webhook notifications safely. Store a transaction ID and skip processing if already handled.

๐ŸŒ
HTTPS Only

Always use HTTPS for webhook endpoints. Never accept insecure HTTP connections.

๐Ÿ“ก
IP Whitelisting

If possible, whitelist the gateway's IP address range to prevent unauthorized requests.

๐Ÿ“Š Common Webhook Events

EventPayload ExampleRecommended Action
payment.confirmed { "type": "payment.confirmed", "data": { "payment_id": "pay_123", "order_id": "ord_456", "amount": "100.00", "currency": "USD" } } Fulfill the order, send confirmation
payment.expired { "type": "payment.expired", "data": { "payment_id": "pay_123", "order_id": "ord_456" } } Cancel the order, notify customer
payment.underpaid { "type": "payment.underpaid", "data": { "payment_id": "pay_123", "expected": "100.00", "received": "50.00" } } Notify customer, request additional payment
refund.completed { "type": "refund.completed", "data": { "refund_id": "ref_123", "payment_id": "pay_456", "amount": "100.00" } } Update refund status in your system

๐Ÿ”ง Troubleshooting Webhooks

Common issues and how to resolve them:

IssuePossible CauseSolution
Webhook not receivedIncorrect endpoint URL, firewall blocking, server downCheck URL, whitelist IPs, check server status
Signature verification failsIncorrect secret key, payload format mismatchVerify secret key, use raw payload (not parsed JSON)
Duplicate webhooksGateway retry mechanism, network issuesImplement idempotency (store processed IDs)
Slow response timesHeavy processing in endpointProcess asynchronously (queue job), respond quickly
SSL certificate errorsExpired or invalid certificateRenew/update SSL certificate

โ“ Frequently Asked Questions

What are webhooks in a payment gateway?

Webhooks are HTTP callbacks that the payment gateway sends to your server to notify you about payment events (e.g., payment confirmed, payment expired, refund processed). They are essential for automating order fulfillment without polling the API.

How do I set up a webhook for a payment gateway?

To set up a webhook: 1) Create an endpoint on your server that accepts POST requests. 2) Configure the webhook URL in the gateway dashboard. 3) Add event subscriptions (payment.confirmed, payment.expired, etc.). 4) Verify webhook signatures (if supported). 5) Test with a sandbox environment.

How do I verify a webhook signature?

Most gateways include a signature in the webhook headers (e.g., X-Webhook-Signature). You verify it by computing an HMAC-SHA256 hash of the raw payload using your webhook secret key and comparing it with the provided signature. Use timing-safe comparison to prevent timing attacks.

What events should I subscribe to for webhooks?

Essential events include: payment.received (detected on blockchain), payment.confirmed (sufficient confirmations), payment.expired (payment request expired), refund.completed, and payment.failed. Subscribe to confirmed events for order fulfillment.

What happens if my webhook endpoint fails?

Most gateways implement retry mechanisms โ€” they will retry sending webhooks multiple times with increasing delays (exponential backoff) if they receive non-2xx responses or timeouts. You should also implement idempotency to handle duplicate webhooks safely.

โšก Save on USDT TRC20 Fees with Tron Energy

Stop burning TRX on every USDT transfer. Buy or rent Tron Energy from Tronsell โ€” instant delivery, competitive rates, and no TRX lockup required.