Guides
Build an online store and get paid
Sell physical items, downloads and services for USDC or SOL, from a ready-made store or a website you design.
Choose a type of store
| Hosted store | Your own store | |
|---|---|---|
| Best for | Opening quickly | Full control of the design |
| Pages | Made and hosted by Switro | Made and hosted by you |
| Products, stock and orders | Switro | Switro |
| Payments | Switro checkout | Switro checkout |
| Coding | Optional | Needed |
Both use the same products, stock and orders. Start with the hosted store. You can build your own design later.
Set your prices in US dollars
Create a store without code
Add your store's details
Choose devnet and add your wallet. Open Store, then Store settings. Add its name and contact details, but keep it hidden for now.

Store settings. Shown with sample data. Add your products
Add a name, price and photo. Choose a physical item, a download or a service. Then choose to count stock, or that it never runs out. Use options for sizes or colours.

Products. Shown with sample data. Add delivery options, if you send anything

Delivery options and prices. Shown with sample data. Open the store and test it
Open the store in Store settings, then buy something with test SOL. Check that the payment is confirmed before you send the order.
Sell downloads and services
| Type | Good for | After payment |
|---|---|---|
| Physical item | Anything you send | You send it to the customer's address |
| Download | Ebooks, music, templates and software | The customer gets your private files, a private note, or both |
| Service | Lessons, bookings and memberships | The customer gets your files or note, if you add them |
- Downloads and services have no delivery price, and do not need an address.
- They never run out, unless you choose to count stock.
- You can add up to 20 files to a product, and each one can be up to 50 MB.
- After payment, the customer gets a private link by email. If they pay on Switro's website, they can also open their order there.
- The link works for 30 days. It stops if you cancel or refund the order.
- If an order also has physical items, the customer only pays for delivery once.

Every customer gets the same files and note
Create a store with code
This sample adds a product, one with options, a download and a delivery option. Switro saves everything or nothing, and running it again creates no duplicates. You need Node.js 22 or later, and your wallet in the devnet settings.
Get a key
Save connect.mjs, then run this. Keep this key only for setting up the store.
Terminal node connect.mjs setup.env store:read store:writeSave and run the sample
Change
slugto your store's address. Nobody else can be using it.build-store.mjs // Creates or updates your Switro store. Running it again creates no duplicates. // It needs an API v2 key with the store:read and store:write permissions. // To open the store to customers, run: node build-store.mjs --publish const API = process.env.SWITRO_API_URL ?? "https://www.switro.com/api"; const store = { settings: { name: "Sample Goods", // Your store's address: https://sample-goods.store.switro.com slug: "sample-goods", contact_email: "hello@example.com", }, categories: [{ slug: "kitchen", name: "Kitchen" }], products: [ { slug: "ceramic-mug", name: "Ceramic mug", description: "Holds 350 ml.", price: 24, stock: 20, categories: ["kitchen"], }, { slug: "steel-bottle", name: "Steel bottle", price: 32, categories: ["kitchen"], // Each option has its own stock. variants: [ { options: { Color: "Green" }, stock: 10 }, { options: { Color: "Black" }, stock: 5, price: 34 }, ], }, { slug: "coffee-guide", name: "Coffee guide", price: 12, // There is nothing to deliver, and it never runs out. kind: "digital", // Only for customers who have paid. You can add private files too. delivery_note: "Thank you! Your guide is at https://example.com/members", }, ], // Only physical products need this. shipping_methods: [{ name: "Standard", price: 6, delivery_time: "3 to 5 days" }], }; async function post(path, body) { const response = await fetch(`${API}/v2/store/${path}`, { method: "POST", headers: { Authorization: `Bearer ${process.env.SWITRO_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify(body), }); const data = await response.json(); if (!response.ok) throw new Error(`Switro answered ${response.status}: ${data.message}`); return data; } if (process.argv.includes("--publish")) { const { network, url } = await post("publish", {}); console.log(`Your ${network} store is open: ${url}`); } else { const { checks, network } = await post("build", store); console.log(`Your ${network} store is saved.`); for (const check of checks) { console.log(check.ok ? `Ready: ${check.name}` : `To do: ${check.help}`); } }Terminal node --env-file=setup.env build-store.mjsCheck it, then open it
Fix anything marked To do, and check your products in the dashboard. Then open the store. This shows its address.
Terminal node --env-file=setup.env build-store.mjs --publishThis opens your store to customers
Anyone with its address can visit it. Check its name, products, prices and delivery first.Your hosted store is ready. Buy something with test SOL, and check the payment in the dashboard.
Be careful when you run it again
PATCH /v2/store/stock.Build your own store
This complete sample shows your products, takes orders, sends customers to pay, checks that they paid, and gives them their downloads. It only asks for an address if something is delivered. Create and open your store above first. The sample uses its products.
Get a separate key
Your website must not be able to change your products, so give it a key with only these permissions:
Terminal node connect.mjs store.env store:read orders:read orders:write
Check the app's name, network and permissions before you approve. Shown with sample data. Save and run your store
store-server.mjs // Your own online store. Switro looks after the products, stock, orders and // payments. It needs an API v2 key with only these permissions: // store:read, orders:read and orders:write. import { createHash, randomUUID } from "node:crypto"; import { createServer } from "node:http"; 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}`; // Use a database in a real store. These are lost when the server stops. const sessions = new Map(); // session ID -> { attempt, orderId } /** Only this server uses the API key. It is never sent to the browser. */ async function switro(method, path, body) { const response = await fetch(`${API}/v2/store${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), }); const data = await response.json().catch(() => ({})); if (response.ok) return data; const error = new Error([data.message].flat().join(". ") || "Switro had a problem"); error.status = response.status; throw error; } // Keeps the catalogue for a minute, so the store stays fast. let saved = { until: 0 }; async function getCatalogue() { if (Date.now() < saved.until) return saved; const [store, products, shipping] = await Promise.all([ switro("GET", ""), // This sample shows up to 100 products. Use `page` to get more. switro("GET", "/products?status=active&limit=100"), switro("GET", "/shipping-methods"), ]); saved = { until: Date.now() + 60_000, isOpen: store.published, name: store.settings?.name ?? "Store", products: products.data, shipping: shipping.data.filter((method) => method.is_active), }; return saved; } /** Shows text as text, so it can never run as code. */ const safe = (value) => String(value ?? "").replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`); function page(response, title, content, status = 200) { response.writeHead(status, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", }); response.end(`<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>${safe(title)}</title> <style> body { max-width: 60rem; margin: auto; padding: 2rem 1rem; font: 1rem/1.5 system-ui; } ul { display: grid; gap: 1rem; grid-template-columns: repeat(auto-fill, minmax(14rem, 1fr)); padding: 0; list-style: none; } li { border: 1px solid #ccc; padding: 1rem; } img { width: 100%; height: 12rem; object-fit: cover; } form { display: grid; gap: 1rem; max-width: 28rem; } label { display: grid; gap: .25rem; } input, select, button { font: inherit; padding: .6rem; } </style> </head> <body><main><h1>${safe(title)}</h1>${content}</main></body> </html>`); } /** The browser only keeps a random session ID. */ function getSession(request, response) { const id = /(?:^|;\s*)session=([0-9a-f-]{36})/.exec(request.headers.cookie ?? "")?.[1]; if (sessions.has(id)) return sessions.get(id); const newId = randomUUID(); const secure = SITE.startsWith("https:") ? "; Secure" : ""; response.setHeader("Set-Cookie", `session=${newId}; HttpOnly; SameSite=Lax; Path=/${secure}`); sessions.set(newId, {}); return sessions.get(newId); } async function readForm(request) { let text = ""; for await (const part of request) { text += part; if (text.length > 10_000) throw new Error("The form is too large"); } return new URLSearchParams(text); } /** What a customer can choose: the product, or one of its options. */ const getChoices = (product) => product.variants.length ? product.variants.map((variant) => ({ ...variant, label: variant.name })) : [{ id: "", label: product.name, price: product.current_price, available: product.available }]; const isAvailable = ({ available }) => available === null || available > 0; /** Downloads and services have nothing to deliver. */ const isDelivered = (product) => product.kind === "physical"; function showProducts(response, { name, products }) { const items = products.map((product) => { const choices = getChoices(product).filter(isAvailable); const image = product.image_url ? `<img alt="" src="${safe(product.image_url)}">` : ""; const prices = [...new Set(getChoices(product).map(({ price }) => price))] .sort((a, b) => a - b) .map((price) => `$${price}`) .join(" or "); const action = choices.length ? `<a href="/buy?product=${safe(product.id)}">Buy ${safe(product.name)}</a>` : "<p>Sold out</p>"; return `<li>${image}<h2>${safe(product.name)}</h2><p>${safe(product.description)}</p> <p>${safe(prices)}</p>${action}</li>`; }); page(response, name, items.length ? `<ul>${items.join("")}</ul>` : "<p>Nothing is for sale yet.</p>"); } function showForm(response, product, shipping) { const options = (list, text) => list.map((item) => `<option value="${safe(item.id)}">${safe(text(item))}</option>`).join(""); const field = (label, name, type, autocomplete) => `<label>${label}<input autocomplete="${autocomplete}" name="${name}" required type="${type}"></label>`; const delivery = ` <label>Delivery<select name="shipping">${options( shipping, (method) => `${method.name}: $${method.price}`, )}</select></label> ${field("Address", "address_1", "text", "address-line1")} ${field("City", "city", "text", "address-level2")} <label>Country code, such as GB <input autocomplete="country" maxlength="2" name="country_code" required> </label>`; page(response, `Buy ${product.name}`, `<form action="/buy" method="post"> <input name="product" type="hidden" value="${safe(product.id)}"> <label>Option<select name="variant">${options( getChoices(product).filter(isAvailable), (choice) => `${choice.label}: $${choice.price}`, )}</select></label> <label>Quantity<input min="1" name="quantity" required type="number" value="1"></label> ${field("Full name", "name", "text", "name")} ${field("Email", "email", "email", "email")} ${isDelivered(product) ? delivery : ""} <button>Continue to payment</button> </form>`); } async function buy(request, response, catalogue) { // Only accepts the form on this website. if (request.headers.origin !== SITE) return page(response, "Go back and try again", "", 403); const form = await readForm(request); const get = (name) => (form.get(name) ?? "").trim(); const product = catalogue.products.find(({ id }) => id === get("product")); const choice = product && getChoices(product).find(({ id }) => id === get("variant")); const method = catalogue.shipping.find(({ id }) => id === get("shipping")); const quantity = Number(get("quantity")); const needsDelivery = !!product && isDelivered(product); if (!choice || (needsDelivery && !method) || !Number.isInteger(quantity) || quantity < 1) { return page(response, "Check your order", '<p><a href="/">Choose a product</a></p>', 400); } const session = getSession(request, response); const toCents = (price) => Math.round(Number(price) * 100); const deliveryPrice = needsDelivery ? toCents(method.price) : 0; const address = { address_1: get("address_1"), city: get("city"), country_code: get("country_code").toUpperCase(), }; const order = { items: [{ product_id: product.id, variant_id: choice.id || undefined, quantity }], shipping_method_id: needsDelivery ? method.id : undefined, delivery: { name: get("name"), email: get("email"), ...(needsDelivery ? address : {}), }, // Switro works out the real total. It refuses the order if that is higher. shown_total: (toCents(choice.price) * quantity + deliveryPrice) / 100, success_url: `${SITE}/order`, cancel_url: SITE, }; const last = session.orderId ? await switro("GET", `/orders/${session.orderId}`) : null; // A paid order is finished, so this is a new one, even if it is the same. if (last?.paid) session.attempt = undefined; // Sending the same order again must not create a second one. Anything // different, or a new order after 10 minutes, needs a new key. const details = createHash("sha256").update(JSON.stringify(order)).digest("hex"); const isSame = session.attempt?.details === details && Date.now() < session.attempt.until; if (!isSame) { // The customer may have just paid, so let them check that order first. if (last && !last.paid && get("start_again") !== "yes") { const fields = [...form].map( ([name, value]) => `<input name="${safe(name)}" type="hidden" value="${safe(value)}">`, ); return page(response, "You have an unpaid order", ` <p><a href="/order">Check your payment</a>. If you have already paid, do not pay again.</p> <form action="/buy" method="post"> ${fields.join("")} <input name="start_again" type="hidden" value="yes"> <button>I have not paid. Start a new order</button> </form>`); } session.attempt = { details, key: randomUUID(), until: Date.now() + 10 * 60_000 }; } try { const checkout = await switro("POST", "/checkout", { ...order, idempotency_key: session.attempt.key, }); session.orderId = checkout.order_id; response.writeHead(303, { Location: checkout.url }).end(); } catch (error) { if (error.status !== 400 && error.status !== 409) throw error; // Something is wrong, sold out, or has a new price. Show the latest catalogue. saved = { until: 0 }; page(response, "Check your order", `<p>${safe(error.message)}</p><p><a href="/">Back to the store</a></p>`, error.status); } } async function showOrder(request, response) { // The order ID comes from the session, so customers cannot see other orders. const { orderId } = getSession(request, response); if (!orderId) return page(response, "There is no order", '<p><a href="/">Back to the store</a></p>'); const order = await switro("GET", `/orders/${orderId}`); // Only `paid` shows that an order is paid. This page's address does not. if (order.paid) { // This link is private, so only this customer's session can see it. const downloads = order.downloads_url ? `<p><a href="${safe(order.downloads_url)}" rel="noreferrer">Open your downloads</a></p>` : ""; return page(response, "Your order is paid", ` <p>Order ${safe(order.id)}. Total: $${safe(order.total)}</p> ${downloads}`); } page(response, "We're checking your payment", `<meta http-equiv="refresh" content="5"> <p>This can take a few minutes. If you have already paid, do not pay again.</p>`); } async function handle(request, response) { const { pathname, searchParams } = new URL(request.url, SITE); const route = `${request.method} ${pathname}`; // Customers can still check their order if the store closes. if (route === "GET /order") return showOrder(request, response); const catalogue = await getCatalogue(); if (!catalogue.isOpen) return page(response, "This store is closed", "", 503); if (route === "GET /") return showProducts(response, catalogue); if (route === "POST /buy") return buy(request, response, catalogue); if (route === "GET /buy") { const product = catalogue.products.find(({ id }) => id === searchParams.get("product")); if (product && getChoices(product).some(isAvailable)) { return showForm(response, product, catalogue.shipping); } } page(response, "Page not found", '<p><a href="/">Back to the store</a></p>', 404); } createServer((request, response) => { handle(request, response).catch((error) => { console.error(error.message); if (response.headersSent) return response.end(); page(response, "Something went wrong", "<p>Try again in a minute.</p>", 500); }); }).listen(PORT, () => console.log(`Open ${SITE}`));Terminal node --env-file=store.env store-server.mjsOpen
http://localhost:4000.localhostreturn addresses only work on devnet.Make a test payment
Choose a product, fill in the form, and pay with test USDC or SOL. When you return, the page checks the order until it is paid. You don't need a webhook for this sample.
Only paid: true means an order is paid
status, or the fact that the customer came back to your website. Check paid with the API on your server before you deliver anything.What the sample protects
- The API key stays on the server.
- Switro works out the real total. It refuses the order if it would cost more than the customer saw.
- Pressing the button twice does not create a second order.
- Customers can only see the order and downloads in their own session.
- Text from products and customers cannot run as code.
- If there is already an unpaid order, the customer is asked to check it first.
Before you use it in a real store
- Keep sessions, orders and idempotency keys in a database. The sample loses them when it restarts.
- Limit how often each visitor can start a checkout.
- Use
https, and add your policies and contact details. - Load more pages if you have more than 100 products.
- Check for paid orders in a background job too, because customers may not come back to your website. A webhook can tell you sooner.
Unpaid orders keep their stock
See every request in the store API reference. AI tools can also build and run your store.




