> ## Documentation Index
> Fetch the complete documentation index at: https://prod-docs.123hub.pro/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Describe only the public 123hub merchant API documented on this site. The primary endpoint is POST /public/api/multihub/v1.
> Preserve API method names, field names, header names, and error codes exactly as documented. Do not invent endpoints or parameters.
> Treat every amount as an integer in minor units unless a page explicitly states otherwise.
> Never expose, request, or fabricate a merchant secret key. The SDK pages contain reference implementations, not official SDK packages.

# Webhooks Guide

> Receive and verify real-time payment and payout notifications

# Webhooks Guide

Webhooks notify your backend when payment and payout states change. Your handler should verify the signature, process the event idempotently, and return a 2xx response quickly.

> [!NOTE]
>
> **Prerequisites:** a public HTTPS callback URL configured for your account,
> and the secret that signs its deliveries. A dedicated webhook secret is shown
> only once, when the callback is created or its secret is rotated; store it
> separately from your API credentials. Older callback set-ups are signed with
> your production API secret instead — see [Signing secret](#signing-secret).

## Events

| Event | Sent when | `status.status` |
| - | - | - |
| `payment.created` | A deposit or payout was created | `created` |
| `payment.completed` | A deposit or payout completed successfully | `success` |
| `payment.failed` | A deposit or payout failed or expired | `error`, `declined` |
| `payment.cancelled` | A deposit or payout was cancelled | `canceled` |
| `payment.refunded` | A deposit was fully or partially refunded | `refunded`, `partially_refunded` |

Each callback destination receives only the events it is subscribed to. A callback URL configured during onboarding is subscribed to `payment.completed`, `payment.failed` and `payment.processing` by default. If you also need `payment.created`, `payment.cancelled` or `payment.refunded`, add them to the destination's subscription (webhook settings in the merchant dashboard, or ask support). Without a `payment.cancelled` subscription, cancelled payments produce no callback.

Payouts are delivered under the same `payment.*` event names as deposits. Use `data.result.payment.destination: "out"` to identify payout callbacks. `payment.refunded` applies to deposits only.

`payment.processing` is not sent on status changes. It can only arrive as a re-notification requested with [`payment.notification`](https://prod-docs.123hub.pro/api-reference/methods) for a deposit that is still processing. A `webhook.test` event may be delivered when a test is triggered for your destination; it carries test data in `data.test_data` and is signed like any other delivery.

## Callback URLs

* Your account can have one callback URL for both deposits and payouts, or separate URLs for deposits and for payouts (set up by our team). When a separate URL exists for a direction, events of that direction go only to it.
* The URL must be a public `https://` address with a valid TLS certificate. Redirects are not followed: a `3xx` response counts as a failed delivery.
* Optional static headers (for example, your own authorization token) can be added to every delivery of a destination. They cannot replace the signature headers listed below.
* A per-payment `webhook_url` is [temporarily unavailable](#per-payment-webhook-urls).

## Payload

Webhook deliveries use an outer envelope. The payment object is under `data.result.payment` and uses the same payment projection as the `payment.status` result.

```json theme={null}
{
  "id": "pay_123:payment.completed",
  "created_at": "2026-04-02T08:23:04.379Z",
  "data": {
    "next": null,
    "result": {
      "payment": {
        "receiver": {},
        "amount": { "value": 500000, "currency": "ARS" },
        "identifiers": {
          "c_id": "merchant-order-1",
          "h_id": "pay_123",
          "p_id": "provider-ref-123",
          "utr": "412345678901"
        },
        "status": {
          "status": "success",
          "final": true,
          "success": true,
          "error": null,
          "history": [
            { "status": "created", "final": false, "success": null, "created": "2026-04-02T08:22:21.453Z", "reason": null, "amount": 500000 },
            { "status": "processing", "final": false, "success": null, "created": "2026-04-02T08:22:22.795Z", "reason": null, "amount": 500000 },
            { "status": "success", "final": true, "success": true, "created": "2026-04-02T08:22:22.795Z", "reason": null, "amount": 500000 }
          ]
        },
        "timestamps": {
          "created": "2026-04-02T08:22:21.453Z",
          "updated": "2026-04-02T08:22:22.795Z",
          "finished": "2026-04-02T08:22:22.795Z"
        },
        "destination": "in",
        "operations": [
          {
            "id": "pay_123",
            "operation_type": "payment.in",
            "amount": { "value": 500000, "currency": "ARS" },
            "timestamps": {
              "created": "2026-04-02T08:22:21.453Z",
              "updated": "2026-04-02T08:22:22.795Z",
              "finished": "2026-04-02T08:22:22.795Z"
            },
            "status": { "status": "success", "final": true, "success": true, "error": null }
          }
        ]
      }
    },
    "success": true,
    "request_id": "729aebbf-5a6b-4299-87fa-1cf05c1121a6",
    "processing_time": 0
  },
  "merchant_id": "19"
}
```

* `id` is `{h_id}:{event}`, for example `pay_123:payment.completed`. Each `payment.refunded` occurrence gets its own suffix (`{h_id}:payment.refunded:{hash}`), so several partial refunds have distinct ids.
* The body of a delivery does not change between retry attempts. A manual re-delivery builds a new body with a new `data.request_id`, but keeps the same `id`.
* `payer`, `description`, `client`, `redirect`, `status.history` and `operations` appear only when data is available. When `operations` is present, `data.result.operation` repeats its first element. `identifiers.utr` appears only when a non-empty UTR/reference value is available.
* `status.error` is a numeric public error code when one is mapped, otherwise an error text or `null`.

> [!WARNING]
>
> Internal fields prefixed with `_` are never included in the delivered webhook
> body. Do not build integrations around `_payment_id` or other internal-only
> fields.

## Headers

| Header | Description |
| - | - |
| `Content-Type` | `application/json` (compact UTF-8 JSON body) |
| `X-Data-Hash` | Legacy signature: `SHA512(rawBody + secret)`, lowercase hex |
| `X-Webhook-Id` | Delivery id. Equals the body `id` for automatic events, `{id}:manual:{suffix}` for manual re-deliveries. The same on every retry attempt |
| `X-Webhook-Timestamp` | ISO 8601 UTC time of this attempt, for example `2026-04-02T08:23:04.379Z`. New on every attempt |
| `X-Webhook-Nonce` | Random UUID, new on every attempt |
| `X-Webhook-Signature-V2` | Compatibility signature: `SHA512(timestamp + rawBody + secret)`, lowercase hex |
| `X-Webhook-Signature-V3` | Preferred signature: HMAC-SHA512 with the secret as key over `timestamp.nonce.webhookId.rawBody`, lowercase hex |

All three signatures are sent on every delivery and use the same secret.

## Signing Secret

Every destination is signed with exactly one secret:

* **Dedicated webhook secret** (recommended). Generated when a destination is created for an account without an active production API key, for every separate deposit-only or payout-only URL, and whenever the webhook secret is rotated. It is shown once. Rotation takes effect immediately and has no overlap period: retries of earlier events are signed with the new secret.
* **Production API secret** (compatibility). A callback URL created while your account already had an active production API key is signed with your newest active production API secret. Rotating that API key therefore changes callback verification within seconds. If no active production API key exists, these deliveries fail until a key is active again or the webhook secret is rotated. Rotate the webhook secret to move such a destination to a dedicated secret.

Per-payment URLs use a secret derived from your API secret; see [Per-Payment Webhook URLs](#per-payment-webhook-urls).

## Verify Signatures

Use the exact raw request body bytes. Re-serializing parsed JSON changes whitespace/key ordering and will break verification.

Prefer `X-Webhook-Signature-V3`. It binds the timestamp, nonce, delivery id, and raw body. `X-Webhook-Signature-V2` and `X-Data-Hash` remain for backward-compatible verification.

For replay protection, reject timestamps more than a few minutes away from your clock (each attempt carries a fresh timestamp, so a 5-minute window is safe) and remember recently seen `X-Webhook-Nonce` values. Do not reject a repeated `X-Webhook-Id`: it is the same on every retry of a delivery.

```python Python theme={null}
import hashlib
import hmac
import json
import time
from datetime import datetime

WEBHOOK_SECRET = "your_webhook_secret"

def verify_webhook_v3(raw_body: bytes, secret: str, headers) -> bool:
    timestamp = headers.get("X-Webhook-Timestamp", "")
    nonce = headers.get("X-Webhook-Nonce", "")
    webhook_id = headers.get("X-Webhook-Id", "")
    received = headers.get("X-Webhook-Signature-V3", "")
    if not (timestamp and nonce and webhook_id and received):
        return False
    try:
        sent_at = datetime.fromisoformat(timestamp.replace("Z", "+00:00")).timestamp()
    except ValueError:
        return False
    if abs(time.time() - sent_at) > 300:
        return False
    message = b".".join([timestamp.encode(), nonce.encode(), webhook_id.encode(), raw_body])
    expected = hmac.new(secret.encode(), message, hashlib.sha512).hexdigest()
    return hmac.compare_digest(expected, received.lower())

def verify_webhook_legacy(raw_body: bytes, secret: str, received_hash: str) -> bool:
    expected = hashlib.sha512(raw_body + secret.encode()).hexdigest()
    return hmac.compare_digest(expected, (received_hash or "").lower())

# Flask-style handler
raw_body = request.get_data()

if not verify_webhook_v3(raw_body, WEBHOOK_SECRET, request.headers):
    return {"error": "Invalid signature"}, 400

payload = json.loads(raw_body)
payment = payload["data"]["result"]["payment"]
status = payment["status"]["status"]
```

```javascript Node.js theme={null}
const crypto = require("crypto");
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET || "your_webhook_secret";

function safeCompareHex(expected, received) {
  if (!/^[a-f0-9]{128}$/i.test(received || "")) {
    return false;
  }
  return crypto.timingSafeEqual(
    Buffer.from(expected, "hex"),
    Buffer.from(received, "hex"),
  );
}

function verifyWebhook(rawBodyBuffer, webhookSecret, receivedHash) {
  const expected = crypto
    .createHash("sha512")
    .update(Buffer.concat([rawBodyBuffer, Buffer.from(webhookSecret)]))
    .digest("hex");

  return safeCompareHex(expected, receivedHash);
}

function verifyWebhookV3(rawBodyBuffer, webhookSecret, headers) {
  const timestamp = headers["x-webhook-timestamp"];
  const nonce = headers["x-webhook-nonce"];
  const webhookId = headers["x-webhook-id"];
  const signature = headers["x-webhook-signature-v3"];
  const timestampMs = Date.parse(timestamp || "");

  if (!timestamp || !nonce || !webhookId || !Number.isFinite(timestampMs)) {
    return false;
  }
  if (Math.abs(Date.now() - timestampMs) > 5 * 60 * 1000) {
    return false;
  }

  const expected = crypto
    .createHmac("sha512", webhookSecret)
    .update(
      [timestamp, nonce, webhookId, rawBodyBuffer.toString("utf8")].join("."),
    )
    .digest("hex");

  return safeCompareHex(expected, signature);
}

// Express example:
// app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
//   const valid =
//     verifyWebhookV3(req.body, WEBHOOK_SECRET, req.headers) ||
//     verifyWebhook(req.body, WEBHOOK_SECRET, req.headers['x-data-hash']);
//
//   if (!valid) {
//     return res.status(400).json({ error: 'Invalid signature' });
//   }
//
//   const payload = JSON.parse(req.body.toString('utf8'));
//   const payment = payload.data.result.payment;
//   const status = payment.status.status;
//
//   res.status(200).json({ received: true });
// });
```

```php PHP theme={null}
<?php
$webhookSecret = getenv('WEBHOOK_SECRET') ?: 'your_webhook_secret';

function verifyWebhookV3(string $rawBody, string $secret, array $server): bool {
    $timestamp = $server['HTTP_X_WEBHOOK_TIMESTAMP'] ?? '';
    $nonce = $server['HTTP_X_WEBHOOK_NONCE'] ?? '';
    $webhookId = $server['HTTP_X_WEBHOOK_ID'] ?? '';
    $received = strtolower($server['HTTP_X_WEBHOOK_SIGNATURE_V3'] ?? '');
    if ($timestamp === '' || $nonce === '' || $webhookId === '' || $received === '') {
        return false;
    }
    $sentAt = strtotime($timestamp);
    if ($sentAt === false || abs(time() - $sentAt) > 300) {
        return false;
    }
    $expected = hash_hmac('sha512', $timestamp . '.' . $nonce . '.' . $webhookId . '.' . $rawBody, $secret);
    return hash_equals($expected, $received);
}

function verifyWebhookLegacy(string $rawBody, string $secret, string $receivedHash): bool {
    $expected = hash('sha512', $rawBody . $secret);
    return hash_equals($expected, strtolower($receivedHash));
}

$rawBody = file_get_contents('php://input');

if (!verifyWebhookV3($rawBody, $webhookSecret, $_SERVER)) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid signature']);
    exit;
}

$payload = json_decode($rawBody, true);
$payment = $payload['data']['result']['payment'];
```

## Retry Behavior

A delivery succeeds when your endpoint answers with any HTTP `2xx` status within the timeout. The response body is ignored. Any other status (including `3xx` redirects), a timeout, a connection or TLS error, or a URL that fails validation at delivery time is a failed attempt.

Defaults per destination:

| Setting | Default |
| - | - |
| Timeout | `30` seconds |
| Attempts | `3` in total, including the first one |
| Base retry delay | `1` second |

The first attempt is made right after the event. Retries use exponential backoff with jitter: retry `n` waits between 50% and 100% of `base delay × 2^(n−1)`, at least 1 second and at most 24 hours. Retries are picked up by a scheduler that runs every 30 seconds, so with the defaults all three attempts happen within one to two minutes. The timeout and number of attempts (up to 10) can be adjusted per destination.

If your endpoint keeps returning server errors or timing out, deliveries to it are paused for a short time (about two minutes by default). Paused deliveries are rescheduled and do not use up attempts.

After the last failed attempt there are no further automatic retries. To recover, query [`payment.status`](https://prod-docs.123hub.pro/api-reference/methods), use the [payment-level resend](https://prod-docs.123hub.pro/api-reference/webhooks.md#merchant-payment-webhook-resend), or call [`payment.notification`](https://prod-docs.123hub.pro/api-reference/methods).

Delivery is at-least-once and order is not guaranteed — for example, a retried `payment.created` can arrive after `payment.completed`. Your handler must be idempotent.

## Handling Statuses

Use `payment.status.final` to decide whether the payment reached a terminal state, and `payment.status.status` to decide which one. Do not rely on `success` alone: refunds are final with `success: true`.

```javascript theme={null}
const payment = payload.data.result.payment;
const { status, final } = payment.status;

if (!final) {
  // created / processing — wait for a final event or poll payment.status
} else if (status === "success") {
  await markOrderPaid(payment.identifiers.c_id);
} else if (status === "refunded" || status === "partially_refunded") {
  await markOrderRefunded(payment.identifiers.c_id);
} else {
  // error, canceled, declined
  await markOrderFailed(payment.identifiers.c_id, payment.status.error);
}
```

Never move an order from a final state back to a non-final one because of a late event.

## Per-Payment Webhook URLs

> [!WARNING]
>
> **Temporarily unavailable.** A `payment.in` or `payment.out` request that contains
> `params.payment.webhook_url` currently fails with `2001 Internal payment processing error`.
> Do not send this field — webhooks go to the callback URL configured for your account during
> onboarding.

When the field becomes available again, it works as follows:

```json theme={null}
{
  "method": "payment.in",
  "service_id": 14701,
  "params": {
    "payment": {
      "identifiers": { "c_id": "order-123" },
      "amount": { "value": 10000, "currency": "INR" },
      "payer": { "email": "customer@example.com" },
      "webhook_url": "https://merchant.example/webhooks/123hub"
    }
  }
}
```

* The URL must be an absolute public `https://` URL. It is validated when the payment is created and again before each delivery.
* The URL receives only that payment's `payment.created`, `payment.completed` and `payment.failed` events — not `payment.cancelled` or `payment.refunded`. Your account-level callback keeps receiving its own subscribed events as well.
* Deliveries are signed with a secret derived from the API secret that authenticated the create request: lowercase hex `HMAC-SHA256(apiSecret, "quadpay:merchant-webhook-signing:v1")`. Do not verify with the API secret itself.
* Up to 3 attempts, with a 60-second base retry delay.

## Best Practices

* Verify every signature before processing.
* Return 2xx quickly and process heavy work asynchronously.
* Deduplicate on the body `id` (it identifies the payment event); log `X-Webhook-Id` and `X-Webhook-Nonce` for support.
* Store `data.request_id`, `identifiers.c_id`, and `identifiers.h_id` for support and reconciliation.
* Treat webhook delivery as at-least-once and unordered; keep polling `payment.status` as a fallback for payments that stay non-final.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.