Skip to Content
ePay.lkDocs

Webhooks

Receive signed events when payments, refunds, payouts and invoices change. Verify Epay-Signature, respond fast, and handle retries idempotently.

Webhooks are how ePay tells your server that something happened — most importantly that a payment succeeded. Fulfil orders from webhooks (or a server-side API check), never from the browser redirect alone.

Set up an endpoint

  1. In the dashboard open Developers → Webhooks → Add endpoint.
  2. Enter a public HTTPS URL on your server, e.g. https://shop.example.lk/webhooks/epay.
  3. Choose the event types to receive, or * for all.
  4. Copy the signing secret (whsec_…). It's shown once — store it like a password, e.g. EPAY_WEBHOOK_SECRET.

Sandbox and production have separate endpoints and secrets. Deployed environments only deliver to public HTTPS addresses; private and loopback addresses are refused, so use a tunnel to receive sandbox events locally.

Event types

Typedata.objectSent when
payment.succeededPaymentThe payment was approved. Fulfil the order.
payment.failedPaymentAn attempt was declined (failure is set). The payer may retry unless it's a legacy one-shot payment (status: "failed").
payment.canceledPaymentCanceled by you or by the payer on the checkout
payment.expiredPaymentNot paid before expires_at
refund.createdRefundA refund was created (may be requires_approval)
refund.succeededRefundThe refund was processed
refund.failedRefundThe acquirer rejected the refund
payout.createdPayoutYou requested a payout
payout.paidPayoutThe payout reached your bank
payout.failedPayoutThe payout could not be paid to your bank
invoice.paidInvoiceAn invoice was paid through the checkout

New event types may be added. Respond 2xx to types you don't handle.

The request

ePay sends a POST with a JSON body — the event envelope — and these headers:

HeaderExample
Content-Typeapplication/json
Epay-Signaturet=1763806601,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd
Epay-Event-Idevt_6yR2mK9pQ4dL
Epay-Event-Typepayment.succeeded
User-AgentePay-Webhooks/1.0
Body
{
  "id": "evt_6yR2mK9pQ4dL",
  "object": "event",
  "type": "payment.succeeded",
  "created_at": "2026-11-22T10:16:41.000Z",
  "livemode": true,
  "environment": "production",
  "data": {
    "object": {
      "id": "pay_8Hq2LxV0cT4mZr7N",
      "object": "payment",
      "status": "succeeded",
      "amount": 125000,
      "currency": "LKR",
      "amount_refunded": 0,
      "fee": 3688,
      "net": 121312,
      "order_id": "1042",
      "source": "api",
      "payment_method": { "type": "card", "card_brand": "visa", "card_last4": "4242" },
      "failure": null,
      "metadata": { "cart_id": "c_98431" },
      "livemode": true,
      "succeeded_at": "2026-11-22T10:16:41.000Z"
    }
  }
}

data.object is the full object at the time of the event (abridged above) — the same shape as the API returns.

Verify the signature

Epay-Signature has a Unix timestamp t and a signature v1:

v1 = hex( HMAC-SHA256( key = your signing secret, message = "<t>.<raw request body>" ) )

To verify:

  1. Read the raw request body exactly as received — before any JSON parsing or re-serialisation.
  2. Split the header on , and each part on the first = to get t and v1.
  3. Reject the request if |now − t| > 300 seconds (replay protection).
  4. Compute the HMAC-SHA256 of t + "." + rawBody with your full signing secret (including the whsec_ prefix) as the key, hex-encoded.
  5. Compare it with v1 using a constant-time comparison. Reject on mismatch with 400.
webhooks.ts (Express)
import crypto from "node:crypto";
import express from "express";

const TOLERANCE_SECONDS = 300;

export function verifyEpaySignature(rawBody: string, header: string | undefined, secret: string): boolean {
  if (!header) return false;
  const parts = Object.fromEntries(
    header.split(",").map((part) => {
      const i = part.indexOf("=");
      return [part.slice(0, i).trim(), part.slice(i + 1).trim()];
    }),
  );
  const t = Number(parts.t);
  if (!Number.isInteger(t) || !parts.v1) return false;
  if (Math.abs(Math.floor(Date.now() / 1000) - t) > TOLERANCE_SECONDS) return false;

  const expected = crypto.createHmac("sha256", secret).update(`${t}.${rawBody}`).digest();
  const received = Buffer.from(parts.v1, "hex");
  return received.length === expected.length && crypto.timingSafeEqual(expected, received);
}

const app = express();

// Use the raw body for this route — express.json() would change the bytes.
app.post("/webhooks/epay", express.raw({ type: "application/json" }), async (req, res) => {
  const rawBody = req.body.toString("utf8");
  if (!verifyEpaySignature(rawBody, req.get("Epay-Signature"), process.env.EPAY_WEBHOOK_SECRET!)) {
    return res.status(400).send("invalid signature");
  }
  const event = JSON.parse(rawBody);

  // Idempotency: ignore events you've already processed.
  if (await db.webhookEvents.exists(event.id)) return res.sendStatus(200);

  await queue.enqueue(event); // do the real work asynchronously
  await db.webhookEvents.insert(event.id);
  res.sendStatus(200);
});

Common verification mistakes

  • Parsing and re-serialising the JSON before computing the HMAC (whitespace and key order change). Always use the raw bytes.
  • Using == instead of a constant-time comparison.
  • Skipping the timestamp check — without it a captured request could be replayed forever.
  • Using the sandbox secret in production (or vice versa).

Retries

A delivery succeeds when your endpoint returns any 2xx within 10 seconds. Anything else — a non-2xx status, a timeout, a TLS or connection error — is retried on this schedule:

AttemptDelay after previous failure
21 minute
35 minutes
415 minutes
51 hour
63 hours
76 hours
812 hours
924 hours

After the 9th failed attempt (about two days later) the delivery is marked dead. You can see every delivery, its response code and error, and retry it manually in Developers → Webhooks. To recover from a longer outage, list what you missed with GET /v1/events.

Best practices

  • Respond fast. Verify, persist or enqueue, return 200. Do slow work (emails, ERP sync) in a background job — the 10-second limit includes your processing time.
  • Be idempotent. Retries and network races mean you can receive the same event more than once. Store processed event.ids (also sent as Epay-Event-Id) and skip duplicates; make fulfilment itself safe to run twice.
  • Don't depend on order. Events can arrive out of order (e.g. refund.succeeded before refund.created). Use the object's status in data.object, or fetch the latest state from the API when order matters.
  • Check what you're fulfilling. On payment.succeeded, match id/order_id to your order and compare amount and currency with what you expected.
  • Check the environment. livemode is true only in production; a sandbox event should never fulfil a real order.
  • Keep the secret secret. If it leaks, add a new endpoint (new secret), switch your handler to it, then delete the old endpoint.
  • Legacy integrations that use notifyUrl receive the old md5-signed format instead — see Migrating from form-POST.

On this page