Payments

Let people pay for what they order. Your app keeps the order in its own table; an action asks the payment provider for a checkout page, with the amount taken from the order on the server; the provider sends the person back and confirms the payment through a signed webhook, which marks the order paid. The browser never decides the amount or the outcome, and your code never holds the key.

There is no built-in checkout in code-first apps yet. The pattern on this page is three files you own: a table, an action, a webhook workflow. (A JSON app's app.pay answers "unavailable" once converted.)

Stripe or Razorpay

  • Stripe: cards worldwide, Checkout pages, subscriptions.
  • Razorpay: customers in India paying in INR by UPI, card, netbanking or wallet. See Razorpay for India.

1. The order

-- db/schema/class_order.sql
create table if not exists class_order (
  id          uuid primary key default gen_random_uuid(),
  user_id     uuid not null default ctx.uid(),
  title       text not null,
  amount      ctx.money not null,
  status      text not null default 'pending',
  checkout_id text,
  created_at  timestamptz not null default now()
);
select ctx.lifecycle('class_order', 'status', $$ pending -> paid | cancelled $$);

-- db/access/class_order.sql: a member reads their own orders; nobody marks one paid from the browser.
drop policy if exists class_order_own_read on class_order;
create policy class_order_own_read on class_order for select using (user_id = (select ctx.uid()));

How orders are created is up to your app (an action that prices the basket from your catalogue, or staff). What matters: no policy lets a member set status or amount.

2. Start the checkout

// app.config.ts
secrets: { STRIPE_SECRET_KEY: { hosts: ["api.stripe.com"], required: ["prod"] } },
http: { allow: ["api.stripe.com"] },
// server/checkout.ts: a Stripe Checkout page for one of the member's own orders.
import { defineAction, v } from "@appbricx/server";

const form = (fields: Record<string, string>) =>
  Object.entries(fields).map(([k, val]) => encodeURIComponent(k) + "=" + encodeURIComponent(val)).join("&");

export const startCheckout = defineAction({
  input: v.object({ order: v.uuid() }),
  roles: ["member"],
  handler: async (ctx, input) => {
    const order = await ctx.db.get("class_order", input.order); // row-level security: only the member's own
    if (!order || order.status !== "pending") throw new Error("That order can't be paid.");
    const appUrl = String((ctx as { app?: { url?: string } }).app?.url ?? "");
    const res = await ctx.http.fetch("https://api.stripe.com/v1/checkout/sessions", {
      method: "POST",
      auth: { bearer: ctx.secrets.ref("STRIPE_SECRET_KEY") },
      headers: { "content-type": "application/x-www-form-urlencoded" },
      body: form({
        mode: "payment",
        "line_items[0][quantity]": "1",
        "line_items[0][price_data][currency]": "eur",
        "line_items[0][price_data][unit_amount]": String(Math.round(Number(order.amount) * 100)),
        "line_items[0][price_data][product_data][name]": String(order.title),
        client_reference_id: String(order.id),
        success_url: appUrl + "/orders?paid=1",
        cancel_url: appUrl + "/orders",
      }),
    });
    if (!res.ok) throw new Error("Stripe answered " + res.status + ".");
    const session = res.json<{ id: string; url: string }>();
    if (!session?.url) throw new Error("Stripe didn't return a checkout page.");
    return { url: session.url };
  },
});

The page calls startCheckout({ order: id }) and sends the person to the returned url (an <a href> to it, since pages don't write location). The key goes into the request by reference, only to api.stripe.com. The app's own address comes from ctx.app.url (the dev preview, or the published address in production), read through a cast because the action types don't include it yet.

3. Stripe confirms

// workflows/stripe.ts
import { webhook } from "@appbricx/workflows";

type StripeEvent = { type?: string; data?: { object?: { client_reference_id?: string; payment_status?: string } } };

export const stripeEvents = webhook(
  "stripe-events",
  { verify: { provider: "stripe", secret: "STRIPE_WEBHOOK_SECRET", events: ["checkout.session.completed"] } },
  async ({ body, row }, step) => {
    const e = (body ?? row) as StripeEvent;
    const s = e.data?.object;
    if (e.type !== "checkout.session.completed" || s?.payment_status !== "paid" || !s.client_reference_id) return { ignored: e.type };
    const paid = await step.sql("mark paid",
      "update class_order set status = 'paid' where id = $1 and status = 'pending' returning id", [s.client_reference_id]);
    return { paid: paid.length };
  },
);
  1. In Stripe, open Developers, Webhooks and add an endpoint with the URL get_contract lists under webhooks (/hooks/<project-id>/stripe-events), for the same events.
  2. Put the endpoint's signing secret (whsec_…) in the project secret STRIPE_WEBHOOK_SECRET with the secrets tool, for each environment. Several (a test and a live endpoint) go in one secret, separated by commas.
  3. The platform checks Stripe's signature before your code runs, and a Stripe event id seen before runs nothing. The workflow runs as the app, so it can mark the order paid where no browser can.

Dry-run it with a made-up event before Stripe ever calls: workflows { "action": "dry_run", "id": "stripeevents", "row": { "type": "checkout.session.completed", "data": { "object": { "client_reference_id": "…", "payment_status": "paid" } } } }. Subscriptions work the same way: create them in an action, listen for invoice.paid and customer.subscription.*.

Razorpay for India (INR, UPI)

People pay on a hosted Razorpay Payment Link and come back to the app.

  1. An action creates the link: POST https://api.razorpay.com/v1/payment_links with auth: { basic: [keyId, ctx.secrets.ref("RAZORPAY_KEY_SECRET")] } (declare the secret with hosts: ["api.razorpay.com"]), a json body with the amount in paise from your row, reference_id set to the row's id and a callback_url back into the app. The page links to the returned short_url.
  2. A webhook workflow verified as Razorpay marks the row paid on payment_link.paid, after checking the amount:
    webhook("razorpay-payments",
      { verify: { provider: "razorpay", secret: "RAZORPAY_WEBHOOK_SECRET",
                  events: ["payment_link.paid", "payment_link.expired", "payment_link.cancelled"] } },
      async ({ body, row }, step) => { /* (body ?? row).event, .payload */ })
  3. In the Razorpay Dashboard, open Settings, Webhooks, add the URL with a secret and the same events, and put that secret in RAZORPAY_WEBHOOK_SECRET. It is not the API key secret.

The platform checks X-Razorpay-Signature (HMAC-SHA256 of the raw body). Razorpay signs no timestamp, so the event id is what stops a replay: each one runs once.

Gotchas

  • A page never sends an amount. The action reads it from the row, under the caller's policies.
  • A return to your page is not proof of payment. Only the verified webhook marks the row paid.
  • Stripe takes form-encoded bodies, not JSON: send a string with content-type: application/x-www-form-urlencoded. Razorpay takes JSON (json:).
  • Amounts in ctx.money are decimal strings in TypeScript ("12.00"): convert to the provider's smallest unit with care.
  • Set the secrets for production before you publish: a publish refuses while a secret required: ["prod"] has no value there.

Related