# Webhooks (/docs/webhooks)



NuruPay sends an HTTPS `POST` to your webhook endpoint when a collection reaches a final state. Add your endpoint in the dashboard under **Developers → Webhooks**; NuruPay shows its **signing secret** (`whsec_…`) once. Test and live mode have separate endpoints, and live endpoints must use `https://`.

## Events [#events]

| Event                  | When                                                                           |
| ---------------------- | ------------------------------------------------------------------------------ |
| `collection.succeeded` | The customer paid.                                                             |
| `collection.failed`    | Declined, insufficient funds, cancelled, or rejected; see `data.failure_code`. |
| `collection.expired`   | Not approved in time; the order was cancelled.                                 |

## Payload [#payload]

```json
{
  "id": "evt_01M3P5FBS9V5FJ1P5R0N8Z64XX",
  "type": "collection.succeeded",
  "created_at": "2026-09-29T08:46:05Z",
  "mode": "live",
  "data": { "id": "col_…", "object": "collection", "status": "succeeded", "amount": 1000, "...": "..." }
}
```

`data` is the full collection object at the moment of the event.

## Verify the signature [#verify-the-signature]

Every webhook carries a `NuruPay-Signature` header:

```
NuruPay-Signature: t=1759132800,v1=c57e6ec5e76a0cdd68ee3fd1eba420ff9abf04cd9755d174d59e1c4d6e926a54
```

`v1` is the hex HMAC-SHA256 of `"<t>.<raw request body>"` using your signing secret. **Always verify it** before trusting the body, and reject timestamps older than five minutes to stop replays.

<Callout type="warn">
  Verify against the **raw bytes** you received. Parsing the JSON and serialising it again changes the bytes and breaks the signature.
</Callout>

<CodeBlockTabs defaultValue="Node.js">
  <CodeBlockTabsList>
    <CodeBlockTabsTrigger value="Node.js">
      Node.js
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="Python">
      Python
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="PHP">
      PHP
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="Go">
      Go
    </CodeBlockTabsTrigger>
  </CodeBlockTabsList>

  <CodeBlockTab value="Node.js">
    ```js
    import crypto from 'node:crypto';

    // Returns true only if the webhook is genuine and fresh.
    // rawBody must be the exact bytes received (do not re-serialise JSON).
    export function verifyNuruPaySignature(rawBody, header, secret, toleranceSeconds = 300, now = Date.now()) {
      const parts = Object.fromEntries(header.split(',').map((p) => p.trim().split('=', 2)));
      const t = Number(parts.t);
      if (!Number.isInteger(t) || !parts.v1) return false;
      if (Math.abs(now / 1000 - t) > toleranceSeconds) return false;
      const expected = crypto.createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex');
      const a = Buffer.from(expected, 'hex');
      const b = Buffer.from(parts.v1, 'hex');
      return a.length === b.length && crypto.timingSafeEqual(a, b);
    }
    ```
  </CodeBlockTab>

  <CodeBlockTab value="Python">
    ```python
    import hashlib
    import hmac
    import time
    from typing import Optional


    def verify_nurupay_signature(raw_body: bytes, header: str, secret: str, tolerance_seconds: int = 300, now: Optional[float] = None) -> bool:
        """True only if the webhook is genuine and fresh. raw_body: the exact bytes received."""
        parts = dict(p.strip().split("=", 1) for p in header.split(",") if "=" in p)
        try:
            t = int(parts["t"])
            sig = parts["v1"]
        except (KeyError, ValueError):
            return False
        if abs((now if now is not None else time.time()) - t) > tolerance_seconds:
            return False
        expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
        return hmac.compare_digest(expected, sig)
    ```
  </CodeBlockTab>

  <CodeBlockTab value="PHP">
    ```php
    <?php
    // True only if the webhook is genuine and fresh. $rawBody: file_get_contents('php://input').
    function verify_nurupay_signature(string $rawBody, string $header, string $secret, int $toleranceSeconds = 300, ?int $now = null): bool {
        $parts = [];
        foreach (explode(',', $header) as $part) {
            [$k, $v] = array_pad(explode('=', trim($part), 2), 2, null);
            $parts[$k] = $v;
        }
        if (!isset($parts['t'], $parts['v1']) || !ctype_digit($parts['t'])) return false;
        $t = (int) $parts['t'];
        if (abs(($now ?? time()) - $t) > $toleranceSeconds) return false;
        $expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);
        return hash_equals($expected, $parts['v1']);
    }
    ```
  </CodeBlockTab>

  <CodeBlockTab value="Go">
    ```go
    import (
    	"crypto/hmac"
    	"crypto/sha256"
    	"encoding/hex"
    	"math"
    	"strconv"
    	"strings"
    	"time"
    )

    // VerifyNuruPaySignature reports whether a webhook is genuine and fresh.
    // rawBody must be the exact bytes received.
    func VerifyNuruPaySignature(rawBody []byte, header, secret string, tolerance time.Duration, now time.Time) bool {
    	var ts, sig string
    	for _, p := range strings.Split(header, ",") {
    		k, v, _ := strings.Cut(strings.TrimSpace(p), "=")
    		switch k {
    		case "t":
    			ts = v
    		case "v1":
    			sig = v
    		}
    	}
    	t, err := strconv.ParseInt(ts, 10, 64)
    	if err != nil || sig == "" || math.Abs(now.Sub(time.Unix(t, 0)).Seconds()) > tolerance.Seconds() {
    		return false
    	}
    	m := hmac.New(sha256.New, []byte(secret))
    	m.Write([]byte(ts + "."))
    	m.Write(rawBody)
    	return hmac.Equal([]byte(hex.EncodeToString(m.Sum(nil))), []byte(sig))
    }
    ```
  </CodeBlockTab>
</CodeBlockTabs>

## Respond quickly [#respond-quickly]

* Return any `2xx` within **10 seconds**, then do slow work (sending emails, updating stock) in the background.
* Anything else, including timeouts and redirects, counts as a failure. NuruPay retries after **1m, 5m, 30m, 2h, 6h, and 12h**, then marks the delivery failed.
* An endpoint that fails continuously for three days is disabled; NuruPay re-enables it once you have fixed it.

## Handle duplicates and ordering [#handle-duplicates-and-ordering]

* Delivery is **at least once**: you may receive the same event twice. Store the event `id` and ignore repeats.
* Events can arrive **out of order**. If order matters, fetch the collection with `GET /v1/collections/{id}` for its current state.
* To double-check an event, fetch it with `GET /v1/events/{id}` using your API key.

## Endpoint requirements [#endpoint-requirements]

* Live-mode endpoints must use `https://`.
* Endpoints must be publicly reachable; private and internal addresses are refused.
