inference bureau
Answers from our docs and articlesesc to close
Try asking
Create an accountSign up

Take payments in a web app: Stripe Checkout, subscriptions and webhooks

Connect a sandbox key, redirect to Stripe's hosted Checkout, and let Stripe's webhook decide who has paid. What a web app on Inference Bureau gets.

Key takeaways

  • Connect a Stripe key per environment in Settings · Integrations: a sandbox key for development, your live key for production. A key of the wrong mode is refused.
  • checkout(user, { price }) returns a Stripe Checkout URL and billingPortal(user) the customer portal. The card is taken on Stripe's pages, never in your app.
  • Coming back to successUrl isn't proof of payment. Access follows Stripe's webhook, which keeps the user's stripeSubscription current, so check it with requireSubscription.
  • A file named api/actions/stripe<Type>.ts runs as a job on each Stripe event of that type. Each event is handled once, and a failed run is retried, so write it to be safe twice.

A web app on Inference Bureau, such as an ib-portal with a paid plan, can take payments into your own Stripe account without handling a card. People pay on Stripe's hosted Checkout, manage their plan in Stripe's customer portal, and the app learns what happened from Stripe's webhooks. Inference Bureau sets up the webhook and keeps each user's customer and subscription in the app's records.

Connect a key for each environment

In Settings → Integrations → Stripe, each environment takes its own key. Development takes a sandbox key (sk_test_… or rk_test_…), so no real money moves while you build. Production takes your live account's (sk_live_… or rk_live_…). A live key in development, or a sandbox key in production, is refused. Until production has a key of its own it reads development's sandbox key, 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 and fills them from the account.

A restricted key needs write on Checkout Sessions, Customer portal, Customers and Webhook Endpoints, and read on Subscriptions, Prices, Products and Events. Without Webhook Endpoints write, the card gives you the endpoint's URL and events to add in Stripe by hand. The app never needs a publishable key, because nothing in the browser talks to Stripe.

Send people to Checkout

Add stripe to the app's package.json. Then checkout 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:

// web/app/billing/actions.ts
"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: "pro_monthly", // a price id, or its lookup key
    successUrl: origin + "/billing?session={CHECKOUT_SESSION_ID}",
    cancelUrl: origin + "/billing",
  }));
}

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. mode is "subscription" by default, or "payment" for a one-time price. trialDays, quantity, allowPromotionCodes and metadata are the other options. Metadata stays on the session and on its subscription or payment, so your code can find what it was for.

billingPortal(user, { returnUrl }) returns the customer portal's URL for a user who already has a Stripe customer. Changing plan, cancelling, cards and invoices all happen there. You choose what the portal offers in Stripe's Dashboard, separately for the sandbox and live.

Who has paid

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

import { requireSubscription, subscriptionOf } 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"] });

requireSubscription passes an active subscription, and a trialing one unless you pass allowTrial: false. A past-due one doesn't pass, because Stripe is still trying to take the payment. It throws SubscriptionRequiredError with status 402. In a route handler, catch it and return e.toResponse().

Run 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, and invoice.payment_failed runs stripeInvoicePaymentFailed. Its params are the whole Stripe event, so the object is params.data.object.

The endpoint sends the checkout events (completed, expired, async payment succeeded and failed), the subscription events (created, updated, deleted, trial will end), invoice.paid, invoice.payment_failed, and customer.updated and customer.deleted.

Every event is checked against the endpoint's signing secret and handled once, however often Stripe sends it. It shows in Logs as a webhook from stripe, with a note saying which action it queued. An event that never arrives is caught up within the hour from Stripe's event list. A failed action run is retried, so check state before you write: fulfil an order only if it isn't already paid.

Test in the sandbox, then go live

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 a bar above the preview offers the page in a new tab. Stripe's Send test event (Developers → Webhooks → the endpoint) sends one to development.

To go live, add your live key to production in the Stripe card, which makes its endpoint in the live account. Then make the same prices, with the same lookup keys, in live mode, set up the customer portal there, and deploy so production has the synced models. Until production has a live key, Problems warns about it.

What it costs on Inference Bureau

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).

Frequently asked questions

Do card details ever reach my app?

No. People pay on Stripe's hosted Checkout, and the app never needs a publishable key, because nothing in the browser talks to Stripe.

Is the redirect back to successUrl enough to unlock a paid page?

No. It only means the person came back. Check subscriptionOf or requireSubscription, which follow Stripe's webhook.

Can I use a live key while developing?

No. Development takes a sandbox key and production a live one. A key of the wrong mode is refused.

What if a webhook never arrives?

It is caught up within the hour from Stripe's event list, and each event is handled once however often Stripe sends it.

One bill for your apps, your models and your reviews.

Host apps and functions next to your model traffic. Routing picks each turn's model by your quality floor, and Auditor reviews every pull request against your own rules.