Appearance
Webhooks
Webhooks let TiruPay proactively notify your service whenever something meaningful happens - a payment is updated, a customer changes, a balance is topped up, and more. Instead of polling the API for changes, your service receives an HTTP POST to a URL you register.
WARNING
If you are using Webhooks, always verify the signature of incoming requests before processing them. See Payload Signing for details.
How Webhooks Work
- Register a URL - Create a
WebhookRegistryentry for your service with the URL TiruPay should deliver events to. - Events fire - Whenever a relevant event occurs in TiruPay (e.g. an order is completed), TiruPay sends a signed HTTP POST to every active registered URL for that service.
- Verify and process - Your endpoint verifies the signature, reads the payload, and acts on it.
WebhookRegistry
A WebhookRegistry ties a callback URL to a service. Each service can have multiple registries - useful for routing events to different backends or environments.
| Field | Type | Description |
|---|---|---|
id | string | Unique identifier |
name | string | Human-readable label |
service_id | string | The service this registry belongs to |
url | string | The endpoint TiruPay will POST to |
is_active | boolean | Whether this registry receives events |
secret | string | HMAC signing secret (only returned on creation) |
created_at | datetime | When the registry was created |
updated_at | datetime | When the registry was last updated |
Secret is shown only once
The secret is included in the response when the registry is first created. It is never returned again. Store it securely immediately after creation.
Payload Structure
Every webhook POST has a JSON body with the following fields:
| Field | Type | Description |
|---|---|---|
webhook_reason | string | The event type that triggered this webhook (see Event Types) |
service_id | string | The service the event belongs to |
relevant_id | string | The primary ID of the entity that changed (e.g. payment ID, order ID) |
data | object | The full entity data at the time of the event |
created_at | datetime | When this webhook was dispatched (ISO 8601, UTC) |
Example Payload
json
{
"webhook_reason": "payment_updated",
"service_id": "svc_abc123",
"relevant_id": "pay_xyz789",
"created_at": "2026-04-23T12:00:00Z",
"data": {
"id": "pay_xyz789",
"order_id": "ord_456",
"status": "paid"
}
}Event Types
| Event | webhook_reason | relevant_id | Description |
|---|---|---|---|
| Payment updated | payment_updated | Payment ID | A payment changed status (e.g. paid, failed, charged back) |
| Order updated | order_updated | Order ID | An order was created, completed, cancelled, or otherwise changed |
| Customer updated | customer_updated | Customer ID | Customer data was changed, or feature assignments were updated |
| Customer rating changed | customer_rating_changed | Customer ID | A customer's scoring or rating changed |
| Price change group event | price_change_group_event | PriceChangeGroup ID | A price change group was created or processed |
| Balance updated | balance_updated | Balance ID | A customer's balance was topped up or modified |
| Coupon fully used | coupon_fully_used | Coupon ID | A coupon reached its max_redemptions limit |
| Payment methods changed | payment_methods_changed | Service ID | The list of available payment methods for the service changed |
| Subscription updated | subscription_updated | Order ID | A subscription's status changed |
| Trial started | trial_started | Subscription ID | A Trial started. The payload is the subscription |
| Trial ending soon | trial_ending_soon | Subscription ID | The customer was reminded that the Trial ends soon |
| Trial updated | trial_updated | Subscription ID | The end of the Trial was moved |
| Trial ended | trial_ended | Subscription ID | The Trial ended. trial_end_reason tells why: expired, converted, upgraded, ended_by_service or terminated |
| Test | test | "test_id" | Sent when triggering a manual test delivery |
Payload Signing
TiruPay signs every webhook using HMAC-SHA256 so your endpoint can verify the request is genuine. The signature is sent in the X-Signature header.
TIP
This equals the signing method used by GitHub and other famous services, so if you've implemented webhook verification for those services, you can reuse the same logic here.
How the Signature Is Computed
- Serialize the JSON body with sorted keys.
- Compute
HMAC-SHA256of the serialized string using the registry'ssecretas the key. - Hex-encode the result and prepend
sha256=.
How to Verify
Compare the X-Signature header against the expected signature. Always use a constant-time comparison to prevent timing attacks.
python
import hashlib
import hmac
import json
def verify_signature(payload: dict, secret: str, signature: str) -> bool:
secret_bytes = secret.encode("utf-8")
payload_string = json.dumps(payload, sort_keys=True, default=str).encode("utf-8")
expected = "sha256=" + hmac.new(secret_bytes, payload_string, digestmod=hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, signature)typescript
import { createHmac, timingSafeEqual } from "crypto";
function verifySignature(payload: object, secret: string, signature: string): boolean {
const body = JSON.stringify(Object.keys(payload).sort().reduce((acc, key) => {
acc[key] = (payload as Record<string, unknown>)[key];
return acc;
}, {} as Record<string, unknown>));
const expected = "sha256=" + createHmac("sha256", secret).update(body).digest("hex");
return timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
}go
import (
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"encoding/json"
"fmt"
)
// VerifySignature mimics the Python hmac verification logic
func VerifySignature(payload map[string]interface{}, secret string, signature string) bool {
// 1. Serialize payload to JSON.
// Go's json.Marshal sorts map keys alphabetically by default.
payloadBytes, err := json.Marshal(payload)
if err != nil {
return false
}
// 2. Initialize HMAC with SHA256
h := hmac.New(sha256.New, []byte(secret))
h.Write(payloadBytes)
// 3. Format the expected string
expectedHash := hex.EncodeToString(h.Sum(nil))
expectedSignature := "sha256=" + expectedHash
// 4. Constant-time comparison to prevent timing attacks
return subtle.ConstantTimeCompare([]byte(expectedSignature), []byte(signature)) == 1
}java
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.util.Map;
import javax.crypto.Mac;
public class SignatureVerifier {
private static final String HMAC_SHA256 = "HmacSHA256";
public static boolean verifySignature(Map<String, Object> payload, String secret, String signature) {
try {
// 1. Serialize payload with sorted keys
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
String payloadString = mapper.writeValueAsString(payload);
// 2. Initialize HMAC-SHA256
SecretKeySpec secretKeySpec = new SecretKeySpec(
secret.getBytes(StandardCharsets.UTF_8),
HMAC_SHA256
);
Mac mac = Mac.getInstance(HMAC_SHA256);
mac.init(secretKeySpec);
// 3. Compute the hash
byte[] hashBytes = mac.doFinal(payloadString.getBytes(StandardCharsets.UTF_8));
// 4. Convert to Hex
StringBuilder hexString = new StringBuilder();
for (byte b : hashBytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
String expectedSignature = "sha256=" + hexString.toString();
// 5. Constant-time comparison (MessageDigest.isEqual is timing-attack safe)
return MessageDigest.isEqual(
expectedSignature.getBytes(StandardCharsets.UTF_8),
signature.getBytes(StandardCharsets.UTF_8)
);
} catch (Exception e) {
return false;
}
}
}rust
use hmac::{Hmac, Mac};
use sha2::Sha256;
use serde_json::to_string;
use std::collections::BTreeMap;
use hex;
// Use a BTreeMap to ensure keys are always sorted alphabetically,
// mimicking Python's sort_keys=True.
type Payload = BTreeMap<String, serde_json::Value>;
type HmacSha256 = Hmac<Sha256>;
fn verify_signature(payload: &Payload, secret: &str, signature: &str) -> bool {
// 1. Serialize payload to JSON string
// serde_json + BTreeMap ensures the output is deterministic.
let payload_string = match serde_json::to_string(payload) {
Ok(s) => s,
Err(_) => return false,
};
// 2. Initialize HMAC-SHA256 with the secret
let mut mac = HmacSha256::new_from_slice(secret.as_bytes())
.expect("HMAC can take key of any size");
// 3. Update with payload bytes
mac.update(payload_string.as_bytes());
// 4. Finalize and hex encode
let result = mac.finalize();
let expected_hash = hex::encode(result.into_bytes());
let expected_signature = format!("sha256={}", expected_hash);
// 5. Constant-time comparison to prevent timing attacks
// We compare as bytes using a secure comparison.
if expected_signature.len() != signature.len() {
return false;
}
// crypto-common/subtle crate provides constant-time equality
// for Mac results, but for the full string:
ring::constant_time::verify_slices_are_equal(
expected_signature.as_bytes(),
signature.as_bytes()
).is_ok()
}Request Headers
Every webhook request includes:
| Header | Value |
|---|---|
Content-Type | application/json |
X-Signature | sha256=<hex_digest> |
User-Agent | TiruPay-Webhooks/1.0 |
Always verify the signature
Never process a webhook payload without verifying its signature first. Without verification, any party that knows your URL could send forged events.
Testing
You can trigger a test delivery at any time via:
POST /webhooks/registry/{registry_id}/test
This sends a test event to the registered URL with a dummy payload. The delivery is logged in Webhook Logs just like a real event, so you can inspect request and response details.
TIP
Test webhooks are signed as real webhooks would. Use test webhooks to verify your signature verification!
Webhook Logs
Every delivery attempt is logged regardless of whether the request succeeded. Logs are useful for debugging missed events or inspecting what TiruPay actually sent.
| Field | Description |
|---|---|
payload | The exact JSON body that was sent |
response_status | The HTTP status code returned by your endpoint (-1 if the request failed entirely) |
response_body | The response body from your endpoint |
request_header | The headers TiruPay sent |
response_header | The headers your endpoint returned |
attempt_number | 1-based attempt count for this delivery. The initial send is attempt 1; a retry increments this. |
next_retry_at | When the next retry is due, if this attempt failed and a retry is still pending. null once delivered or once retries are exhausted. |
created_at | When this attempt was made |
Automatic retries with backoff
If a delivery fails - any non-2xx response, or a connection/timeout error - TiruPay retries it automatically, up to 5 times, with a growing pause between attempts: 1 minute, 5 minutes, 30 minutes, 2 hours, then 12 hours. That's up to 6 attempts in total (the initial send plus 5 retries). A 2xx response at any attempt stops further retries.
A retry resends the identical payload and signature that failed - build your handler to be idempotent (safe to process the same event more than once) rather than assuming every delivery is new.
If a newer delivery for the same event (same reason, service and relevant ID) to the same registry already succeeded by the time an older delivery's retry comes due, that retry is dropped rather than sent - so you never receive a stale payload after you've already received fresher data for the same object.
Once all 5 retries are exhausted, the delivery is marked permanently failed and a webhook_delivery_failed notification fires. Use the test endpoint to trigger a fresh delivery, or re-fetch the relevant resource via the API.
Delivery Guarantees
- TiruPay delivers webhooks asynchronously via a background job queue.
- Your endpoint has 25 seconds to respond before the request times out.
- Return any
2xxstatus code to acknowledge the event. Any other status code is recorded as a failure in the logs.
Respond quickly
Return a 200 OK immediately and process the event asynchronously in your own system. Long-running processing in the webhook handler risks timeouts.
Good to know
Multiple registries
A service can have multiple active registries. All of them receive every event. This is useful for fan-out scenarios (e.g. sending events to both a production backend and a logging service).
Deactivating registries
Set is_active: false on a registry to stop deliveries without deleting the registry and losing its secret and log history.
Payload shape can evolve
The data field contains the model dump of the relevant entity at the time of the event. As TiruPay adds new fields to its models, new keys may appear in data. Make sure your handler ignores unknown fields rather than failing on them.
Access Control
WebhookRegistry
| Role | Can list | Can view | Can create | Can update |
|---|---|---|---|---|
| User | - | - | - | - |
| Service | Own service | Own service | Own service | Own service |
| Admin | Own services | Own services | Own services | Own services |
| Superadmin | All | All | All | All |
Webhook Logs
| Role | Can list | Can view |
|---|---|---|
| User | - | - |
| Service | Own service | Own service |
| Admin | Own services | Own services |
| Superadmin | All | All |
Relationships
- Notifications - The sibling admin-facing system. A webhook delivery that has exhausted all its retries fires a
webhook_delivery_failednotification. - Services - Each WebhookRegistry belongs to one service and only receives events for that service.
- Payments - Payment status changes fire
payment_updatedevents. - Orders - Order lifecycle transitions fire
order_updatedandsubscription_updatedevents. - Customers - Customer and feature changes fire
customer_updatedevents. - Balances - Balance top-ups and modifications fire
balance_updatedevents. - Coupons - Coupon exhaustion fires
coupon_fully_usedevents. - Scheduled Price Changes - Group creation and processing fire
price_change_group_eventevents.