Stripe setup for a new SaaS: keys, prices, webhook
What to create in Stripe before checkout code can run: a restricted key, prices with lookup keys, the webhook endpoint and its one-time secret.
Four objects in Stripe, three kinds of value on your server
Before checkout code can run, a new SaaS needs four things to exist in Stripe: a product, at least one price, a webhook endpoint on the production domain and, if you want a launch discount, a coupon. Your server then needs three kinds of value as environment variables: an API key, the ID of each price, and the signing secret of the webhook endpoint, which starts with whsec_. Create all of it in a sandbox first, because nothing made there exists in live mode.
The rest of this page follows the order Shipyard's Stripe adapter works in, with the API call behind each step and the errors that show up when one is skipped. The code samples assume a Next.js app, but the Stripe side is the same for any stack.
Sandbox and live share nothing
Every request to Stripe runs either in a sandbox (the newer name for test mode) or in live mode. Each has its own keys, and an object made in one cannot be used in the other: a sandbox price ID in a live checkout call is simply an unknown ID. Plan to create everything twice. The dashboard has a Copy to live mode button on a product's page that carries the product and its prices across, and the API route is to run the same script again with a live key.
One difference matters on the day you go live. Sandbox keys can be viewed again whenever you like. A live secret key that you create yourself is displayed once, at creation, and cannot be revealed later. If you close the dialog without copying it, the fix is to rotate the key and store the replacement.
| Value | Prefix | Where it lives | What it can do |
|---|---|---|---|
| Publishable key | pk_test_ / pk_live_ | Browser | Identifies the account to Stripe.js and Elements. Not needed at all if the server creates Checkout Sessions and redirects. |
| Secret key | sk_test_ / sk_live_ | Server only | Everything. Its permissions cannot be narrowed. |
| Restricted key | rk_test_ / rk_live_ | Server only | Only the resources you set to Read or Write. |
| Webhook signing secret | whsec_ | Server only | Not an API key. Proves an incoming event was sent by Stripe. One per endpoint. |
A restricted key that covers setup and checkout
Stripe's own documentation now steers new integrations towards restricted keys instead of the unrestricted secret key. On the API keys page, press Create restricted key, name it, and set each resource to None, Read or Write. Write includes Read. The key is a drop-in replacement: the SDK takes it exactly where it took the secret key.
These are the resources a subscription SaaS touches during setup and at runtime. The first six come straight from the calls the Shipyard adapter makes; the last two are what the app itself needs to sell.
If a permission is missing, the call fails, the key's request log shows a 403, and the error body names the permission to add. Open the key's menu, choose Edit key, and tick it. The key value does not change.
| Resource | Level | Used for |
|---|---|---|
| Products | Write | Create the product, archive it on teardown. |
| Prices | Write | Create prices and find them again by lookup key. |
| Coupons | Write | Create the launch coupon. |
| Webhook Endpoints | Write | Register the endpoint and read its secret once. |
| Customers | Write | Create a customer at checkout, and for the delivery test below. |
| Events | Read | Check that a test event was delivered. |
| Checkout Sessions | Write | Start a payment from your server. |
| Subscriptions | Write | Change or cancel a plan from your server. |
Prices your code can find again
A product is the thing you sell and a price is one way of charging for it. unit_amount is in the smallest unit of the currency, so 19 dollars is 1900. Two small choices at creation time save trouble later.
First, give the product your own id instead of accepting a generated one. A second run of the same script then finds the product by that ID and skips it, which makes setup safe to repeat. Second, give every price a lookup_key. Your code and your setup script can then fetch the price by a name you chose, and a price change becomes a new price that takes over the key with transfer_lookup_key=true, with no redeploy.
You need the replacement route because a price is nearly immutable: after creation only its metadata, nickname, lookup key and active flag can change, never the amount. Deleting is limited too. A product that has prices cannot be deleted, only archived by setting active to false, and a price cannot be deleted through the API at all. Shipyard therefore archives products on teardown, and when a project is launched again it finds the archived product by ID and switches it back on, so the account does not fill up with duplicates.
# create a monthly price that can be found by name
curl https://api.stripe.com/v1/prices \
-u "$STRIPE_SECRET_KEY:" \
-d product=acme_pro \
-d unit_amount=1900 \
-d currency=usd \
-d "recurring[interval]=month" \
-d lookup_key=acme_pro_monthly
# later: fetch it by that name
curl -G https://api.stripe.com/v1/prices \
-u "$STRIPE_SECRET_KEY:" \
-d "lookup_keys[]=acme_pro_monthly"The webhook endpoint and the secret you see once
A webhook endpoint is a URL on your domain that Stripe posts events to, such as a completed checkout or a cancelled subscription. Without it a customer can pay and your database never hears about it. The URL has to be public and served over HTTPS with TLS 1.2 or newer.
In the dashboard the path is Workbench, Webhooks, Create an event destination, Your account, then the events, then Webhook endpoint as the destination type and your URL. The form marks the Thin payload as recommended. Pick Snapshot if your handler expects the classic Event object with data.object in it, as the handler on this page does. An account can hold up to 16 event destinations.
Through the API it is one call, and the detail that catches people is in the response. The secret field is returned only when the endpoint is created. The dashboard will show it to you again; the API will not. A script that creates the endpoint and fails to store the secret cannot ask for it later. Shipyard handles that case by deleting the endpoint whose secret it never saved and creating a fresh one, instead of leaving an endpoint nobody can verify.
Subscribe only to events you handle. Shipyard registers seven: checkout.session.completed, customer.created, customer.subscription.created, customer.subscription.updated, customer.subscription.deleted, invoice.paid and invoice.payment_failed.
curl https://api.stripe.com/v1/webhook_endpoints \
-u "$STRIPE_SECRET_KEY:" \
-d url="https://example.com/api/stripe/webhook" \
-d "enabled_events[]=checkout.session.completed" \
-d "enabled_events[]=customer.subscription.updated" \
-d "enabled_events[]=customer.subscription.deleted" \
-d "enabled_events[]=invoice.payment_failed"
# the JSON that comes back contains "secret": "whsec_..." this one timeVerifying the signature in a Next.js route
Stripe signs each delivery and puts the signature in the Stripe-Signature header. The signature is computed over the exact bytes of the request body, so the handler must read the body as text. Calling req.json() first, or letting a body parser run, changes those bytes and every verification fails. This is the core of the route in Shipyard's starter template.
Three behaviours shape the rest of the handler. Stripe can deliver the same event more than once, so record the event ID and skip repeats. Events are not guaranteed to arrive in the order they happened, so do not build logic that needs customer.subscription.created before invoice.paid. And the official libraries reject a signature whose timestamp is more than five minutes old by default, which means a server with a wrong clock fails verification even with the right secret.
export async function POST(req: NextRequest) {
const secret = process.env.STRIPE_WEBHOOK_SECRET;
const signature = req.headers.get('stripe-signature');
if (!secret || !signature) return NextResponse.json({ error: 'not configured' }, { status: 400 });
let event: Stripe.Event;
try {
// raw text, not req.json(): the signature covers the exact bytes
event = stripe.webhooks.constructEvent(await req.text(), signature, secret);
} catch {
return NextResponse.json({ error: 'bad signature' }, { status: 400 });
}
// insert event.id into a table with a unique key; if it was already there, stop
// then switch on event.type and update the user's plan
return NextResponse.json({ received: true });
}Where each value goes
Set these on the host, not in the repository, and redeploy if your host only reads variables at start. The names below are the ones Shipyard writes; if your code reads STRIPE_API_KEY instead of STRIPE_SECRET_KEY, the value has to be stored under that name too.
| Variable | Value | Comes from |
|---|---|---|
STRIPE_SECRET_KEY | sk_test_... or rk_test_... | API keys page |
STRIPE_WEBHOOK_SECRET | whsec_... | The create-endpoint response, or the endpoint page in Workbench |
STRIPE_PRICE_PRO_MONTHLY | price_... | One variable per price, named after its key |
STRIPE_COUPON_WELCOME | The coupon ID | The coupon you created; Shipyard uses the code itself as the ID |
Failures in the event deliveries tab, and their causes
Open the endpoint in Workbench and look at Event deliveries. Each failed attempt shows one of a small set of statuses.
- Signature errors on every event: the body was parsed before verification, or the secret belongs to a different endpoint. The sandbox endpoint, the live endpoint and
stripe listeneach have their own secret, even for the same URL. (302) ERR: Stripe treats any redirect as a failed delivery. If your bare domain redirects to www, or http to https, register the final address.(Timed out) ERR: the handler does slow work before answering. Return a 2xx first, then process.(TLS error) ERR: the certificate chain is incomplete or the server offers a TLS version below 1.2.(400) ERRor(404) ERR: the route does not exist in the deployed build, rejects POST, or sits behind a login or CSRF check.- Nothing arrives at all: the endpoint is in the other mode. A sandbox payment never reaches a live endpoint.
Retries, and a delivery test that needs no card
When a delivery fails in live mode, Stripe retries with growing gaps for up to three days. In a sandbox it retries three times over a few hours, so a broken test endpoint goes quiet quickly. You can resend an event by hand from the dashboard for 15 days after it was created.
For local work, the Stripe CLI forwards events to your machine and prints the signing secret to use while it runs.
Against the deployed site, Shipyard uses a test that has no side effects, and you can do the same by hand. With the endpoint subscribed to customer.created, create a customer in the sandbox, fetch the resulting event, and watch its pending_webhooks count. When it reaches 0 your endpoint has answered with a 2xx. Then delete the customer. No card, no checkout page, and it exercises the real URL, certificate and secret.
stripe login
stripe listen --forward-to localhost:3000/api/stripe/webhook
# in a second terminal
stripe trigger checkout.session.completedWhat Shipyard does here, and what it leaves to you
From the pricing in your launch config, Shipyard creates the products, prices and coupon in the sandbox, registers the webhook endpoint at https://yourdomain/api/stripe/webhook, and writes the key, the signing secret and the price IDs into your host's variables. Its health check runs the customer test above. It refuses to start if the key's prefix does not match the mode it expects, so a launch cannot run against live by accident.
Creating the Stripe account and finishing business verification are yours, and so is the decision to take real money: shipyard go-live <name> repeats the setup with a live key and asks before it does. The key stays in the keychain on your computer.
Sources
- Stripe: API keysdocs.stripe.com
- Stripe: Restricted API keysdocs.stripe.com
- Stripe: Manage products and pricesdocs.stripe.com
- Stripe: Receive Stripe events in your webhook endpointdocs.stripe.com
- Stripe API reference: The Webhook Endpoint objectdocs.stripe.com
Launch in an hour, not a weekend
Shipyard connects your accounts once, then sets up the domain, hosting, database, email and payments for every new product.
See how it works