All jobs

Write Tests for a Stripe Webhook Handler

Yes. An agent adds a test runner, signs test payloads with Stripe's helper, covers each event your handler acts on, runs them on a real database and opens a PR.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent reads the handler before writing a test. In a Next.js app like shadcn-ui/taxonomy, app/api/webhooks/stripe/route.ts exports POST: it reads the raw body with req.text(), takes the signature from headers().get("Stripe-Signature"), and calls stripe.webhooks.constructEvent(body, signature, env.STRIPE_WEBHOOK_SECRET), answering 400 with Webhook Error: … when that throws. On checkout.session.completed it calls stripe.subscriptions.retrieve(session.subscription) and writes stripeSubscriptionId, stripeCustomerId, stripePriceId and stripeCurrentPeriodEnd to the user named in session.metadata.userId; on invoice.payment_succeeded it does the same lookup and updates the user found by stripeSubscriptionId. lib/stripe.ts builds the client with apiVersion: "2022-11-15" on stripe 11.18.0 from the lockfile, lib/db.ts caches a PrismaClient, and env.mjs requires STRIPE_WEBHOOK_SECRET. package.json has no test script and no test runner: its devDependencies are eslint, prettier, husky, commitlint and the Prisma CLI.

So the first commit is the runner: vitest as a devDependency, a test script, and vitest.config.ts with environment: "node" and an alias for the @/* path from tsconfig.json. The tests live beside the handler in app/api/webhooks/stripe/route.test.ts. Signatures are real: stripe.webhooks.generateTestHeaderString({ payload, secret }) from the stripe package signs each test body with the same secret the handler verifies, so constructEvent runs unmodified. next/headers is replaced with vi.mock so headers() returns the test's signature, because the handler reads it there rather than from the request, and stripe.subscriptions.retrieve is replaced with vi.spyOn returning a fixture subscription with id, customer, items.data[0].price.id and current_period_end, so no call leaves the sandbox.

The cases follow the branches. A body signed with the wrong secret answers 400 and writes nothing. A checkout.session.completed event whose metadata.userId names a user the test created sets the four Stripe columns, with stripeCurrentPeriodEnd equal to current_period_end times 1000. An invoice.payment_succeeded event updates the user whose stripeSubscriptionId matches and leaves stripeCustomerId alone. An event type the handler does not handle, such as customer.subscription.deleted, answers 200 and changes nothing, which the test pins on purpose: lib/subscription.ts treats a user as PRO while stripeCurrentPeriodEnd plus a day is in the future, so a cancellation never reaches the database until the period ends, and the pull request says so rather than changing the handler. A checkout event with no metadata.userId is pinned the same way, with today's behavior recorded in the test name.

The tests run against a real database, not a Prisma mock. The sandbox has no Docker, so the agent installs MySQL with apt-get, sets DATABASE_URL, runs pnpm prisma migrate deploy to apply the two migrations under prisma/migrations, and runs pnpm vitest run with placeholder STRIPE_API_KEY and STRIPE_WEBHOOK_SECRET values, since the key is never used and the secret only has to match on both sides. Each test creates its own user with a fresh id and deletes it afterwards. pnpm lint and pnpm tsc --noEmit close the run; tsconfig.json has strictNullChecks: true, so the fixtures are typed as Stripe.Checkout.Session and Stripe.Invoice.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "There are no tests for the Stripe webhook handler in app/api/webhooks/stripe/route.ts. Add vitest with a test script and a config that resolves the @/ alias, then write tests beside the handler. Sign each payload with stripe.webhooks.generateTestHeaderString using the same secret the handler reads, mock next/headers so headers() returns that signature, and stub stripe.subscriptions.retrieve with a fixture subscription. Cover: a bad signature answers 400 and writes nothing; checkout.session.completed sets the user's Stripe columns including the period end; invoice.payment_succeeded updates the user found by subscription id; an unhandled event type answers 200 and changes nothing. Run the tests against a local MySQL with prisma migrate deploy applied, creating and deleting a user per test. Run lint and tsc. Open a pull request quoting the test output and listing any gap the tests expose without changing the handler.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
  1. Get an API key. In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
  2. Send the request. POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
  3. Read what came back. Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

What comes back

The pull request adds vitest.config.ts, the test script and vitest devDependency in package.json, app/api/webhooks/stripe/route.test.ts, and a small fixtures module with the subscription, checkout session and invoice objects. Its description quotes the vitest run output with each test name and result, and the lint and type check results.

It also lists what the tests found and left alone: the invoice.payment_succeeded branch casts event.data.object to Stripe.Checkout.Session although it is an invoice (both carry subscription, so it works), and no event tells the database about a cancelled or changed subscription. A reviewer checks that the signature test calls the real constructEvent, that no test reaches api.stripe.com, and that each test deletes the user it made. The transcript at GET /o/{org}/sessions/{id}/messages has the database setup and the test run in full.

Nothing is sent to Stripe and nothing touches your database. Fixing the gaps is a follow-up message to the same session, POST /o/{org}/sessions/{id}/messages, which wakes the sandbox with the tests already in place.

Run it on every pull request that touches the webhook route

Once the tests exist, the job repeats on every change to the handler. Add an automation on the Project with a github trigger on pull_request.opened and pull_request.synchronize and a prompt that runs the webhook tests, extends them for any event type the pull request adds, and reports the result as a review. The trigger adds the pull request after the prompt; it fills in no placeholder.

The same test run starts from your own server with this body and the pull request URL in resources (https://github.com/your-org/your-app/pull/123), with a request_id that is a UUID v5 of the pull request's head commit so a retried send returns the run already begun.

The use case this job follows, with its automation and trigger: Write the missing tests.

Why run it on Rush?

A webhook handler is the one route you cannot click through, and a test that mocks Prisma only proves the mock. The signed payload, the real constructEvent, the real update against a MySQL that started empty, and the row read back are what make these tests worth keeping, and on a laptop that means a database, a .env swap and a secret in a shell history. The sandbox has its own database for the run, and the output is in the transcript.

A team with several apps on the same starter runs this once per repository, in parallel, and reads one pull request per app. Each run names the gaps it found in its own handler, which is the list a reviewer actually wants.

Frequently asked questions

Why not the Stripe CLI and stripe trigger?

stripe trigger needs a Stripe account, a signed-in CLI and a listener that forwards events to a running server, and the events it sends are Stripe's, not the ones your handler acts on. generateTestHeaderString signs any payload locally with your secret, so the test controls the event, runs offline and finishes in milliseconds.

Do the tests call Stripe?

No. stripe.subscriptions.retrieve is replaced for each test with a fixture subscription, and STRIPE_API_KEY is a placeholder. If a test reached the network it would fail on the placeholder key, which is the point.

Why a real MySQL instead of mocking Prisma?

The handler's whole job is the update. A mocked db.user.update passes whatever the test expects; a real row read back after the request proves the where, the column names and the date conversion. The database lives only in the sandbox.

Can the same run fix the gaps it finds?

Ask for it in a follow-up to the session. The pull request from this run adds tests only, so a reviewer sees today's behavior pinned before any handler change; the follow-up adds customer.subscription.updated and deleted handling with tests beside the existing ones.

More Stripe jobs

More jobs like this: Write the missing tests

Keep reading