# Webhook Delivery System

SX Digital Pay provides a robust webhook delivery system with automatic retries to ensure reliable event notification delivery to your endpoints.

## Delivery Behavior

### Immediate Delivery
When an event occurs (e.g., payment completed), SX Digital Pay immediately attempts to deliver the webhook to your configured `webhookUrl`. The first delivery attempt is always synchronous and immediate.

### Timeout
Each delivery attempt has a **20-second timeout**. If your endpoint does not respond within this window, the attempt is considered failed.

### Success Criteria
A webhook delivery is considered **successful** when your endpoint returns an HTTP status code in the `2xx` range (200-299).

## Automatic Retry System

If the initial delivery fails, SX Digital Pay automatically schedules retries using an exponential backoff strategy.

### Retry Schedule

| Attempt | Delay After Previous Failure |
|---------|------------------------------|
| 1       | Immediate (first attempt)    |
| 2       | 1 minute                     |
| 3       | 5 minutes                    |
| 4       | 15 minutes                   |
| 5       | 1 hour                       |
| 6       | 4 hours                      |
| 7       | 12 hours                     |

**Total retry window: approximately 17 hours** before the delivery is marked as permanently failed.

### Retry Conditions

Retries are scheduled for:
- HTTP `5xx` errors (server errors)
- HTTP `429` (rate limited)
- Connection timeouts
- Network errors (DNS failures, connection refused, etc.)

Retries are **NOT** scheduled for:
- HTTP `2xx` (success - delivery complete)
- HTTP `4xx` errors (except 429) - these indicate client-side issues that won't be resolved by retrying

### Permanent Failure

A webhook delivery is marked as **permanently failed** when:
- All 6 retry attempts have been exhausted
- A non-retryable HTTP status code is received (e.g., `400`, `401`, `403`, `404`)

## Webhook Event Structure

All webhook events follow this structure:

```json
{
  "id": "evt_abc123...",
  "type": "payment_link.payment_status_changed",
  "createdAt": "2024-01-15T10:30:00.000Z",
  "data": {
    // Event-specific payload
  }
}
```

### Event Types

| Event Type | Description |
|------------|-------------|
| `payment_link.created` | Payment link was created |
| `payment_link.status_changed` | Link status changed (ACTIVE, INACTIVE, EXPIRED) |
| `payment_link.payment_status_changed` | Payment status changed (NOT_STARTED, PENDING, COMPLETED) |

## Best Practices for Your Endpoint

### 1. Respond Quickly
Return a `2xx` response as fast as possible (ideally < 1 second). Process the webhook payload asynchronously if needed.

```javascript
// Good: Acknowledge immediately, process later
app.post('/webhooks/sxpay', (req, res) => {
  // Validate signature first
  if (!verifySignature(req)) {
    return res.status(401).send('Invalid signature')
  }

  // Queue for async processing
  queue.add('process-webhook', req.body)

  // Respond immediately
  res.status(200).send('OK')
})
```

### 2. Handle Duplicates (Idempotency)
Your endpoint may receive the same event multiple times (e.g., network issues after you responded but before SX received the response). Use the `id` field to deduplicate:

```javascript
app.post('/webhooks/sxpay', async (req, res) => {
  const { id } = req.body

  // Check if already processed
  if (await isEventProcessed(id)) {
    return res.status(200).send('Already processed')
  }

  // Mark as processing before doing work
  await markEventAsProcessing(id)

  // Process the event...

  res.status(200).send('OK')
})
```

### 3. Return Appropriate Status Codes

| Scenario | Status Code | SX Behavior |
|----------|-------------|-------------|
| Success | `200-299` | Delivery marked as complete |
| Invalid signature | `401` | No retry (permanent failure) |
| Invalid payload | `400` | No retry (permanent failure) |
| Endpoint busy | `429` | Retry scheduled |
| Server error | `500` | Retry scheduled |
| Endpoint down | Timeout | Retry scheduled |

### 4. Use HTTPS
Always configure `webhookUrl` with HTTPS to ensure webhook payloads are encrypted in transit.

### 5. Implement Signature Verification
See [Webhook Validation](https://developers.sxdigitalpay.com/webhook-validation-1821299m0.md) for details on validating the `x-sxpay-signature` header.

## Monitoring Webhook Deliveries

While there is no public API to query webhook delivery status, you can:

1. **Log all incoming webhooks** on your side with timestamps and event IDs
2. **Use `GET /payment-links/{id}`** as a source of truth to verify the current state
3. **Contact support** if you suspect delivery issues: `developers@sxdigitalpay.com`

## Troubleshooting

### Not Receiving Webhooks

1. **Verify `webhookUrl` is correct** - Check the URL in your payment link creation request
2. **Check your server logs** - Look for incoming requests from SX Digital Pay
3. **Ensure HTTPS is working** - Invalid SSL certificates will cause connection failures
4. **Check firewall rules** - Your endpoint must be publicly accessible
5. **Verify response time** - Responses taking > 20 seconds will timeout

### Receiving Duplicate Events

This is expected behavior in distributed systems. Always implement idempotency using the event `id` field.

### Events Arriving Out of Order

Due to retry scheduling, events may arrive out of order (e.g., `payment_status_changed` before `created`). Use `GET /payment-links/{id}` as the source of truth, or sort events by `createdAt` before processing.

## Summary

- First delivery attempt is **immediate**
- Failed deliveries are **automatically retried** up to 6 times over ~17 hours
- Return `2xx` quickly to acknowledge receipt
- Implement **idempotency** to handle duplicates
- Use **signature verification** for security
- Use the **API as source of truth** when in doubt

