Billing is one of those things every SaaS needs and nobody wants to build. You have to deal with checkout, recurring charges, failed payments, upgrades, cancellations, invoices, and (the part that bites everyone eventually) sales tax and VAT in dozens of countries.
Paddle takes a big chunk of that off your plate because it acts as your Merchant of Record. Paddle is the seller on the invoice, so it calculates, collects, and remits tax for you. Your job is to wire up checkout and keep your database in sync.
In this post I'll walk through a minimal but production-shaped setup with Paddle Billing:
- Create products and prices
- Open checkout with Paddle.js
- Handle webhooks (securely) to keep your DB in sync
- Let users manage their subscription via the customer portal
- Test everything in the sandbox
The examples use Next.js (App Router) + TypeScript, but the ideas apply to any stack.
1. Set up products and prices
In the Paddle dashboard (start with the sandbox at sandbox-vendors.paddle.com):
- Catalog → Products: create a product, e.g.
Pro Plan - Add prices to it, e.g.
$12 / monthand$120 / year
Each price gets an ID like pri_01h.... That ID is what you pass to checkout. A product is what you sell; a price is how you bill for it.
Then grab two credentials from Developer Tools → Authentication:
- A client-side token (starts with
test_in sandbox). It's safe to expose in the browser. - An API key for server-side calls. Keep this secret.
# .env.local NEXT_PUBLIC_PADDLE_CLIENT_TOKEN=test_xxxxxxxxx NEXT_PUBLIC_PADDLE_ENV=sandbox NEXT_PUBLIC_PADDLE_PRICE_PRO_MONTHLY=pri_01h... PADDLE_API_KEY=xxxxxxxx PADDLE_WEBHOOK_SECRET=pdl_ntfset_xxxxxxxx 2. Open checkout with Paddle.js
Install the official wrapper:
npm install @paddle/paddle-js Initialize Paddle once on the client, then open the overlay checkout when the user clicks "Upgrade":
'use client'; import { initializePaddle, type Paddle } from '@paddle/paddle-js'; import { useEffect, useState } from 'react'; export function UpgradeButton({ userId, email }: { userId: string; email: string }) { const [paddle, setPaddle] = useState<Paddle>(); useEffect(() => { initializePaddle({ environment: process.env.NEXT_PUBLIC_PADDLE_ENV as 'sandbox' | 'production', token: process.env.NEXT_PUBLIC_PADDLE_CLIENT_TOKEN!, }).then(setPaddle); }, []); const openCheckout = () => { paddle?.Checkout.open({ items: [{ priceId: process.env.NEXT_PUBLIC_PADDLE_PRICE_PRO_MONTHLY!, quantity: 1 }], customer: { email }, // This is the important bit: it links the Paddle subscription back to YOUR user customData: { userId }, settings: { successUrl: `${window.location.origin}/billing/success`, }, }); }; return ( <button onClick={openCheckout} disabled={!paddle}> Upgrade to Pro </button> ); } Two things worth calling out:
-
customDatais your best friend. Whatever you put here shows up ascustom_dataon the transaction and subscription in webhooks. That's how you know which user just paid. - Don't grant access on
successUrl. The redirect only means the user finished the checkout UI. Grant access when the webhook arrives (next section).
3. Handle webhooks
Webhooks are the source of truth. In Developer Tools → Notifications, create a destination pointing to https://yourapp.com/api/webhooks/paddle and subscribe to at least:
subscription.createdsubscription.updatedsubscription.canceledtransaction.completedtransaction.payment_failed
Paddle shows you a secret key for that destination. Put it in PADDLE_WEBHOOK_SECRET.
Verify the signature
Every request includes a Paddle-Signature header that looks like:
ts=1671552777;h1=eb4d0dc8853be92b7f063b9f3ba5233eb920a09459b6e6b2c26705b4364db151 The signature is an HMAC-SHA256 of ts + ":" + rawBody using your secret. The Node SDK does this for you:
npm install @paddle/paddle-node-sdk // lib/paddle.ts import { Environment, Paddle } from '@paddle/paddle-node-sdk'; export const paddle = new Paddle(process.env.PADDLE_API_KEY!, { environment: process.env.NEXT_PUBLIC_PADDLE_ENV === 'production' ? Environment.production : Environment.sandbox, }); // app/api/webhooks/paddle/route.ts import { EventName } from '@paddle/paddle-node-sdk'; import { paddle } from '@/lib/paddle'; import { db } from '@/lib/db'; export async function POST(req: Request) { const signature = req.headers.get('paddle-signature') ?? ''; const rawBody = await req.text(); // must be the RAW body, not re-serialized JSON let event; try { event = await paddle.webhooks.unmarshal(rawBody, process.env.PADDLE_WEBHOOK_SECRET!, signature); } catch { return new Response('Invalid signature', { status: 401 }); } switch (event.eventType) { case EventName.SubscriptionCreated: case EventName.SubscriptionUpdated: case EventName.SubscriptionCanceled: { const sub = event.data; const userId = (sub.customData as { userId?: string } | null)?.userId; if (!userId) break; await db.subscription.upsert({ where: { paddleSubscriptionId: sub.id }, create: { paddleSubscriptionId: sub.id, paddleCustomerId: sub.customerId, userId, status: sub.status, // active | trialing | past_due | paused | canceled priceId: sub.items[0]?.price?.id, currentPeriodEnd: sub.currentBillingPeriod?.endsAt, lastEventAt: event.occurredAt, }, update: { status: sub.status, priceId: sub.items[0]?.price?.id, currentPeriodEnd: sub.currentBillingPeriod?.endsAt, lastEventAt: event.occurredAt, }, }); break; } case EventName.TransactionPaymentFailed: // e.g. email the user, show a banner in-app break; } return new Response('ok'); } Webhook gotchas I'd plan for from day one
- Use the raw body. If your framework parses JSON first and you re-stringify it, the signature won't match.
- Events can arrive out of order or more than once. Make handlers idempotent (upsert by subscription ID) and ignore events older than the
lastEventAtyou've already stored. - Respond fast. Do the DB write, return
200, and push slow work (emails, analytics) to a queue. Paddle retries failed deliveries. - Derive access from status. A simple rule:
activeandtrialingget access;past_duegets access plus a "fix your payment" banner;pausedandcanceleddon't.
4. Let users manage their subscription
You don't need to build "update card", "view invoices", or "cancel" screens. Paddle has a hosted customer portal, and you can generate an authenticated link from your backend:
// app/api/billing/portal/route.ts import { paddle } from '@/lib/paddle'; import { getCurrentUserSubscription } from '@/lib/auth'; export async function POST() { const sub = await getCurrentUserSubscription(); if (!sub) return new Response('No subscription', { status: 404 }); const session = await paddle.customerPortalSessions.create(sub.paddleCustomerId, [ sub.paddleSubscriptionId, ]); return Response.json({ url: session.urls.general.overview }); } Redirect the user to that URL from a "Manage billing" button. Any change they make there comes back to you as a subscription.updated / subscription.canceled webhook, so your existing handler already covers it.
If you'd rather keep cancel in your own UI (for a cancellation survey, say), call the API directly:
await paddle.subscriptions.cancel(subscriptionId, { effectiveFrom: 'next_billing_period', // let them keep access until the period ends }); 5. Test in the sandbox
Before going live, run the full loop in sandbox:
- Open checkout and pay with the test card
4242 4242 4242 4242, any future expiry, any CVC. - Confirm
subscription.createdhits your endpoint and the row appears in your DB. - Open the customer portal, switch plans, then cancel. Check that
subscription.updated/subscription.canceledupdate the row. - Use Developer Tools → Notifications to replay events and check your handler is idempotent.
For local development, expose your dev server with a tunnel (ngrok, Cloudflare Tunnel, etc.) and point a sandbox notification destination at it.
When you're ready for production, you'll swap the client token, API key, webhook secret, price IDs, and environment value. Keep them all in env vars so it's a config change, not a code change.
Wrapping up
The whole integration comes down to:
- Client: Paddle.js opens checkout with
customDatapointing to your user. - Server: one webhook route that verifies signatures and upserts subscription state.
- Self-serve: the customer portal handles cards, invoices, and cancellations.
- Tax: handled by Paddle as Merchant of Record.
That's a small amount of code for a billing system that works worldwide. If you've shipped Paddle in production and have tips (or war stories about webhooks), drop them in the comments 👇