> Source: https://developers.terrawallet.us/docs/webhooks . Terra Wallet developer docs (early access).

# Webhooks

Terra sends a signed HTTP `POST` to your endpoint when something happens, for example when a payment succeeds.
Verify the signature on every event before you trust it.

> **Preview.** The API is in early access and may change before launch.

## Register an endpoint

```bash
curl https://terrawallet.us/api/v1/webhook_endpoints \
  -H "Authorization: Bearer $TERRA_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: webhook-endpoint-main" \
  -d '{ "url": "https://shop.example.com/webhooks/terra",
        "events": ["payment_intent.succeeded", "invoice.paid", "subscription.renewed"] }'
```

The response contains the signing secret, `whsec_...`. It is shown **once**: store it like a password, for example
in `TERRA_WEBHOOK_SECRET`.

Endpoint rules:

- `https` only, on a public address. Private, loopback, link-local, CGNAT and cloud metadata addresses are
  refused.
- Terra resolves the address again on **every** delivery attempt, so a DNS change cannot point it at an internal
  network later.
- Redirects are not followed. Each attempt times out after 10 seconds, and Terra reads at most 256 KB of your
  response.

## Event types

| Event | When |
|---|---|
| `payment_intent.succeeded` | A payment intent was paid in full, verified on chain |
| `payment_intent.expired` | A payment intent expired without a full payment |
| `payment_intent.underpaid` | The customer paid less than the quoted amount |
| `invoice.paid` | An invoice was paid |
| `invoice.overdue` | An invoice passed its due date unpaid |
| `subscription.created` | A subscription was created |
| `subscription.renewed` | A subscription renewed for a new period |
| `subscription.payment_failed` | A renewal payment failed |
| `subscription.past_due` | A subscription is past due |
| `subscription.canceled` | A subscription was canceled |
| `payout_wallet.activated` | A payout wallet finished its cooldown and is active |

Each event carries a unique id (`evt_...`) and its type. The full event schema is published with the OpenAPI
document.

## The signature

Every delivery has a `Terra-Signature` header:

```text
Terra-Signature: t=1763884800,v1=5f2b...
```

- `t` is the Unix time when Terra signed the event.
- `v1` is the lowercase hex HMAC-SHA256 of `t + "." + raw_body`, keyed with your endpoint secret.

To verify:

1. Read the **raw** request body, exactly as received. Parsing and re-serialising JSON changes the bytes and
   breaks the signature.
2. Split the header on `,` and read `t` and every `v1`.
3. Reject the event if `t` is more than **5 minutes** from your clock (replay protection).
4. Compute the HMAC of `t + "." + raw_body` with your secret and compare it with each `v1` in **constant time**.
5. Only then parse the JSON.

### Node.js

```js
import { createHmac, timingSafeEqual } from "node:crypto";

const TOLERANCE_SECONDS = 5 * 60;

export function verifyTerraSignature(rawBody, header, secret, nowSeconds = Math.floor(Date.now() / 1000)) {
  if (typeof header !== "string" || header.length > 1024 || !secret) return false;
  let timestamp = null;
  const signatures = [];
  for (const part of header.split(",")) {
    const i = part.indexOf("=");
    if (i < 0) continue;
    const key = part.slice(0, i).trim();
    const value = part.slice(i + 1).trim();
    if (key === "t") timestamp = value;
    else if (key === "v1") signatures.push(value);
  }
  if (!timestamp || !/^\d+$/.test(timestamp) || signatures.length === 0) return false;
  if (Math.abs(nowSeconds - Number(timestamp)) > TOLERANCE_SECONDS) return false;
  const expected = createHmac("sha256", secret).update(`${timestamp}.`).update(rawBody).digest();
  return signatures.some((sig) => {
    if (!/^[0-9a-f]+$/i.test(sig)) return false;
    const given = Buffer.from(sig, "hex");
    return given.length === expected.length && timingSafeEqual(given, expected);
  });
}
```

With Express, take the raw body for this one route:

```js
// npm install express
import express from "express";
import { verifyTerraSignature } from "./verify-terra-signature.js";

const app = express();

app.post("/webhooks/terra", express.raw({ type: "application/json" }), async (req, res) => {
  if (!verifyTerraSignature(req.body, req.get("Terra-Signature"), process.env.TERRA_WEBHOOK_SECRET)) {
    return res.status(400).send("invalid signature");
  }
  const event = JSON.parse(req.body.toString("utf8"));
  if (await alreadyHandled(event.id)) return res.sendStatus(200); // repeats are normal
  await queueForProcessing(event); // do slow work after you answer
  res.sendStatus(200);
});
```

### Python

```python
import hashlib
import hmac
import time
from typing import Optional

TOLERANCE_SECONDS = 5 * 60
HEX = set("0123456789abcdef")

def verify_terra_signature(raw_body: bytes, header: str, secret: str, now: Optional[float] = None) -> bool:
    if not header or len(header) > 1024 or not secret:
        return False
    timestamp = None
    signatures = []
    for part in header.split(","):
        key, sep, value = part.strip().partition("=")
        if not sep:
            continue
        if key == "t":
            timestamp = value
        elif key == "v1":
            signatures.append(value.lower())
    if timestamp is None or not (timestamp.isascii() and timestamp.isdigit()) or not signatures:
        return False
    current = time.time() if now is None else now
    if abs(current - int(timestamp)) > TOLERANCE_SECONDS:
        return False
    expected = hmac.new(secret.encode(), timestamp.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return any(set(sig) <= HEX and hmac.compare_digest(expected, sig) for sig in signatures)
```

With Flask, `request.get_data()` returns the raw bytes:

```python
# pip install flask
import json
import os

from flask import Flask, abort, request

app = Flask(__name__)

@app.post("/webhooks/terra")
def terra_webhook():
    raw = request.get_data()
    if not verify_terra_signature(raw, request.headers.get("Terra-Signature", ""), os.environ["TERRA_WEBHOOK_SECRET"]):
        abort(400)
    event = json.loads(raw)
    # Handle each event id once, then do slow work in a background job.
    return "", 200
```

### PHP

```php
<?php
declare(strict_types=1);

const TERRA_TOLERANCE_SECONDS = 300;

function verify_terra_signature(string $rawBody, string $header, string $secret, ?int $now = null): bool
{
    if ($header === '' || strlen($header) > 1024 || $secret === '') {
        return false;
    }
    $timestamp = null;
    $signatures = [];
    foreach (explode(',', $header) as $part) {
        $pair = explode('=', trim($part), 2);
        if (count($pair) !== 2) {
            continue;
        }
        [$key, $value] = $pair;
        if ($key === 't') {
            $timestamp = $value;
        } elseif ($key === 'v1') {
            $signatures[] = strtolower($value);
        }
    }
    if ($timestamp === null || !ctype_digit($timestamp) || $signatures === []) {
        return false;
    }
    if (abs(($now ?? time()) - (int) $timestamp) > TERRA_TOLERANCE_SECONDS) {
        return false;
    }
    $expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
    foreach ($signatures as $signature) {
        if (hash_equals($expected, $signature)) {
            return true;
        }
    }
    return false;
}

// In your endpoint: read the raw body, never $_POST.
$rawBody = (string) file_get_contents('php://input');
$header = (string) ($_SERVER['HTTP_TERRA_SIGNATURE'] ?? '');
if (!verify_terra_signature($rawBody, $header, (string) getenv('TERRA_WEBHOOK_SECRET'))) {
    http_response_code(400);
    exit;
}
$event = json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR);
http_response_code(200);
```

Full handlers for Next.js, Node, Python and PHP are available from the MCP tool `get_code_sample` with
`product: "webhooks"`.

## Handling events safely

- **Answer fast.** Return a `2xx` within a few seconds, then do slow work in a background job. Anything else counts
  as a failed delivery.
- **Repeats are normal.** Terra retries with exponential backoff for 3 days, so the same event can arrive more
  than once. Store each event id and skip ids you have handled.
- **Order is not guaranteed.** A `payment_intent.succeeded` can arrive after a later event. Decide from the
  object's current state, not from arrival order.
- **An event is a hint, not proof.** Terra signs only events it verified on chain, but before you ship goods,
  confirm the payment's state with the API using your secret key.
- **Never log the secret** or the full signature header.

## Deliveries and replays

The dashboard keeps a delivery log for each endpoint, with every attempt and its response status, and lets you
replay a delivery by hand. Retries continue with exponential backoff for 3 days.

## Debugging a failed webhook

Check these in order:

1. **Raw body.** Is your framework parsing JSON before your handler runs? Use the raw bytes.
2. **Secret.** Is it the `whsec_...` of this endpoint? Each endpoint has its own secret, and an endpoint
   registered with a test key belongs to test mode only.
3. **Clock.** Is your server clock within 5 minutes of real time? Use NTP.
4. **Header name.** The header is `Terra-Signature`. In PHP it arrives as `$_SERVER['HTTP_TERRA_SIGNATURE']`.
5. **Response.** Does your endpoint return `2xx` within 10 seconds, with no redirect?
6. **Address.** Is the URL `https` and publicly reachable? Private and internal addresses are refused.

The MCP prompt "Debug a failed webhook" walks an AI assistant through the same checks.
