API basics
Early accessWebhooks
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.
Register an endpoint#
Shell
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:
httpsonly, 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=f2b...tis the Unix time when Terra signed the event.v1is the lowercase hex HMAC-SHA256 oft + "." + raw_body, keyed with your endpoint secret.
To verify:
- Read the raw request body, exactly as received. Parsing and re-serialising JSON changes the bytes and breaks the signature.
- Split the header on
,and readtand everyv1. - Reject the event if
tis more than 5 minutes from your clock (replay protection). - Compute the HMAC of
t + "." + raw_bodywith your secret and compare it with eachv1in constant time. - Only then parse the JSON.
Node.js#
JavaScript
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-a-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:
JavaScript
// npm install expressimport 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 hashlibimport hmacimport timefrom typing import Optional TOLERANCE_SECONDS = 5 * 60HEX = 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 flaskimport jsonimport 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 "", 200PHP#
PHP
<?phpdeclare(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
2xxwithin 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.succeededcan 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:
- Raw body. Is your framework parsing JSON before your handler runs? Use the raw bytes.
- 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. - Clock. Is your server clock within 5 minutes of real time? Use NTP.
- Header name. The header is
Terra-Signature. In PHP it arrives as$_SERVER['HTTP_TERRA_SIGNATURE']. - Response. Does your endpoint return
2xxwithin 10 seconds, with no redirect? - Address. Is the URL
httpsand publicly reachable? Private and internal addresses are refused.
The MCP prompt "Debug a failed webhook" walks an AI assistant through the same checks.