# 5. Pay-in webhook

Royal Pay sends payment status changes to the `webhookUrl` supplied in the payment creation request.

## Example payload

```json title="Body"
{
  "transactionId": "RP-7f3a9c21d84e5b02",
  "status": "approved",
  "amount": 200,
  "remarks": "Payment successful",
  "updatedAt": "2026-11-30T08:21:00.000Z",
  "orderId": "1234567890",
  "userId": "user_101",
  "utrNumber": "531512345678"
}
```

The fields are the same as [4. Get transaction status](https://docs.royalpe.site/payin/transaction-status).

| Webhook status | Sent when |
|---|---|
| `progress` | The pay-in was created. |
| `pending` | The customer submitted payment proof. Sent again if they submit a different UTR. |
| `approved` | The payment is verified. **Credit the customer.** |
| `rejected` | The payment was not accepted. |
| `cancelled` | The pay-in ended before any proof was submitted. |

Every pay-in sends `progress` first, then one or more of the others. A create call retried with the same `orderId` doesn't send `progress` again.

## Headers

```http title="Request"
POST /webhook/payment HTTP/1.1
Content-Type: application/json
User-Agent: RoyalPay-Webhooks/1.0
X-Event-Id: EV-3c9d1f0a7b2e4d58
X-Timestamp: 1796040981
X-Signature: 6f1e0b0c4a1d0c9f7b0d3c2e5a8b1f4d6c9e2a5b8d1f4c7a0e3b6d9c2f5a8e1b
```

| Header | Description |
|---|---|
| `X-Event-Id` | Unique event ID (`EV-…`). Retries keep the same ID. |
| `X-Timestamp` | When this attempt was signed, Unix seconds. |
| `X-Signature` | Hex HMAC-SHA256, below. |

## Verify the signature

HMAC-SHA256 with your **webhook signing key** (merchant portal → **View keys**) over:

```text title="Signed text"
X-Event-Id + "." + X-Timestamp + "." + raw request body
```

Compare with `X-Signature` in constant time, and refuse timestamps more than 5 minutes old. Sign the **raw body bytes**: re-encoded JSON won't match.

```javascript title="Node.js"
import crypto from "node:crypto";
import express from "express";

const app = express();
// Keep the raw body: the signature is over the exact bytes.
app.post("/webhook/payment", express.raw({ type: "application/json" }), (req, res) => {
  const id = req.get("X-Event-Id"), ts = req.get("X-Timestamp"), sig = req.get("X-Signature") || "";
  const expected = crypto
    .createHmac("sha256", process.env.ROYALPAY_SIGNING_KEY)
    .update(`${id}.${ts}.`)
    .update(req.body)
    .digest("hex");
  const fresh = Math.abs(Date.now() / 1000 - Number(ts)) < 300;
  if (!fresh || sig.length !== expected.length ||
      !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected))) {
    return res.status(401).end();
  }
  const event = JSON.parse(req.body);
  // Idempotent: credit once per transactionId, only on "approved".
  handle(event).then(() => res.status(200).end());
});
```

```php title="PHP"
$raw = file_get_contents("php://input");
$id  = $_SERVER["HTTP_X_EVENT_ID"] ?? "";
$ts  = $_SERVER["HTTP_X_TIMESTAMP"] ?? "";
$sig = $_SERVER["HTTP_X_SIGNATURE"] ?? "";
$expected = hash_hmac("sha256", $id . "." . $ts . "." . $raw, getenv("ROYALPAY_SIGNING_KEY"));
if (abs(time() - (int)$ts) > 300 || !hash_equals($expected, $sig)) {
  http_response_code(401);
  exit;
}
$event = json_decode($raw, true);
// Credit once per transactionId when $event["status"] === "approved".
http_response_code(200);
```

```python title="Python"
import hashlib, hmac, os, time
from flask import Flask, request, abort

app = Flask(__name__)

@app.post("/webhook/payment")
def royalpay_webhook():
    raw = request.get_data()  # the exact bytes received
    event_id = request.headers.get("X-Event-Id", "")
    ts = request.headers.get("X-Timestamp", "0")
    expected = hmac.new(os.environ["ROYALPAY_SIGNING_KEY"].encode(),
                        f"{event_id}.{ts}.".encode() + raw, hashlib.sha256).hexdigest()
    if abs(time.time() - int(ts)) > 300 or not hmac.compare_digest(expected, request.headers.get("X-Signature", "")):
        abort(401)
    event = request.get_json()
    # Credit once per transactionId when event["status"] == "approved".
    return "", 200
```

## Acknowledgement and retries

- Answer with any **2xx** within **8 seconds**. Credit and send emails after answering.
- Anything else is retried with the same `X-Event-Id` after 10 s, 30 s, 1 min, 5 min, 15 min, 30 min, 1 h, 3 h and 6 h: 10 tries, about 12 hours in all.
- Redirects are not followed. A `webhookUrl` whose host resolves to a private, loopback or link-local address is never called.

## Handling them correctly

- **Credit once.** The same event can arrive twice. Key crediting on `transactionId`, and credit only the first `approved`.
- **Check the details.** `orderId`, `userId` and `amount` must match what you created.
- **Order isn't guaranteed.** `approved` is final and wins over a late `pending`.
- **Missed one?** [4. Get transaction status](https://docs.royalpe.site/payin/transaction-status) always has the current answer.

---

Source: https://docs.royalpe.site/payin/webhook · All docs: https://docs.royalpe.site/llms-full.txt · Updated 2026-11-30
