# Make a Stripe Webhook Handler Idempotent

Yes. An agent records each Stripe event id before acting on it, ignores redeliveries and out-of-order renewals, tests it with signed payloads, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-webhook-idempotency/stripe/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the handler as it is. In a Next.js app laid out like shadcn-ui/taxonomy, `app/api/webhooks/stripe/route.ts` reads the raw body, verifies it with `stripe.webhooks.constructEvent` and `STRIPE_WEBHOOK_SECRET`, and then acts on two event types: on `checkout.session.completed` it retrieves the subscription and writes `stripeSubscriptionId`, `stripeCustomerId`, `stripePriceId` and `stripeCurrentPeriodEnd` to the user named in the session's `metadata.userId`; on `invoice.payment_succeeded` it retrieves the subscription again and updates the price id and period end on the user with that subscription id. Nothing records which events were handled. Stripe retries a delivery that does not get a 2xx and does not promise order, so a timeout on the database makes the same event arrive again, and a renewal invoice delivered after a later one can set `stripeCurrentPeriodEnd` backwards. `lib/stripe.ts` pins the API version at `2022-11-15` on `stripe` `^11.18.0`, `lib/subscription.ts` decides `isPro` from `stripePriceId` and the period end, and `prisma/schema.prisma` is a MySQL datasource with the Stripe fields on `User`.

It adds a `StripeEvent` model to the schema: the event's `id` as the primary key, its `type`, the `created` timestamp from the event, and `processedAt`. The handler inserts the row first, inside the same transaction as the user update, and treats Prisma's `P2002` unique-constraint error as "already handled": it answers 200 without touching the user, so a retry of a delivery that was in fact completed does nothing. If the update fails after the insert, the transaction rolls back together, the handler answers 500, and Stripe's retry gets a clean second attempt.

For ordering, the agent compares before it writes: an `invoice.payment_succeeded` whose subscription's `current_period_end` is earlier than what the user row already holds is recorded and acknowledged but does not move the period end back. It also adds `customer.subscription.deleted` and `customer.subscription.updated`, which the handler ignores today even though a cancellation is how a user stops being `isPro` before the period lapses, and reads the subscription from the event object instead of calling `stripe.subscriptions.retrieve` where the event already carries it, which removes one API call per delivery. Unhandled types are acknowledged with 200 so Stripe does not retry them.

It proves the handler with Stripe's own test helper. `stripe.webhooks.generateTestHeaderString` signs a payload with the webhook secret, so a test can post a `checkout.session.completed`, post it again, and assert the user was written once and the second call answered 200 with no change; then post two renewals out of order and assert the later period end survives. The agent installs a MySQL in its sandbox, runs `prisma migrate dev` for the new table, and runs those tests against it, since the project has no test runner yet it adds one under `__tests__` with the minimum setup and says so. It finishes with `yarn lint`.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Make the Stripe webhook handler idempotent. Read app/api/webhooks/stripe/route.ts, lib/stripe.ts, lib/subscription.ts, lib/db.ts, prisma/schema.prisma, env.mjs and package.json first. Add a StripeEvent model keyed by the event id with type, created and processedAt. In the handler, insert the event row in the same transaction as the user update, treat a P2002 on that insert as already handled and answer 200, and roll back together on any later failure. Do not move stripeCurrentPeriodEnd backwards when an older renewal arrives late. Handle customer.subscription.deleted and customer.subscription.updated, read the subscription from the event object where it is present, and acknowledge unhandled types. Write tests that sign payloads with stripe.webhooks.generateTestHeaderString and cover a redelivered checkout event and two out-of-order renewals; add a minimal test runner if the project has none. Install a MySQL in the sandbox, run the migration and the tests, run yarn lint, and open a pull request with the output.",
  "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

What comes back is a pull request that changes `route.ts` and `schema.prisma`, adds one migration and a test file, and adds the test runner if there was none. The description shows the transaction with the event insert, the `P2002` branch, the period-end guard, and the test output for the redelivery and the out-of-order renewals.

The run's record keeps the migration against a real MySQL and each signed request the tests sent, so a reviewer can see the second delivery acknowledged with no write rather than take it on faith.

Before merging, a reviewer decides whether the `StripeEvent` table needs pruning, which the pull request leaves as a later job, and whether to replay recent events from the Stripe dashboard against staging once the handler is deployed.

## Run it on every alert on repeated Stripe webhook failures

This is the job to run when the monitor reports the webhook route answering 500 or the Stripe dashboard shows an endpoint with failing deliveries. Stripe signs its own requests and cannot add the `Authorization` header a Rush `webhook` trigger needs, so a small handler on the reader's server receives the alert and forwards its body to the trigger's URL with the trigger's bearer secret and an `Idempotency-Key` made from the alert's id, so a re-fired alert does not start a second run. The trigger adds the payload after the prompt, so the run reads which event type was failing.

The first run adds the event table and the guards. A later run on a repository that already has them reads the alert, replays the failing event type through the tests, and opens a pull request that handles the case the alert found, each on its own branch and linked to the alert.

## Why run it on Rush?

A webhook handler that is not idempotent works until the first database hiccup, and then a customer is downgraded by a late renewal or double-written by a retry. The fix is a table and a transaction, but the proof is a signed payload delivered twice against a real database, which is tedious to set up by hand. The agent does it in its own sandbox with MySQL and Stripe's test signer, and keeps every request and result.

The pull request is one model, one transaction and three tests, so review is quick. A company with several apps on the same checkout and billing pattern runs them all at once, each in its own sandbox with its own pull request.

## Frequently asked questions

### Why insert the event before acting, not after?

Inserting first inside the transaction makes the unique constraint the lock: two concurrent deliveries of the same event cannot both pass it, and one of them sees `P2002` and stops. Inserting after would leave a window where both run the update. If the update fails, the rollback removes the event row too, so the retry is clean.

### Does the handler still verify signatures?

Yes, exactly as before: `constructEvent` with the raw body and `STRIPE_WEBHOOK_SECRET` runs first, and a bad signature is still a 400. The tests use `generateTestHeaderString` to produce valid signatures for their payloads rather than skipping the check.

### How does an older renewal get ignored?

The handler compares the subscription's `current_period_end` with the value already on the user and only writes when it is later. The event row is still recorded, so a redelivery of that older event is also a no-op. Both cases are covered by the out-of-order test.

### Will the StripeEvent table grow forever?

One row per event, so it grows with subscription activity. Stripe retries for days, not months, so rows older than that can be pruned by a scheduled job. The agent leaves pruning out of this pull request and names it as the follow-up.

## More Stripe jobs

- [Find Why Customers Churned in Stripe](https://getrush.ai/run/churn-analysis/stripe/)
- [Report Failed Payments in Stripe](https://getrush.ai/run/failed-payments-report/stripe/)
- [Build a Monthly Revenue Report From Stripe](https://getrush.ai/run/monthly-revenue-report/stripe/)

## More jobs like this: Fix a bug from an alert

- [Fix "The 'ansible.builtin.include' action plugin has been removed" in an Ansible playbook](https://getrush.ai/run/fix-ansible-include-action-removed/ansible/)
- [Fix "apt-key: not found" and "apt-key is deprecated" in a Dockerfile](https://getrush.ai/run/fix-apt-key-not-found/docker/)
- [Fix "PytestDeprecationWarning: The configuration option asyncio_default_fixture_loop_scope is unset"](https://getrush.ai/run/fix-asyncio-default-fixture-loop-scope-unset-warning/pytest-asyncio/)

## Keep reading

- [What an agent can do in Stripe itself, once you connect it](https://getrush.ai/integrations/stripe/)
- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
