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

# Code samples

> **Preview.** The samples call the v1 API directly; the Terra SDKs are not published yet. Package names may change.

## Terra Connect

### Terra Connect: Next.js

```tsx
// Terra Connect in Next.js (App Router): find Terra Wallet with EIP-6963, then sign in with a signed message.
// Works today with the Terra Wallet extension. No Terra SDK needed.
// npm install ethers

// File: app/components/connect-terra-wallet.tsx
"use client";

import { useEffect, useState } from "react";

type Eip1193Provider = { request(args: { method: string; params?: unknown[] }): Promise<unknown> };
type Announced = { info: { uuid: string; name: string; icon: string; rdns: string }; provider: Eip1193Provider };

const TERRA_RDNS = "com.terrawallet.app";

export function ConnectTerraWallet() {
  const [terra, setTerra] = useState<Announced | null>(null);
  const [account, setAccount] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const onAnnounce = (event: Event) => {
      const detail = (event as CustomEvent<Announced>).detail;
      if (detail?.info?.rdns === TERRA_RDNS) setTerra(detail);
    };
    window.addEventListener("eip6963:announceProvider", onAnnounce);
    window.dispatchEvent(new Event("eip6963:requestProvider"));
    return () => window.removeEventListener("eip6963:announceProvider", onAnnounce);
  }, []);

  async function signIn() {
    setError(null);
    if (!terra) {
      setError("Terra Wallet is not installed in this browser. On a phone, use WalletConnect.");
      return;
    }
    try {
      const [address] = (await terra.provider.request({ method: "eth_requestAccounts" })) as string[];
      const { message } = await fetch("/api/auth/nonce", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ address }),
      }).then((r) => r.json());
      const signature = await terra.provider.request({ method: "personal_sign", params: [message, address] });
      const res = await fetch("/api/auth/verify", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ message, signature }),
      });
      if (!res.ok) throw new Error("verification failed");
      setAccount(address);
    } catch (e) {
      setError((e as { code?: number }).code === 4001 ? "You rejected the request." : "Could not sign in.");
    }
  }

  if (account) return <p>Signed in as {account}</p>;
  return (
    <div>
      <button onClick={signIn}>{terra ? "Sign in with Terra Wallet" : "Terra Wallet not found"}</button>
      {error && <p role="alert">{error}</p>}
    </div>
  );
}

// File: app/api/auth/nonce/route.ts
import { NextResponse } from "next/server";
import { randomBytes } from "node:crypto";
import { getAddress } from "ethers";

export async function POST(req: Request) {
  const { address } = await req.json();
  const nonce = randomBytes(16).toString("hex");
  const domain = "shop.example.com"; // your domain
  // Sign-In with Ethereum (EIP-4361) message format.
  const message =
    `${domain} wants you to sign in with your Ethereum account:\n${getAddress(address)}\n\n` +
    `Sign in to ${domain}.\n\nURI: https://${domain}\nVersion: 1\nChain ID: 1\nNonce: ${nonce}\n` +
    `Issued At: ${new Date().toISOString()}`;
  const res = NextResponse.json({ message });
  res.cookies.set("siwe_nonce", nonce, { httpOnly: true, secure: true, sameSite: "strict", maxAge: 300 });
  return res;
}

// File: app/api/auth/verify/route.ts
import { NextRequest } from "next/server";
import { verifyMessage } from "ethers";

export async function POST(req: NextRequest) {
  const { message, signature } = await req.json();
  const nonce = req.cookies.get("siwe_nonce")?.value;
  if (!nonce || typeof message !== "string" || !message.includes(`\nNonce: ${nonce}\n`)) {
    return NextResponse.json({ ok: false }, { status: 400 });
  }
  let address: string;
  try {
    address = verifyMessage(message, signature); // recovers the signer
  } catch {
    return NextResponse.json({ ok: false }, { status: 400 });
  }
  if (!message.includes(`\n${address}\n`)) return NextResponse.json({ ok: false }, { status: 400 });
  const res = NextResponse.json({ ok: true, address });
  res.cookies.delete("siwe_nonce"); // one nonce, one sign-in
  // Create your own session for `address` here.
  return res;
}
```

### Terra Connect: React

```tsx
// Terra Connect in React: a hook that finds Terra Wallet through EIP-6963 and connects to it.
// Works today with the Terra Wallet extension. No Terra SDK needed.
// For phones and other wallets, add WalletConnect (see the wagmi guide).

import { useCallback, useEffect, useState } from "react";

type Eip1193Provider = {
  request(args: { method: string; params?: unknown[] }): Promise<unknown>;
  on?(event: string, listener: (...args: unknown[]) => void): void;
  removeListener?(event: string, listener: (...args: unknown[]) => void): void;
};
type Announced = { info: { uuid: string; name: string; icon: string; rdns: string }; provider: Eip1193Provider };

const TERRA_RDNS = "com.terrawallet.app";

export function useTerraWallet() {
  const [wallet, setWallet] = useState<Announced | null>(null);
  const [account, setAccount] = useState<string | null>(null);
  const [chainId, setChainId] = useState<string | null>(null);

  useEffect(() => {
    const onAnnounce = (event: Event) => {
      const detail = (event as CustomEvent<Announced>).detail;
      if (detail?.info?.rdns === TERRA_RDNS) setWallet(detail);
    };
    window.addEventListener("eip6963:announceProvider", onAnnounce);
    window.dispatchEvent(new Event("eip6963:requestProvider"));
    return () => window.removeEventListener("eip6963:announceProvider", onAnnounce);
  }, []);

  useEffect(() => {
    const provider = wallet?.provider;
    if (!provider?.on) return;
    const onAccounts = (...args: unknown[]) => setAccount(((args[0] as string[]) ?? [])[0] ?? null);
    const onChain = (...args: unknown[]) => setChainId(String(args[0]));
    provider.on("accountsChanged", onAccounts);
    provider.on("chainChanged", onChain);
    return () => {
      provider.removeListener?.("accountsChanged", onAccounts);
      provider.removeListener?.("chainChanged", onChain);
    };
  }, [wallet]);

  const connect = useCallback(async () => {
    if (!wallet) throw new Error("Terra Wallet is not installed");
    const accounts = (await wallet.provider.request({ method: "eth_requestAccounts" })) as string[];
    setAccount(accounts[0] ?? null);
    setChainId(String(await wallet.provider.request({ method: "eth_chainId" })));
    return accounts[0] ?? null;
  }, [wallet]);

  const switchChain = useCallback(
    async (chainIdHex: string) => {
      if (!wallet) throw new Error("Terra Wallet is not installed");
      await wallet.provider.request({ method: "wallet_switchEthereumChain", params: [{ chainId: chainIdHex }] });
    },
    [wallet],
  );

  return { installed: wallet !== null, info: wallet?.info ?? null, account, chainId, connect, switchChain };
}

export function ConnectButton() {
  const { installed, info, account, connect } = useTerraWallet();
  const [error, setError] = useState<string | null>(null);

  if (account) return <span>Connected: {account}</span>;
  return (
    <>
      <button
        disabled={!installed}
        onClick={() =>
          connect().catch((e: { code?: number }) =>
            setError(e?.code === 4001 ? "You rejected the request." : "Could not connect."),
          )
        }
      >
        {info ? <img src={info.icon} alt="" width={20} height={20} /> : null}
        {installed ? "Connect Terra Wallet" : "Terra Wallet not found"}
      </button>
      {error && <p role="alert">{error}</p>}
    </>
  );
}
```

### Terra Connect: HTML

```html
<!--
  Terra Connect on a plain HTML page: find Terra Wallet with EIP-6963 and connect.
  Works today with the Terra Wallet extension. No Terra SDK and no build step needed.
-->
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Connect Terra Wallet</title>
  </head>
  <body>
    <button id="connect" disabled>Looking for Terra Wallet...</button>
    <p id="status" role="status"></p>

    <script type="module">
      const TERRA_RDNS = "com.terrawallet.app";
      const button = document.getElementById("connect");
      const status = document.getElementById("status");
      let terra = null;

      window.addEventListener("eip6963:announceProvider", (event) => {
        if (event.detail?.info?.rdns !== TERRA_RDNS) return;
        terra = event.detail;
        button.disabled = false;
        button.textContent = "Connect Terra Wallet";
      });
      window.dispatchEvent(new Event("eip6963:requestProvider"));

      setTimeout(() => {
        if (!terra) button.textContent = "Terra Wallet not found";
      }, 1000);

      button.addEventListener("click", async () => {
        try {
          const [account] = await terra.provider.request({ method: "eth_requestAccounts" });
          const chainId = await terra.provider.request({ method: "eth_chainId" });
          // textContent, never innerHTML: wallet data is untrusted input.
          status.textContent = `Connected ${account} on chain ${parseInt(chainId, 16)}`;
        } catch (error) {
          status.textContent = error?.code === 4001 ? "You rejected the request." : "Could not connect.";
        }
      });
    </script>
  </body>
</html>
```

### Terra Connect: React Native

```tsx
// Terra Connect from a React Native dApp: pair over WalletConnect v2 and hand the pairing to Terra Wallet with
// its terrawallet://wc deep link. Works today with the Terra Wallet app. No Terra SDK needed.
// npm install @walletconnect/sign-client @walletconnect/react-native-compat
// Get a project id from your WalletConnect (Reown) dashboard.

import "@walletconnect/react-native-compat"; // must be the first import
import SignClient from "@walletconnect/sign-client";
import { Linking } from "react-native";

let clientPromise: ReturnType<typeof SignClient.init> | null = null;

function getClient() {
  clientPromise ??= SignClient.init({
    projectId: "<your-walletconnect-project-id>",
    metadata: {
      name: "Example App",
      description: "Pay and sign in with your wallet",
      url: "https://app.example.com",
      icons: ["https://app.example.com/icon.png"],
      redirect: { native: "exampleapp://" }, // Terra Wallet sends the user back here
    },
  });
  return clientPromise;
}

/** Pair with Terra Wallet and return the session. */
export async function connectTerraWallet() {
  const client = await getClient();
  const { uri, approval } = await client.connect({
    optionalNamespaces: {
      eip155: {
        chains: ["eip155:1", "eip155:8453"], // Ethereum, Base
        methods: ["personal_sign", "eth_signTypedData_v4", "eth_sendTransaction"],
        events: ["accountsChanged", "chainChanged"],
      },
    },
  });
  if (uri) {
    // Open Terra Wallet on this phone with the pairing URI.
    await Linking.openURL(`terrawallet://wc?uri=${encodeURIComponent(uri)}`);
  }
  return approval(); // resolves when the user approves in Terra Wallet
}

function utf8ToHex(text: string) {
  return "0x" + Array.from(new TextEncoder().encode(text), (b) => b.toString(16).padStart(2, "0")).join("");
}

/** Ask Terra Wallet to sign a message, bringing the wallet to the front for the request. */
export async function signMessage(topic: string, address: string, message: string) {
  const client = await getClient();
  const pending = client.request<string>({
    topic,
    chainId: "eip155:1",
    request: { method: "personal_sign", params: [utf8ToHex(message), address] },
  });
  await Linking.openURL(`terrawallet://wc?sessionTopic=${encodeURIComponent(topic)}`);
  return pending; // the signature, once the user approves
}

// Usage:
//   const session = await connectTerraWallet();
//   const address = session.namespaces.eip155.accounts[0].split(":")[2];
//   const signature = await signMessage(session.topic, address, "Sign in to Example App");
// Verify the signature on your server (see the node or python connect sample).
```

### Terra Connect: Node.js

```js
// Terra Connect, server side in Node.js: verify a "Sign in with your wallet" message signed in Terra Wallet.
// Terra Connect itself runs in the browser or app; this is the check your server does afterwards.
// Works today. npm install ethers

import { randomBytes } from "node:crypto";
import { getAddress, verifyMessage } from "ethers";

/** A fresh single-use nonce. Store it with the user's pending sign-in and expire it after a few minutes. */
export function newNonce() {
  return randomBytes(16).toString("hex");
}

/** A Sign-In with Ethereum (EIP-4361) message for the wallet to sign with personal_sign. */
export function buildLoginMessage({ domain, address, nonce, chainId = 1, issuedAt = new Date().toISOString() }) {
  return [
    `${domain} wants you to sign in with your Ethereum account:`,
    getAddress(address),
    "",
    `Sign in to ${domain}.`,
    "",
    `URI: https://${domain}`,
    "Version: 1",
    `Chain ID: ${chainId}`,
    `Nonce: ${nonce}`,
    `Issued At: ${issuedAt}`,
  ].join("\n");
}

/**
 * True when `signature` is `address`'s signature of `message` and the message carries the nonce you issued.
 * Delete the nonce after one use, whatever the result.
 */
export function verifyLogin({ message, signature, address, nonce }) {
  if (typeof message !== "string" || typeof signature !== "string") return false;
  let recovered;
  try {
    recovered = verifyMessage(message, signature);
  } catch {
    return false; // malformed signature
  }
  if (getAddress(recovered) !== getAddress(address)) return false;
  return message.includes(`\nNonce: ${nonce}\n`);
}
```

### Terra Connect: Python

```python
# Terra Connect, server side in Python: verify a "Sign in with your wallet" message signed in Terra Wallet.
# Terra Connect itself runs in the browser or app; this is the check your server does afterwards.
# Works today. pip install eth-account

import secrets
from datetime import datetime, timezone

from eth_account import Account
from eth_account.messages import encode_defunct

def new_nonce() -> str:
    """A fresh single-use nonce. Store it with the pending sign-in and expire it after a few minutes."""
    return secrets.token_hex(16)

def build_login_message(domain: str, address: str, nonce: str, chain_id: int = 1) -> str:
    """A Sign-In with Ethereum (EIP-4361) message for the wallet to sign with personal_sign."""
    issued_at = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
    return "\n".join(
        [
            f"{domain} wants you to sign in with your Ethereum account:",
            address,
            "",
            f"Sign in to {domain}.",
            "",
            f"URI: https://{domain}",
            "Version: 1",
            f"Chain ID: {chain_id}",
            f"Nonce: {nonce}",
            f"Issued At: {issued_at}",
        ]
    )

def verify_login(message: str, signature: str, address: str, nonce: str) -> bool:
    """True when signature is address's signature of message and the message carries your nonce."""
    try:
        recovered = Account.recover_message(encode_defunct(text=message), signature=signature)
    except Exception:
        return False  # malformed signature
    if recovered.lower() != address.lower():
        return False
    return f"\nNonce: {nonce}\n" in message
```

### Terra Connect: PHP

Terra Connect runs in the browser or in an app, not on a PHP server.

- **On your pages:** use the `html` connect sample (EIP-6963 discovery, works today with the Terra Wallet
  extension) or WalletConnect v2 for phones.
- **On your PHP server:** the usual job is to verify a signed "Sign in with your wallet" message. That needs
  secp256k1 public-key recovery and Keccak-256, which PHP does not include. Use a maintained library that
  implements Sign-In with Ethereum (EIP-4361) for PHP, or verify in a small Node or Python service: see the
  `node` and `python` connect samples.
- Whatever you use, check three things: the recovered address equals the claimed address, the message carries
  the single-use nonce you issued, and the nonce is deleted after one use.

## Terra Pay checkout

### Terra Pay checkout: Next.js

```tsx
// Terra Pay in Next.js (App Router): create a payment intent on the server and redirect to hosted checkout.
// Preview: the Terra API is in early access and may change before launch.
// Set TERRA_SECRET_KEY (tw_test_sk_... or tw_live_sk_...) in your server environment only, never NEXT_PUBLIC_.

// File: app/api/checkout/route.ts
import { NextResponse } from "next/server";

// Live-mode (mainnet) assets with verified contracts, from the Terra docs page "Supported networks and assets".
// Test mode accepts testnet assets only.
const ACCEPTED_ASSETS = [
  { chain: "tron", symbol: "USDT", contract: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", decimals: 6 },
  { chain: "base", symbol: "USDC", contract: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", decimals: 6 },
  { chain: "solana", symbol: "USDC", contract: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", decimals: 6 },
];

// Your own data access. Never take the price from the browser.
declare function loadOrder(id: string): Promise<{ id: string; total: string } | null>;

export async function POST(req: Request) {
  const { orderId } = (await req.json()) as { orderId?: string };
  const order = orderId ? await loadOrder(orderId) : null;
  if (!order) return NextResponse.json({ error: "ORDER_NOT_FOUND" }, { status: 404 });

  const res = await fetch("https://terrawallet.us/api/v1/payment_intents", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.TERRA_SECRET_KEY}`,
      "Content-Type": "application/json",
      "Idempotency-Key": `order-${order.id}-checkout`, // a retry returns the same intent
    },
    body: JSON.stringify({
      amount: order.total, // a decimal string such as "120.00"
      currency: "USD",
      accepted_assets: ACCEPTED_ASSETS,
      description: `Order ${order.id}`,
      metadata: { order_id: order.id },
      success_url: `https://shop.example.com/orders/${order.id}/thanks`,
      cancel_url: "https://shop.example.com/cart",
    }),
  });
  const intent = await res.json();
  if (!res.ok) {
    console.error("Terra API error", res.status, intent?.error?.code, intent?.error?.requestId);
    return NextResponse.json({ error: "CHECKOUT_UNAVAILABLE" }, { status: 502 });
  }
  // Store intent.id with the order, then send the customer to hosted checkout.
  return NextResponse.json({ checkoutUrl: intent.checkout_url });
}

// File: app/checkout/pay-button.tsx
"use client";

import { useState } from "react";

export function PayButton({ orderId }: { orderId: string }) {
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function pay() {
    setBusy(true);
    setError(null);
    try {
      const res = await fetch("/api/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ orderId }),
      });
      if (!res.ok) throw new Error("checkout failed");
      const { checkoutUrl } = await res.json();
      window.location.assign(checkoutUrl); // https://pay.terrawallet.us/c/pi_...
    } catch {
      setError("Checkout is not available right now. Please try again.");
      setBusy(false);
    }
  }

  return (
    <>
      <button onClick={pay} disabled={busy}>{busy ? "Opening checkout..." : "Pay with crypto"}</button>
      {error && <p role="alert">{error}</p>}
    </>
  );
}

// Fulfil the order only from a verified payment_intent.succeeded webhook, never from the success_url redirect.
// See the "webhooks" sample for Next.js.
```

### Terra Pay checkout: React

```tsx
// Terra Pay in a React app: a "Pay with crypto" button that asks YOUR server for a checkout URL and redirects.
// Preview: the Terra API is in early access and may change before launch.
// The payment intent is created on your server with your secret key (see the node, python, php or nextjs
// samples). A secret key must never be in React code.

import { useState } from "react";

export function PayWithCrypto({ orderId }: { orderId: string }) {
  const [state, setState] = useState<"idle" | "busy" | "error">("idle");

  async function startCheckout() {
    setState("busy");
    try {
      // Your endpoint creates POST /v1/payment_intents and returns its checkout_url.
      const res = await fetch("/api/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ orderId }),
      });
      if (!res.ok) throw new Error(`checkout ${res.status}`);
      const { checkoutUrl } = (await res.json()) as { checkoutUrl: string };
      if (!checkoutUrl.startsWith("https://pay.terrawallet.us/")) throw new Error("unexpected checkout URL");
      window.location.assign(checkoutUrl);
    } catch {
      setState("error");
    }
  }

  return (
    <div>
      <button onClick={startCheckout} disabled={state === "busy"}>
        {state === "busy" ? "Opening checkout..." : "Pay with crypto"}
      </button>
      {state === "error" && <p role="alert">Checkout is not available right now. Please try again.</p>}
    </div>
  );
}

// After payment, checkout returns the customer to your success_url. That redirect is not proof of payment:
// show "We are confirming your payment" and fulfil from the verified webhook.
```

### Terra Pay checkout: HTML

```html
<!--
  Terra Pay on a plain HTML page: a button that asks YOUR server for a checkout URL, then redirects.
  Preview: the Terra API is in early access and may change before launch.
  Your server creates the payment intent with its secret key (see the node, python or php pay samples).
  A secret key must never appear in HTML or JavaScript.
  No server at all? Create a payment link in the dashboard and use a plain link to it instead:
    <a href="https://pay.terrawallet.us/l/plink_...">Pay with crypto</a>
-->
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Checkout</title>
  </head>
  <body>
    <button id="pay" data-order-id="1042">Pay with crypto</button>
    <p id="status" role="status"></p>

    <script type="module">
      const button = document.getElementById("pay");
      const status = document.getElementById("status");

      button.addEventListener("click", async () => {
        button.disabled = true;
        status.textContent = "Opening checkout...";
        try {
          const res = await fetch("/api/checkout", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ orderId: button.dataset.orderId }),
          });
          if (!res.ok) throw new Error("checkout failed");
          const { checkoutUrl } = await res.json();
          if (!String(checkoutUrl).startsWith("https://pay.terrawallet.us/")) throw new Error("unexpected URL");
          window.location.assign(checkoutUrl);
        } catch {
          status.textContent = "Checkout is not available right now. Please try again.";
          button.disabled = false;
        }
      });
    </script>
  </body>
</html>
```

### Terra Pay checkout: React Native

```tsx
// Terra Pay in a React Native app: ask YOUR server for a checkout URL and open hosted checkout.
// Preview: the Terra API is in early access and may change before launch.
// Your server creates the payment intent with its secret key (see the node, python or php pay samples).
// Never ship a secret key in an app: anyone can extract it.

import { useState } from "react";
import { Alert, Button, Linking } from "react-native";

const API = "https://api.yourapp.example"; // your backend

export function PayButton({ orderId }: { orderId: string }) {
  const [busy, setBusy] = useState(false);

  async function pay() {
    setBusy(true);
    try {
      const res = await fetch(`${API}/checkout`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ orderId }),
      });
      if (!res.ok) throw new Error(`checkout ${res.status}`);
      const { checkoutUrl } = (await res.json()) as { checkoutUrl: string };
      if (!checkoutUrl.startsWith("https://pay.terrawallet.us/")) throw new Error("unexpected checkout URL");
      // Hosted checkout opens in the browser. If Terra Wallet is installed, the customer can pay in one tap
      // from there; any other wallet works through WalletConnect or by address and QR code.
      await Linking.openURL(checkoutUrl);
    } catch {
      Alert.alert("Checkout unavailable", "Please try again in a moment.");
    } finally {
      setBusy(false);
    }
  }

  return <Button title={busy ? "Opening checkout..." : "Pay with crypto"} onPress={pay} disabled={busy} />;
}

// Set the payment intent's success_url to a page or app link of yours. When the customer comes back, show
// "Confirming your payment" and wait for your server, which fulfils only from the verified webhook.
```

### Terra Pay checkout: Node.js

```js
// Terra Pay in Node.js: create a payment intent and return its hosted checkout URL.
// Preview: the Terra API is in early access and may change before launch.
// Node 18 or later, no dependencies. Run: TERRA_SECRET_KEY=tw_test_sk_... node pay.mjs

import { createServer } from "node:http";
import { fileURLToPath } from "node:url";

const TERRA_API = "https://terrawallet.us/api/v1";

// Live-mode (mainnet) assets with verified contracts, from the Terra docs page "Supported networks and assets".
// Test mode accepts testnet assets only.
const ACCEPTED_ASSETS = [
  { chain: "tron", symbol: "USDT", contract: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", decimals: 6 },
  { chain: "bsc", symbol: "USDT", contract: "0x55d398326f99059fF775485246999027B3197955", decimals: 18 },
  { chain: "base", symbol: "USDC", contract: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", decimals: 6 },
];

/** Create a payment intent for an order you loaded from YOUR database. */
export async function createCheckout(order) {
  const res = await fetch(`${TERRA_API}/payment_intents`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.TERRA_SECRET_KEY}`,
      "Content-Type": "application/json",
      "Idempotency-Key": `order-${order.id}-checkout`,
    },
    body: JSON.stringify({
      amount: order.total, // decimal string, for example "120.00"
      currency: "USD",
      accepted_assets: ACCEPTED_ASSETS,
      description: `Order ${order.id}`,
      metadata: { order_id: String(order.id) },
      expires_in_s: 900,
      success_url: `https://shop.example.com/orders/${order.id}/thanks`,
      cancel_url: "https://shop.example.com/cart",
    }),
  });
  const body = await res.json().catch(() => null);
  if (!res.ok) {
    const e = body?.error ?? {};
    throw Object.assign(new Error(e.message ?? `Terra API error ${res.status}`), {
      status: res.status,
      code: e.code,
      requestId: e.requestId,
    });
  }
  return { intentId: body.id, checkoutUrl: body.checkout_url, status: body.status };
}

// A tiny endpoint: POST /api/checkout {"orderId":"1042"} -> {"checkoutUrl":"https://pay.terrawallet.us/c/pi_..."}
async function loadOrder(id) {
  return id === "1042" ? { id: "1042", total: "120.00" } : null; // replace with your database
}

const server = createServer(async (req, res) => {
  if (req.method !== "POST" || req.url !== "/api/checkout") return res.writeHead(404).end();
  try {
    let raw = "";
    for await (const chunk of req) {
      raw += chunk;
      if (raw.length > 10_000) return res.writeHead(413).end();
    }
    const order = await loadOrder(JSON.parse(raw).orderId);
    if (!order) return res.writeHead(404).end();
    const { checkoutUrl } = await createCheckout(order);
    res.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify({ checkoutUrl }));
  } catch (err) {
    console.error("checkout failed", err.code ?? "", err.requestId ?? "");
    res.writeHead(502).end();
  }
});

if (process.argv[1] === fileURLToPath(import.meta.url)) server.listen(3000);
```

### Terra Pay checkout: Python

```python
# Terra Pay in Python: create a payment intent and redirect to hosted checkout.
# Preview: the Terra API is in early access and may change before launch.
# pip install requests flask
# Run: TERRA_SECRET_KEY=tw_test_sk_... flask --app pay run

import os

import requests

TERRA_API = "https://terrawallet.us/api/v1"

# Live-mode (mainnet) assets with verified contracts, from the Terra docs page "Supported networks and assets".
# Test mode accepts testnet assets only.
ACCEPTED_ASSETS = [
    {"chain": "tron", "symbol": "USDT", "contract": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t", "decimals": 6},
    {"chain": "ethereum", "symbol": "USDC", "contract": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "decimals": 6},
    {"chain": "solana", "symbol": "USDC", "contract": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "decimals": 6},
]

class TerraError(Exception):
    def __init__(self, status, code, message, request_id):
        super().__init__(f"Terra API {status} {code}: {message} ({request_id})")
        self.status, self.code, self.request_id = status, code, request_id

def create_checkout(order_id: str, total: str) -> dict:
    """Create a payment intent for an order loaded from YOUR database. total is a decimal string."""
    res = requests.post(
        f"{TERRA_API}/payment_intents",
        headers={
            "Authorization": f"Bearer {os.environ['TERRA_SECRET_KEY']}",
            "Idempotency-Key": f"order-{order_id}-checkout",
        },
        json={
            "amount": total,
            "currency": "USD",
            "accepted_assets": ACCEPTED_ASSETS,
            "description": f"Order {order_id}",
            "metadata": {"order_id": order_id},
            "success_url": f"https://shop.example.com/orders/{order_id}/thanks",
            "cancel_url": "https://shop.example.com/cart",
        },
        timeout=30,
    )
    body = res.json() if res.content else {}
    if not res.ok:
        err = body.get("error", {})
        raise TerraError(res.status_code, err.get("code"), err.get("message"), err.get("requestId"))
    return {"intent_id": body["id"], "checkout_url": body["checkout_url"], "status": body["status"]}

def create_app():
    from flask import Flask, abort, redirect

    app = Flask(__name__)

    def load_order(order_id):
        return {"id": "1042", "total": "120.00"} if order_id == "1042" else None  # your database

    @app.post("/checkout/<order_id>")
    def checkout(order_id):
        order = load_order(order_id)
        if order is None:
            abort(404)
        try:
            session = create_checkout(order["id"], order["total"])
        except TerraError as err:
            app.logger.error("Terra checkout failed: %s %s", err.code, err.request_id)
            abort(502)
        # Store session["intent_id"] with the order, then send the customer to hosted checkout.
        return redirect(session["checkout_url"], code=303)

    return app

if __name__ == "__main__":
    create_app().run(port=3000)
```

### Terra Pay checkout: PHP

```php
<?php
// Terra Pay in PHP: create a payment intent and redirect to hosted checkout.
// Preview: the Terra API is in early access and may change before launch.
// PHP 8.1 or later with the curl extension. Set TERRA_SECRET_KEY in the server environment.

declare(strict_types=1);

const TERRA_API = 'https://terrawallet.us/api/v1';

// Live-mode (mainnet) assets with verified contracts, from the Terra docs page "Supported networks and assets".
// Test mode accepts testnet assets only.
const TERRA_ACCEPTED_ASSETS = [
    ['chain' => 'tron', 'symbol' => 'USDT', 'contract' => 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', 'decimals' => 6],
    ['chain' => 'polygon', 'symbol' => 'USDC', 'contract' => '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359', 'decimals' => 6],
    ['chain' => 'arbitrum', 'symbol' => 'USDC', 'contract' => '0xaf88d065e77c8cC2239327C5EDb3A432268e5831', 'decimals' => 6],
];

/** POST to the Terra API with your secret key. Returns the decoded JSON body. */
function terra_post(string $path, array $body, string $idempotencyKey): array
{
    $ch = curl_init(TERRA_API . $path);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . (string) getenv('TERRA_SECRET_KEY'),
            'Content-Type: application/json',
            'Idempotency-Key: ' . $idempotencyKey,
        ],
        CURLOPT_POSTFIELDS => json_encode($body, JSON_THROW_ON_ERROR),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
    ]);
    $raw = curl_exec($ch);
    $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);
    $data = is_string($raw) && $raw !== '' ? json_decode($raw, true) : null;
    if ($raw === false || $status >= 400 || !is_array($data)) {
        $err = is_array($data) ? ($data['error'] ?? []) : [];
        throw new RuntimeException(sprintf(
            'Terra API %d %s (%s)',
            $status,
            (string) ($err['code'] ?? 'NETWORK_ERROR'),
            (string) ($err['requestId'] ?? '')
        ));
    }
    return $data;
}

/** Create a payment intent for an order loaded from YOUR database. $total is a decimal string. */
function terra_create_checkout(string $orderId, string $total): array
{
    $intent = terra_post('/payment_intents', [
        'amount' => $total,
        'currency' => 'USD',
        'accepted_assets' => TERRA_ACCEPTED_ASSETS,
        'description' => 'Order ' . $orderId,
        'metadata' => ['order_id' => $orderId],
        'success_url' => 'https://shop.example.com/orders/' . rawurlencode($orderId) . '/thanks',
        'cancel_url' => 'https://shop.example.com/cart',
    ], 'order-' . $orderId . '-checkout');
    return ['intent_id' => $intent['id'], 'checkout_url' => $intent['checkout_url']];
}

// checkout.php?order=1042
if (PHP_SAPI !== 'cli') {
    $orderId = (string) ($_GET['order'] ?? '');
    $order = $orderId === '1042' ? ['id' => '1042', 'total' => '120.00'] : null; // your database
    if ($order === null) {
        http_response_code(404);
        exit;
    }
    try {
        $checkout = terra_create_checkout($order['id'], $order['total']);
    } catch (RuntimeException $e) {
        error_log($e->getMessage());
        http_response_code(502);
        exit;
    }
    // Store $checkout['intent_id'] with the order, then send the customer to hosted checkout.
    header('Location: ' . $checkout['checkout_url'], true, 303);
    exit;
}
```

## Subscriptions

### Subscriptions: Next.js

```tsx
// Terra Pay subscriptions in Next.js (App Router): subscribe the signed-in user to a plan, and grant or remove
// access from verified subscription webhooks.
// Preview: the Terra API is in early access and may change before launch.
// v1 subscriptions are "pay each period": Terra emails a renewal invoice each period and the customer pays it
// from their own wallet. Nothing is ever taken from a wallet automatically.
// Create the plan once (see the node sample) and set TERRA_PLAN_ID=plan_... in your environment.

// File: app/api/subscribe/route.ts
import { NextResponse } from "next/server";

declare function currentUser(): Promise<{ id: string; email: string } | null>; // your auth

export async function POST() {
  const user = await currentUser();
  if (!user) return NextResponse.json({ error: "SIGN_IN_REQUIRED" }, { status: 401 });

  const res = await fetch("https://terrawallet.us/api/v1/subscriptions", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.TERRA_SECRET_KEY}`,
      "Content-Type": "application/json",
      "Idempotency-Key": `subscribe-${user.id}-${process.env.TERRA_PLAN_ID}`,
    },
    body: JSON.stringify({ plan: process.env.TERRA_PLAN_ID, customer_email: user.email }),
  });
  const subscription = await res.json();
  if (!res.ok) {
    console.error("Terra API error", res.status, subscription?.error?.code, subscription?.error?.requestId);
    return NextResponse.json({ error: "SUBSCRIBE_UNAVAILABLE" }, { status: 502 });
  }
  // Save subscription.id with the user. The first invoice is emailed to the customer.
  return NextResponse.json({ subscriptionId: subscription.id, status: subscription.status });
}

// No sign-in on your side? Share the plan's subscription link instead:
//   https://pay.terrawallet.us/s/plan_...

// File: app/api/webhooks/terra/route.ts (subscription events)
// Verify the signature first: see the "webhooks" sample for verifyTerraSignature.
declare function verifyTerraSignature(rawBody: string, header: string | null, secret: string | undefined): boolean;
declare function alreadyHandled(eventId: string): Promise<boolean>;
declare function setAccess(event: { id: string; type: string }, active: boolean): Promise<void>;

export async function handleSubscriptionWebhook(req: Request) {
  const raw = await req.text();
  if (!verifyTerraSignature(raw, req.headers.get("Terra-Signature"), process.env.TERRA_WEBHOOK_SECRET)) {
    return new Response("invalid signature", { status: 400 });
  }
  const event = JSON.parse(raw) as { id: string; type: string };
  if (await alreadyHandled(event.id)) return new Response(null, { status: 200 });

  switch (event.type) {
    case "subscription.created":
    case "subscription.renewed":
      await setAccess(event, true);
      break;
    case "subscription.past_due":
    case "subscription.canceled":
      await setAccess(event, false);
      break;
    case "subscription.payment_failed":
      // Remind the customer to pay their renewal invoice.
      break;
  }
  return new Response(null, { status: 200 });
}
```

### Subscriptions: React

```tsx
// Terra Pay subscriptions in React: a Subscribe button.
// Preview: the Terra API is in early access and may change before launch.
// v1 subscriptions are "pay each period": the customer pays a renewal invoice each period from their own wallet.

import { useState } from "react";

// Option 1, no backend: link to the plan's hosted subscription page. The plan id is public, not a secret.
export function SubscribeLink({ planId }: { planId: string }) {
  return (
    <a href={`https://pay.terrawallet.us/s/${encodeURIComponent(planId)}`} rel="noopener">
      Subscribe with crypto
    </a>
  );
}

// Option 2, signed-in users: ask YOUR server to create the subscription (POST /v1/subscriptions with your
// secret key; see the nextjs or node subscriptions samples), so it is tied to the user's account.

export function SubscribeButton() {
  const [state, setState] = useState<"idle" | "busy" | "done" | "error">("idle");

  async function subscribe() {
    setState("busy");
    try {
      const res = await fetch("/api/subscribe", { method: "POST" });
      if (!res.ok) throw new Error(`subscribe ${res.status}`);
      setState("done");
    } catch {
      setState("error");
    }
  }

  if (state === "done") return <p>Check your email for your first invoice.</p>;
  return (
    <>
      <button onClick={subscribe} disabled={state === "busy"}>
        {state === "busy" ? "Subscribing..." : "Subscribe with crypto"}
      </button>
      {state === "error" && <p role="alert">Could not subscribe right now. Please try again.</p>}
    </>
  );
}
```

### Subscriptions: HTML

```html
<!--
  Terra Pay subscriptions on a plain HTML page: link to the plan's hosted subscription page.
  Preview: the Terra API is in early access and may change before launch.
  Create the plan once with your secret key on a server or in the dashboard (POST /v1/plans), then paste its
  plan_ id below. The plan id is public, not a secret.
  v1 subscriptions are "pay each period": the customer gets a renewal invoice each period and pays it from
  their own wallet, with reminders 7, 3 and 1 days before.
-->
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Pro plan</title>
  </head>
  <body>
    <h1>Pro</h1>
    <p>Paid each month in USDT or USDC from your own wallet.</p>
    <a href="https://pay.terrawallet.us/s/plan_..." rel="noopener">Subscribe with crypto</a>
  </body>
</html>
```

### Subscriptions: React Native

```tsx
// Terra Pay subscriptions in React Native: open the plan's hosted subscription page, or ask your server to
// subscribe the signed-in user.
// Preview: the Terra API is in early access and may change before launch.
// Never ship a secret key in an app. Subscriptions are created by your server or on the hosted page.

import { Alert, Button, Linking } from "react-native";

const API = "https://api.yourapp.example"; // your backend

/** No backend needed: the hosted subscription page. The plan id is public. */
export function SubscribeLink({ planId }: { planId: string }) {
  return (
    <Button
      title="Subscribe with crypto"
      onPress={() => Linking.openURL(`https://pay.terrawallet.us/s/${encodeURIComponent(planId)}`)}
    />
  );
}

/** Signed-in users: your server calls POST /v1/subscriptions with its secret key. */
export function SubscribeButton({ authToken }: { authToken: string }) {
  async function subscribe() {
    try {
      const res = await fetch(`${API}/subscribe`, {
        method: "POST",
        headers: { Authorization: `Bearer ${authToken}` }, // YOUR app's session, not a Terra key
      });
      if (!res.ok) throw new Error(`subscribe ${res.status}`);
      Alert.alert("Subscribed", "Check your email for your first invoice.");
    } catch {
      Alert.alert("Could not subscribe", "Please try again in a moment.");
    }
  }
  return <Button title="Subscribe with crypto" onPress={subscribe} />;
}

// Unlock features from your server's state, which it updates from verified subscription webhooks
// (subscription.created, renewed, past_due, canceled), never from anything the app reports.
```

### Subscriptions: Node.js

```js
// Terra Pay subscriptions in Node.js: create a plan once, subscribe customers, and react to subscription events.
// Preview: the Terra API is in early access and may change before launch.
// Node 18 or later, no dependencies.
// v1 subscriptions are "pay each period": Terra emails a renewal invoice each period, with reminders 7, 3 and
// 1 days before, and the customer pays it from their own wallet.

const TERRA_API = "https://terrawallet.us/api/v1";

async function terraPost(path, body, idempotencyKey) {
  const res = await fetch(`${TERRA_API}${path}`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.TERRA_SECRET_KEY}`,
      "Content-Type": "application/json",
      "Idempotency-Key": idempotencyKey,
    },
    body: JSON.stringify(body),
  });
  const json = await res.json().catch(() => null);
  if (!res.ok) {
    const e = json?.error ?? {};
    throw Object.assign(new Error(e.message ?? `Terra API error ${res.status}`), {
      status: res.status,
      code: e.code,
      requestId: e.requestId,
    });
  }
  return json;
}

/** Run once (for example in a setup script) and store the plan_ id in your config. */
export async function createProPlan() {
  const plan = await terraPost(
    "/plans",
    { name: "Pro", amount: "10.00", currency: "USD", interval: "month", interval_count: 1, trial_days: 14 },
    "plan-pro-monthly-v1",
  );
  // Share https://pay.terrawallet.us/s/<plan.id> or subscribe customers from your server below.
  return plan.id;
}

/** Subscribe a signed-in customer. Returns the subscription with its first invoice. */
export async function subscribe(user, planId) {
  return terraPost("/subscriptions", { plan: planId, customer_email: user.email }, `subscribe-${user.id}-${planId}`);
}

/**
 * Call this from your webhook endpoint AFTER verifying the Terra-Signature header (see the webhooks sample).
 * Store event ids and skip repeats: deliveries can repeat and arrive out of order.
 */
export async function onSubscriptionEvent(event, { grantAccess, revokeAccess, remindToPay }) {
  switch (event.type) {
    case "subscription.created":
    case "subscription.renewed":
      return grantAccess(event);
    case "subscription.past_due":
    case "subscription.canceled":
      return revokeAccess(event);
    case "subscription.payment_failed":
      return remindToPay(event);
    default:
      return undefined; // ignore event types you did not subscribe to
  }
}
```

### Subscriptions: Python

```python
# Terra Pay subscriptions in Python: create a plan once, subscribe customers, and react to subscription events.
# Preview: the Terra API is in early access and may change before launch.
# pip install requests
# v1 subscriptions are "pay each period": Terra emails a renewal invoice each period, with reminders 7, 3 and
# 1 days before, and the customer pays it from their own wallet.

import os

import requests

TERRA_API = "https://terrawallet.us/api/v1"

def terra_post(path: str, body: dict, idempotency_key: str) -> dict:
    res = requests.post(
        TERRA_API + path,
        json=body,
        headers={
            "Authorization": f"Bearer {os.environ['TERRA_SECRET_KEY']}",
            "Idempotency-Key": idempotency_key,
        },
        timeout=30,
    )
    data = res.json() if res.content else {}
    if not res.ok:
        err = data.get("error", {})
        raise RuntimeError(f"Terra API {res.status_code} {err.get('code')} ({err.get('requestId')})")
    return data

def create_pro_plan() -> str:
    """Run once and store the plan_ id in your config."""
    plan = terra_post(
        "/plans",
        {"name": "Pro", "amount": "10.00", "currency": "USD", "interval": "month", "interval_count": 1, "trial_days": 14},
        "plan-pro-monthly-v1",
    )
    # Share https://pay.terrawallet.us/s/<plan id> or subscribe customers with subscribe() below.
    return plan["id"]

def subscribe(user_id: str, email: str, plan_id: str) -> dict:
    """Subscribe a signed-in customer. Returns the subscription with its first invoice."""
    return terra_post("/subscriptions", {"plan": plan_id, "customer_email": email}, f"subscribe-{user_id}-{plan_id}")

def on_subscription_event(event: dict, grant_access, revoke_access, remind_to_pay) -> None:
    """Call AFTER verifying the Terra-Signature header (see the webhooks sample). Skip event ids you have seen."""
    kind = event.get("type")
    if kind in ("subscription.created", "subscription.renewed"):
        grant_access(event)
    elif kind in ("subscription.past_due", "subscription.canceled"):
        revoke_access(event)
    elif kind == "subscription.payment_failed":
        remind_to_pay(event)
```

### Subscriptions: PHP

```php
<?php
// Terra Pay subscriptions in PHP: create a plan once, subscribe customers, and react to subscription events.
// Preview: the Terra API is in early access and may change before launch.
// PHP 8.1 or later with the curl extension.
// v1 subscriptions are "pay each period": Terra emails a renewal invoice each period, with reminders 7, 3 and
// 1 days before, and the customer pays it from their own wallet.

declare(strict_types=1);

function terra_post(string $path, array $body, string $idempotencyKey): array
{
    $ch = curl_init('https://terrawallet.us/api/v1' . $path);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . (string) getenv('TERRA_SECRET_KEY'),
            'Content-Type: application/json',
            'Idempotency-Key: ' . $idempotencyKey,
        ],
        CURLOPT_POSTFIELDS => json_encode($body, JSON_THROW_ON_ERROR),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
    ]);
    $raw = curl_exec($ch);
    $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);
    $data = is_string($raw) && $raw !== '' ? json_decode($raw, true) : null;
    if ($raw === false || $status >= 400 || !is_array($data)) {
        $err = is_array($data) ? ($data['error'] ?? []) : [];
        throw new RuntimeException(sprintf('Terra API %d %s (%s)', $status, (string) ($err['code'] ?? ''), (string) ($err['requestId'] ?? '')));
    }
    return $data;
}

/** Run once and store the plan_ id in your config. */
function terra_create_pro_plan(): string
{
    $plan = terra_post('/plans', [
        'name' => 'Pro',
        'amount' => '10.00',
        'currency' => 'USD',
        'interval' => 'month',
        'interval_count' => 1,
        'trial_days' => 14,
    ], 'plan-pro-monthly-v1');
    // Share https://pay.terrawallet.us/s/<plan id> or subscribe customers below.
    return (string) $plan['id'];
}

/** Subscribe a signed-in customer. Returns the subscription with its first invoice. */
function terra_subscribe(string $userId, string $email, string $planId): array
{
    return terra_post('/subscriptions', ['plan' => $planId, 'customer_email' => $email], 'subscribe-' . $userId . '-' . $planId);
}

/** Call AFTER verifying the Terra-Signature header (see the webhooks sample). Skip event ids you have seen. */
function terra_on_subscription_event(array $event, callable $grantAccess, callable $revokeAccess, callable $remindToPay): void
{
    switch ($event['type'] ?? '') {
        case 'subscription.created':
        case 'subscription.renewed':
            $grantAccess($event);
            break;
        case 'subscription.past_due':
        case 'subscription.canceled':
            $revokeAccess($event);
            break;
        case 'subscription.payment_failed':
            $remindToPay($event);
            break;
    }
}
```

## Webhooks

### Webhooks: Next.js

```tsx
// Terra webhooks in Next.js (App Router): verify the Terra-Signature header on the raw body, handle each event
// once, and answer fast.
// Preview: the Terra API is in early access and may change before launch.
// Set TERRA_WEBHOOK_SECRET (whsec_..., shown once when you registered the endpoint) in your server environment.

// File: app/api/webhooks/terra/route.ts
import { createHmac, timingSafeEqual } from "node:crypto";

export const runtime = "nodejs"; // node:crypto
export const dynamic = "force-dynamic";

const TOLERANCE_SECONDS = 5 * 60;

function verifyTerraSignature(rawBody: string, header: string | null, secret: string | undefined): boolean {
  if (!header || header.length > 1024 || !secret) return false;
  let timestamp: string | null = null;
  const signatures: string[] = [];
  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(Date.now() / 1000 - Number(timestamp)) > TOLERANCE_SECONDS) return false;
  const expected = createHmac("sha256", secret).update(`${timestamp}.${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);
  });
}

// Your own storage and job queue.
declare function markHandled(eventId: string): Promise<boolean>; // false if the id was already stored
declare function enqueue(event: { id: string; type: string }): Promise<void>;

export async function POST(req: Request) {
  const raw = await req.text(); // the exact body Terra signed; do not use req.json() first
  if (!verifyTerraSignature(raw, req.headers.get("Terra-Signature"), process.env.TERRA_WEBHOOK_SECRET)) {
    return new Response("invalid signature", { status: 400 });
  }
  const event = JSON.parse(raw) as { id: string; type: string };

  // Deliveries can repeat and arrive out of order: handle each event id once.
  if (!(await markHandled(event.id))) return new Response(null, { status: 200 });

  // Answer within seconds; do the real work (fulfilment, emails) in a background job. Before shipping goods,
  // confirm the payment's current state with the API using your secret key.
  await enqueue(event);
  return new Response(null, { status: 200 });
}
```

### Webhooks: React

Webhooks are received by your **server**, never by a React app in the browser.

- Terra sends each event as a signed `POST` to an `https` endpoint you registered with
  `POST /v1/webhook_endpoints`. Verifying it needs the endpoint secret (`whsec_...`), which must never reach a
  browser.
- Use the `nextjs`, `node`, `python` or `php` webhooks sample for the endpoint.
- In React, show what your server knows: after checkout returns the customer to your `success_url`, show
  "Confirming your payment" and poll or subscribe to **your own** backend, which updates the order from the
  verified webhook.

### Webhooks: HTML

Webhooks are received by your **server**, never by an HTML page.

- Terra sends each event as a signed `POST` to an `https` endpoint you registered with
  `POST /v1/webhook_endpoints`. Verifying it needs the endpoint secret (`whsec_...`), which must never be in a
  page.
- On a PHP site, use the `php` webhooks sample. Otherwise use the `node` or `python` sample.
- On the page, show what your server knows: for example a "Thanks, we are confirming your payment" page at your
  `success_url` that reloads until your server marks the order paid from the verified webhook.

### Webhooks: React Native

Webhooks are received by your **server**, never by a mobile app.

- Terra sends each event as a signed `POST` to an `https` endpoint you registered with
  `POST /v1/webhook_endpoints`. Verifying it needs the endpoint secret (`whsec_...`), which must never ship in an
  app.
- Use the `nextjs`, `node`, `python` or `php` webhooks sample for the endpoint.
- In the app, read the order or subscription state from **your own** backend (or send a push notification from
  your server once it has handled the verified event). Never unlock anything from a value the app reports.

### Webhooks: Node.js

```js
// Terra webhooks in Node.js: verify the Terra-Signature header on the raw body, handle each event once, and
// answer fast.
// Preview: the Terra API is in early access and may change before launch.
// Node 18 or later, no dependencies. Run: TERRA_WEBHOOK_SECRET=whsec_... node webhooks.mjs

import { createHmac, timingSafeEqual } from "node:crypto";
import { createServer } from "node:http";
import { fileURLToPath } from "node:url";

const TOLERANCE_SECONDS = 5 * 60; // reject events signed more than 5 minutes ago (replay protection)
const MAX_BODY_BYTES = 1024 * 1024; // your own cap for incoming bodies

/** True when `header` (Terra-Signature) is a valid signature of `rawBody` (Buffer or string) with `secret`. */
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);
  });
}

const handled = new Set(); // use your database in production, keyed by event id

async function handleEvent(event) {
  switch (event.type) {
    case "payment_intent.succeeded":
      // Confirm the payment's state with the API using your secret key, then fulfil the order.
      break;
    case "payment_intent.underpaid":
    case "payment_intent.expired":
      // Tell the customer; offer a new checkout.
      break;
    default:
      break;
  }
}

const server = createServer(async (req, res) => {
  if (req.method !== "POST" || req.url !== "/webhooks/terra") return res.writeHead(404).end();
  const chunks = [];
  let size = 0;
  for await (const chunk of req) {
    size += chunk.length;
    if (size > MAX_BODY_BYTES) return res.writeHead(413).end();
    chunks.push(chunk);
  }
  const rawBody = Buffer.concat(chunks);
  if (!verifyTerraSignature(rawBody, req.headers["terra-signature"], process.env.TERRA_WEBHOOK_SECRET)) {
    return res.writeHead(400).end("invalid signature");
  }
  const event = JSON.parse(rawBody.toString("utf8"));
  if (handled.has(event.id)) return res.writeHead(200).end(); // repeats are normal
  handled.add(event.id);
  res.writeHead(200).end(); // answer fast
  handleEvent(event).catch((err) => console.error("webhook job failed", event.id, err.message));
});

if (process.argv[1] === fileURLToPath(import.meta.url)) server.listen(3000);
```

### Webhooks: Python

```python
# Terra webhooks in Python: verify the Terra-Signature header on the raw body, handle each event once, and
# answer fast.
# Preview: the Terra API is in early access and may change before launch.
# pip install flask
# Run: TERRA_WEBHOOK_SECRET=whsec_... flask --app webhooks:create_app run

import hashlib
import hmac
import json
import os
import time
from typing import Optional

TOLERANCE_SECONDS = 5 * 60  # reject events signed more than 5 minutes ago (replay protection)
HEX = set("0123456789abcdef")

# True when header (Terra-Signature) is a valid signature of raw_body with secret.
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)

def create_app():
    from flask import Flask, abort, request

    app = Flask(__name__)
    handled = set()  # use your database in production, keyed by event id

    @app.post("/webhooks/terra")
    def terra_webhook():
        raw = request.get_data()  # the exact bytes Terra signed
        header = request.headers.get("Terra-Signature", "")
        if not verify_terra_signature(raw, header, os.environ.get("TERRA_WEBHOOK_SECRET", "")):
            abort(400)
        event = json.loads(raw)
        if event.get("id") in handled:
            return "", 200  # repeats are normal
        handled.add(event.get("id"))
        # Answer fast: hand the event to a background job. For payment_intent.succeeded, confirm the payment's
        # state with the API using your secret key before fulfilling.
        return "", 200

    return app
```

### Webhooks: PHP

```php
<?php
// Terra webhooks in PHP: verify the Terra-Signature header on the raw body, handle each event once, and
// answer fast.
// Preview: the Terra API is in early access and may change before launch.
// PHP 8.1 or later. Set TERRA_WEBHOOK_SECRET (whsec_...) in the server environment.

declare(strict_types=1);

const TERRA_TOLERANCE_SECONDS = 300; // reject events signed more than 5 minutes ago (replay protection)

/** True when $header (Terra-Signature) is a valid signature of $rawBody with $secret. */
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;
}

// The endpoint, for example webhooks/terra.php
if (PHP_SAPI !== 'cli') {
    $rawBody = (string) file_get_contents('php://input'); // the raw body, never $_POST
    $header = (string) ($_SERVER['HTTP_TERRA_SIGNATURE'] ?? '');
    if (!verify_terra_signature($rawBody, $header, (string) getenv('TERRA_WEBHOOK_SECRET'))) {
        http_response_code(400);
        exit;
    }
    try {
        $event = json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR);
    } catch (JsonException $e) {
        http_response_code(400);
        exit;
    }
    // Deliveries can repeat and arrive out of order: store $event['id'] and skip ids you have handled.
    // Answer fast, then process in a background job. For payment_intent.succeeded, confirm the payment's state
    // with the API using your secret key before fulfilling.
    http_response_code(200);
    exit;
}
```
