# Checkout


Three ways to collect a payment after `POST /v1/payments`:

| Option | Effort | UX |
|---|---|---|
| **Hosted page** — redirect to `checkout_url` | lowest | full page on `https://razcryptogateway.com` |
| **`checkout.js` modal** | low | Razorpay-style modal on your site (full-screen on mobile) |
| **Custom checkout** — your own UI via API | most | fully yours |

## 1. Hosted page
Redirect the customer to `payment.checkout_url`. Flow: choose **network → coin** (steps skipped if
only one option) → QR + address + exact amount + timer → live status → success.
After `paid`, if you passed `redirect_url`, we send the customer to:
```
https://shop.example.com/thanks?payment_id=pay_…&reference_id=order_1042&status=paid&signature=<hex>
```
Verify `signature` (below) before trusting the query.

## 2. `checkout.js`
```html
<script src="https://razcryptogateway.com/v1/checkout.js"></script>
<button id="pay">Pay with crypto</button>
<script>
  document.getElementById("pay").onclick = () => {
    RazCrypto.open({
      key: "pk_test_…",                 // publishable key
      payment_id: "pay_3fK9sQ2mZt7LxR1aPq0B", // created on your server
      locale: "en",                       // "en" | "hi"
      theme: "auto",                      // "light" | "dark" | "auto"
      onSuccess(res) {
        // res = { payment_id, reference_id, status: "paid", signature }
        fetch("/verify-payment", { method: "POST", headers: { "Content-Type": "application/json" },
          body: JSON.stringify(res) });
      },
      onPending(res) { /* status "confirming": seen on-chain, waiting for confirmations */ },
      onClose() { /* customer closed the modal */ },
      onError(err) { /* { code, message } */ },
    });
  };
</script>
```
- Opens an iframe to `https://razcryptogateway.com/embed/{payment_id}`; the iframe exchanges your publishable
  key for the payment's client token (`POST /checkout/v1/sessions`, secret keys are refused). Messages use
  `postMessage`; origins and the source window are checked on both sides. `Esc` asks before closing.
- `onSuccess` fires on `paid`. Your webhook still arrives — handle both idempotently.
- About 2 KB gzip, no dependencies. Also on npm as `@razcrypto/checkout`.
- Pinned builds (`/v1/checkout.<version>.js`) publish an SRI hash so you can add
  `integrity="sha384-…" crossorigin="anonymous"`; `/v1/checkout.js` always serves the latest v1.

## 3. Checkout signature (callback & redirect)
```
signature = hex( HMAC_SHA256( signing_secret, payment_id + "|" + reference_id + "|" + status ) )
```
`signing_secret` is your API app's secret `whsec_…` (Dashboard → Developers → App → Signing secret);
it is the same secret that signs webhooks. Use the whole string, including `whsec_`, as the HMAC key.
`reference_id` is an empty string if you did not set one. Verify on **your server**, with a
constant-time compare, and check `payment_id` belongs to your order. For full certainty, also fetch
`GET /v1/payments/{id}`. (We never store your `sk_…` key in readable form, so it cannot sign.)

```js
// Node
const msg = `${payment_id}|${reference_id ?? ""}|${status}`;
const expected = crypto.createHmac("sha256", process.env.RAZCRYPTO_SIGNING_SECRET).update(msg).digest("hex");
const ok = crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
```
```php
$ok = hash_equals(hash_hmac('sha256', "$paymentId|$referenceId|$status", getenv('RAZCRYPTO_SIGNING_SECRET')), $signature);
```
```python
ok = hmac.compare_digest(hmac.new(secret.encode(), f"{pid}|{ref}|{status}".encode(), hashlib.sha256).hexdigest(), signature)
```

## 4. Custom checkout (server-side)
**Single coin?** Send `chain` + `coin` in `POST /v1/payments` and the response already has `quote` (address, amount, QR) — see [Payments → One call for your own payment page](/docs/payments). Otherwise:

1. `POST /v1/payments` → payment.
2. Show your own network/coin picker using `GET /v1/payments/{id}/methods`:
```json
{ "object": "list", "data": [
  { "chain": "bsc", "chain_name": "BNB Smart Chain", "coins": [
    { "coin": "USDT", "name": "Tether USD", "decimals": 18, "logo_url": "https://…/usdt.svg", "estimated_amount": "25.03" }
  ] }
] }
```
3. `POST /v1/payments/{id}/quote` `{ "chain": "bsc", "coin": "USDT" }` → payment with `quote`
   (`address`, exact `amount`, `payment_uri`, `wallet_links`, `expires_at`).
4. Show QR of `payment_uri` (and an address-only QR option — some exchanges reject URIs).
5. Poll `GET /v1/payments/{id}` every 5–10 s, or rely on webhooks.

### Payment URI formats we return
| Family | Format |
|---|---|
| EVM native | `ethereum:<address>@<chainId>?value=<wei>` |
| EVM token | `ethereum:<token_contract>@<chainId>/transfer?address=<address>&uint256=<base_units>` (EIP-681) |
| Solana | `solana:<address>?amount=<decimal>&spl-token=<mint>&reference=<ref>&label=<name>` (Solana Pay) |

`wallet_links`: MetaMask (`https://metamask.app.link/send/…`), Trust Wallet
(`https://link.trustwallet.com/send?asset=…&address=…&amount=…`), Phantom (Solana Pay URI /
`https://phantom.app/ul/browse/…`).

## 5. Public checkout API (used by our page and `checkout.js`)
Base: `https://razcryptogateway.com/checkout/v1`. Authorised by the payment's
client token — the `t` value in `checkout_url` — as `?t=` or the `X-Checkout-Token` header.
Not for server use; customer data and metadata are never returned here.

| Method | Path | Purpose |
|---|---|---|
| POST | `/sessions` | `{ "key": "pk_…", "payment_id" }` → `client_token` (used by the `checkout.js` iframe; secret keys refused) |
| GET | `/payments/{id}` | Public payment view + merchant branding + `test_mode` |
| GET | `/payments/{id}/methods` | Networks & coins |
| POST | `/payments/{id}/quote` | `{ "chain", "coin" }` — lock coin, get address + exact amount (also used to refresh an expired rate) |
| POST | `/payments/{id}/cancel` | Only if the merchant set `cancel_url` and nothing was received |
| GET | `/payments/{id}/events` | Server-Sent Events: `event: status` with `{ "status": … }` on every change; `: ping` every 25 s |
| GET | `/payments/{id}/qr.svg` · `/qr.png` | QR image; `?type=uri` (payment URI, default) or `?type=address` (plain address — some exchanges reject URIs) |
| POST | `/payments/{id}/claim` | "I already paid": `{ "tx_hash" }`. We read the transaction from the chain; transfers to this payment's address in the quoted coin that are not linked to another payment are attached (even with an inexact amount). Response = payment view + `claim: { attached }`. 404 if the tx is not on chain yet. Live mode only; 5/min |
| POST | `/payments/{id}/closed` | Customer left via the exit dialog; recorded on the timeline (payment stays open) |

When the payment is `paid`, `GET /payments/{id}` includes
`result: { payment_id, reference_id, status, signature, redirect_to }` — the `checkout.js` `onSuccess`
payload; `redirect_to` is your `redirect_url` with those values added as query parameters. Links made in the
dashboard (no API app) redirect without `signature` — check the payment with the API before you trust it.

Real output (test mode, coin-priced payment that was auto-quoted):
```bash
curl "https://razcryptogateway.com/checkout/v1/payments/pay_QP3ECwWl7qMXI5cz1xP4?t=ct_…"
```
```json
{
  "id": "pay_QP3ECwWl7qMXI5cz1xP4",
  "object": "payment",
  "livemode": false,
  "status": "pending",
  "flags": [],
  "amount": "10",
  "currency": "USDT",
  "reference_id": "order_1043",
  "description": null,
  "allowed_chains": [
    "bsc"
  ],
  "allowed_coins": null,
  "quote": {
    "chain": "bsc",
    "coin": "USDT",
    "address": "0x52908400098527886E0F7030069857D2E4169EE7",
    "amount": "10.0003",
    "payment_uri": "ethereum:0x55d398326f99059fF775485246999027B3197955@56/transfer?address=0x52908400098527886E0F7030069857D2E4169EE7&uint256=10000300000000000000",
    "wallet_links": [
      {
        "wallet": "metamask",
        "url": "https://metamask.app.link/send/0x55d398326f99059fF775485246999027B3197955@56/transfer?address=0x52908400098527886E0F7030069857D2E4169EE7&uint256=10000300000000000000"
      },
      {
        "wallet": "trust",
        "url": "https://link.trustwallet.com/send?asset=c20000714_t0x55d398326f99059fF775485246999027B3197955&address=0x52908400098527886E0F7030069857D2E4169EE7&amount=10.0003"
      }
    ],
    "finality": "finalized",
    "expires_at": "2026-10-02T12:05:14.266Z"
  },
  "amount_received": null,
  "transfers": [],
  "checkout_url": "https://razcryptogateway.com/pay_QP3ECwWl7qMXI5cz1xP4?t=ct_…",
  "redirect_url": null,
  "cancel_url": null,
  "payment_link": null,
  "expires_at": "2026-10-02T12:05:14.266Z",
  "paid_at": null,
  "created_at": "2026-10-02T11:35:14.267Z",
  "merchant": {
    "name": "Docs Demo Store",
    "accent_color": null,
    "logo_url": null,
    "support_email": null,
    "show_powered_by": true
  },
  "test_mode": true
}
```
Wrong or missing token:
```json
{
  "error": {
    "type": "invalid_request_error",
    "code": "resource_missing",
    "message": "Payment not found",
    "request_id": "req_0bFUNugT9RTLsBwu",
    "doc_url": "https://razcryptogateway.com/docs/errors#resource_missing"
  }
}
```
