Sub topic 13
Taking payments
This chapter covers how to charge real money in an MVP without handling card data yourself. It assumes you have a working data model with user ownership (see the chapters on data modeling and on accounts and access control) and that you know what a webhook is from the integrations chapter.
Decide whether to charge yet
Payments add work: tax, refunds, failed charges and support. Charge early only if your hypothesis is about willingness to pay. If the hypothesis is "users will complete the core flow," a free launch is cheaper to run. A common middle path is to take a manual payment first, such as an invoice or a payment link you send by hand, and automate it after people have paid.
Never touch card numbers
You should not collect, store or log card numbers. A payment provider such as Stripe, Paddle or Lemon Squeezy does that for you. Your app sends the user to a page the provider hosts, or embeds a provider-hosted form. This keeps most of your PCI DSS burden (the card industry's security standard) with the provider.
There are three common ways to take a payment, in rising order of effort:
| Approach | How it works | Best for | Main limit |
|---|---|---|---|
| Payment link | The provider gives you a URL for a fixed product. You paste it into a button. | One-off tests, pre-sales | Hard to tie a payment to a specific user without extra setup |
| Hosted checkout | Your app creates a checkout session and redirects the user to the provider's page. | Most MVPs | Needs a small server-side step |
| Embedded form | The provider's form is shown inside your page. | Custom look | More code and more to test |
Hosted checkout is the default choice. Most no-code and AI builders have a Stripe connector or can generate this step for you.
Merchant of record versus payment processor
A payment processor like Stripe moves the money. You remain the seller, so you are responsible for sales tax and VAT registration and collection (Stripe offers tools for this, but you still configure and file). A merchant of record such as Paddle or Lemon Squeezy becomes the legal seller, collects and remits taxes, and pays you the remainder, in return for a higher fee. If you sell to customers in several countries and have no finance help, a merchant of record removes a lot of risk. Check current fees and supported countries on each provider's site before you decide.
The payment flow
The key idea: the user's browser returning to your "success" page does not prove they paid. Users close tabs, redirects fail, and anyone can type a success URL. The provider's webhook is the trustworthy signal.
Attach your own user ID to the checkout session (Stripe calls this client_reference_id or metadata). Without it, the webhook tells you a payment happened but not for whom.
Verify webhooks
Your webhook endpoint is a public URL. Anyone can send it a fake "payment completed" message. Providers sign each request with a secret you share with them. Verify the signature against the raw request body before acting. If a framework parses the JSON first and you re-serialize it, the bytes change and the check fails.
The function below works for providers that send an HMAC-SHA256 signature in hex. Stripe's format differs (it signs a timestamp plus the body in a Stripe-Signature header), so for Stripe use the provider's official library. The principle is the same.
import { createHmac, timingSafeEqual } from "node:crypto";
// Verifies an HMAC-SHA256 signature (hex) sent by a service with a shared secret.
export function isValidSignature(rawBody, signatureHex, secret) {
const expected = createHmac("sha256", secret).update(rawBody).digest();
const received = Buffer.from(signatureHex, "hex");
return received.length === expected.length && timingSafeEqual(received, expected);
}timingSafeEqual compares in constant time, so an attacker cannot learn the correct signature by measuring response times. The length check comes first because timingSafeEqual throws on buffers of different sizes.
Store the payment state in your own data
Add the minimum fields to your data model, and let only the webhook handler write them:
plan(for examplefreeorpro) on the user or account row.provider_customer_id, so you can look the customer up later.subscription_status(such asactive,past_due,canceled).current_period_end, so access can last until the paid period ends.
Row-level security should let users read these fields but not change them. If a user can update their own plan column from the browser, they can upgrade themselves for free. Writes should come from a server-side function using a privileged key, never from client code. This is a common mistake in generated apps, so check it when you review the output.
Handle the events that matter
Subscriptions generate more events than a single payment. For an MVP, handle a small set and ignore the rest:
- Checkout completed: create or activate the plan.
- Payment failed: mark
past_dueand email the user. Providers retry failed cards for a period you configure. - Subscription canceled or ended: downgrade at
current_period_end. - Refund or dispute: flag for manual review.
Two properties make this reliable:
- Idempotency. Providers can deliver the same event more than once. Store each event ID and skip ones you have already processed, or write handlers so that repeating them changes nothing (setting
plan = protwice is harmless; adding 100 credits twice is not). - Fast response. Return a 2xx status quickly and do slow work afterward. If you respond with an error, the provider retries, which multiplies the duplicate problem.
Test mode before live mode
Every major provider has a test mode with separate keys and fake cards. Complete the whole flow there, including a failed card, a cancellation and a duplicate webhook. Use the provider's CLI or dashboard to resend events. Then switch to live keys.
Keep secret keys in your platform's secrets or environment settings. Never paste them into a prompt for an AI builder, into client-side code, or into a public repository.
Common errors
- Granting access on the redirect instead of the webhook.
- Using test keys in production, or live keys in a preview site.
- Not attaching the user ID, leaving payments you cannot match to accounts.
- Parsing the body before verifying the signature.
- Ignoring failed payments, so churn is invisible.
- Forgetting a way for users to cancel and manage billing. Most providers offer a hosted customer portal, which saves you building it.
Exercise
A user pays on the hosted checkout page, but your app shows "success" only after the redirect back to your site. Another user pastes your success URL into their browser without paying and gets pro features. What went wrong, and what two changes fix it?
Show answer
The app trusts the redirect, which anyone can trigger. Fix it by (1) granting the plan only when a verified, signed webhook from the provider reports a completed payment, and (2) making the success page read the plan from your database instead of assuming payment happened. Also attach the user ID to the checkout session so the webhook can update the correct account.
Exercise
Your webhook handler adds 100 credits to a user each time it receives a "payment completed" event. After a network blip the provider sends the same event twice. How do you prevent double credits?
Show answer
Make the handler idempotent. Store the provider's event ID (or payment ID) in a table with a unique constraint, and skip the event if it is already there. Do the insert and the credit update in one transaction so a crash cannot leave one without the other.