Skip to content

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 ​

  1. Register a URL - Create a WebhookRegistry entry for your service with the URL TiruPay should deliver events to.
  2. 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.
  3. 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.

FieldTypeDescription
idstringUnique identifier
namestringHuman-readable label
service_idstringThe service this registry belongs to
urlstringThe endpoint TiruPay will POST to
is_activebooleanWhether this registry receives events
secretstringHMAC signing secret (only returned on creation)
created_atdatetimeWhen the registry was created
updated_atdatetimeWhen 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:

FieldTypeDescription
webhook_reasonstringThe event type that triggered this webhook (see Event Types)
service_idstringThe service the event belongs to
relevant_idstringThe primary ID of the entity that changed (e.g. payment ID, order ID)
dataobjectThe full entity data at the time of the event
created_atdatetimeWhen 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 ​

Eventwebhook_reasonrelevant_idDescription
Payment updatedpayment_updatedPayment IDA payment changed status (e.g. paid, failed, charged back)
Order updatedorder_updatedOrder IDAn order was created, completed, cancelled, or otherwise changed
Customer updatedcustomer_updatedCustomer IDCustomer data was changed, or feature assignments were updated
Customer rating changedcustomer_rating_changedCustomer IDA customer's scoring or rating changed
Price change group eventprice_change_group_eventPriceChangeGroup IDA price change group was created or processed
Balance updatedbalance_updatedBalance IDA customer's balance was topped up or modified
Coupon fully usedcoupon_fully_usedCoupon IDA coupon reached its max_redemptions limit
Payment methods changedpayment_methods_changedService IDThe list of available payment methods for the service changed
Subscription updatedsubscription_updatedOrder IDA subscription's status changed
Trial startedtrial_startedSubscription IDA Trial started. The payload is the subscription
Trial ending soontrial_ending_soonSubscription IDThe customer was reminded that the Trial ends soon
Trial updatedtrial_updatedSubscription IDThe end of the Trial was moved
Trial endedtrial_endedSubscription IDThe Trial ended. trial_end_reason tells why: expired, converted, upgraded, ended_by_service or terminated
Testtest"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 ​

  1. Serialize the JSON body with sorted keys.
  2. Compute HMAC-SHA256 of the serialized string using the registry's secret as the key.
  3. 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:

HeaderValue
Content-Typeapplication/json
X-Signaturesha256=<hex_digest>
User-AgentTiruPay-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.

FieldDescription
payloadThe exact JSON body that was sent
response_statusThe HTTP status code returned by your endpoint (-1 if the request failed entirely)
response_bodyThe response body from your endpoint
request_headerThe headers TiruPay sent
response_headerThe headers your endpoint returned
attempt_number1-based attempt count for this delivery. The initial send is attempt 1; a retry increments this.
next_retry_atWhen the next retry is due, if this attempt failed and a retry is still pending. null once delivered or once retries are exhausted.
created_atWhen 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 2xx status 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 ​

RoleCan listCan viewCan createCan update
User----
ServiceOwn serviceOwn serviceOwn serviceOwn service
AdminOwn servicesOwn servicesOwn servicesOwn services
SuperadminAllAllAllAll

Webhook Logs ​

RoleCan listCan view
User--
ServiceOwn serviceOwn service
AdminOwn servicesOwn services
SuperadminAllAll

Relationships ​

  • Notifications - The sibling admin-facing system. A webhook delivery that has exhausted all its retries fires a webhook_delivery_failed notification.
  • Services - Each WebhookRegistry belongs to one service and only receives events for that service.
  • Payments - Payment status changes fire payment_updated events.
  • Orders - Order lifecycle transitions fire order_updated and subscription_updated events.
  • Customers - Customer and feature changes fire customer_updated events.
  • Balances - Balance top-ups and modifications fire balance_updated events.
  • Coupons - Coupon exhaustion fires coupon_fully_used events.
  • Scheduled Price Changes - Group creation and processing fire price_change_group_event events.