# Webhook Validation

## Webhook Signature Verification (Optional but recommended for security purposes, ensuring that the webhook is actually being received from SX.)
When you set `webhookUrl` while creating a payment link, SX Digital Pay signs every webhook request (`payment_link.created`, `payment_link.status_changed`, `payment_link.payment_status_changed`).

Headers:
- `x-sxpay-signature`: HMAC-SHA256 hex digest of `"{timestamp}.{rawBody}"` using the link's `webhookSecret`.
- `x-sxpay-timestamp`: Epoch milliseconds (use to prevent replay).

Verification steps:
1) Read the raw request body (exact bytes, before JSON parse).
2) Compute `expected = HMAC_SHA256(webhookSecret, timestamp + "." + rawBody)`.
3) Compare `expected` with `x-sxpay-signature` using constant-time comparison.
4) Optionally reject if the timestamp is too old (e.g., > 5 minutes) to mitigate replay attacks.

## Alternative or Complementary Validation (Source of Truth)
In addition to (or instead of) signature verification, you can use the `get link details` endpoint as the source of truth before running internal processes. This is especially useful when you want to confirm the current payment link state or avoid acting on out-of-order or duplicated webhook deliveries.

Recommended flow:
1) Receive the webhook call and parse the payload to extract the payment link identifier.
2) Call `get link details` using your API credentials.
3) Use the API response as the authoritative state for the link/payment.
4) Run internal processes (e.g., crediting balance, updating orders) based on the API response.

Notes:
- This approach can be combined with signature verification for stronger security.
- If the webhook payload conflicts with the API response, prefer the API response.
- Keep the `get link details` request lightweight and idempotent to handle webhook retries safely.

### Node.js Example
```js
import crypto from 'node:crypto'

function verifySignature({ rawBody, signature, timestamp, webhookSecret }) {
  const expected = crypto
    .createHmac('sha256', webhookSecret)
    .update(`${timestamp}.${rawBody}`)
    .digest('hex')

  if (!crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature))) {
    throw new Error('Invalid signature')
  }
}
```

### Handling Failures
- If verification fails, return a non-2xx status; SX Digital Pay will treat the delivery as failed.
- Make sure your endpoint responds quickly (ideally < 20s) and is highly available.

## Automatic Retry System
SX Digital Pay automatically retries failed webhook deliveries using exponential backoff:

| Attempt | Delay |
|---------|-------|
| 1 | Immediate |
| 2 | 1 minute |
| 3 | 5 minutes |
| 4 | 15 minutes |
| 5 | 1 hour |
| 6 | 4 hours |
| 7 | 12 hours |

Retries occur for:
- HTTP `5xx` errors
- HTTP `429` (rate limited)
- Timeouts and network errors

Retries do **NOT** occur for HTTP `4xx` errors (except 429), as these indicate permanent client-side issues.

For complete details, see [Webhook Delivery System](https://developers.sxdigitalpay.com/webhook-delivery-system-1955363m0.md).

## Best Practices
- Store `webhookSecret` securely; it is only returned at link creation time.
- Use HTTPS for `webhookUrl`.
- Log request IDs and timestamps to help debug delivery issues.
- Rotate API keys and webhook endpoints/secrets when decommissioning environments.

