# Build a custom card-to-USDC checkout with the Caravel Pay API and webhooks

Source: https://caravelpay.app/guides/card-to-usdc-api-webhook-integration-guide/ · Caravel Pay guides · By the Caravel Pay team · Published 2026-11-26 · Updated 2026-11-26

Developer guide to POST /v1/connect, POST /v1/checkouts, HMAC-SHA256 webhook verification in Node.js and PHP, idempotency, key rotation and underpaid handling.

Integrating a custom card, Apple Pay and Google Pay checkout that settles in Polygon USDC takes three HTTP calls and one webhook handler: call unsigned `POST /v1/connect` once to obtain your `merchant_id` and 64-character hex `secret`, call signed `POST /v1/checkouts` per order and redirect the buyer to `checkout_url`, then verify incoming HMAC-SHA256 `POST` webhooks and re-read `GET /v1/checkouts/{id}` before fulfilling the order.

This end-to-end developer guide covers request signing, canonical test vectors, production-ready Node.js and PHP webhook handlers, idempotency with `order_id`, multi-token payouts, zero-downtime key rotation and all six checkout statuses as of 26 November 2026.

## Architecture and official SDKs

1. **Connect once (`POST /v1/connect`):** send your HTTPS `site_url` and ordinary Polygon `payout_address`. Receive `merchant_id` and `secret` (shown once).
2. **Create checkout on your server (`POST /v1/checkouts`):** sign with HMAC-SHA256, store `checkout.id` against your order, and redirect the buyer (`303 See Other`) to `checkout_url`.
3. **Buyer pays on the hosted checkout:** Visa, Mastercard, Apple Pay, Google Pay (via an independent card provider) or direct Polygon USDC, USDC.e or POL.
4. **Receive signed webhook (`POST {callback_url}`):** verify `Caravel-Signature` over the raw body, check the 300-second timestamp window, deduplicate by `event.id`, re-read `GET /v1/checkouts/{id}`, and fulfil only when `status === "paid"`.

If you prefer not to write the HTTP signing and constant-time verification code yourself, Caravel Pay ships zero-dependency SDKs: the [Node.js SDK](https://caravelpay.app/docs/node-sdk) ([`caravel-pay-1.2.2.tgz`](https://caravelpay.app/download/caravel-pay-1.2.2.tgz), Node 18.17+) and the [PHP SDK](https://caravelpay.app/docs/php-sdk) ([`caravel-php-1.2.2.zip`](https://caravelpay.app/download/caravel-php-1.2.2.zip), PHP 7.4–8.5 with `ext-curl` and `ext-json`), plus a Postman collection and single-file LLM spec on [Plugins and downloads](https://caravelpay.app/plugins/).

## Step 1: Get API keys with POST /v1/connect

`POST /v1/connect` is the only unsigned endpoint. Run it once from your server — never from browser or mobile client code:

*POST /v1/connect (run once on your server)*

```sh
curl https://api.caravelpay.app/v1/connect \
  -H "Content-Type: application/json" \
  --data-binary '{
    "site_url": "https://shop.example",
    "payout_address": "0x52908400098527886E0F7030069857D2E4169EE7",
    "email": "ops@shop.example",
    "platform": "api",
    "fee_mode": "seller"
  }'
```

*201 Created response*

```json
{
  "merchant_id": "mch_7Q2KZX4PRB",
  "secret": "9b2e7c4a1f6d8e3b5a0c9d2f7e4b1a6c3d8f5e2b9a7c4d1e6f3b8a5c2d9e7f4a",
  "status": "active",
  "fee_rate": "2%"
}
```

- **Origin lock:** every `return_url`, `cancel_url` and `callback_url` you pass later must be HTTPS on your registered `site_url` (with or without `www`).
- **Secret handling:** treat `secret` as a plain 64-character UTF-8 string when computing HMAC-SHA256 — **do not hex-decode it**. Store it outside your web root; it is never returned again.
- **Wallet rules:** `payout_address` must be an ordinary Polygon `0x` address you control (MetaMask, Rabby or a hardware wallet). Smart-contract wallets, token addresses and exchange deposit contracts are refused ([wallet rules](https://caravelpay.app/docs/connect#wallet)).

## Step 2: Sign requests and call POST /v1/checkouts

Every authenticated API call sends three headers: `Caravel-Merchant`, `Caravel-Timestamp` (current Unix seconds, within ±300 seconds of Caravel's clock) and `Caravel-Signature` (lowercase hex HMAC-SHA256). Build the canonical string with single `\n` separators and **no trailing newline**:

*Canonical string to sign*

```text
${timestamp}\n${METHOD}\n${path}\n${rawBody}
```

Use uppercase `METHOD` (`POST` or `GET`), the path without scheme or host (including query string if present, such as `/v1/checkouts?limit=50`), and the exact serialized `rawBody` bytes (empty string for `GET`). Verify your signing function against the official test vector in [Authentication docs](https://caravelpay.app/docs/authentication#test-vector) before sending live traffic.

*Create a checkout · Node.js 18+ (built-in fetch & node:crypto)*

```js
import crypto from "node:crypto";

const MERCHANT = process.env.CARAVEL_MERCHANT;
const SECRET = process.env.CARAVEL_SECRET;

export function signRequest(secret, timestamp, method, path, rawBody = "") {
  return crypto
    .createHmac("sha256", secret)
    .update(`${timestamp}\n${method}\n${path}\n${rawBody}`)
    .digest("hex");
}

export async function caravelRequest(method, path, payload = null) {
  const rawBody = payload ? JSON.stringify(payload) : ""; // Serialize ONCE
  const ts = String(Math.floor(Date.now() / 1000));
  const res = await fetch(`https://api.caravelpay.app${path}`, {
    method,
    headers: {
      ...(payload ? { "Content-Type": "application/json" } : {}),
      "Caravel-Merchant": MERCHANT,
      "Caravel-Timestamp": ts,
      "Caravel-Signature": signRequest(SECRET, ts, method, path, rawBody),
    },
    ...(payload ? { body: rawBody } : {}),
  });
  const data = await res.json();
  if (!res.ok) {
    const err = new Error(`${data.error?.code || "http_" + res.status}: ${data.error?.message || ""}`);
    err.status = res.status;
    err.code = data.error?.code;
    err.retryAfter = Number(res.headers.get("Retry-After") || 0);
    throw err;
  }
  return data;
}

// Create a checkout (USD or any of 26 other supported currencies)
const checkout = await caravelRequest("POST", "/v1/checkouts", {
  order_id: "ord_1042",
  amount: "136.41", // 2 decimals (0 decimals for JPY and KRW)
  currency: "USD",
  customer_email: "buyer@example.com",
  return_url: "https://shop.example/orders/1042/thanks",
  cancel_url: "https://shop.example/cart",
  callback_url: "https://shop.example/webhooks/caravel",
});
// Persist checkout.id with order 1042, then redirect buyer to checkout.checkout_url
```

*Create a checkout · PHP 7.4+ (ext-curl)*

```php
<?php
function caravel_request(string $method, string $path, ?array $payload = null): array
{
    $merchant = getenv('CARAVEL_MERCHANT');
    $secret   = getenv('CARAVEL_SECRET');
    $rawBody  = $payload !== null ? json_encode($payload, JSON_UNESCAPED_SLASHES) : '';
    $ts       = (string) time();
    $sig      = hash_hmac('sha256', "$ts\n$method\n$path\n$rawBody", $secret);

    $headers = [
        "Caravel-Merchant: $merchant",
        "Caravel-Timestamp: $ts",
        "Caravel-Signature: $sig",
    ];
    if ($payload !== null) {
        $headers[] = 'Content-Type: application/json';
    }

    $ch = curl_init('https://api.caravelpay.app' . $path);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST  => $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_HTTPHEADER     => $headers,
    ]);
    if ($payload !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $rawBody);
    }

    $resp   = (string) curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $data   = json_decode($resp, true) ?? [];
    if ($status < 200 || $status >= 300) {
        throw new RuntimeException(($data['error']['code'] ?? "http_$status") . ': ' . ($data['error']['message'] ?? ''));
    }
    return $data;
}

$checkout = caravel_request('POST', '/v1/checkouts', [
    'order_id'       => 'ord_1042',
    'amount'         => '136.41',
    'currency'       => 'USD',
    'customer_email' => 'buyer@example.com',
    'return_url'     => 'https://shop.example/orders/1042/thanks',
    'cancel_url'     => 'https://shop.example/cart',
    'callback_url'   => 'https://shop.example/webhooks/caravel',
]);
header('Location: ' . $checkout['checkout_url'], true, 303);
```

**Multi-currency and fee modes:** you can price checkouts in US dollars or 26 other currencies (EUR, GBP, CAD, AUD, NZD, SEK, NOK, DKK, CHF, PLN, CZK, HUF, RON, HKD, SGD, MXN, BRL, ZAR, ILS, INR, THB, MYR, PHP, TRY, JPY and KRW). Pass your store's own `amount` and `currency` without converting it yourself (JPY and KRW take whole integers like `"5000"`; optional `fx_buffer_bps` adds 0–500 bps of FX margin). Call `GET /v1/fx-quote?currency=EUR&amount=45.00` before redirecting to tell your buyer the estimated USD charge. Optional `fee_mode` overrides your default per checkout (`"seller"`, `"split"` or `"buyer"` — check local surcharge rules in the EU/UK first).

## Step 3: Idempotency, retries and expiry

- **`order_id` is your idempotency key.** Sending the exact same `order_id` with the same parameters returns the existing checkout (and the same locked `fx_rate` for non-USD orders) instead of creating a duplicate. Re-sign every retry with a fresh `Caravel-Timestamp`.
- **When to retry vs fix:** retry network timeouts, `429 rate_limited` (after `Retry-After` seconds), `500 server_error` and `503 service_unavailable` with exponential backoff and the same `order_id`. Never retry `400`, `401`, `403` or `409 order_id_conflict` (triggered if you reuse an `order_id` with a different amount, currency or `fee_mode`). See [Errors reference](https://caravelpay.app/docs/errors).
- **60-minute expiry:** checkouts expire 60 minutes after creation. If a buyer retries after expiry, generate a new `order_id` such as `ord_1042-2`.
- **Reconciliation via cursor pagination:** run a periodic job calling `GET /v1/checkouts?limit=100` (passing `cursor=next_cursor` until `null`) so even a prolonged webhook outage cannot leave an order out of sync.

## Step 4: Verify HMAC-SHA256 webhooks (Node.js and PHP)

Webhooks use the exact same signing format as API calls, over `POST`, the path (plus query string) of your `callback_url`, and the raw request bytes. Every webhook also sends `Caravel-Merchant` (for zero-downtime key rotation), `Caravel-Event` (matching `event.id`, stable across retries) and `User-Agent: CaravelPay-Webhooks/1`.

**Five rules every production webhook handler must follow:**

1. **Read raw bytes before JSON parsing.** Re-serializing parsed JSON breaks the HMAC.
2. **Compare in constant time and check the 300-second window.** Reject anything else with `401`.
3. **Support multiple secrets during wallet/key rotation.** When you call `POST /v1/connect` again to change wallets or rotate a secret, keep the old `merchant_id => secret` pair in a lookup map for at least 24 hours so in-flight checkouts still verify.
4. **Deduplicate on `event.id` and re-read `GET /v1/checkouts/{id}`.** Webhooks can retry (15 attempts over 24 hours: 1, 5, 15, 30 min, 1, 2, 3 h, then every 3 h) or arrive out of order. Re-fetching the checkout guarantees you act on its current authoritative state.
5. **Answer `2xx` within 10 seconds** and handle both `payout` and multi-token `payouts` (when a direct-crypto buyer pays partly in USDC and partly in USDC.e, sum `payouts` if present).

*Production HMAC-SHA256 webhook handler · Node.js (Express)*

```js
import crypto from "node:crypto";
import express from "express";
import { caravelRequest } from "./caravel.mjs";

const app = express();

// Keep old keys for >= 24h after rotating wallet/secret via POST /v1/connect
const SECRETS = {
  [process.env.CARAVEL_MERCHANT]: process.env.CARAVEL_SECRET,
  ...(process.env.CARAVEL_OLD_MERCHANT
    ? { [process.env.CARAVEL_OLD_MERCHANT]: process.env.CARAVEL_OLD_SECRET }
    : {}),
};

// Mount express.raw BEFORE any global express.json() middleware
app.post("/webhooks/caravel", express.raw({ type: "application/json" }), async (req, res) => {
  const merchantId = req.get("Caravel-Merchant") ?? "";
  const timestamp = req.get("Caravel-Timestamp") ?? "";
  const signature = req.get("Caravel-Signature") ?? "";
  const secret = SECRETS[merchantId];

  if (!secret || !/^\d+$/.test(timestamp)) return res.sendStatus(401);
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return res.sendStatus(401);

  // Behind a reverse proxy that rewrites paths, sign the exact path from callback_url
  const signedPath = req.originalUrl;
  const rawBody = req.body.toString("utf8");
  const expected = crypto
    .createHmac("sha256", secret)
    .update(`${timestamp}\nPOST\n${signedPath}\n${rawBody}`)
    .digest("hex");

  const valid =
    signature.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
  if (!valid) return res.sendStatus(401);

  const eventId = req.get("Caravel-Event") ?? "";
  if (eventId && (await db.events.has(eventId))) return res.sendStatus(200);

  const event = JSON.parse(rawBody);
  if (await db.events.has(event.id)) return res.sendStatus(200);

  // Re-read authoritative checkout state before mutating order
  const live = await caravelRequest("GET", `/v1/checkouts/${event.data.id}`);
  const order = await db.orders.findByCheckoutId(live.id);
  if (!order) {
    await db.events.add(event.id);
    return res.sendStatus(200);
  }

  // Verify amount & currency in your own currency (never compare paid_amount to non-USD totals)
  if (live.amount !== order.amount || live.currency !== order.currency) {
    await db.orders.flagMismatch(order.id, live);
    await db.events.add(event.id);
    return res.sendStatus(200);
  }

  switch (live.status) {
    case "paid": {
      const transfers = live.payouts ?? (live.payout ? [live.payout] : []);
      await db.orders.markPaid(order.id, transfers); // Fulfil even if order was previously expired
      break;
    }
    case "underpaid":
      await db.orders.markHold(order.id, "underpaid", live.paid_amount);
      break;
    case "review":
      await db.orders.markHold(order.id, "review", live.paid_amount);
      break;
    case "expired":
      await db.orders.cancelIfPending(order.id);
      break;
  }

  await db.events.add(event.id);
  return res.sendStatus(200);
});
```

*Production HMAC-SHA256 webhook handler · PHP 7.4+*

```php
<?php
require __DIR__ . '/caravel.php';

$secrets = array_filter([
    getenv('CARAVEL_MERCHANT')     => getenv('CARAVEL_SECRET'),
    getenv('CARAVEL_OLD_MERCHANT') => getenv('CARAVEL_OLD_SECRET'),
]);

$merchantId = $_SERVER['HTTP_CARAVEL_MERCHANT'] ?? '';
$timestamp  = $_SERVER['HTTP_CARAVEL_TIMESTAMP'] ?? '';
$signature  = $_SERVER['HTTP_CARAVEL_SIGNATURE'] ?? '';
$secret     = $secrets[$merchantId] ?? null;

if (!$secret || !ctype_digit($timestamp) || abs(time() - (int) $timestamp) > 300) {
    http_response_code(401);
    exit;
}

$rawBody  = file_get_contents('php://input');
$path     = $_SERVER['REQUEST_URI']; // Must match callback_url path + query string
$expected = hash_hmac('sha256', "$timestamp\nPOST\n$path\n$rawBody", $secret);

if (!hash_equals($expected, $signature)) {
    http_response_code(401);
    exit;
}

$event = json_decode($rawBody, true);
if (!is_array($event) || empty($event['id']) || empty($event['data']['id'])) {
    http_response_code(400);
    exit;
}

if (db_event_handled($event['id'])) {
    http_response_code(200);
    exit;
}

// Re-read the checkout via signed GET before changing order state
$live  = caravel_request('GET', '/v1/checkouts/' . rawurlencode($event['data']['id']));
$order = db_find_order_by_checkout_id($live['id']);

if ($order && $live['amount'] === $order['amount'] && $live['currency'] === $order['currency']) {
    switch ($live['status']) {
        case 'paid':
            $transfers = $live['payouts'] ?? (isset($live['payout']) ? [$live['payout']] : []);
            db_mark_order_paid($order['id'], $transfers);
            break;
        case 'underpaid':
        case 'review':
            db_hold_order($order['id'], $live['status'], $live['paid_amount'] ?? '0');
            break;
        case 'expired':
            db_cancel_if_pending($order['id']);
            break;
    }
}

db_remember_event($event['id']);
http_response_code(200);
```

## Step 5: Statuses, underpayments, late payments and testing

Never fulfil an order when the buyer lands on `return_url` — anyone can visit that URL, and the payment may still be confirming. Fulfil strictly on `status === "paid"`:

| Status | Webhook event | What it means & how your code should react |
|---|---|---|
| `awaiting_payment` | — | Created; buyer has not paid yet. Keep order pending. |
| `confirming` | — | Payment detected on Polygon, awaiting confirmation. Show "confirming" UI; do not fulfil yet. |
| `paid` | `checkout.paid` | At least 85% of checkout amount arrived (leaving room for the card provider's cut) and payout was sent (`payout.tx_hash`). Fulfil the order — even if an earlier `checkout.expired` already cancelled it. |
| `underpaid` | `checkout.underpaid` | Less than 85% arrived (usually a short direct-crypto transfer or tiny ticket hit by provider minimums). Hold the order, inspect `paid_amount` vs `amount`, and resolve with the buyer (top up or manual wallet refund). |
| `expired` | `checkout.expired` | 60 minutes elapsed without payment. Release inventory; allow buyer to start a new checkout with a new `order_id`. |
| `review` | `checkout.review` | Payment arrived after expiry or in an unsupported token/network. Keep order on hold and wait for a follow-up webhook or email [hello@caravelpay.app](mailto:hello@caravelpay.app) with the checkout id. |

### Fees recap and testing without a sandbox

Caravel Pay charges a flat **2% Caravel fee** on the order total (covering Polygon payout gas; $0 monthly and $0 setup). On a $100.00 card checkout in default `seller` mode, most independent card providers keep their own fee and exchange-rate spread — about 3% is typical of recent card orders through Caravel Pay, leaving 97.00 USDC arriving and roughly **95.00 USDC** in your Polygon wallet (estimate, not a guarantee: varies by provider, method, country and order size; about 1 in 4 arrived in full, a few routes up to about 8%–10%). Direct Polygon USDC checkouts pay out 98.00 USDC.

There is no sandbox environment. Test your integration in two passes:

1. **Local signature test:** send a signed `curl` webhook to your endpoint using the command in [Webhooks: Test your endpoint](https://caravelpay.app/docs/webhooks#testing) — verify it returns `200`, then flip one byte in the body after signing and verify it returns `401`.
2. **Live $1.00 end-to-end test:** create a real `"amount": "1.00"` checkout and pay it from a crypto wallet (for a card route use about `"10.00"`, because card providers set their own minimums, and most start between $5 and $7), confirm your webhook fires, re-reads `paid`, updates your database and records `payout.tx_hash`, and check your Polygon wallet.

## Frequently asked questions

### Why does my Caravel-Signature return 401 invalid_signature?

The four most common causes are: (1) signing the full URL instead of just the path (`/v1/checkouts`), (2) hex-decoding your 64-character secret instead of using it as a plain UTF-8 string, (3) adding a trailing newline after `rawBody`, or (4) letting your HTTP framework parse and re-encode JSON instead of verifying the exact raw bytes.

### Should I trust the webhook payload alone or call GET /v1/checkouts/{id}?

Always treat the verified webhook as a trigger and re-read `GET /v1/checkouts/{id}` before fulfilling an order. Because webhooks can arrive out of order during retries, re-fetching guarantees you act on the current authoritative status and payout object.

### Why does Caravel Pay mark a checkout paid at 85% instead of 100%?

On card payments, most independent card providers deduct their processing fee and exchange-rate spread before USDC reaches Polygon. The fixed 85% threshold leaves room for normal card provider cuts while automatically flagging severely short transfers (below 85%) as `underpaid` so your system never ships on a short payment.

### How do I rotate my payout wallet or secret without breaking open checkouts?

Call `POST /v1/connect` again with your new wallet or site details to obtain a new `merchant_id` and `secret`. Switch new `POST /v1/checkouts` calls to the new credentials, and keep the old `merchant_id => secret` mapping in your webhook handler for at least 24 hours so webhooks for in-flight checkouts still verify.

### What if checkout.paid arrives after I already received checkout.expired?

Rarely, a payment initiated just before the 60-minute expiry confirms on-chain slightly afterward. Caravel Pay sends `checkout.paid` and pays out your wallet as normal — your handler should fulfil the order (or alert staff to re-open/refund) whenever `paid` arrives, even if the local order was cancelled on expiry.

### What is the difference between payout and payouts on a checkout object?

On normal single-token payments (including all card payments), `payout` holds the transfer object (`amount`, `asset`, `tx_hash`) and `payouts` is omitted. If a direct-crypto buyer pays partly in one token and partly in another (such as USDC and USDC.e), Caravel Pay sends one payout per token and includes the full list in `payouts`; sum those amounts rather than assuming a single transfer.

## Sources

1. Caravel Pay API docs: [Get your API keys](https://caravelpay.app/docs/connect), [Authentication and request signing](https://caravelpay.app/docs/authentication), [Checkouts](https://caravelpay.app/docs/checkouts), [Webhooks](https://caravelpay.app/docs/webhooks), [Checkout statuses](https://caravelpay.app/docs/statuses), [Errors](https://caravelpay.app/docs/errors), checked 2026-11-26.
2. Caravel Pay SDKs & payouts: [Node.js SDK](https://caravelpay.app/docs/node-sdk), [PHP SDK](https://caravelpay.app/docs/php-sdk), [Payouts and fees](https://caravelpay.app/docs/payouts), [Plugins and downloads](https://caravelpay.app/plugins/), checked 2026-11-26.
