# Webhooks

OnCharge sends a signed `POST` to your webhook endpoints whenever something happens in your store: a payment succeeds or fails on any rail (card, crypto or Card to Crypto), a refund goes through, a shopper disputes a charge or its evidence is due, the cardholder's bank reports fraud, every package of an order is confirmed delivered, a payout reaches your bank or comes back, or your account needs something. Webhooks are how your store learns that an order is paid. Do not rely on the shopper's browser returning to your site.

## Set up endpoints

1. Create an HTTPS route on your server, for example `https://shop.example.com/webhooks/oncharge`, that accepts `POST` with a JSON body.
2. Add it on the **Webhooks** page of the merchant portal. A store can have up to 16 endpoints (your order system, your accounting, a monitoring tool…). For each one, choose the events it receives (every event, whole groups such as `payout.*`, or single events) and give it a description. An endpoint you added before endpoints had event choices keeps the payment, refund, chargeback and delivery events it received then; add the others on the same page. OnCharge shows each endpoint's **signing secret** (`oc_cbsec_…`) once. Store it as a server-side secret, e.g. `ONCHARGE_WEBHOOK_SECRET`.
3. Verify the signature of every request before you trust it (below), then respond with any `2xx` status within 8 seconds.

Each endpoint has its own secret, which you can rotate, and can be disabled and enabled again: a disabled endpoint is sent nothing. The page also shows every event of the last 30 days, where it went, and lets you send any of them to an endpoint again.

The platform integrations include their own endpoint, so you do not write one: add the URL they give you and paste its signing secret into their settings.

| Platform | Webhook URL to add | Where the secret goes |
|---|---|---|
| WooCommerce (plugin 1.4.0+) | `https://<your store>/?wc-api=oncharge_callback` | **Webhook Signing Secret** in the plugin settings |
| Magento 2 (beta) | `https://<your store>/oncharge/webhook` | **Callback Signing Secret** in the payment method settings |
| Wix (beta) | `https://<your site>/_functions/onchargeWebhook` | `oncharge_webhook_secret` in the Secrets Manager |

## The request

```http
POST /webhooks/oncharge HTTP/1.1
Content-Type: application/json
OnCharge-Event-Id: evt_5f0c2a8e-1b7d-4c39-9e64-2d8f1a7b3c90
OnCharge-Signature: t=1767225600,v1=e6be572e7034db173b697bf2ca8964d5a340767572bf5ddb7b5c7dad8afd1bdb
```

```json title="payment.captured"
{
  "id": "evt_5f0c2a8e-1b7d-4c39-9e64-2d8f1a7b3c90",
  "type": "payment.captured",
  "created": 1767225600,
  "livemode": true,
  "data": {
    "session_id": "8b0f6f2e-4d1a-4c4e-9a52-6f3e1d2c7b11",
    "order_id": "1001",
    "reference": "order-1001",
    "amount": 4900,
    "currency": "USD",
    "status": "captured",
    "rail": "card",
    "payment_reference": "ocpay_8b0f6f2e4d1a4c4e9a526f3e1d2c7b11",
    "payment_link_id": null,
    "payment_method": "card"
  },
  "event": "payment.captured",
  "status": "captured",
  "psp_reference": "ocpay_8b0f6f2e4d1a4c4e9a526f3e1d2c7b11"
}
```

Every event has `id`, `type`, `created`, `livemode` and `data`, and every `data` has `rail`. Payment events from a checkout carry these fields:

| Field | Meaning |
|---|---|
| `id` | Unique event ID, also in the `OnCharge-Event-Id` header. The same on every retry and replay. |
| `type` | One of the event types below. |
| `created` | Unix time the event was created. |
| `livemode` | `false` for events from test payments. |
| `data.session_id` | The checkout session the event is about. |
| `data.order_id` | Your order ID if OnCharge has it (sent at session creation or attached later), else `null`. |
| `data.reference` | The `reference` you sent when creating the session. |
| `data.amount`, `data.currency` | Minor units (cents) and ISO code. For `refund.succeeded`, the total refunded so far. Can be `null` if unknown. |
| `data.status` | The order's payment status after the event (for example `captured`, `refunded`), or `null`. |
| `data.rail` | `card`, `crypto` (a crypto checkout, or a coin paid to your wallet) or `card_to_crypto`. |
| `data.payment_reference` | OnCharge's reference for the payment (`ocpay_…`). |
| `data.payment_link_id` | The [payment link](https://oncharge.io/docs/payment-links) the checkout was made from, or `null`. |
| `data.payment_method` | How the shopper paid: `card`, `bank_debit`, `cash_app_pay`, `klarna`, `affirm` or `afterpay` ([Payment methods](https://oncharge.io/docs/payment-methods)); `null` for crypto. A `payment.pending` with `bank_debit` is still being collected: ship after `payment.captured`. |
| `data.invoice_id` | Only on a payment for an [invoice](https://oncharge.io/docs/invoices): the invoice's id. The session's `order_id` and `reference` are the invoice number. |
| `event`, `status`, `psp_reference` | Repeats of older fields kept for existing plugins, which store `psp_reference` as the order's transaction ID. A payment made before 2026-12-01 keeps its original value there; from 2026-12-01 on it is the `ocpay_` reference. New code should read `type` and `data`. |

## Payments on every rail

Card checkout, crypto checkout and payments paid straight to your own wallet use the same `payment.*` events. `data.rail` says which:

| `data.rail` | Where the payment came from |
|---|---|
| `card` | Card checkout (any card, Apple Pay, Google Pay). |
| `crypto` | A crypto checkout, or a coin paid straight to your wallet through the [crypto plugin](https://oncharge.io/docs/crypto-plugin) or the [Gateway API](https://oncharge.io/docs/gateway-api). |
| `card_to_crypto` | Card, Cash App or Venmo through the plugin or the Gateway API, paid out to your wallet in USDC. |

A payment paid to your wallet has no checkout session, so its `data` has `session_id: null` and these fields instead:

```json title="payment.captured (Card to Crypto, plugin)"
{
  "id": "evt_0a6c3e1b-9d2f-4b7a-8c5e-1f3a5c7e9b2d",
  "type": "payment.captured",
  "created": 1767225600,
  "livemode": true,
  "data": {
    "payment_id": "3b1d6c2e-7f40-4a8e-9d51-6a2f0c9e1b74",
    "payment_reference": "ocpay_3b1d6c2e7f404a8e9d516a2f0c9e1b74",
    "session_id": null,
    "order_id": "1043",
    "reference": null,
    "amount": 2500,
    "currency": "USD",
    "status": "captured",
    "rail": "card_to_crypto",
    "source": "plugin",
    "method": "cashapp",
    "coin": "USDC (Polygon)",
    "coin_amount": "23.00",
    "wallet": "0x2f1c…9a4e",
    "payment_tx": null,
    "payout_tx": "0x8b3e5d0c4f1a2b6e9d7c3a1f5e8b2d4c6a0e9f1b3d5c7a9e2f4b6d8c0a1e3f41c7"
  }
}
```

`source` is `plugin` or `gateway`, `method` is `card`, `cashapp`, `venmo` or `crypto`, `wallet` is your wallet masked, and the transaction hashes are on public chains. Gateway payments also carry `net_coin_amount` (what reached your wallet). The money is already in your wallet: OnCharge holds none of it, and it is never part of a payout.

## Event types

| `type` | When | What to do |
|---|---|---|
| `payment.pending` | The shopper has to complete an extra step; on a gateway wallet, a payment seen on the chain and not confirmed yet. | Nothing yet; wait for the next event. |
| `payment.authorized` | The payment was approved but is not captured yet. | Wait for `payment.captured` before fulfilling. |
| `payment.captured` | The payment succeeded. | Mark the order paid and fulfil it. |
| `payment.under_review` | A payment to your wallet arrived but does not match the order (for example a different amount). | Check it before you ship. `data.reason` says why. |
| `payment.capture_failed` | Capturing an approved payment failed. | Treat the order as unpaid. |
| `payment.refused` | The payment was declined. | Mark the order failed or let the shopper retry. |
| `payment.cancelled` | The payment was cancelled, or the checkout expired. | Release reserved stock. |
| `payment.expired` | The checkout or payment window expired before it was paid. | Release reserved stock. |
| `refund.succeeded` | A refund went through. | Record the refund. `data.amount` is the total refunded. |
| `refund.failed` | A refund could not be completed. | Alert your staff; the money was not returned. |
| `chargeback.opened` | The shopper disputed the payment with their bank. | Flag the order. Its payout is held. Upload evidence through [disputes](https://oncharge.io/docs/api#disputes); depending on your account, you or the OnCharge team submit the response (the dispute's `responded_by`). |
| `dispute.evidence_due` | A dispute needs its evidence by `data.evidence_due_by`. Sent once per dispute and deadline. | Upload what is missing before the date. |
| `chargeback.won` | The dispute was decided in your favour. | Optional: note it on the order. |
| `chargeback.lost` | The dispute was decided in the shopper's favour. | Note it on the order. |
| `fraud_warning.received` | The cardholder's bank reported the payment as fraud. | Do not ship. The payout is on hold, and OnCharge may refund it to stop a dispute. |
| `delivery.confirmed` | Every package of the order was confirmed delivered to the order's address. | Optional: mark the order delivered. The payout is now scheduled. |
| `payout.paid` | A payout reached your bank, or (`data.method` `instant`) your debit card, with `data.fee` taken out. `data.payout_id` is the ID [`GET /api/v1/payouts`](https://oncharge.io/docs/api#listpayouts) lists. | Reconcile it. |
| `payout.failed` | A payout could not be delivered. `data.problem` says why and what happens next. A debit card payout (`data.method` `instant`) that fails goes to your bank with your next payout. | Fix your bank details if asked to. |
| `payout.returned` | Your bank sent a payout back. | Fix your bank details; it is sent again. |
| `account.updated` | What your account can do changed (`data.account`: `status`, `payments_enabled`, `payouts_enabled`, `requirements_due`, `deadline`; `data.changed` lists what changed). | Optional: show it in your tools. |
| `account.requirements_due` | Your account needs more information by `data.deadline`. | Provide it under Settings in the portal. |
| `account.restricted` | Your account stopped taking payments or receiving payouts. `data.reason` says why. | Act on the reason. |
| `swap.created`, `swap.completed`, `swap.failed`, `swap.refunded`, `swap.expired` | A crypto conversion through the plugin or the Gateway API started or ended (`data.swap_id` is its `ocswp_` reference). | Optional: record it. |
| `subscription.created`, `subscription.updated`, `subscription.trial_will_end`, `subscription.past_due`, `subscription.paused`, `subscription.resumed`, `subscription.canceled` | A [subscription](https://oncharge.io/docs/subscriptions) started, changed (`data.change` says what), nears the end of its trial, has a failed payment being retried, paused, resumed or ended. `data` is the subscription. | Keep your records in step: grant or end access, update the customer's account. |
| `subscription.period.paid`, `subscription.period.payment_failed` | A subscription period (or a plan change) was paid, or its charge failed (`data.failure`, `data.next_attempt_at`). Each period's payment also fires the usual `payment.*` events. | On `paid`, ship the period if it ships and report its tracking with `data.session_id`: its payout waits for delivery. |

The first seven in the [webhook contract](https://oncharge.io/docs/api#webhooks) (`payment.pending`, `payment.captured`, `payment.refused`, `payment.cancelled`, `refund.succeeded`, `chargeback.opened`, `delivery.confirmed`) are the ones most stores need. Each event is sent once per change. Acknowledge (`2xx`) any type you do not handle; new types may be added. The [API reference](https://oncharge.io/docs/api#webhooks) has a sample of every event.

## Verify the signature

`OnCharge-Signature` has the form `t=<unix seconds>,v1=<hex>`:

1. Split the header on `,` and read `t` and every `v1` value.
2. Compute `expected = hex(hmac_sha256(signing_secret, t + "." + raw_body))`, where `raw_body` is the request body **exactly as received** (before any JSON parsing) and the key is your `oc_cbsec_…` secret as-is.
3. Accept the event only if `expected` equals one of the `v1` values (constant-time comparison) and `|now - t| <= 300` seconds.

Test vector: secret `oc_cbsec_example_secret_do_not_use`, `t=1767225600` and the `payment.captured` body above, serialized without whitespace, give `v1=e6be572e7034db173b697bf2ca8964d5a340767572bf5ddb7b5c7dad8afd1bdb`.

> Parse JSON only after verifying. Frameworks that parse the body for you (Express `json()`, Next.js `request.json()`) change the bytes; read the raw body instead.

### Node.js

```js title="verify-webhook.mjs" test="webhook-node"
import { createHmac, timingSafeEqual } from 'node:crypto';

export function verifyOnChargeWebhook(rawBody, signatureHeader, secret, toleranceSeconds = 300) {
  let timestamp = null;
  const signatures = [];
  for (const part of String(signatureHeader ?? '').split(',')) {
    const [key, value] = part.trim().split('=', 2);
    if (key === 't') timestamp = value;
    else if (key === 'v1' && value) signatures.push(value);
  }
  if (!timestamp || !/^\d+$/.test(timestamp) || signatures.length === 0) {
    throw new Error('Malformed OnCharge-Signature header');
  }
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSeconds) {
    throw new Error('Webhook timestamp is outside the tolerance');
  }
  const expected = createHmac('sha256', secret).update(`${timestamp}.${rawBody}`, 'utf8').digest();
  const valid = signatures.some((sig) => {
    const given = Buffer.from(sig, 'hex');
    return given.length === expected.length && timingSafeEqual(given, expected);
  });
  if (!valid) throw new Error('Invalid webhook signature');
  return JSON.parse(rawBody);
}
```

With Express, read the raw body:

```js title="server.mjs"
import express from 'express';
import { verifyOnChargeWebhook } from './verify-webhook.mjs';

const app = express();

app.post('/webhooks/oncharge', express.raw({ type: 'application/json' }), async (req, res) => {
  let event;
  try {
    event = verifyOnChargeWebhook(req.body.toString('utf8'), req.get('OnCharge-Signature'), process.env.ONCHARGE_WEBHOOK_SECRET);
  } catch {
    return res.status(400).send('Invalid signature');
  }
  if (await alreadyProcessed(event.id)) return res.sendStatus(200);

  switch (event.type) {
    case 'payment.captured':
      await markOrderPaid(event.data.order_id ?? event.data.reference, event.data.session_id);
      break;
    case 'payment.refused':
    case 'payment.cancelled':
      await markOrderFailed(event.data.order_id ?? event.data.reference);
      break;
    case 'refund.succeeded':
      await recordRefund(event.data.session_id, event.data.amount);
      break;
    case 'chargeback.opened':
      await flagOrder(event.data.session_id);
      break;
  }
  await rememberProcessed(event.id);
  res.sendStatus(200);
});
```

In a Next.js route handler, use `const rawBody = await request.text()` and `request.headers.get('OnCharge-Signature')`. See [Next.js](https://oncharge.io/docs/nextjs) for a complete route, or use the SDK (below).

### PHP

```php title="verify-webhook.php" test="webhook-php"
<?php
function oncharge_verify_webhook(string $rawBody, string $signatureHeader, string $secret, int $tolerance = 300): array
{
    $timestamp = null;
    $signatures = [];
    foreach (explode(',', $signatureHeader) as $part) {
        $pair = explode('=', trim($part), 2);
        if (count($pair) !== 2) {
            continue;
        }
        if ($pair[0] === 't') {
            $timestamp = $pair[1];
        } elseif ($pair[0] === 'v1' && $pair[1] !== '') {
            $signatures[] = $pair[1];
        }
    }
    if ($timestamp === null || !preg_match('/^\d+$/', $timestamp) || !$signatures) {
        throw new RuntimeException('Malformed OnCharge-Signature header');
    }
    if (abs(time() - (int) $timestamp) > $tolerance) {
        throw new RuntimeException('Webhook timestamp is outside the tolerance');
    }
    $expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
    foreach ($signatures as $signature) {
        if (hash_equals($expected, $signature)) {
            return json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR);
        }
    }
    throw new RuntimeException('Invalid webhook signature');
}
```

```php title="webhook.php"
<?php
require __DIR__ . '/verify-webhook.php';

$rawBody = file_get_contents('php://input');
try {
    $event = oncharge_verify_webhook($rawBody, $_SERVER['HTTP_ONCHARGE_SIGNATURE'] ?? '', getenv('ONCHARGE_WEBHOOK_SECRET'));
} catch (Throwable $e) {
    http_response_code(400);
    exit('Invalid signature');
}

if ($event['type'] === 'payment.captured') {
    // Mark the order paid: $event['data']['order_id'] ?? $event['data']['reference']
}
http_response_code(200);
```

### Python

```python title="verify_webhook.py" test="webhook-python"
import hashlib
import hmac
import json
import time


def verify_oncharge_webhook(raw_body: bytes, signature_header: str, secret: str, tolerance: int = 300) -> dict:
    timestamp, signatures = None, []
    for part in (signature_header or "").split(","):
        key, _, value = part.strip().partition("=")
        if key == "t":
            timestamp = value
        elif key == "v1" and value:
            signatures.append(value)
    if not timestamp or not timestamp.isdigit() or not signatures:
        raise ValueError("Malformed OnCharge-Signature header")
    if abs(time.time() - int(timestamp)) > tolerance:
        raise ValueError("Webhook timestamp is outside the tolerance")
    expected = hmac.new(secret.encode("utf-8"), timestamp.encode("ascii") + b"." + raw_body, hashlib.sha256).hexdigest()
    if not any(hmac.compare_digest(expected, signature) for signature in signatures):
        raise ValueError("Invalid webhook signature")
    return json.loads(raw_body)
```

With Flask:

```python title="app.py"
import os
from flask import Flask, abort, request
from verify_webhook import verify_oncharge_webhook

app = Flask(__name__)


@app.post("/webhooks/oncharge")
def oncharge_webhook():
    try:
        event = verify_oncharge_webhook(
            request.get_data(), request.headers.get("OnCharge-Signature", ""), os.environ["ONCHARGE_WEBHOOK_SECRET"]
        )
    except ValueError:
        abort(400)
    if event["type"] == "payment.captured":
        pass  # mark the order paid
    return "", 200
```

### With the Node SDK

The [Node SDK](https://oncharge.io/docs/sdks) does the verification for you. In a Next.js route handler:

```ts title="app/api/webhooks/oncharge/route.ts"
import { createWebhookHandler } from '@oncharge/node/next';

export const { POST } = createWebhookHandler({
  secret: process.env.ONCHARGE_WEBHOOK_SECRET,
  async onEvent(event, { request }) {
    if (event.type === 'payment.captured') {
      // mark the order paid
    }
    // throw to have OnCharge retry later
  },
});
```

The handler answers `400` (with the reason, e.g. `{"error":"signature_mismatch"}`) to a bad signature, `500` if `onEvent` throws (so OnCharge retries), and `200` without calling `onEvent` again for an event ID it has already handled. It remembers event IDs in memory; pass `eventIdStore: { has(id), add(id) }` backed by your database or Redis when you run several instances, or `eventIdStore: false` to handle every delivery. `toleranceSeconds` defaults to 300.

In any other framework:

```ts
import { OnCharge, OnChargeSignatureError } from '@oncharge/node';

try {
  const event = OnCharge.webhooks.constructEvent(rawBody, request.headers.get('OnCharge-Signature'), process.env.ONCHARGE_WEBHOOK_SECRET!);
  // handle event
} catch (err) {
  if (err instanceof OnChargeSignatureError) {
    // err.code: missing_signature | invalid_signature_header | timestamp_outside_tolerance | signature_mismatch | invalid_payload
  }
}
```

`OnCharge.webhooks.generateTestHeader({ payload, secret })` returns a valid `OnCharge-Signature` for a payload, for testing your endpoint without OnCharge.

## Delivery and retries

- Respond with any `2xx` within **8 seconds**. Do slow work (emails, ERP sync) after responding or in a queue.
- Any other response, or a timeout, is retried with backoff for up to **24 hours**.
- The same event can arrive more than once. Store processed `OnCharge-Event-Id` values and skip repeats.
- Events can arrive out of order. If you need the current state, read it with [`GET /api/v1/checkout/sessions/{id}`](https://oncharge.io/docs/api#getcheckoutsession).
- Each endpoint gets its own copy of an event, signed with its own secret, and retried on its own. When an endpoint fails, OnCharge waits a few minutes before sending it more, so its events are delayed, not lost.

## Catch up and replay

Every event is kept for **30 days**, exactly as your endpoints received it:

- [`GET /api/v1/events`](https://oncharge.io/docs/api#listevents) lists them newest first (filter by `type`, such as `payment.captured` or `payout.*`, and by day; paged with `next_cursor`).
- [`GET /api/v1/events/{event_id}`](https://oncharge.io/docs/api#getevent) returns one.
- [`POST /api/v1/events/{event_id}/replay`](https://oncharge.io/docs/api#replayevent) with `{ "endpoint_id": "…" }` sends it to one of your endpoints again, with the same `id`, so your duplicate check still works.

They are signed like every other API request ([authentication](https://oncharge.io/docs/authentication)). With the Node SDK: `oncharge.events.list()`, `.retrieve(id)` and `.replay(id, { endpointId })`.

## Legacy signature header

Requests also carry `X-Oncharge-Signature`, a body-only HMAC with the same secret, kept for older WooCommerce plugins. New integrations should verify `OnCharge-Signature`, which also protects against replays. The WooCommerce plugin (1.4.0+), Magento module and Wix integration check `OnCharge-Signature` first and fall back to the legacy header only when the new one is absent.
