Devmachinist /Docs
Sign in Start
All docs

Payments API

Apps built on the API builder can sell things with Stripe Checkout. The money goes to the store owner's own Stripe account (yours or your client's), never through Devmachinist's own billing. This page covers the routes a store app calls at runtime, the order fields the server fills in, and the store webhook.

Everything here lives under the API's public runtime, https://devmachinist.com/_api/<apiId>/…. It is CORS-open like the rest of /_api (see the data API). The shopper's identity is the API's own sign-in token, sent as Authorization: Bearer <token> (see sign-in for your app). For the product view of the same features, see Payments & stores.

The examples use the API id mhx3k2pq9a7f2c. API ids are short lowercase letters and digits; you find yours in the builder under API.

How a payment works #

  1. The app sends the cart as a list of ids and quantities to POST /_api/<apiId>/checkout.
  2. The server reads every price, variant and stock level from the API's own data, creates an order with status pending, then creates a Stripe Checkout session for exactly those amounts.
  3. The app sends the shopper to the session's url. Stripe collects the card, the shipping address and the shipping choice.
  4. Stripe sends the shopper back to <your page>#order/<orderId>.
  5. The order becomes paid only when Stripe confirms it: through the store webhook, or because GET /_api/<apiId>/checkout/<orderId> asks Stripe directly while the order is still pending.

The browser never decides a price. Prices sent by the browser are ignored, and the server only marks an order paid when the amount and currency Stripe charged match what it priced.

Until payments are turned on in API → Payments, checkout still works: it creates the order as unpaid and returns "url": null. The e-commerce template shows "Order placed, waiting for payment" in that case.

Setting up payments in the builder #

Payment settings are made in the builder, in API → Payments. They are not part of the runtime and no browser ever receives a key. There are two methods.

SettingYour own keysStripe Connect
What you enterThe store's secret key (sk_live_…, sk_test_…, or a restricted rk_… key) and the webhook signing secret (whsec_…)Nothing secret. You create an onboarding link and open it yourself or send it to the store owner
Who is the merchantThe account that owns the keyThe store owner's own Stripe Standard account
How the server chargesWith the store's keyA direct charge on the owner's account (the platform key plus a Stripe-Account header)
Where Stripe events arriveThe store webhook, POST /_api/<apiId>/payments/webhook, which you add in the Stripe dashboardThe platform's Connect webhook, automatically. Events count only when they come from the store's current account
FeesNoneAn optional platform fee and your developer fee, taken as one application fee
AvailableAlwaysOnly when the Devmachinist server has Stripe set up

Other settings on the same screen:

  • Currency: one of usd, eur, gbp, cad, aud, nzd, chf, sek, nok, dkk, pln, czk, jpy, sgd, hkd, mxn, brl, inr, zar, aed. Default usd.
  • Store URL: an https:// address (or http://localhost for testing). Stripe returns shoppers there when the app's own address can't be used, which is the case for Android and desktop apps.
  • Allowed origins: up to 20 web origins that may be used as return addresses (see below).
  • Product model and Order model: default Product and Order. The variant model is always Variant.
  • Your fee: the developer fee for Connect stores (see Developer fees).
  • Enabled: payments turn on only once a key is saved (keys) or a Stripe account is connected (Connect). A Connect store also needs Stripe to have enabled charges on the account.

The builder shows the webhook address to paste into Stripe, the list of events to send, and whether the key is in test or live mode. Onboarding links last 14 days by default (1 to 30), only their hash is stored, and each link only ever controls its own account.

Check payment status #

http
GET /_api/<apiId>/payments

Public. Tells the app whether online payment is on, so it can choose between "Continue to payment" and "Place order".

bash
curl https://devmachinist.com/_api/mhx3k2pq9a7f2c/payments
json
{ "enabled": true, "provider": "stripe", "currency": "usd", "mode": "test" }

mode is test or live when payments are on, and null when they are off.

Start a checkout #

http
POST /_api/<apiId>/checkout
Authorization: Bearer <shopper token>
Content-Type: application/json

If the API has sign-in turned on, the shopper must be signed in: without a valid token the answer is 401 {"error":"Sign in to check out"}. If the API has no sign-in, anyone may check out and the order has no user_id.

Body:

FieldTypeNotes
itemsarray, requiredUp to 50 entries of { id, variant, qty }. id is the product id, variant the variant id (leave it out for products without variants), qty is clamped to 1–99. Extra entries are ignored
emailstringReceipt email. Defaults to the signed-in shopper's email
returnUrlstringThe page Stripe should send the shopper back to. See the rules below
shippingobjectA structured address, saved only when the order model has a shipping field. Use it when Stripe is not collecting the address: { name, phone, address: { line1, line2, city, state, postal_code, country } }
shipping_namestringSaved on the order as plain text (up to 200 characters)
shipping_addressstringSaved on the order as plain text (up to 2,000 characters)
bash
curl -X POST https://devmachinist.com/_api/mhx3k2pq9a7f2c/checkout \
  -H "Authorization: Bearer $SHOPPER_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "items": [ { "id": 7, "variant": 3, "qty": 2 }, { "id": 1, "qty": 1 } ],
    "returnUrl": "https://shop.example.com/"
  }'

Response when payments are on:

json
{
  "order": {
    "id": 42,
    "user_id": "5",
    "email": "ada@example.com",
    "items": [
      { "id": 7, "variant": 3, "sku": "TEE-BLA-L", "name": "Heavyweight Tee — Black / L", "price": 36, "qty": 2 },
      { "id": 1, "variant": null, "sku": "TOTE-01", "name": "Everyday Tote", "price": 48, "qty": 1 }
    ],
    "total": 120,
    "status": "pending",
    "shipping_name": null,
    "shipping_address": null,
    "created_at": "2026-11-13T10:15:02.114Z",
    "checkout_session": "cs_test_a1B2c3D4e5"
  },
  "url": "https://checkout.stripe.com/c/pay/cs_test_a1B2c3D4e5",
  "payments": true
}

Send the shopper to url. When payments are off the answer is { "order": {…}, "url": null, "payments": false } and the order simply waits as pending.

What the server does with the cart #

  • Each product is read from the product model. A missing product is 409 A product in your cart is no longer available.
  • If the product has active variants, the item must name one: otherwise 409 Choose the options for <name>. A variant that is inactive or belongs to another product is 409 That option of <name> is no longer available.
  • The price is the variant's price when it is above 0, else the product's price. An item with no price is 409 <name> has no price.
  • Stock is the variant's stock, else the product's stock (when the product model has that field). Asking for more than is left is 409 Only <n> of <name> left.
  • The line name is the product name, plus — <variant title> for a variant. The product or variant image is sent to Stripe only if it is an https:// URL.
  • The order total is the sum of the lines. Shipping is added by Stripe on top.

Return URL rules #

Stripe sends the shopper back to <base>#order/<orderId> after paying and to <base>#cart if they cancel. The server picks <base> like this:

  1. returnUrl, if it is an https:// address (or http:// on localhost, 127.0.0.1 or a .localhost name) and its origin is allowed. Its hash is dropped; path and query are kept.
  2. Otherwise the Store URL, with a trailing /.
  3. Otherwise the request fails with 400 before any order is created, asking you to set the store URL.

An origin is allowed when it is in Allowed origins or is the origin of the Store URL. If you set neither, any https:// return address is accepted.

Shipping in Stripe Checkout #

When the store's shipping settings are on and list at least one country, the Stripe session collects the shipping address (only those countries), the phone number, and lets the shopper pick one of the store's rates. A rate costs nothing when the order total reaches freeOver. A days text such as 3–5 business days becomes Stripe's delivery estimate.

If shipping settings were never saved, the defaults apply: shipping on, United States only, one rate "Standard shipping" at 5.00. Save your own with PUT /admin/store, or turn shipping off there.

Errors #

StatusWhen
400Empty cart, or no usable return address while payments are on
401The API has sign-in and the request has no valid shopper token
404No API with that id
409A product or variant is gone, options are missing, there is no price, or not enough stock
429More than 30 checkouts in 10 minutes from one address
501The API has no product model or no order model
502Stripe refused the request. The order already exists as pending without a checkout session

All errors are { "error": "<message>" }.

Check an order #

http
GET /_api/<apiId>/checkout/<orderId>
Authorization: Bearer <shopper token>

Returns the shopper's view of one order. While the order is pending and has a checkout session, the server asks Stripe for the session first and settles the order if it has been paid. This makes the return page work even before the webhook is set up.

bash
curl https://devmachinist.com/_api/mhx3k2pq9a7f2c/checkout/42 \
  -H "Authorization: Bearer $SHOPPER_TOKEN"
json
{
  "id": 42,
  "status": "paid",
  "total": 120,
  "items": [ { "id": 7, "variant": 3, "sku": "TEE-BLA-L", "name": "Heavyweight Tee — Black / L", "price": 36, "qty": 2 } ],
  "paid_at": "2026-11-13T10:16:40.903Z",
  "currency": "usd",
  "shipping_cost": 5,
  "tracking_number": null,
  "tracking_carrier": null,
  "tracking_url": null,
  "fulfillment_status": "submitted"
}

The answer is 404 Order not found when the order doesn't exist, when it belongs to another signed-in account (if the order model has user_id), or when the API has sign-in and the request has no token. On an API without sign-in, anyone who knows the order id can read this summary.

Store settings #

Read the shipping rates #

http
GET /_api/<apiId>/store

Public. Use it to show shipping prices in the cart.

bash
curl https://devmachinist.com/_api/mhx3k2pq9a7f2c/store
json
{
  "shipping": {
    "enabled": true,
    "countries": ["US", "CA"],
    "rates": [
      { "name": "Standard shipping", "amount": 5, "days": "3–5 business days" },
      { "name": "Express", "amount": 15, "days": "1–2 business days" }
    ],
    "freeOver": 75
  },
  "currency": "usd"
}

Admin: read and change store settings #

http
GET /_api/<apiId>/admin/store
PUT /_api/<apiId>/admin/store

Admin routes need a token of a user whose role on this API is admin (401 Authentication required without a token, 403 Admins only for other users). Both return the shipping settings, the list of countries you can ship to, the fulfillment settings (hints only, never secrets) and the public payment info.

json
{
  "shipping": { "enabled": true, "countries": ["US", "CA"], "rates": [ { "name": "Standard shipping", "amount": 5, "days": "3–5 business days" } ], "freeOver": 75 },
  "countries": ["US", "CA", "GB", "IE", "AU", "NZ", "DE", "FR", "ES", "IT", "NL", "BE", "AT", "CH", "SE", "NO", "DK", "FI", "PL", "PT", "CZ", "JP", "SG", "HK", "MX", "BR", "IN", "ZA", "AE"],
  "fulfillment": { "enabled": false, "provider": "shipbob", "autoSubmit": true, "ready": false, "providers": { "…": "…" }, "shipbob": { "channelId": "", "sandbox": false, "speed": "Standard", "token": null }, "amazon": { "…": "…" } },
  "payments": { "enabled": true, "provider": "stripe", "currency": "usd", "mode": "test" }
}

The PUT body takes shipping, fulfillment, or both. Only the keys you send change.

shipping fieldRules
enabledtrue or false
countriesTwo-letter codes from the countries list. At least one while shipping is on
ratesUp to 5 of { name, amount, days }. amount is 0 to 10,000 in the store currency, name up to 60 characters, days up to 40. At least one while shipping is on
freeOverA positive order total from which shipping is free, or null
bash
curl -X PUT https://devmachinist.com/_api/mhx3k2pq9a7f2c/admin/store \
  -H "Authorization: Bearer $ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "shipping": { "countries": ["US", "CA", "GB"], "rates": [ { "name": "Standard", "amount": 6, "days": "3-5 business days" } ], "freeOver": 100 } }'

Fulfillment add-on #

A store can hand paid orders to a warehouse: ShipBob, or Amazon Multi-Channel Fulfillment through the Selling Partner API. It is off until an admin turns it on. The settings go in PUT /admin/store as fulfillment:

FieldValues
enabledtrue or false. Turning it on needs complete connection details
providershipbob or amazon
autoSubmittrue (default): send each order as soon as it is paid. false: send by hand
shipbob{ token, channelId, sandbox, speed }. speed is Standard, Expedited, 2-Day or Overnight
amazon{ region, marketplaceId, clientId, clientSecret, refreshToken, speed }. region is na, eu or fe. speed is Standard, Expedited or Priority

Secrets (token, clientSecret, refreshToken) are encrypted when saved and only ever shown back as hints. Leave them out to keep the stored value.

bash
curl -X PUT https://devmachinist.com/_api/mhx3k2pq9a7f2c/admin/store \
  -H "Authorization: Bearer $ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "fulfillment": { "provider": "shipbob", "shipbob": { "token": "'"$SHIPBOB_TOKEN"'", "channelId": "123456" }, "enabled": true } }'

Test the connection #

http
POST /_api/<apiId>/admin/fulfillment/test
json
{ "ok": true, "detail": "Connected to ShipBob — channel “My Store”", "channels": [ { "id": "123456", "name": "My Store" } ] }

For ShipBob, ok is false when the token works but the channel id isn't one of yours. Missing details or rejected credentials answer 400 {"error": "…"} with the provider's message (502 when the provider itself fails).

Send or sync one order #

http
POST /_api/<apiId>/admin/orders/<orderId>/fulfill
POST /_api/<apiId>/admin/orders/<orderId>/sync

fulfill sends a paid order to the warehouse and answers { "ok": true, "ref": "<provider order id>" }, or { "ok": true, "already": true } if it was sent before. sync reads the status and tracking back: { "ok": true, "status": "…", "tracking": "1Z999…" }. Failures answer 400 {"error": "…"}, for example when fulfillment is off, the order isn't paid, an item has no SKU, or the address is incomplete.

bash
curl -X POST https://devmachinist.com/_api/mhx3k2pq9a7f2c/admin/orders/42/fulfill \
  -H "Authorization: Bearer $ADMIN_TOKEN"

The warehouse ships by SKU. The SKU is read again from the product or variant when the order is sent, so fixing a SKU and retrying works. Every 10 minutes the server syncs submitted orders and retries queued or failed ones, up to 5 tries per order.

Order fields #

These are the fields the payments runtime reads and writes. The e-commerce template's Order model has all of them; if you build your own order model, include the ones you need.

FieldSet byMeaning
user_idcheckoutThe shopper's user id on this API, as text
emailcheckoutReceipt email
itemscheckout[{ id, variant, sku, name, price, qty }] as priced by the server
totalcheckoutSum of the items, without shipping
statusruntime, adminspending, paid, shipped, cancelled or refunded
created_atcheckoutISO date
checkout_sessioncheckoutThe Stripe Checkout session id
payment_idpaymentThe Stripe payment intent id
paid_atpaymentISO date
shippingcheckout or payment{ name, phone, address: { line1, line2, city, state, postal_code, country } } (only if the model has this field)
shipping_name, shipping_addresscheckout or paymentThe same as plain text
shipping_costpaymentWhat the shopper paid for shipping (only if the model has this field)
fulfillment_statusfulfillmentqueued, submitted, shipped or error
fulfillment_providerfulfillmentshipbob, amazon, or manual when an admin enters tracking by hand
fulfillment_reffulfillmentThe warehouse's order id
fulfillment_error, fulfillment_triesfulfillmentThe last error and the number of attempts
tracking_number, tracking_carrier, tracking_urlfulfillment, adminsTracking details

When an order is paid, the server also takes the items out of stock: the variant's stock when the item has a variant, else the product's. When a warehouse reports tracking or a shipment, fulfillment_status and status become shipped.

In the template, the order model's rules are read owner, create none, write admin: shoppers list only their own orders through the data API, nobody can create one except through checkout, and admins change them.

Products, options and variants #

Product options is a JSON field with the optionList shape. It describes what a shopper picks:

json
[
  { "name": "Color", "kind": "color", "values": [ { "label": "Black", "swatch": "#1f2937" }, { "label": "Oat", "swatch": "#e7dcc8" } ] },
  { "name": "Size", "kind": "text", "values": [ { "label": "S" }, { "label": "M" }, { "label": "L" } ] }
]

kind is color or text. A value may also be a plain string, which becomes { "label": "…" }. Any other shape is refused with a 400 when you save it.

Each combination is a row of the Variant model:

FieldMeaning
product_idThe product it belongs to (required)
titleShown to the shopper and on the order line, e.g. Black / M
optionsA JSON map of option name to value: { "Color": "Black", "Size": "M" }
skuThe warehouse SKU
priceLeave empty to use the product's price
stockUnits left
imageShown for this combination
activefalse hides it without deleting it

Checkout from a React page #

The e-commerce template writes a small client to src/lib/checkout.js. It builds on request from the generated data client (src/api/<api-slug>.js), which adds the shopper's token and the X-PB-Device header for you (see the generated client). You can copy it into any project whose API has a product and an order model:

js
// src/lib/checkout.js
import { request } from '../api/my-store.js'

/** { enabled, currency, mode: 'test' | 'live' | null } */
export const paymentInfo = () => request('GET', '/payments')
/** { shipping: { enabled, countries, rates: [{ name, amount, days }], freeOver }, currency } */
export const storeInfo = () => request('GET', '/store')

export function startCheckout({ items, email, shipping }) {
  return request('POST', '/checkout', {
    items: items.map(({ id, variant, qty }) => ({ id, variant: variant ?? undefined, qty })), email,
    ...(shipping ? { shipping, shipping_name: shipping.name, shipping_address: [shipping.address.line1, shipping.address.line2, shipping.address.city + ' ' + shipping.address.state + ' ' + shipping.address.postal_code, shipping.address.country].filter(Boolean).join(', ') } : {}),
    returnUrl: window.__PB_BASE__ ? window.location.origin + window.__PB_BASE__ : window.location.href.split('#')[0],
  })
}

/** The order's status (and tracking); asks Stripe directly while it is still pending. */
export const orderStatus = (id) => request('GET', '/checkout/' + encodeURIComponent(id))

window.__PB_BASE__ is set on published sites, where pages have real paths. In the preview the page address without its hash is used.

A checkout page sends the cart and follows the returned link. With Stripe on, Stripe collects the address; with Stripe off, the page sends one itself:

jsx
import React, { useEffect, useState } from 'react'
import { Auth, NoAuth, useAuth, LoginForm } from '../api/my-store-auth.jsx'
import { startCheckout, paymentInfo } from '../lib/checkout.js'

export default function Checkout({ items }) {
  const { user } = useAuth()
  const [pay, setPay] = useState(null)
  const [error, setError] = useState(null)
  useEffect(() => { paymentInfo().then(setPay).catch(() => setPay({ enabled: false })) }, [])

  const place = async () => {
    setError(null)
    try {
      const r = await startCheckout({ items, email: user.email, shipping: null })
      if (r.url) window.location.href = r.url          // Stripe Checkout
      else setError('Order #' + r.order.id + ' is placed and waiting for payment.')
    } catch (e) { setError(e.message) }                // e.g. "Only 2 of Desk Lamp left"
  }

  return (
    <main className="mx-auto max-w-xl px-4 py-12">
      <NoAuth><LoginForm title="Sign in to check out" /></NoAuth>
      <Auth>
        <button onClick={place} disabled={!pay} className="rounded-full bg-brand-600 px-6 py-3 text-white">
          {pay && pay.enabled ? 'Continue to payment' : 'Place order'}
        </button>
        {error && <p className="mt-3 text-sm text-red-500">{error}</p>}
      </Auth>
    </main>
  )
}

Stripe brings the shopper back to #order/<id>. Confirmation can take a moment, so the template's Order page checks a few times:

jsx
import React, { useEffect, useState } from 'react'
import { orderStatus } from '../lib/checkout.js'
import { routeParam } from '../site.js'

export default function Order() {
  const [id] = useState(() => routeParam(1))
  const [order, setOrder] = useState(null)
  useEffect(() => {
    if (!id) return
    let tries = 0, timer
    const check = () => orderStatus(id).then(o => {
      setOrder(o)
      if (o.status === 'pending' && ++tries < 8) timer = setTimeout(check, 1500)
    })
    check()
    return () => clearTimeout(timer)
  }, [id])
  if (!order) return <p>Checking your payment…</p>
  return <h1>{['paid', 'shipped'].includes(order.status) ? 'Thank you — payment received' : 'Order ' + order.status}</h1>
}

In test mode, pay with the card 4242 4242 4242 4242, any future date and any CVC.

The store webhook #

http
POST /_api/<apiId>/payments/webhook
Stripe-Signature: t=…,v1=…

Used by stores on your own keys. In the Stripe dashboard, add an endpoint with the address the builder shows (https://devmachinist.com/_api/<apiId>/payments/webhook) and these events, then paste its signing secret (whsec_…) into API → Payments:

EventWhat the server does
checkout.session.completedMarks the order paid if the session is paid (see below). For a membership checkout, makes the reader a member
checkout.session.async_payment_succeededMarks the order paid, for payment methods that confirm later
checkout.session.async_payment_failedSets a still-pending order to cancelled
checkout.session.expiredSets a still-pending order to cancelled
charge.refundedOn a full refund, sets the order to refunded. Partial refunds leave the order as it is
customer.subscription.updatedUpdates a member's status, renewal date and cancel date
customer.subscription.deletedEnds a membership
invoice.paidRefreshes a member's renewal date

Marking an order paid only happens when all of these hold: the session's metadata names this API and this order, the session is the order's own checkout session, Stripe says it is paid, the currency matches, the items subtotal equals the order total, and the amount charged equals subtotal plus shipping minus discount plus tax. It is idempotent: an order that is already paid, shipped or refunded is left alone. Paying sets status, payment_id, paid_at and the shipping fields, takes the items out of stock, queues the order for the warehouse if fulfillment is on, and records your developer fee on Connect stores.

The signature is checked with HMAC-SHA256 over the exact bytes Stripe sent, with a 5-minute tolerance on the timestamp.

StatusBody
200{ "received": true } for every verified event, handled or not
400{ "error": "No webhook signing secret is set for this store" }, "Bad signature" or "Bad payload"
404{ "error": "API not found" }
Stores on Stripe Connect don't use this address. Their events reach Devmachinist's own Connect endpoint and are applied to the store only when they come from the account currently connected to it. You have nothing to set up.

Developer fees #

If you build a store for a client and it uses Stripe Connect, you can take a percentage of each sale. Set Your fee in API → Payments, up to 20 %.

  • The fee applies only with the store owner's consent. They accept it on the onboarding link (the percentage is fixed when the link is made), or later through an approval email that goes only to the address Stripe has for their account.
  • The fee charged is the lower of what you ask and what the owner accepted, and 0 without consent. Lowering your fee applies at once; raising it waits for a new approval.
  • Each checkout adds your share and Devmachinist's share, if any, to one Stripe application fee on the owner's charge. Membership subscriptions use the same total as application_fee_percent.
  • When the order is paid, your share is recorded as a pending earning. Every 10 minutes the server transfers it to your Devmachinist payout account (the same one used for Shop sales, with the current payout agreement accepted). The amount comes from the application fee Stripe actually collected. Funds that are not available yet stay pending and are retried.
  • A full refund returns the application fee to the owner and cancels your pending earning, or reverses the transfer if it was already paid.

Stores on your own keys take no fees. See your earnings under Earnings in the account menu.

Memberships #

Paid memberships (the blog template's paywall) use the same Stripe settings, keys or Connect, and the same webhook. The app calls POST /_api/<apiId>/membership/subscribe with { returnUrl } and sends the reader to the returned { url }, a Stripe subscription checkout. Stripe returns them to <base>#account?subscribed=1, or <base>#subscribe if they cancel, with the same return-address rules as orders. Membership status is only ever set from verified Stripe events or a direct subscription lookup. The routes, the free-read meter and the client hooks are described in sign-in for your app.