> ## Documentation Index
> Fetch the complete documentation index at: /llms.txt
> Use this file to discover all available pages before exploring further.

# Handle events safely

> Process each event once, answer fast, and never act twice on the same payment.

A correct webhook handler does four things, in this order: verify, de-duplicate, acknowledge, then work.

**1. Verify**

Check the signature and the timestamp. Reject with `401` if either fails. See [Verify
signatures](/webhooks/verify-signatures.md).

**2. De-duplicate**

Record the event `id`. If you have seen it, answer `200` and stop.

**3. Acknowledge**

Answer `2xx` straight away.

**4. Work**

Do the slow part, such as updating orders or sending email, in a background job.

## Webhook idempotency

> [!WARNING]
>
> **Treat every delivery as at-least-once.** The same event can arrive twice: when your `200` is
> lost on the network, when a retry crosses with a slow first attempt, or when someone retries it by
> hand. If your handler credits a customer each time it runs, a duplicate credits them twice.

De-duplicate on the event `id`. It is identical on every retry of the same event.

The safe way is a unique constraint, so the check and the write are one atomic step:

```sql
CREATE TABLE payve_events (
  event_id    TEXT PRIMARY KEY,
  type        TEXT NOT NULL,
  received_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
```

```javascript Node
// Returns true only the first time this event id is seen.
async function saveEventIdIfNew(event) {
  const result = await db.query(
    `INSERT INTO payve_events (event_id, type)
     VALUES ($1, $2)
     ON CONFLICT (event_id) DO NOTHING`,
    [event.id, event.type],
  );
  return result.rowCount === 1;
}
```

```python Python
# Returns True only the first time this event id is seen.
def save_event_id_if_new(event) -> bool:
    cur = db.execute(
        """INSERT INTO payve_events (event_id, type)
           VALUES (%s, %s)
           ON CONFLICT (event_id) DO NOTHING""",
        (event["id"], event["type"]),
    )
    return cur.rowcount == 1
```

```php PHP
// Returns true only the first time this event id is seen.
function save_event_id_if_new(PDO $db, array $event): bool
{
    $stmt = $db->prepare(
        'INSERT INTO payve_events (event_id, type) VALUES (?, ?)
         ON CONFLICT (event_id) DO NOTHING'
    );
    $stmt->execute([$event['id'], $event['type']]);
    return $stmt->rowCount() === 1;
}
```

> [!WARNING]
>
> Do not check with a `SELECT` and then `INSERT`. Two copies of the same event arriving together
> both pass the `SELECT`. Let the database's unique constraint decide.

### A second guard: the transaction itself

An event id check does not cover everything. An event resent through the API has a new id, and an endpoint you register twice receives the same transaction under two ids.

So make the business action idempotent too. Key it on the transaction's public id and the outcome:

```javascript
// Only moves the order forward once, however many events arrive.
await db.query(
  `UPDATE orders
      SET status = 'paid', paid_at = now()
    WHERE payve_public_id = $1 AND status <> 'paid'`,
  [event.data.public_id ?? event.data.publicId],
);
```

## Respond fast, process later

Answer within a few seconds. Payve waits up to 30 seconds, then counts the attempt as failed and retries, which produces the duplicates you are trying to avoid.

> [!TIP]
>
> Do only three things before you answer: verify, store the event id, and put the event on a queue.
> Everything else belongs in a worker.

If your queue or database is down, answer `500` or `503` so that Payve retries. Do not answer `200` for an event you failed to store.

## Branch on the event type

Decide what to do from `type`. Do not decide from `data.status`: that field holds the transaction's detailed internal state, which has more values than the four statuses the API returns.

```javascript
switch (event.type) {
  case 'payout.successful':
    await markPaid(event.data);
    break;
  case 'payout.failed':
    await markFailedAndNotify(event.data);
    break;
  case 'payin.successful':
    await confirmThenFulfil(event.data);
    break;
  case 'payin.failed':
  case 'payin.expired':
    await releaseOrder(event.data);
    break;
  case 'conversion.successful':
  case 'conversion.failed':
    await recordConversion(event.data);
    break;
  default:
    // An event type you do not know. Acknowledge it and move on.
    break;
}
```

> [!NOTE]
>
> Always answer `2xx` to an event type you do not recognise. Answering `4xx` stops retries and shows
> as a failed delivery.

## Confirm before you release value

For anything that hands over goods or money, fetch the transaction and act on what the API says now.

```javascript
async function confirmThenFulfil(data) {
  const payin = await payve(`/v1/payins/${data.id}`, {
    headers: { 'x-api-key': process.env.PAYVE_API_KEY },
  });

  // "successful" with subStatus "underpaid" credited nothing. Do not fulfil.
  if (payin.status === 'successful' && payin.subStatus !== 'underpaid') {
    await fulfilOrder(payin.merchantReference);
  }
}
```

> [!WARNING]
>
> A `payin.successful` event is also sent for a payment link that was overpaid or underpaid. An
> underpaid payment credits nothing to your wallet. Check `subStatus` on the pay-in before you
> fulfil an order.

## Events can arrive out of order

Network retries mean a later event can reach you before an earlier one. Never assume order. Use the transaction's current state from a `GET` when order matters.

## Checklist

* [ ] The signature is verified against the raw body.
* [ ] Deliveries with a timestamp more than five minutes off are rejected.
* [ ] The event `id` is stored under a unique constraint.
* [ ] The business action is idempotent on the transaction's public id.
* [ ] The handler answers `2xx` in under five seconds.
* [ ] Storage failures answer `5xx`, never `200`.
* [ ] Unknown event types answer `2xx`.
* [ ] A scheduled job reconciles transactions that never got an event.
