Guides
Add checkout to your website
Create a payment page for each order, send your customer to it, then check on your server that they paid.
How it works
- Your server works out the total and saves the order.
- Your server creates a checkout, and saves its ID with the order.
- Your customer pays on Switro.
- Switro sends your server a webhook.
- Your server gets the payment from the API, checks it, then marks the order as paid.

Coming back to your website does not prove payment
Complete sample
This is a small shop with one product. It uses Node.js 22 or later, with nothing else to install.
Get your API key and wallet ready
Choose devnet in the dashboard and add your wallet. Then open Settings, then API, and copy your Checkout API key.

Your API key and webhook settings. The keys shown are not real. Shown with sample data. Save the two files in one folder
checkout-server.mjs // A small shop that uses hosted checkout, with one product. // It also needs verify-webhook.mjs, in the same folder. import { randomUUID } from "node:crypto"; import { createServer } from "node:http"; import { verifySwitroWebhook } from "./verify-webhook.mjs"; const API = process.env.SWITRO_API_URL ?? "https://www.switro.com/api"; const PORT = Number(process.env.PORT ?? 4000); const SITE = process.env.SITE_URL ?? `http://localhost:${PORT}`; const NETWORK = process.env.SWITRO_NETWORK ?? "devnet"; // Prices stay on your server. Never use a price sent by the browser. const PRODUCT = { name: "Ceramic mug", cents: 2400 }; // Use a database in a real shop. These are lost when the server stops. const orders = new Map(); // order ID -> { checkoutId, cents, paymentId } async function switro(method, path, body) { const response = await fetch(`${API}${path}`, { method, redirect: "error", signal: AbortSignal.timeout(20_000), headers: { Authorization: `Bearer ${process.env.SWITRO_API_KEY}`, "Content-Type": "application/json", }, body: body && JSON.stringify(body), }); if (!response.ok) throw new Error(`Switro answered ${response.status}`); return response.json(); } async function readBody(request) { const parts = []; let size = 0; for await (const part of request) { size += part.length; if (size > 100_000) throw new Error("The request is too large"); parts.push(part); } return Buffer.concat(parts); } /** Asks Switro about the payment, and checks it against the saved order. */ async function checkPayment(paymentId) { const payment = await switro("GET", `/v1/payment/${encodeURIComponent(paymentId)}`); const order = [...orders.values()].find(({ checkoutId }) => checkoutId === payment.checkout_id); const isPaid = order && payment.status === "confirmed" && payment.network === NETWORK && Math.round(Number(payment.amount_original) * 100) === order.cents; if (!isPaid || order.paymentId) return; order.paymentId = payment.id; // Deliver the order here, only once. } function page(response, content) { response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); response.end(`<!doctype html><html lang="en"><meta charset="utf-8"> <meta name="viewport" content="width=device-width"><title>Sample shop</title>${content}</html>`); } const getOrderId = (request) => /(?:^|;\s*)order=([0-9a-f-]{36})/.exec(request.headers.cookie ?? "")?.[1]; async function handle(request, response) { const route = `${request.method} ${new URL(request.url, SITE).pathname}`; if (route === "GET /") { return page(response, `<h1>${PRODUCT.name}</h1><p>$${(PRODUCT.cents / 100).toFixed(2)}</p> <form action="/checkout" method="post"><button>Buy now</button></form>`); } if (route === "POST /checkout") { // Only accepts the form on this website. if (request.headers.origin !== SITE) return response.writeHead(403).end(); const orderId = randomUUID(); const checkout = await switro("POST", "/v1/checkout", { amount_total: PRODUCT.cents / 100, amount_currency: "USD", order_reference_id: orderId, success_url: `${SITE}/order`, cancel_url: SITE, items: [{ item_title: PRODUCT.name, item_quantity: 1, item_amount: PRODUCT.cents / 100 }], }); // Save the order before the customer pays. orders.set(orderId, { checkoutId: checkout.id, cents: PRODUCT.cents, paymentId: null }); const secure = SITE.startsWith("https:") ? "; Secure" : ""; return response .writeHead(303, { Location: checkout.url, "Set-Cookie": `order=${orderId}; HttpOnly; SameSite=Lax; Path=/${secure}`, }) .end(); } if (route === "GET /order") { // Opening this page does not prove that someone paid. const order = orders.get(getOrderId(request)); if (!order) return page(response, "<h1>There is no order</h1>"); return page(response, order.paymentId ? "<h1>Your order is paid</h1>" : `<meta http-equiv="refresh" content="5"><h1>We're checking your payment</h1> <p>If you have already paid, do not pay again.</p>`); } if (route === "POST /webhooks/switro") { const event = verifySwitroWebhook( await readBody(request), request.headers["switro-signature"], process.env.SWITRO_WEBHOOK_SECRET, ); if (!event) return response.writeHead(400).end(); // In a real shop, save the payment ID, answer, then check it in a job. // Then you can check it again if something goes wrong. await checkPayment(event.payment_id); return response.writeHead(204).end(); } response.writeHead(404).end(); } createServer((request, response) => { handle(request, response).catch((error) => { console.error(error.message); if (!response.headersSent) response.writeHead(500); response.end("Something went wrong. Try again."); }); }).listen(PORT, () => console.log(`Open ${SITE}`));verify-webhook.mjs import { createHmac, timingSafeEqual } from "node:crypto"; const MAX_AGE_SECONDS = 5 * 60; /** * Returns the event if the webhook is from Switro, or null if it is not. * * @param {Uint8Array | string} body The raw body, exactly as it was received * @param {string | null | undefined} header The Switro-Signature header * @param {string} secret The whole webhook secret, including "whsec_" * @param {number} [now] The current time in seconds, for tests */ export function verifySwitroWebhook(body, header, secret, now = Date.now() / 1000) { // Without a secret, anyone could create a valid signature. if (!secret) throw new Error("The Switro webhook secret is not set"); const match = /^t=(\d{1,12}),v1=([0-9a-f]{64})$/.exec(header ?? ""); if (!match) return null; const [, timestamp, signature] = match; if (Math.abs(now - Number(timestamp)) > MAX_AGE_SECONDS) return null; const expected = createHmac("sha256", secret).update(`${timestamp}.`).update(body).digest(); if (!timingSafeEqual(expected, Buffer.from(signature, "hex"))) return null; try { return JSON.parse(Buffer.from(body).toString("utf8")); } catch { return null; } }Add your settings
Save this as
shop.env, and replace the API key. You will add the webhook secret after your first payment.shop.env SWITRO_API_KEY=your-devnet-checkout-key SWITRO_WEBHOOK_SECRET= SWITRO_NETWORK=devnet SITE_URL=http://localhost:4000Keep this file private
Never add it to git. Add*.envto your.gitignorefile first. On a live website, use your host's secret settings.Start the shop
Terminal node --env-file=shop.env checkout-server.mjsOpen
http://localhost:4000to see the checkout. The order will not be marked as paid yet, because webhooks cannot reachlocalhost.Turn on webhooks
- Put the shop on a test server with a public
httpsaddress. - On that server, set
SITE_URLto its address, without a/at the end. If your host needs a different port, also setPORT. - In your devnet API settings, set the webhook address to your website's address followed by
/webhooks/switro. Save it. - Make one devnet payment. Switro creates your secret when it sends this first webhook. The sample refuses it, because it does not have the secret yet.
- Reload your API settings. Copy the Webhook secret into
SWITRO_WEBHOOK_SECRET, then restart the shop. - Start a new order and pay for it. Your order page should say that it is paid.
The first test order will stay unpaid, because its webhook was refused. This is expected.
- Put the shop on a test server with a public
Before you use it in a real shop
This sample keeps orders in memory
- Work out every price on your server. Switro charges
amount_total. It does not check it against the items. - Save the payment ID before you answer the webhook, then check the payment in a background job. Try again if the check fails.
- Deliver each order once. Use a database transaction, and make each payment ID unique.
- Don't rely only on webhooks. Also check for missed payments.
- Don't create another checkout too soon. Each one lasts 10 minutes, and
POST /v1/checkouthas no idempotency key. Use the saved checkout while it still works. Before you replace it, check that nobody has paid it or has a payment in progress. Keep the old ID with the order.
See every field in the API v1 reference.

