> Receive payment notifications by webhook

Source: https://docs.apipay.vn/en/api/webhooks

# Webhooks

When money arrives in a connected bank account, ApiPay sends a signed `POST` request to your URL. Webhooks are the equivalent of **IPN** in other payment gateways.

Integration takes 3 steps:

1. Register a webhook URL and store its `secret`.
2. Verify the `ApiPay-Signature` header on every request.
3. Return a `2xx` status, then update the order.

## Register a webhook

Create a webhook in the dashboard under **Webhooks**, or call the API:

```bash
POST /v1/client/webhooks
```

| Parameter        | Type     | Required | Description                                                              |
| ---------------- | -------- | -------- | ------------------------------------------------------------------------ |
| `webhookUrl`     | string   | Yes      | URL that receives webhooks. Live: HTTPS on port 443. Sandbox: HTTP and custom ports allowed |
| `bankPublicIds`  | string[] | No       | Only receive transactions for these banks. Omit to receive all, including banks connected later |
| `isActive`       | boolean  | No       | Enable or disable the webhook. Default `true`                            |
| `timeoutSeconds` | integer  | No       | Wait time per delivery, `5` to `10` seconds. Default `10`                |
| `extraHeader`    | object   | No       | Extra header to send, as `{"name": "X-Api-Key", "value": "..."}`. Name must start with `X-` |
| `events`         | string[] | No       | Events to receive. Default `transaction.in` and `transaction.out`. See [Choose events](#choose-events) |

```bash
curl -X POST https://app.apipay.vn/v1/client/webhooks \
  -H "Authorization: Bearer " \
  -H "Content-Type: application/json" \
  -d '{"webhookUrl": "https://your-domain.com/webhooks/apipay"}'
```

```json
{
  "data": {
    "id": "wh_abc123",
    "webhookUrl": "https://your-domain.com/webhooks/apipay",
    "secret": "a1b2c3d4..."
  },
  "statusCode": 201,
  "timestamp": "2026-08-12T14:27:45.000Z"
}
```

Store `secret` on your server. You use it to verify signatures.

## Manage webhooks

| Endpoint                                             | Description                                               |
| ---------------------------------------------------- | --------------------------------------------------------- |
| `GET /v1/client/webhooks`                            | List webhooks (`page`, `limit`)                           |
| `PATCH /v1/client/webhooks/:id`                      | Update the same fields as create. Send `null` to reset one |
| `PATCH /v1/client/webhooks/:id/toggle`               | Enable or disable a webhook                               |
| `DELETE /v1/client/webhooks/:id`                     | Delete a webhook                                          |
| `GET /v1/client/webhooks/deliveries`                 | Delivery history                                          |
| `POST /v1/client/webhooks/history/:historyId/resend` | Resend a failed delivery                                  |

## Choose events

Each webhook receives only the events you pick.

| Event                       | Sent when                                                        |
| --------------------------- | ---------------------------------------------------------------- |
| `transaction.in`            | Money arrives in your bank account                               |
| `transaction.out`           | Money leaves your bank account                                   |
| `payment_request.completed` | One of your payment requests is paid                             |

In the dashboard, open **Webhooks**, add or edit a webhook and open the **Events** section. A new webhook starts with `transaction.in` selected. Tick the others if you need them.

By API, send `events` when you create or update a webhook:

```bash
curl -X PATCH https://app.apipay.vn/v1/client/webhooks/wh_abc123 \
  -H "Authorization: Bearer " \
  -H "Content-Type: application/json" \
  -d '{"events": ["transaction.in", "payment_request.completed"]}'
```

## Event `transaction.in`

ApiPay sends this event when money arrives in your account.

```json
{
  "event": "transaction.in",
  "data": {
    "transactionId": "550e8400-e29b-41d4-a716-446655440000",
    "referenceCode": "FT26081212345",
    "amount": "100000",
    "type": "IN",
    "content": "ORDER-12345",
    "transactionDate": "2026-08-12T10:30:00.000Z",
    "bankAccountPublicId": "bnk_abc123",
    "gateway": "970422",
    "accountNumber": "0123456789",
    "vaNumber": null,
    "connectedAccount": null
  }
}
```

| Field                      | Type           | Description                                                 |
| -------------------------- | -------------- | ----------------------------------------------------------- |
| `event`                    | string         | Event name                                                  |
| `data.transactionId`       | string         | ApiPay transaction ID. Use it as your idempotency key       |
| `data.referenceCode`       | string         | Bank reference code                                         |
| `data.amount`              | string         | Amount (VND)                                                |
| `data.type`                | string         | `IN` (incoming)                                             |
| `data.content`             | string         | Transfer description                                        |
| `data.transactionDate`     | string         | Transaction time (ISO 8601)                                 |
| `data.bankAccountPublicId` | string         | Bank account that received the money                        |
| `data.gateway`             | string         | Bank BIN, for example `970422` (MB)                         |
| `data.accountNumber`       | string         | Receiving account number                                    |
| `data.vaNumber`            | string \| null | Virtual account number, if any                              |
| `data.connectedAccount`    | object \| null | Customer who linked this bank through [ApiPay Connect](/en/connect): `id` and your `externalRef`. `null` for your own banks |

Match the order by `amount` and `content`. Banks may add text before or after the description, so check whether `data.content` **contains** the content of your [payment request](/en/api/payment-requests), case-insensitively.

## Event `payment_request.completed`

Use this event when you sell with [payment requests](/en/api/payment-requests): it tells you which request was paid, so you do not compare amount and description yourself.

Example: your shop creates a payment request for order 12345 and the customer pays it. ApiPay sends:

```json
{
  "event": "payment_request.completed",
  "data": {
    "paymentRequest": {
      "publicId": "APIPAYJSCAF9H23M74K",
      "amount": "100000",
      "content": "ORDER-12345",
      "title": "Order 12345",
      "status": "COMPLETED",
      "completedAt": "2026-08-12T10:30:02.000Z"
    },
    "transaction": {
      "transactionId": "550e8400-e29b-41d4-a716-446655440000",
      "referenceCode": "FT26081212345",
      "amount": "100000",
      "type": "IN",
      "content": "ORDER-12345",
      "transactionDate": "2026-08-12T10:30:00.000Z",
      "bankAccountPublicId": "bnk_abc123",
      "gateway": "970422",
      "accountNumber": "0123456789",
      "vaNumber": null,
      "connectedAccount": null
    }
  }
}
```

| Field                           | Type           | Description                                             |
| ------------------------------- | -------------- | ------------------------------------------------------- |
| `data.paymentRequest.publicId`  | string         | The payment request that was paid                       |
| `data.paymentRequest.amount`    | string \| null | Amount of the request (VND). `null` if it had no fixed amount |
| `data.paymentRequest.content`   | string \| null | Transfer description of the request                     |
| `data.paymentRequest.title`     | string \| null | Title of the request                                    |
| `data.paymentRequest.status`    | string         | `COMPLETED`                                             |
| `data.paymentRequest.completedAt` | string       | When the request was completed (ISO 8601)               |
| `data.transaction`              | object         | The transfer that paid it. Same fields as `data` in `transaction.in` |

- Off by default. Turn it on in [Choose events](#choose-events).
- Sent separately from `transaction.in`, in no fixed order. Both carry the same `transactionId`, so fulfill the order from one of them only.
- In the sandbox it is sent when you pay a test payment request. Live Test does not send it.

## Webhook authentication

Every request carries an `ApiPay-Signature` header: the HMAC-SHA256 (hex) of the **raw body**, signed with the webhook `secret`. Compute it over the raw body you received, not over re-serialized JSON.

```javascript
const crypto = require("crypto");
const express = require("express");

const app = express();

function isValidSignature(rawBody, signature, secret) {
  const expected = Buffer.from(crypto.createHmac("sha256", secret).update(rawBody).digest("hex"), "hex");
  const received = Buffer.from(String(signature || ""), "hex");
  return received.length === expected.length && crypto.timingSafeEqual(received, expected);
}

app.post("/webhooks/apipay", express.raw({type: "*/*"}), (req, res) => {
  if (!isValidSignature(req.body, req.headers["apipay-signature"], process.env.APIPAY_WEBHOOK_SECRET)) {
    return res.status(401).json({error: "Invalid signature"});
  }

  const {event, sandbox, data} = JSON.parse(req.body.toString("utf8"));

  if (event === "transaction.in" && !sandbox) {
    // Update the order using data.content and data.amount
  }

  res.status(200).json({received: true});
});
```

```python
import hashlib
import hmac
import json
import os

from flask import Flask, request

app = Flask(__name__)

def is_valid_signature(raw_body: bytes, signature: str, secret: str) -> bool:
    expected = hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature or "")

@app.post("/webhooks/apipay")
def apipay_webhook():
    raw_body = request.get_data()
    if not is_valid_signature(raw_body, request.headers.get("ApiPay-Signature"), os.environ["APIPAY_WEBHOOK_SECRET"]):
        return {"error": "Invalid signature"}, 401

    payload = json.loads(raw_body)
    if payload["event"] == "transaction.in" and not payload.get("sandbox"):
        pass  # Update the order using payload["data"]["content"] and ["amount"]

    return {"received": True}, 200
```

```php
<?php

$rawBody = file_get_contents('php://input');
$signature = $_SERVER['HTTP_APIPAY_SIGNATURE'] ?? '';
$expected = hash_hmac('sha256', $rawBody, getenv('APIPAY_WEBHOOK_SECRET'));

if (!hash_equals($expected, $signature)) {
  http_response_code(401);
  exit;
}

$payload = json_decode($rawBody, true);

if ($payload['event'] === 'transaction.in' && empty($payload['sandbox'])) {
  // Update the order using $payload['data']['content'] and ['amount']
}

http_response_code(200);
echo json_encode(['received' => true]);
```

## Retries

A delivery succeeds when your endpoint returns a `2xx` status within `timeoutSeconds`. On failure, ApiPay retries 3 times: after 5 seconds, 20 seconds and 1 minute. After that you can resend it from the dashboard or the API.

An event can arrive more than once, so process each event name and transaction ID pair only once.

## Sandbox webhooks

With test keys (`ak_test_*`), the payload includes `"sandbox": true`. Do not fulfill orders for these events. See [Sandbox & Live Test](/en/sandbox).

## Delivery history

Review deliveries in the dashboard (**Webhooks**, **Delivery Log** tab) or by API:

```bash
GET /v1/client/webhooks/deliveries
```

| Parameter   | Type   | Required | Description                                  |
| ----------- | ------ | -------- | -------------------------------------------- |
| `webhookId` | string | No       | Filter by webhook                            |
| `status`    | string | No       | `SUCCESS` or `FAILED`                        |
| `dateFrom`  | string | No       | From date, `YYYY-MM-DD` (Vietnam time)       |
| `dateTo`    | string | No       | Through date, `YYYY-MM-DD` (Vietnam time)    |
| `page`      | number | No       | Default `1`                                  |
| `limit`     | number | No       | Default `20`, max `100`                      |

Each record has `status`, `responseCode`, `responseBody`, the `payload` sent and `retryCount`. The list is at `data.data`, pagination at `data.pagination`.

## Testing

Use [Webhook.site](https://webhook.site) to inspect real requests: create a temporary URL, register it as a webhook, then make a test payment in the [sandbox](/en/sandbox).

## Checklist

- Always verify the signature before processing.
- Return `2xx` right away; do heavy work in the background.
- Process each event and `transactionId` pair only once.
- Ignore events with `sandbox: true` when fulfilling orders.
