Roc Solid
Markup in Roc · pages on a native server · components in WebAssembly

The ecosystem · packages/stripe

Charge from the first day

Stripe's hosted Checkout takes payments and starts subscriptions, its Customer Portal lets people change their plan or card or cancel, and a webhook keeps your database in step. Your app asks its own tables who has paid. Cards are typed on Stripe's pages, never yours.

The package handles the parts where small mistakes cost money: webhook signatures, events that come twice or late, one customer per person, and a thank-you page that knows before the event arrives. Your app keeps its prices (made in Stripe's Dashboard), its pages, and on_event!: what it does when someone pays.

A first app#

Each file below is from packages/stripe/example, which sells a subscription (Basic or Pro) and an e-book, with the auth package's dev sign-in. Its tests pay every way, on SQLite and Postgres, against a stand-in for Stripe's API.

1. The plugin and the webhook. List the plugin, for its tables. The server needs STRIPE_SECRET_KEY and STRIPE_WEBHOOK_SECRET to start. Under --dev it starts without them, with Stripe off. The webhook is your route (D-116), calling the package's handler with your on_event!.

packages/stripe/example/main.roc
## packages/stripe's example: an app that sells a subscription (Basic or Pro, monthly) and an e-book
## (once), through Stripe's hosted Checkout. The plugin brings its tables (D-082). The webhook is a
## route of the app's (routes/stripe/webhook/, D-116) calling the package's handler, which keeps the
## tables in step with Stripe. `Billing.on_event!` is the app's own part of each event: an e-book
## bought becomes an order. People sign in with packages/auth's dev sign-in (`rocx dev`: any
## address at once); `Accounts.admit!` keeps a row for each.
##
## Its pages: the pricing page (`/`), Checkout's way back (`/billing/done`), the account (`/account`:
## the subscription, cancelled or kept from there, its card and invoices, the orders, a button to
## the portal), a page for subscribers (`/pro`) and the e-book, for those who bought it (`/ebook`).
app [program] { auth: "../../auth/main.roc", crypto: "../../crypto/main.roc", pf: platform "../../../server/platform/main.roc", stripe: "../main.roc" }

import auth.Auth
import stripe.Stripe
import Generated/App

program = App.program({
	init!: |_started| Ok({}),
	plugins: [
		Auth.plugin({}),
		# STRIPE_SECRET_KEY and STRIPE_WEBHOOK_SECRET, from the environment (README.md: the Stripe CLI's
		# `stripe listen` gives the second).
		Stripe.plugin({}),
	],
	database: Sqlite("data/stripe.db"),
})
routes/stripe/webhook/+server.roc
import stripe.Stripe
import ../../../Billing

respond! = |{ request, .. }| Stripe.webhook_route!(request, Billing.on_event!)

2. Off to Checkout. A plan's button posts its price to your endpoint, which calls Stripe.checkout! and redirects. The mode comes from your plan, never the form. Each user gets one Stripe customer, made the first time. A price may be named by its lookup key, set in the Dashboard: Stripe.price!("pro_monthly") is its id, the same key in test and live mode.

packages/stripe/example/routes/(signed-in)/api/billing/checkout/+server.roc
import pf.Server
import pf.Endpoint
import stripe.Stripe
import ../../../../../Middlewares
import ../../../../../Plans

## POST /api/billing/checkout, from a plan's button (`price`): off to Stripe's Checkout for it,
## coming back to /billing/done once it is paid, or to / if they turn back. A subscription or a
## payment as the plan is, never as the form says; someone subscribed already changes plan in the
## portal (their account page). A price the page doesn't offer is a 400; Stripe refusing, or out of
## reach, a 502.
post! : { request : Server.Request, params : {}, context : Middlewares.Me, body : { price : Str } } => Try({}, Endpoint.Refusal)
post! = |{ context, body, .. }|
	match Plans.of!(body.price) {
		Err(NotFound) => Err(BadRequest("There is no such plan."))
		Ok(plan) if plan.subscription and Stripe.subscribed!(context.user) => Err(Answer(Server.redirect("/account")))
		Ok(plan) => {
			bought = Stripe.checkout!({
				user: context.user,
				email: context.email,
				mode: if (plan.subscription) Subscription else Payment,
				prices: [{ price: plan.price, quantity: 1 }],
				success_url: "/billing/done",
				cancel_url: "/",
			})
			match bought {
				Ok(url) => Err(Answer(Server.redirect(url)))
				Err(StripeErr(why)) => Err(Status(502, why))
				Err(DbErr(why)) => Err(Failed(why))
			}
		}
	}

3. Back from Checkout. Stripe redirects as soon as it is paid, often before its events. Stripe.checkout_session! fetches the session (by the ?session_id= the package put in the success URL) and keeps it, so this page already knows.

packages/stripe/example/routes/(signed-in)/api/billing/done/+server.roc
import pf.Server
import pf.Endpoint
import stripe.Stripe
import ../../../../../Middlewares
import ../../../../../Plans

## GET /api/billing/done?session_id=…: for the page Checkout comes back to (/billing/done): what
## was bought, as Stripe says now (`Stripe.checkout_session!`, which keeps it too, so the account
## and the pro pages know before Stripe's events have come). Someone else's session, or none, is a
## 404.
get! : { request : Server.Request, params : {}, context : Middlewares.Me } => Try({ what : Str, subscription : Bool, paid : Bool }, Endpoint.Refusal)
get! = |{ request, context, .. }| {
	id = Server.form_fields(request.query).find_first(|field| field.name == "session_id").map_ok(|field| field.value) ?? ""
	match Stripe.checkout_session!(context.user, id) {
		Ok(session) => Ok({ what: Plans.named!(session.prices.map(|line| line.price)), subscription: session.mode == Subscription, paid: session.paid })
		Err(NotYours) => Err(NotFound)
		Err(StripeErr(why)) => Err(Status(502, why))
		Err(DbErr(why)) => Err(Failed(why))
	}
}

4. When someone pays. on_event! gets each event after the package keeps it, in the same transaction. Here a bought e-book becomes an order; a failed renewal is logged:

packages/stripe/example/Billing.roc
import pf.Db
import pf.Log
import pf.Time
import stripe.Stripe
import Plans

## The app's own part of Stripe's events (`Stripe.webhook_route!`'s `on_event!`, given in
## routes/stripe/webhook/+server.roc), after the package has kept what each says, in the same
## transaction.
Billing := [].{

	## An e-book bought (a Checkout Session in payment mode, paid; or paid later, for a payment
	## method that takes days) becomes an order: written once, as its key is the session, and the
	## event is handled once anyway. A renewal that failed is on the log: a real app would mail them
	## (queue a job, here, so the mail goes once the event is kept). An `Err` rolls the event back,
	## and Stripe sends it again later.
	on_event! : Stripe.Event => Try({}, Str)
	on_event! = |event|
		match event.about {
			Session(session) if session.mode == Payment and session.paid and (event.type == "checkout.session.completed" or event.type == "checkout.session.async_payment_succeeded") =>
				ordered!(event.user, session).map_err(|DbErr(why)| "the order couldn't be written: ${why}")
			Invoice(invoice) if event.type == "invoice.payment_failed" => {
				Log.warn!("billing: a payment failed", { user: event.user, invoice: invoice.id, attempts: invoice.attempt_count, pay_at: invoice.hosted_url })
				Ok({})
			}
			_ => Ok({})
		}
}

## The order for a paid Checkout Session: what it was for, its total and currency.
ordered! : Str, Stripe.Session => Try({}, [DbErr(Str)])
ordered! = |user, session| {
	what = Plans.named!(session.prices.map(|line| line.price))
	_ = Db.run!(
		"insert into orders (session_id, user_id, what, amount, currency, created_at) values ($1, $2, $3, $4, $5, $6) on conflict do nothing",
		[Text(session.id), Text(user), Text(what), Int(session.amount_total), Text(session.currency), Int(Time.now_millis!({}).to_i64_wrap())],
	)?
	Ok({})
}

5. Pages for those who paid. Middleware checks Stripe.subscribed! for the subscribers' pages and Stripe.paid_for! for the e-book; anyone else goes to the pricing page.

Middlewares.roc, in part
## Subscribers only: signed in, as `signed_in`, with a subscription that is paid for
## (`Stripe.subscribed!`: active, trialing, or past due while Stripe tries the card again).
## Anyone else goes to the pricing page.
subscribers : Middleware({}, Middlewares.Me)
subscribers = Auth.required_with(
	|{}, session|
		match Accounts.user!(session.user) {
			Ok(Found(user)) if Stripe.subscribed!(user.id) => Ok({ user: user.id, email: user.email })
			Ok(Found(_)) => Err(Answer(Server.redirect("/?subscribe=1")))
			_ => Err(SignedOut)
		},
)

## Readers of the e-book only: signed in, as `signed_in`, and they have paid for it
## (`Stripe.paid_for!`, its price). Anyone else goes to the pricing page.
readers : Middleware({}, Middlewares.Me)
readers = Auth.required_with(
	|{}, session|
		match Accounts.user!(session.user) {
			Ok(Found(user)) if Stripe.paid_for!(user.id, Plans.ebook!({})) => Ok({ user: user.id, email: user.email })
			Ok(Found(_)) => Err(Answer(Server.redirect("/")))
			_ => Err(SignedOut)
		},
)

Each guards a group (a directory in brackets, which adds nothing to the paths): the Pro page and its endpoint are in routes/(subscribers)/, behind its +middleware.roc:

packages/stripe/example/routes/(subscribers)/+middleware.roc
import ../../Middlewares

## Pro: signed in, with a subscription paid for; anyone else goes to the pricing page.
middleware = Middlewares.subscribers

6. The portal. A button on the account page opens Stripe's Customer Portal, which comes back when they are done. Their changes arrive as events.

packages/stripe/example/routes/(signed-in)/api/billing/portal/+server.roc
import pf.Server
import pf.Endpoint
import stripe.Stripe
import ../../../../../Middlewares

## POST /api/billing/portal: off to Stripe's Customer Portal (their plan, their card, their invoices,
## cancelling), coming back to /account. Someone who has never checked out goes to the pricing page.
post! : { request : Server.Request, params : {}, context : Middlewares.Me, body : {} } => Try({}, Endpoint.Refusal)
post! = |{ context, .. }|
	match Stripe.portal!(context.user, "/account") {
		Ok(url) => Err(Answer(Server.redirect(url)))
		Err(NoCustomer) => Err(Answer(Server.redirect("/")))
		Err(StripeErr(why)) => Err(Status(502, why))
		Err(DbErr(why)) => Err(Failed(why))
	}

Developing with the Stripe CLI#

Use test mode: sk_test_ keys, nothing charged, and the test card 4242 4242 4242 4242 (any future date, any CVC). In the Dashboard, in test mode, make your products and prices (checkout! takes their price_… ids), and save the Customer Portal's settings once: until then, Stripe makes no portal sessions in test mode. Forward events with the Stripe CLI:

stripe listen --forward-to localhost:8080/stripe/webhook   # prints the webhook secret: whsec_…
export STRIPE_SECRET_KEY=sk_test_… STRIPE_WEBHOOK_SECRET=whsec_…
rocx dev                                                 # in another terminal
stripe trigger checkout.session.completed                # an event of your own

In production, add a webhook endpoint in the Dashboard (Developers, Webhooks) at <public URL>/stripe/webhook, and give the server its signing secret. Send it the checkout.session.*, customer.subscription.*, invoice.paid, invoice.payment_failed, customer.deleted, charge.refunded and charge.dispute.* events. A one-time payment refunded in full or disputed no longer counts as paid (a dispute won gives it back). At start the server logs its keys' mode, and warns about live keys under --dev.

How a payment goes#

Stripe.checkout!({ user, email, mode, prices, success_url, cancel_url }) finds or makes the user's Stripe customer (your id in its metadata) and a Checkout Session with the user as its client_reference_id. After the success page (step 3), events reach the webhook: checkout.session.completed, customer.subscription.created, invoice.paid. Renewals, failed payments, plan changes and portal cancellations arrive the same way later, and Stripe.subscribed! follows them.

Option of checkout!Is
user : Stryour id for whoever pays
email : Strtheir address, for a customer made now (optional)
mode : [Payment, Subscription]once, or every period
prices : List({ price : Str, quantity : U64 })Stripe's price ids, and how many
success_url, cancel_urla path of your site, or a URL; the success URL gets session_id={CHECKOUT_SESSION_ID}
trial_days : U64a subscription's free days first (optional)
promotion_codes : Boolwhether a promotion code may be typed (optional)
metadata : List((Str, Str))more of your own, on the session (optional)

The webhook#

Stripe.webhook_route!(request, on_event!) answers POST /stripe/webhook from your route file, behind its folder's middleware, which must let Stripe's servers in (webhook_at tells the plugin the path, for its log line at start). For each request:

Keep slow work out of on_event!: queue a job for the receipt or the email, and it commits with the event.

These read your database, never Stripe: a page that checks them waits on no other server, and nothing the browser sends decides who has paid.

FunctionSays
Stripe.subscribed!(user)whether they have a subscription that is active, trialing, or past due while Stripe tries the card again
Stripe.paid_for!(user, what)whether such a subscription has a price or product (price_…, prod_…), or a paid one-time payment was for the price and hasn't been refunded in full or disputed since
Stripe.subscription!(user)their subscription: status, items (each price's amount, currency, interval and lookup key: what this subscriber pays), when it renews or ends, whether it ends then
Stripe.payments!(user)their one-time payments that were paid, and not refunded in full or disputed since

A billing page of your own#

The portal (Stripe.portal!(user, return_url), its URL, or NoCustomer) does everything a subscriber may change. To show billing on a page of your own instead, in your words, these ask Stripe each time (read them on that page, not on every page):

FunctionDoes
Stripe.card!(user)the card their subscription is charged to (brand, last four digits, expiry): the subscription's, else their customer's default; NoCard for none
Stripe.invoices!(user)their invoices, the newest first, each with its number, status, amount, page and PDF
Stripe.cancel!(user)their subscription ends at its period's end (a trial's end, before the first charge), and subscription! says so at once
Stripe.keep!(user)undoes that: it goes on, charged as before
Stripe.card_portal!(user, return_url)the portal opened at changing the card, coming back once it is changed: cards are typed on Stripe's pages

For the rest of Stripe's API (a refund, a plan changed), Stripe.post! and Stripe.get! call it as the package does: the secret key, a pinned Stripe-Version, an idempotency key on a create, a retry after a network error. That key is new each call. When the app may ask twice (a job run again, a form sent twice), Stripe.post_with! takes your own key, so Stripe creates once.

Testing without Stripe#

STRIPE_API_URL points the package at another server. The example's tests start a stand-in for Stripe's API (example/test/stand-in.mjs, Node with no dependencies): the endpoints the package calls, answering with Stripe's objects, and what paying on Checkout's page would do (a subscription on a Visa ending 4242, with its first invoice), or a month's bill, or a card saved in the portal. It keeps every request it was sent, for a test to look at. Each test signs an event as Stripe does and sends it to the webhook. Copy it into your app's tests.

The tables#

The plugin's migrations (stripe/0001_stripe to stripe/0003_forgotten) make five tables, the same on SQLite and Postgres: stripe_customers (each user's Stripe customer), stripe_checkouts, stripe_subscriptions (as the events last said), stripe_events (those handled, swept after 30 days) and stripe_forgotten (customers whose users were deleted). The package keeps no users: it knows them by your app's id.

Deleting someone, Stripe.forget!(user) deletes their customer at Stripe, which ends their subscription there at once (no refund), then their rows here. Their invoices stay at Stripe, as tax law wants. Stripe's events about that customer afterwards are taken and kept nowhere, so they can't bring the rows back.

Safety#

A routes/+middleware.roc that requires sign-in everywhere would refuse Stripe's webhook too: guard your routes by directory instead. The webhook has no Origin, so the platform's cross-site check lets it through.

Status#

Built and tested: Checkout (payments, subscriptions, trials, promotion codes), the Customer Portal, the webhook, the checks for who has paid, refunds and disputes taking back a one-time payment, and a billing page of your own (the card, the invoices, cancelling and keeping). Not yet, in the package's PROPOSALS.md: Stripe Tax, metered billing, Connect, embedded Checkout and changing a plan from the app.