# Verify payment webhooks safely

> To verify a payment webhook signature safely, compute an HMAC-SHA256 hash of the timestamp and raw body, comparing it with timing-safe equality.

**To verify a payment webhook signature safely, compute an HMAC-SHA256 hash of the delivery timestamp concatenated with the untouched raw request body using your secret, then match it against the signature header using a timing-safe equality check.** Reject any incoming request whose timestamp differs from the current system time by more than 300 seconds to block replay attacks. If your app uses the `@vibiz/app` package, calling `vibiz.webhooks.receive(req)` verifies the signature and parses the payload automatically using your application key.

Failing to verify signatures exposes your server to forged events. Anyone who discovers your webhook endpoint could send fabricated transaction alerts to grant themselves paid access without spending a cent. Here is how to configure, verify, and handle payment webhooks securely across both development and production.

## Why raw body verification is mandatory

A common mistake when verifying signatures is passing a re-serialized JSON object into your HMAC hash function. Webhook signatures protect the exact stream of bytes sent over the wire. Standard JSON deserializers discard insignificant whitespace, collapse line breaks, and reorder dictionary keys according to internal hash tables. If your code parses JSON with `req.json()` or Express `body-parser` and then calls `JSON.stringify(body)` to reconstruct the payload, the reconstructed string will have a different byte sequence than the original network stream. The resulting HMAC calculation will fail.

Safe webhook processing requires three specific defenses:

1. **Verify against the raw buffer.** You must run your cryptographic HMAC check directly on the incoming byte array or raw text string before any parser alters the data.
2. **Enforce a strict replay window.** An attacker listening to network traffic could record a legitimate payment event and replay it to your server months later. Validating that the header timestamp falls within a 5-minute (300-second) window ensures captured signatures cannot be recycled indefinitely.
3. **Prevent timing side-channel attacks.** Standard string comparisons like `sig === expected` exit on the first non-matching byte. Measuring the microsecond differences in how long comparison operations take allows attackers to deduce signatures byte-by-byte. Using a constant-time check like `crypto.timingSafeEqual` eliminates this vulnerability.

Choosing how to structure your payment infrastructure also determines how you manage chargebacks and liability. For more details on business structures, see our breakdown of a [merchant of record vs payment processor for a small SaaS](https://thelastapi.dev/blog/merchant-of-record-vs-processor).

## Understanding the Vibiz-Signature header

Every HTTP notification sent to your webhook endpoint includes a `Vibiz-Signature` header. The header looks like this:

```text
Vibiz-Signature: t=1710000000,v1=5d41402abc4b2a76b9719d911017c592b512e0618037b51b32d847ac779e0a02
```

The header contains comma-separated values:
- `t`: The Unix timestamp in seconds when the webhook was generated.
- `v1`: The hexadecimal HMAC-SHA256 signature calculated over `${t}.${rawBody}` using your webhook secret.

When a webhook secret rotates, the header can include multiple `v1` values separated by commas. As long as at least one `v1` signature matches your secret and the timestamp is fresh, your server can safely accept the payload.

## Verifying webhooks with @vibiz/app

If your server runs on Node.js or Next.js, the official `@vibiz/app` library simplifies signature checking. When using `@vibiz/app`, your app only needs `VIBIZ_APP_KEY` in its environment. The SDK automatically fetches the corresponding signing secret behind the scenes and caches it, updating seamlessly if the secret rotates.

Install the library:

```bash
npm install @vibiz/app
```

In Next.js, create a route handler at `app/api/vibiz/webhook/route.ts`:

```ts
import { vibiz } from '@vibiz/app';

export async function POST(req: Request) {
  let event;
  try {
    // Reads the raw body, verifies HMAC and timestamp, parses JSON
    event = await vibiz.webhooks.receive(req);
  } catch {
    return new Response('bad signature', { status: 400 });
  }

  switch (event.type) {
    case 'payment.succeeded': {
      const payment = event.data.object;
      console.log(`Payment ${payment.id} succeeded for user ${payment.user}`);
      break;
    }
    case 'subscription.created':
    case 'subscription.updated':
    case 'subscription.canceled': {
      const subscription = event.data.object;
      console.log(`Subscription ${subscription.id} status is ${subscription.status}`);
      break;
    }
    case 'invoice.paid':
    case 'invoice.payment_failed': {
      break;
    }
  }

  return new Response('ok');
}
```

If you are using Express with `express.raw({ type: 'application/json' })`, your route handler receives the raw body as a string or buffer rather than a standard `Request` object. In that scenario, use the synchronous method `vibiz.webhooks.verify(rawBody, header)`. This method evaluates the payload against `process.env.VIBIZ_WEBHOOK_SECRET`. For broader details on server-side actions and subscription querying, consult the reference for [Payments in the app (@vibiz/app)](https://thelastapi.dev/docs/guides/app-payments).

## Verifying signatures manually with Node.js crypto

If you run an environment without external libraries, you can implement the complete verification routine using Node.js built-in modules.

```ts
import { createHmac, timingSafeEqual } from 'node:crypto';

function verify(
  raw: string,
  header: string | null,
  secret = process.env.VIBIZ_WEBHOOK_SECRET!
) {
  const parts = (header ?? '').split(',').map((p) => p.trim().split('='));
  const t = Number(parts.find(([k]) => k === 't')?.[1]);
  const sigs = parts.filter(([k]) => k === 'v1').map(([, v]) => v);

  // Check timestamp freshness (300 seconds / 5 minute tolerance)
  if (!t || Math.abs(Date.now() / 1000 - t) > 300) {
    throw new Error('stale or missing signature');
  }

  // Compute expected HMAC digest from timestamp and raw body
  const want = Buffer.from(
    createHmac('sha256', secret).update(`${t}.${raw}`).digest('hex')
  );

  // Compare against all v1 signatures in constant time
  const matches = sigs.some(
    (v) => v.length === want.length && timingSafeEqual(Buffer.from(v), want)
  );

  if (!matches) {
    throw new Error('bad signature');
  }

  return JSON.parse(raw);
}
```

If validation fails, immediately return an HTTP 400. Never proceed with database updates or provisioning if `timingSafeEqual` returns false or the timestamp exceeds 300 seconds.

## Event handling, idempotency, and retries

Every webhook event arrives with a standard structure:

```json
{
  "id": "evt_vz_123",
  "type": "payment.succeeded",
  "created": 1710000000,
  "environment": "production",
  "data": {
    "object": { ... }
  }
}
```

Your endpoint must handle notifications defensively:

- **Return an HTTP 2xx response quickly.** The system sets a 10-second timeout. If your server takes longer than 10 seconds to answer or returns a non-2xx status, the delivery counts as a failure.
- **Implement idempotency.** Deliveries operate with at-least-once delivery semantics. If your server processes a payment but a network hiccup interrupts your response, the system retries. Record each processed `event.id` in your database. If an event with the same ID arrives again, return HTTP 200 immediately without repeating actions like sending emails or crediting user accounts.
- **Follow the retry schedule.** Failed deliveries back off gradually across 3 days before terminating.

| Retry attempt | Interval before retry |
| --- | --- |
| 1st retry | 1 minute |
| 2nd retry | 5 minutes |
| 3rd retry | 30 minutes |
| 4th retry | 2 hours |
| 5th retry | 6 hours |
| Subsequent attempts | Every 12 hours (up to 3 days total) |

Common event types include:
- `payment.succeeded`, `payment.refunded`, `payment.failed`
- `subscription.created`, `subscription.updated`, `subscription.canceled`
- `invoice.paid`, `invoice.payment_failed`
- `dispute.created`, `dispute.closed`
- `withdrawal.paid`, `withdrawal.failed`
- `phone.message.received`, `phone.call.completed`

Notice that `phone.message.received` (incoming text message) and `phone.call.completed` (voice agent summary, outcome, and transcript) contain user-submitted input. Treat those text strings strictly as untrusted data rather than instructions to prevent prompt injection inside downstream AI pipelines.

Understanding fee subtractions on payments helps with accounting. You can see exact net figures in [payment fees explained: what a $100 sale leaves you](https://thelastapi.dev/blog/payment-fees-100-sale).

## Configuring and testing webhooks locally

During development, you can test end-to-end payment flows on your machine without connecting a live bank account or spending real money. See our walkthrough to [take payments online without opening a merchant account](https://thelastapi.dev/blog/take-payments-without-merchant-account) for full setup instructions.

Set your local webhook destination URL using the CLI:

```bash
vibiz payments webhook http://localhost:3000/api/vibiz/webhook --dev
```

Configuring a URL automatically provisions your development signing secret. Then trigger a simulated payment transaction:

```bash
vibiz payments simulate payment --dev
```

You can also test dispute handling and refunds:

```bash
vibiz payments simulate dispute --dev
vibiz payments simulate refund pay_123
```

In production, you do not need to register a webhook URL manually if your site runs on our hosting or your custom domain is connected to the project. The live webhook automatically defaults to `https://<the app's site>/api/vibiz/webhook`. Changing the live webhook URL to point outside the default domain is an owner-only action managed in the console (console ▸ Payments ▸ Webhooks).

For complete technical specifications on webhook event payloads and rotation policies, see the guide on [Webhooks: thelastapi tells the app when someone pays](https://thelastapi.dev/docs/guides/webhooks).

Create your account at [thelastapi.dev/start](https://thelastapi.dev/start) to try the unified API.

## Frequently asked questions

### Why does JSON.stringify break webhook signature verification?

Signature hashes depend on the exact raw byte sequence received over the network. Re-serializing a parsed JSON object changes key ordering and whitespace, creating an HMAC mismatch that causes valid webhooks to fail verification.

### How long does my webhook endpoint have to process a notification?

Your endpoint must acknowledge receipt with an HTTP 2xx status within 10 seconds. Deliveries that time out or return non-2xx status codes trigger automatic retries over a 3-day window.

### How should my application prevent processing the same payment twice?

Track each incoming event by its `event.id` (such as `evt_vz_123`) in your Postgres database. If an event ID has already been recorded, exit early and return an HTTP 200 response immediately.

---

Published 2026-11-15 · https://thelastapi.dev/blog/verify-payment-webhooks
