Stripe
Apps/Web apps/Stripe

Stripe

A web app takes payments and subscriptions into your own Stripe account, through Stripe's hosted Checkout and customer portal. Connect a sandbox for development and your live account for production; Inference Bureau sets up the webhooks, keeps each user's customer and subscription in the app's records, and runs your code on Stripe's events.

Connecting Stripe

In Settings → Integrations → Stripe, each environment takes its own key: a sandbox key (sk_test_… or rk_test_…) for development, so no real money moves while you build, and your live account's (sk_live_… or rk_live_…) for production. A live key in development, or a sandbox key in production, is refused. Production reads development's sandbox key until it has its own, and Problems says so.

Saving a key checks it with Stripe, saves it as the environment's STRIPE_SECRET_KEY, and makes a webhook endpoint in that account, whose signing secret is saved as STRIPE_WEBHOOK_SECRET. In development it also adds the synced models (below) and fills them from the account. The card shows each environment's endpoint, and its Details show the URL, the events it sends and the last delivery.

A restricted key needs
WriteCheckout Sessions, Customer portal, Customers, Webhook Endpoints
ReadSubscriptions, Prices, Products, Events

A key without Webhook Endpoints write gets the endpoint's URL and events to add in Stripe by hand, and a field for its signing secret. The app never needs a publishable key: nothing in the browser talks to Stripe.

The card's Build with the assistant writes a Billing page, the Subscribe button and Manage billing for you, with the helpers below.

Checkout

Add stripe to the app's package.json. checkout(user, …) from @inferencebureau/apps-sdk/stripe finds the user's Stripe customer (or makes one, with metadata.ib_user), creates a Checkout Session and returns its URL; redirect to it. price is a price's id or its lookup key. A lookup key, set on the price in Stripe's Product catalog, lets you change the price in Stripe without changing code.

// web/app/billing/actions.ts: the Subscribe button's server action.
"use server";
import { redirect } from "next/navigation";
import { checkout } from "@inferencebureau/apps-sdk/stripe";
import { requireUser } from "../../lib/auth";

export async function subscribe() {
  const user = await requireUser();
  const origin = process.env.IB_APP_URL!;
  redirect(await checkout(user, {
    price: process.env.STRIPE_PRICE!, // a price id, or its lookup key: pro_monthly
    successUrl: `${origin}/billing?session={CHECKOUT_SESSION_ID}`,
    cancelUrl: `${origin}/billing`,
  }));
}
Option
mode"subscription" (the default) for a recurring price, "payment" for a one-time one.
trialDaysA subscription's free trial.
quantitySeats, or how many.
allowPromotionCodesA promotion code field on Stripe's page.
metadataKept on the session and on its subscription or payment, for your actions to find what it was for (an order, a booking).

Who has paid

The return to successUrl only means the person came back; it isn't proof of payment. Access follows Stripe's webhook, which keeps the user's stripeSubscription current, usually within seconds. On the return page, say the payment is being confirmed until subscriptionOf shows it.

import { requireSubscription, subscriptionOf, SubscriptionRequiredError } from "@inferencebureau/apps-sdk/stripe";

// A page: what they have, or null.
const sub = await subscriptionOf(user);

// A paid page or action: throws unless active (or trialing), on one of these prices.
await requireSubscription(user, { prices: ["pro_monthly", "pro_yearly"] });

// A route handler: answer 402 instead.
try { await requireSubscription(user); }
catch (e) { if (e instanceof SubscriptionRequiredError) return e.toResponse(); throw e; }

requireSubscription passes an active subscription, and a trialing one unless allowTrial: false. A past-due one doesn't pass: Stripe is still trying to take the payment. It throws SubscriptionRequiredError (status 402).

The customer portal

Changing plan, cancelling, cards and invoices all happen in Stripe's customer portal. billingPortal(user, { returnUrl }) returns its URL for a user who has a Stripe customer. Choose what the portal offers in Stripe's Dashboard (Settings → Billing → Customer portal), separately for the sandbox and live.

import { billingPortal } from "@inferencebureau/apps-sdk/stripe";

redirect(await billingPortal(user, { returnUrl: `${origin}/billing` }));

Running code on an event

Add api/actions/stripe<Type>.ts and it runs as a job on each event of that type: checkout.session.completed runs stripeCheckoutSessionCompleted, invoice.payment_failed runs stripeInvoicePaymentFailed. Its params are the whole Stripe event, so the object is params.data.object. A failed run is retried; make it safe to run twice.

// api/actions/stripeCheckoutSessionCompleted.ts: runs on checkout.session.completed.
import type { GlobalActionRun } from "@inferencebureau/apps-sdk";

export const run: GlobalActionRun = async ({ params, api }) => {
  const session = params.data.object; // the event is the action's params
  if (session.payment_status !== "paid") return;
  const booking = await api.booking.findFirst({ filter: { code: { equals: session.metadata.booking } } });
  if (!booking || booking.paid) return; // safe to run twice
  await api.booking.update(booking.id, { paid: true });
};

Each event shows in Logs as a webhook from stripe, with a note saying which action it queued and what it synced. Each is handled once, however often Stripe sends it. An event that never arrives is caught up within the hour from Stripe's event list. The endpoint sends:

Events
Checkoutcheckout.session.completed, .expired, .async_payment_succeeded, .async_payment_failed
Subscriptionscustomer.subscription.created, .updated, .deleted, .trial_will_end
Invoicesinvoice.paid, invoice.payment_failed
Customerscustomer.updated, customer.deleted

The synced models

stripeCustomer (stripeId, email, name, user) and stripeSubscription (stripeId, customer, user, status, price, lookupKey, quantity, currentPeriodEnd, cancelAtPeriodEnd, trialEnd) are kept from Stripe's events. They are linked to the app's user through the ib_user that checkout() sets. Read them like any model. Add fields of your own if you like, but keep these names and don't write them. Development has them once Stripe is connected; production gets them with the next deploy.

Testing in the sandbox

Pay with Stripe's test card, 4242 4242 4242 4242, any future date and any CVC. Stripe's pages refuse to open inside the console's Preview, so when the app sends you there, a bar above the preview offers the page in a new tab; on the app's own address it goes straight there. Stripe's Send test event (Developers → Webhooks → the endpoint) sends one to development.

Going live

Add your live account's key to production in the Stripe card. Its endpoint is made in the live account. Make the same prices (with the same lookup keys) in live mode, set the customer portal up there, and deploy so production has the synced models. Until then, Problems warns that production has no live key.

Stripe charges its fees to your Stripe account directly. On Inference Bureau, each webhook and the action it runs count as runs, and the synced records as storage, like any other (Plans and usage).