Skip to content
YusrDocs

Webhooks#

Webhooks are HTTPS requests that Yusr sends to your server when something happens: a transfer arrives, an account expires, a settlement is paid out. They are the most reliable way to confirm payments, because they reach your backend even if the customer closes the checkout page.

Every webhook is signed, retried for about 22 hours if your server doesn't answer, and delivered at least once.

Event types#

EventSent when
transaction.paidThe exact amount arrived before expiry, or a top-up completed an underpaid transaction.
transaction.underpaidLess than the requested amount arrived. Sent again for each further partial transfer.
transaction.overpaidMore than the requested amount arrived.
transaction.expiredThe account expired without receiving any money.
transaction.late_paymentMoney arrived after the transaction expired or was cancelled.
transaction.reversedEverything received was returned to the payer.
transaction.cancelledYou cancelled a pending transaction.
settlement.completedA settlement was paid out to your bank account.

Each endpoint subscribes to a list of event types. If you don't pass events when you create an endpoint, it receives all of them.

The payload#

Every webhook is a POST with a JSON body. The data object holds the full, current transaction (or settlement for settlement.completed), so you rarely need a follow-up API call.

HTTP
POST /webhooks/yusr HTTP/1.1
Content-Type: application/json
User-Agent: Yusr-Webhooks/1.0
X-Yusr-Event-Id: evt_01JA9QB2V8K1M3N5P7Q9R2S4T6
X-Yusr-Event-Type: transaction.paid
X-Yusr-Timestamp: 1791295632
X-Yusr-Signature: v1=dc0334c8b6bb54fe399933e6060d0a59fdba4bc24a86a32713092944104a3463
JSON
{
  "id": "evt_01JA9QB2V8K1M3N5P7Q9R2S4T6",
  "type": "transaction.paid",
  "created_at": "2026-10-06T14:07:12.000Z",
  "mode": "live",
  "data": {
    "transaction": {
      "id": "txn_01JA9Q3K7M2V8X4N6P0R2T5W7Y",
      "object": "transaction",
      "mode": "live",
      "status": "paid",
      "amount": 2500000,
      "amount_received": 2500000,
      "fee": 37500,
      "fee_bearer": "merchant",
      "net_amount": 2462500,
      "currency": "NGN",
      "reference": "order-1042",
      "description": "Order #1042",
      "customer": { "name": "Ada Obi", "email": "ada@example.com", "phone": null },
      "payment": {
        "account_number": "9912345678",
        "bank_name": "Partner Bank",
        "account_name": "ACME STORES / YUSR",
        "amount": 2500000,
        "expires_at": "2026-10-06T14:30:00.000Z"
      },
      "flags": { "overpaid": false, "underpaid": false, "late": false },
      "payments": [
        {
          "id": "pay_01JA9QB2T3W4X5Y6Z7A8B9C0D1",
          "amount": 2500000,
          "payer_name": "ADA OBI",
          "payer_bank": "Partner Bank",
          "payer_account_number": "******4321",
          "received_at": "2026-10-06T14:07:12.000Z"
        }
      ],
      "metadata": { "cart_id": "c_88" },
      "created_at": "2026-10-06T14:00:00.000Z",
      "updated_at": "2026-10-06T14:07:12.000Z",
      "paid_at": "2026-10-06T14:07:12.000Z",
      "expires_at": "2026-10-06T14:30:00.000Z"
    }
  }
}
FieldDescription
idUnique event ID (evt_…), also sent as X-Yusr-Event-Id. Use it to deduplicate.
typeThe event type, also sent as X-Yusr-Event-Type.
created_atWhen the event happened.
modetest or live.
data{ "transaction": … } for transaction events, { "settlement": … } for settlement.completed.

The same payload is pushed to realtime subscribers and returned by GET /v1/events/{id}.

Register an endpoint#

Register endpoints in the dashboard under Developers → Webhooks, or with the API. You can have up to 10 endpoints per mode, each with its own events and signing secret. Live endpoints must use https:// and resolve to a public IP address; test endpoints may use http://.

curl https://api.yusr.ng/v1/webhooks \
  -H "Authorization: Bearer $YUSR_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://shop.example.com/webhooks/yusr",
    "events": ["transaction.paid", "transaction.underpaid", "transaction.overpaid", "transaction.expired"],
    "description": "Order fulfilment"
  }'
JSON
{
  "id": "whk_01JA9QF4H8C2M6N0P3R5T7V9X1",
  "object": "webhook_endpoint",
  "mode": "test",
  "url": "https://shop.example.com/webhooks/yusr",
  "events": [
    "transaction.paid",
    "transaction.underpaid",
    "transaction.overpaid",
    "transaction.expired"
  ],
  "description": "Order fulfilment",
  "enabled": true,
  "secret": "whsec_Xq3Lr8Tz1Vb6Nm4Kp9Wd2Hs7Jc5Fg0Ye3Ua8RiM2",
  "disabled_reason": null,
  "failing_since": null,
  "created_at": "2026-10-06T14:00:00.000Z"
}

The secret is returned only in this response (and when you roll it). Store it as an environment variable such as YUSR_WEBHOOK_SECRET.

Verify signatures#

Anyone can send a POST to your webhook URL, so check every request before acting on it. Yusr signs each delivery with your endpoint's secret:

X-Yusr-Timestamp: <unix time in seconds>
X-Yusr-Signature: v1=<hex HMAC-SHA256(secret, "<X-Yusr-Timestamp>.<raw request body>")>

To verify a request:

  1. Read the raw request body as bytes, before any JSON parsing.
  2. Reject the request if X-Yusr-Timestamp is more than 5 minutes (300 seconds) away from your clock. This stops an attacker from replaying an old, validly signed request.
  3. Compute the HMAC-SHA256 of timestamp + "." + raw body with your signing secret, as lowercase hex.
  4. Compare it, in constant time, with each v1= value in X-Yusr-Signature (the header may hold several, separated by commas). Accept the request if any of them matches.
  5. Respond 400 if verification fails.

With the official libraries#

The Node.js and PHP libraries implement all of the above. Python has no official library: use the function in the Python tab, which is tested against our shared test vectors.

import express from 'express';
import { Yusr, SignatureVerificationError } from '@yusr/node';

const app = express();

app.post(
  '/webhooks/yusr',
  express.raw({ type: 'application/json' }), // raw Buffer body, not parsed JSON
  async (req, res) => {
    let event;
    try {
      event = Yusr.webhooks.constructEvent(req.body, req.headers, process.env.YUSR_WEBHOOK_SECRET); // checks the signature and the 5-minute tolerance
    } catch (err) {
      if (err instanceof SignatureVerificationError)
        return res.status(400).send('invalid signature');
      throw err;
    }

    // Deliveries are at-least-once: skip events you have already handled.
    if (await alreadyProcessed(event.id)) return res.sendStatus(200);

    switch (event.type) {
      case 'transaction.paid':
      case 'transaction.overpaid':
        await fulfilOrder(event.data.transaction.reference, event.data.transaction.amount_received);
        break;
      case 'transaction.underpaid':
        await flagUnderpayment(event.data.transaction);
        break;
      case 'transaction.expired':
        await releaseStock(event.data.transaction.reference);
        break;
    }
    await markProcessed(event.id);
    res.sendStatus(200);
  },
);

// Register JSON parsing for your other routes after the webhook route.
app.use(express.json());

Without a library#

If you can't add a dependency, these functions implement the same checks with only the standard library. They mirror the official libraries and pass the same test vectors.

import crypto from 'node:crypto';

/**
 * Returns true if the request was signed by Yusr.
 * rawBody: the request body exactly as received (Buffer or string).
 */
export function verifyYusrWebhook(
  rawBody,
  signatureHeader,
  timestampHeader,
  secret,
  tolerance = 300,
  now = Math.floor(Date.now() / 1000),
) {
  if (!signatureHeader || !timestampHeader || !/^\d+$/.test(timestampHeader.trim())) return false;
  const timestamp = timestampHeader.trim();
  if (tolerance > 0 && Math.abs(now - Number(timestamp)) > tolerance) return false; // possible replay
  const expected = crypto
    .createHmac('sha256', secret)
    .update(Buffer.concat([Buffer.from(`${timestamp}.`, 'utf8'), Buffer.from(rawBody)]))
    .digest();
  let valid = false;
  for (const part of signatureHeader.split(',')) {
    const value = part.trim();
    if (!value.startsWith('v1=')) continue;
    const candidate = Buffer.from(value.slice(3).trim().toLowerCase(), 'hex');
    if (candidate.length === expected.length && crypto.timingSafeEqual(candidate, expected)) {
      valid = true;
    }
  }
  return valid;
}

Test vector#

Use this vector in a unit test of your verifier. Pass 1791295200 as the current time (the now argument), or turn the timestamp tolerance off, because the timestamp is in the past.

InputValue
Secretwhsec_test_4eC39HqLyjWDarjtT1zdp7dc
X-Yusr-Timestamp1791295200
Raw body{"id":"evt_01JA9QC0000000000000000000","type":"transaction.paid"}
X-Yusr-Signaturev1=9003c2c97f1b7c57a1257471cb2567d2a769bb0e2edce25a6f92535d903c3dce

Your verifier must accept this input, and reject it when the body changes by a single byte, when the secret is different, or when the current time is more than 300 seconds after the timestamp.

Respond quickly#

Yusr counts a delivery as successful when your endpoint returns any 2xx status within 10 seconds. Anything else (a 3xx redirect, which is not followed, a 4xx or 5xx status, a timeout or a connection error) is a failure and will be retried.

Acknowledge first, work later: verify the signature, store the event or put it on a queue, return 200, then do slow work (emails, ERP updates, PDF invoices) in a background job.

Retries#

Failed deliveries are retried with increasing delays. After the first attempt, Yusr tries again:

AttemptDelay after previous attemptTime since first attempt
1—0
21 minute1 min
35 minutes6 min
415 minutes21 min
530 minutes51 min
61 hour1 h 51 min
72 hours3 h 51 min
84 hours7 h 51 min
96 hours13 h 51 min
108 hours21 h 51 min

After the tenth attempt (about 22 hours) the delivery is marked as failed. You can still resend it from the dashboard or with the API. If an endpoint keeps failing for 3 days, it is disabled automatically: its enabled becomes false and disabled_reason explains why. Fix the endpoint, then re-enable it.

Every attempt is logged with its status code, latency and the first 2,000 characters of your response body. See Developers → Webhooks in the dashboard.

Handle duplicates and ordering#

Delivery is at least once. A retry after a timeout, a manual resend or a network glitch can deliver the same event twice. Make your handler idempotent:

  • Record each processed event id (or the X-Yusr-Event-Id header) in a table with a unique constraint, and skip events you have already seen.
  • Make the business action itself idempotent too, for example "mark order 1042 as paid" rather than "add ₦25,000 to the balance".

Events can also arrive out of order, for example transaction.paid before a delayed transaction.underpaid retry. Use the status inside the payload, which is always the transaction's state when the event was created, and compare updated_at with what you have stored. When in doubt, fetch the latest state with GET /v1/transactions/{id}.

Send a test event#

Send a signed sample event to an endpoint to check your handler end to end. The test event is a transaction.paid event for a placeholder transaction (txn_test_00000000000000000000, reference test-webhook, metadata {"test": true}), so make sure your handler doesn't ship a real order for it.

curl -X POST https://api.yusr.ng/v1/webhooks/whk_01JA9QF4H8C2M6N0P3R5T7V9X1/test \
  -H "Authorization: Bearer $YUSR_SECRET_KEY"

The call waits for the attempt and returns the delivery result:

JSON
{
  "id": "whd_01JA9QG6K0M2P4R6T8V0X2Z4B6",
  "object": "webhook_delivery",
  "event_id": "evt_01JA9QG6J8B0D2F4H6K8M0P2R4",
  "event_type": "transaction.paid",
  "endpoint_id": "whk_01JA9QF4H8C2M6N0P3R5T7V9X1",
  "url": "https://shop.example.com/webhooks/yusr",
  "attempt": 1,
  "status": "succeeded",
  "status_code": 200,
  "latency_ms": 83,
  "response_body": "ok",
  "error": null,
  "next_retry_at": null,
  "delivered_at": "2026-10-06T14:00:01.029Z",
  "is_test": true,
  "created_at": "2026-10-06T14:00:00.862Z",
  "updated_at": "2026-10-06T14:00:01.031Z"
}

In the sandbox you can also trigger real events with the simulator.

Test locally#

Yusr's servers deliver webhooks, so a URL like http://localhost:3000/webhooks would point at our own machines, not yours. To receive events on your laptop:

  1. Start your app locally, for example on port 3000.
  2. Run a tunnelling service such as ngrok or cloudflared to get a public HTTPS URL that forwards to that port.
  3. Register the tunnel URL as a test-mode endpoint and copy its secret.
  4. Create a sandbox transaction and simulate a payment, or send a test event.

To unit test your handler without any network, sign a payload yourself with the library helpers and post it to your route:

import { Yusr } from '@yusr/node';

const payload = JSON.stringify({
  id: 'evt_test_1',
  type: 'transaction.paid',
  created_at: new Date().toISOString(),
  mode: 'test',
  data: { transaction: { id: 'txn_test_1', reference: 'order-1042', status: 'paid' } },
});
const headers = Yusr.webhooks.generateTestHeaders({ payload, secret: 'whsec_test' });

await fetch('http://localhost:3000/webhooks/yusr', {
  method: 'POST',
  headers: { 'content-type': 'application/json', ...headers },
  body: payload,
});

Manage endpoints#

Update, disable, delete and inspect endpoints with the API or the dashboard.

# List
curl https://api.yusr.ng/v1/webhooks -H "Authorization: Bearer $YUSR_SECRET_KEY"

# Disable (or change "url", "events", "description")
curl -X PATCH https://api.yusr.ng/v1/webhooks/whk_01JA9QF4H8C2M6N0P3R5T7V9X1 \
  -H "Authorization: Bearer $YUSR_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "enabled": false }'

# Delete
curl -X DELETE https://api.yusr.ng/v1/webhooks/whk_01JA9QF4H8C2M6N0P3R5T7V9X1 \
  -H "Authorization: Bearer $YUSR_SECRET_KEY"

Deleting returns { "id": "whk_…", "object": "webhook_endpoint", "deleted": true }.

Roll the signing secret#

Roll a secret if it may have leaked, or as routine hygiene. The new secret takes effect immediately: every delivery after the roll is signed with the new secret only, and the response is the only time you see it.

curl -X POST https://api.yusr.ng/v1/webhooks/whk_01JA9QF4H8C2M6N0P3R5T7V9X1/roll-secret \
  -H "Authorization: Bearer $YUSR_SECRET_KEY"
JSON
{ "secret": "whsec_Pf7Gk2Wq9Zt4Bn1Hx6Vc3Lm8Rs0Dy5Ej2Ku7Ao4T" }

Events and resending#

Every webhook corresponds to an event that you can list, fetch and resend. This is useful for reconciliation and for recovering after an outage on your side.

# Events for one transaction
curl -G https://api.yusr.ng/v1/events \
  -H "Authorization: Bearer $YUSR_SECRET_KEY" \
  --data-urlencode "transaction=txn_01JA9Q3K7M2V8X4N6P0R2T5W7Y"

# One event
curl https://api.yusr.ng/v1/events/evt_01JA9QB2V8K1M3N5P7Q9R2S4T6 \
  -H "Authorization: Bearer $YUSR_SECRET_KEY"

# Deliver it again to your endpoints
curl -X POST https://api.yusr.ng/v1/events/evt_01JA9QB2V8K1M3N5P7Q9R2S4T6/resend \
  -H "Authorization: Bearer $YUSR_SECRET_KEY"

GET /v1/events accepts type, transaction, limit (1–100, default 20) and starting_after. A resend queues a new delivery to every enabled endpoint subscribed to the event type, or only to one endpoint if you pass { "endpoint_id": "whk_…" }, and returns { "object": "resend", "queued": 1 }.

Security checklist#

  • Verify the signature and timestamp on every request, using the raw body.
  • Serve your endpoint over HTTPS (required in live mode).
  • Store signing secrets like passwords: environment variables or a secrets manager, never in code.
  • Deduplicate by event id, and make fulfilment idempotent.
  • Treat the webhook as a trigger, and the amounts inside it as the source of truth only after verification.
  • Return 2xx quickly and do slow work asynchronously.