Webhooks
Webhooks notify your server about payment events in real-time. They're the most reliable way to know when a payment succeeds or fails.
Why Use Webhooks?
- Reliable: Don't depend on customers returning to your site
- Real-time: Get notified immediately when payments complete
- Secure: Verify authenticity with signatures
- Async: Process payments without blocking your checkout flow
Setting Up Webhooks
- Go to Dashboard → Settings → Webhooks
- Enter your webhook URL (must be HTTPS in production)
- Select events to subscribe to
- Copy the webhook secret for signature verification
Webhook Events
You can subscribe to and receive these events:
Payment Events
| Event | Description | When Triggered |
|---|---|---|
payment.success | Payment completed successfully | Payment confirmed by gateway |
payment.failed | Payment failed | Gateway rejected the payment |
payment.authorized | Payment authorized, funds held but not yet captured | Gateway authorizes the card |
payment.voided | Authorized payment voided before capture | Authorization is cancelled |
payment.refunded | Payment refunded (full or partial) | A refund is processed |
Settlement Events
| Event | Description | When Triggered |
|---|---|---|
settlement.completed | Settlement payout completed | Funds transferred to your bank |
settlement.failed | Settlement payout failed | Payout failed; funds returned to wallet |
Webhook Payload Structure
All webhooks follow this structure:
{
"id": "evt_1234567890",
"event": "payment.success",
"timestamp": "2024-11-29T10:30:00.000Z",
"version": "1.0",
"data": { ... }
}
payment.success Payload
{
"id": "evt_1712000000000_abc123def",
"event": "payment.success",
"timestamp": "2026-04-01T10:30:00.000Z",
"version": "1.0",
"data": {
"orderId": "ORD_1712000000000_abc123",
"transactionId": "TXN_1712000000000_xyz789",
"externalOrderId": "YOUR_ORDER_123",
"amount": 100.00,
"currency": "USD",
"status": "success",
"paymentMethod": "crypto",
"customer": {
"name": "John Doe",
"email": "john@example.com",
"phone": "+1234567890"
},
"metadata": {},
"gatewayPaymentId": "pay_gateway_abc123",
"completedAt": "2026-04-01T10:30:00.000Z",
"createdAt": "2026-04-01T10:25:00.000Z"
}
}
payment.failed Payload
{
"id": "evt_1712000000000_def456ghi",
"event": "payment.failed",
"timestamp": "2026-04-01T10:30:00.000Z",
"version": "1.0",
"data": {
"orderId": "ORD_1712000000000_abc123",
"transactionId": "TXN_1712000000000_xyz789",
"externalOrderId": "YOUR_ORDER_123",
"amount": 100.00,
"currency": "USD",
"status": "failed",
"paymentMethod": "card",
"customer": {
"name": "John Doe",
"email": "john@example.com",
"phone": "+1234567890"
},
"metadata": {},
"failureReason": "3D Secure authentication failed",
"failureCode": "20151",
"failedAt": "2026-04-01T10:30:00.000Z",
"createdAt": "2026-04-01T10:25:00.000Z"
}
}
failureCode follows Uplef's unified 5-digit format. See the Failure codes reference for the complete list.
payment.authorized Payload
Sent when a gateway authorizes a payment but hasn't captured it yet. Same data shape as payment.success, with status: "authorized" and no completedAt.
{
"id": "evt_1712000000000_aut123abc",
"event": "payment.authorized",
"timestamp": "2026-04-01T10:30:00.000Z",
"version": "1.0",
"data": {
"orderId": "ORD_1712000000000_abc123",
"transactionId": "TXN_1712000000000_xyz789",
"externalOrderId": "YOUR_ORDER_123",
"amount": 100.00,
"currency": "USD",
"status": "authorized",
"paymentMethod": "card",
"customer": {
"name": "John Doe",
"email": "john@example.com",
"phone": "+1234567890"
},
"metadata": {},
"gatewayPaymentId": "pay_gateway_abc123",
"createdAt": "2026-04-01T10:25:00.000Z"
}
}
payment.voided Payload
Sent when an authorized payment is voided before capture. Same shape with status: "voided".
{
"id": "evt_1712000000000_void456def",
"event": "payment.voided",
"timestamp": "2026-04-01T10:35:00.000Z",
"version": "1.0",
"data": {
"orderId": "ORD_1712000000000_abc123",
"transactionId": "TXN_1712000000000_xyz789",
"externalOrderId": "YOUR_ORDER_123",
"amount": 100.00,
"currency": "USD",
"status": "voided",
"paymentMethod": "card",
"customer": {
"name": "John Doe",
"email": "john@example.com",
"phone": "+1234567890"
},
"metadata": {},
"gatewayPaymentId": "pay_gateway_abc123",
"createdAt": "2026-04-01T10:25:00.000Z"
}
}
payment.refunded Payload
Sent when a refund is processed. Carries the base transaction fields plus a nested refund object with the refund details. Fires for both full and partial refunds (isFullRefund distinguishes them).
{
"id": "evt_1712000000000_ref789jkl",
"event": "payment.refunded",
"timestamp": "2026-04-01T11:00:00.000Z",
"version": "1.0",
"data": {
"orderId": "ORD_1712000000000_abc123",
"transactionId": "TXN_1712000000000_xyz789",
"externalOrderId": "YOUR_ORDER_123",
"amount": 100.00,
"currency": "USD",
"status": "refunded",
"paymentMethod": "card",
"customer": {
"name": "John Doe",
"email": "john@example.com",
"phone": "+1234567890"
},
"metadata": {},
"gatewayPaymentId": "pay_gateway_abc123",
"refund": {
"refundId": "REF_abc123",
"refundedAmount": 100.00,
"totalRefunded": 100.00,
"remainingAmount": 0,
"reason": "Customer requested refund",
"gatewayRefundId": "re_gateway_xyz",
"processedAt": "2026-04-01T11:00:00.000Z",
"initiatedBy": "merchant",
"isFullRefund": true
}
}
}
settlement.completed Payload
{
"id": "evt_1712000000000_stl012mno",
"event": "settlement.completed",
"timestamp": "2026-04-01T12:00:00.000Z",
"version": "1.0",
"data": {
"settlementId": "STL_abc123",
"amount": 500.00,
"currency": "USD",
"status": "completed",
"utr": "UTR123456789",
"completedAt": "2026-04-01T12:00:00.000Z"
}
}
settlement.failed Payload
{
"id": "evt_1712000000000_stl345pqr",
"event": "settlement.failed",
"timestamp": "2026-04-01T12:00:00.000Z",
"version": "1.0",
"data": {
"settlementId": "STL_abc123",
"amount": 500.00,
"currency": "USD",
"status": "failed",
"failureReason": "Insufficient balance in payout account",
"failedAt": "2026-04-01T12:00:00.000Z"
}
}
Signature Verification
Always verify webhook signatures to ensure authenticity. Every webhook includes the signature header X-Uplef-Signature.
The signature is a lowercase hex HMAC-SHA256 of the raw request body, keyed with your webhook secret:
X-Uplef-Signature = lowercase_hex( HMAC_SHA256( raw_request_body, webhook_secret ) )
Compute the HMAC over the exact bytes you received. Do not parse the JSON and re-serialize it (e.g. JSON.stringify(req.body), json.dumps(request.json), json_encode($payload)).
Re-serializing changes the bytes and breaks the signature, because each language formats JSON differently:
- Numbers: our body contains
"amount": 100.00, which is transmitted as100. Python'sjson.dumpsre-emits it as100.0— a different string, so a different signature. - Non-ASCII: a name like
Joséis sent as-is, but Python'sjson.dumpsescapes the accented character to a\uXXXXsequence by default — again, different bytes. - Spacing and key order can also differ between libraries.
Always capture the raw body first, verify the signature, and only then parse the JSON.
- Node.js
- Python
- PHP
- Ruby
- Go
const crypto = require('crypto');
const express = require('express');
const app = express();
// Keep the raw body so the signature is checked against the exact bytes we received.
app.use(express.json({
verify: (req, res, buf) => { req.rawBody = buf; },
}));
function verifyWebhookSignature(rawBody, signature, secret) {
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(rawBody) // raw bytes — NOT JSON.stringify(req.body)
.digest('hex');
const received = Buffer.from(signature || '', 'utf8');
const expected = Buffer.from(expectedSignature, 'utf8');
// Lengths must match before timingSafeEqual, or it throws.
return received.length === expected.length &&
crypto.timingSafeEqual(received, expected);
}
app.post('/webhooks/uplef', (req, res) => {
const signature = req.headers['x-uplef-signature'];
if (!verifyWebhookSignature(req.rawBody, signature, process.env.WEBHOOK_SECRET)) {
console.error('Invalid webhook signature');
return res.status(401).send('Invalid signature');
}
// Signature is valid — now use the parsed body.
const { event, data } = req.body;
switch (event) {
case 'payment.success':
handlePaymentSuccess(data);
break;
case 'payment.failed':
handlePaymentFailed(data);
break;
// ... handle other events
}
// Always return 200 to acknowledge receipt
res.status(200).send('OK');
});
import hmac
import hashlib
import json
from flask import Flask, request
app = Flask(__name__)
def verify_webhook_signature(raw_body, signature, secret):
expected = hmac.new(
secret.encode(),
raw_body, # raw bytes — NOT json.dumps(request.json)
hashlib.sha256
).hexdigest()
return hmac.compare_digest(signature or '', expected)
@app.route('/webhooks/uplef', methods=['POST'])
def handle_webhook():
raw_body = request.get_data() # exact bytes received
signature = request.headers.get('X-Uplef-Signature')
if not verify_webhook_signature(raw_body, signature, WEBHOOK_SECRET):
return 'Invalid signature', 401
# Signature is valid — now parse the body.
payload = json.loads(raw_body)
event = payload.get('event')
data = payload.get('data')
if event == 'payment.success':
handle_payment_success(data)
elif event == 'payment.failed':
handle_payment_failed(data)
return 'OK', 200
<?php
function verifyWebhookSignature($rawBody, $signature, $secret) {
$expected = hash_hmac('sha256', $rawBody, $secret); // sign the raw bytes
return hash_equals($expected, $signature);
}
$rawBody = file_get_contents('php://input'); // exact bytes received
// PHP upper-cases header names: X-Uplef-Signature -> HTTP_X_UPLEF_SIGNATURE
$signature = $_SERVER['HTTP_X_UPLEF_SIGNATURE'] ?? '';
if (!verifyWebhookSignature($rawBody, $signature, WEBHOOK_SECRET)) {
http_response_code(401);
exit('Invalid signature');
}
// Signature is valid — now parse the body.
$payload = json_decode($rawBody, true);
$event = $payload['event'];
$data = $payload['data'];
switch ($event) {
case 'payment.success':
handlePaymentSuccess($data);
break;
case 'payment.failed':
handlePaymentFailed($data);
break;
}
http_response_code(200);
echo 'OK';
require 'openssl'
require 'json'
def verify_webhook_signature(raw_body, signature, secret)
expected = OpenSSL::HMAC.hexdigest('sha256', secret, raw_body) # sign the raw bytes
Rack::Utils.secure_compare(signature.to_s, expected)
end
post '/webhooks/uplef' do
raw_body = request.body.read # exact bytes received
signature = request.env['HTTP_X_UPLEF_SIGNATURE']
unless verify_webhook_signature(raw_body, signature, ENV['WEBHOOK_SECRET'])
halt 401, 'Invalid signature'
end
# Signature is valid — now parse the body.
payload = JSON.parse(raw_body)
case payload['event']
when 'payment.success'
handle_payment_success(payload['data'])
when 'payment.failed'
handle_payment_failed(payload['data'])
end
status 200
'OK'
end
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"net/http"
)
func verifyWebhookSignature(rawBody []byte, signature, secret string) bool {
mac := hmac.New(sha256.New, []byte(secret))
mac.Write(rawBody) // sign the raw bytes
expected := hex.EncodeToString(mac.Sum(nil))
return hmac.Equal([]byte(signature), []byte(expected))
}
func webhookHandler(w http.ResponseWriter, r *http.Request) {
signature := r.Header.Get("X-Uplef-Signature")
rawBody, err := io.ReadAll(r.Body) // exact bytes received
if err != nil {
http.Error(w, "Cannot read body", http.StatusBadRequest)
return
}
if !verifyWebhookSignature(rawBody, signature, webhookSecret) {
http.Error(w, "Invalid signature", http.StatusUnauthorized)
return
}
// Signature is valid — now parse the body.
var payload map[string]interface{}
json.Unmarshal(rawBody, &payload)
event := payload["event"].(string)
data := payload["data"].(map[string]interface{})
switch event {
case "payment.success":
handlePaymentSuccess(data)
case "payment.failed":
handlePaymentFailed(data)
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}
Timestamped Signature (v2) — Recommended
X-Uplef-Signature proves a webhook came from us and was not altered. It does not prove when it was sent, so a request captured in transit stays valid forever and can be replayed.
To close that gap, every webhook also carries two extra headers:
| Header | Meaning |
|---|---|
X-Webhook-Timestamp | When we sent this attempt — milliseconds since the Unix epoch |
X-Uplef-Signature-V2 | HMAC-SHA256 of {timestamp}.{raw_body}, same secret |
X-Uplef-Signature-V2 = lowercase_hex(
HMAC_SHA256( timestamp + "." + raw_request_body, webhook_secret )
)
Because the timestamp is inside the signed material, it cannot be rewritten without breaking the signature. That lets you reject anything outside a freshness window and defeat replays.
X-Uplef-Signature is unchanged and still fully supported — same value, same algorithm. Both signatures are sent on every webhook. Move to v2 when it suits you; there is no deadline and no setting to change.
Verifying v2
Two checks, both required — a signature check alone gives you no replay protection.
- Node.js
- Python
- PHP
const crypto = require('crypto');
const TOLERANCE_MS = 5 * 60 * 1000; // 5 minutes
function verifyWebhookV2(rawBody, timestamp, signature, secret) {
// 1. Freshness — reject anything too old or too far in the future.
if (!/^\d+$/.test(timestamp || '')) return false;
if (Math.abs(Date.now() - Number(timestamp)) > TOLERANCE_MS) return false;
// 2. Signature over `${timestamp}.${rawBody}`.
const expected = crypto
.createHmac('sha256', secret)
.update(`${timestamp}.${rawBody}`) // rawBody is the exact bytes received
.digest('hex');
const received = Buffer.from(signature || '', 'utf8');
const computed = Buffer.from(expected, 'utf8');
return received.length === computed.length &&
crypto.timingSafeEqual(received, computed);
}
app.post('/webhooks/uplef', (req, res) => {
const ok = verifyWebhookV2(
req.rawBody,
req.headers['x-webhook-timestamp'],
req.headers['x-uplef-signature-v2'],
process.env.WEBHOOK_SECRET
);
if (!ok) return res.status(401).send('Invalid signature');
const { event, data } = req.body;
// ... handle the event
res.status(200).send('OK');
});
import hmac, hashlib, time
TOLERANCE_MS = 5 * 60 * 1000 # 5 minutes
def verify_webhook_v2(raw_body, timestamp, signature, secret):
# 1. Freshness
if not timestamp or not timestamp.isdigit():
return False
if abs(int(time.time() * 1000) - int(timestamp)) > TOLERANCE_MS:
return False
# 2. Signature over "{timestamp}.{raw_body}"
signed = timestamp.encode() + b'.' + raw_body # raw_body is bytes
expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
return hmac.compare_digest(signature or '', expected)
@app.route('/webhooks/uplef', methods=['POST'])
def handle_webhook():
raw_body = request.get_data() # exact bytes received
if not verify_webhook_v2(
raw_body,
request.headers.get('X-Webhook-Timestamp'),
request.headers.get('X-Uplef-Signature-V2'),
WEBHOOK_SECRET,
):
return 'Invalid signature', 401
# ... handle the event
return 'OK', 200
<?php
const TOLERANCE_MS = 300000; // 5 minutes
function verifyWebhookV2($rawBody, $timestamp, $signature, $secret) {
// 1. Freshness
if (!ctype_digit((string) $timestamp)) {
return false;
}
$nowMs = (int) round(microtime(true) * 1000);
if (abs($nowMs - (int) $timestamp) > TOLERANCE_MS) {
return false;
}
// 2. Signature over "{timestamp}.{rawBody}"
$expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
return hash_equals($expected, (string) $signature);
}
$rawBody = file_get_contents('php://input'); // exact bytes received
$timestamp = $_SERVER['HTTP_X_WEBHOOK_TIMESTAMP'] ?? '';
$signature = $_SERVER['HTTP_X_UPLEF_SIGNATURE_V2'] ?? '';
if (!verifyWebhookV2($rawBody, $timestamp, $signature, WEBHOOK_SECRET)) {
http_response_code(401);
exit('Invalid signature');
}
// ... handle the event
Choosing a tolerance
5 minutes is a good default. The window has to absorb the clock difference between your server and ours, so if you see valid webhooks rejected, check your server clock (NTP) before widening it.
Each delivery attempt is signed at the moment it is sent, so a retry 24 hours later carries a current timestamp — not the original one. Never cache a timestamp across attempts, and never treat a repeated X-Webhook-ID as a stale request. Use X-Webhook-ID (or the payload's id) for idempotency, and the timestamp only for freshness.
Retry Policy
If your endpoint doesn't respond with HTTP 2xx within 30 seconds, we will retry:
| Attempt | Delay |
|---|---|
| 1st retry | 5 minutes |
| 2nd retry | 30 minutes |
| 3rd retry | 2 hours |
| 4th retry | 8 hours |
| 5th retry | 24 hours |
After 5 failed attempts, the webhook is marked as failed. You can view failed webhooks and trigger manual retries from the dashboard.
Best Practices
1. Respond Quickly
Return a 200 response as soon as possible. Process the webhook asynchronously:
app.post('/webhooks/uplef', (req, res) => {
// Immediately acknowledge receipt
res.status(200).send('OK');
// Process asynchronously
processWebhook(req.body).catch(console.error);
});
async function processWebhook(payload) {
// Do your actual processing here
const { event, data } = payload;
if (event === 'payment.success') {
await updateOrderStatus(data.orderId, 'paid');
await sendConfirmationEmail(data.customer.email);
await fulfillOrder(data.orderId);
}
}
2. Handle Idempotency
Webhooks may be delivered more than once. Use the event id to deduplicate:
const processedEvents = new Set(); // Use Redis in production
async function processWebhook(payload) {
if (processedEvents.has(payload.id)) {
console.log('Duplicate webhook, skipping:', payload.id);
return;
}
processedEvents.add(payload.id);
// Process the event...
}
3. Always Verify Signatures
Never trust webhook data without verifying the signature. This prevents attackers from spoofing webhooks.
4. Use HTTPS
Your webhook endpoint must use HTTPS in production. This ensures the webhook data is encrypted in transit.
5. Log Everything
Keep detailed logs of webhook events for debugging:
app.post('/webhooks/uplef', (req, res) => {
console.log('Webhook received:', {
id: req.body.id,
event: req.body.event,
timestamp: req.body.timestamp,
});
// Process webhook...
res.status(200).send('OK');
});
6. Handle All Events
Always have a default case for unknown events:
switch (event) {
case 'payment.success':
// ...
break;
case 'payment.failed':
// ...
break;
default:
console.log('Unknown event type:', event);
}
Testing Webhooks
Using Dashboard
- Go to Settings → Webhooks → Test
- Select an event type
- Click Send Test Webhook
Using CLI (coming soon)
uplef webhooks trigger payment.success --order ORD_123
Webhook Endpoint Requirements
- Must accept POST requests
- Must return HTTP 2xx within 30 seconds
- Must accept
application/jsoncontent type - Should use HTTPS (required in production)
- Should verify signatures
Troubleshooting
Webhooks Not Arriving
- Check your webhook URL is correct in dashboard
- Verify your server is publicly accessible
- Check firewall/security group settings
- Look at webhook delivery logs in dashboard
Signature Verification Failing
- Ensure you're using the correct webhook secret (from Settings → Webhooks)
- Sign the raw request body bytes, not a re-serialized copy of the parsed JSON — re-serializing changes number formatting (
100.00→100), spacing, key order, and non-ASCII escaping, all of which break the signature - Make sure your framework isn't parsing and discarding the raw body before you read it (use Express's
verifyhook, Flask'srequest.get_data(), or readphp://input/request.bodydirectly) - Confirm the header name is
X-Uplef-Signatureand you compare it as a lowercase hex digest
Duplicate Webhooks
This is normal behavior for retries. Implement idempotency handling using the event id.