# Handle Stripe Subscription Cancellations in a Next.js App

Yes. An agent makes your Stripe webhook handle cancellations and plan changes, stops checkout from creating duplicate customers, tests it, and opens a PR.

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

## What the agent does

The agent reads what the webhook handles and what the app believes as a result. In a Next.js app laid out like shadcn-ui/taxonomy, `app/api/webhooks/stripe/route.ts` verifies the signature with `stripe.webhooks.constructEvent` and `env.STRIPE_WEBHOOK_SECRET`, then acts on exactly two event types: `checkout.session.completed`, which stores `stripeSubscriptionId`, `stripeCustomerId`, `stripePriceId` and `stripeCurrentPeriodEnd` on the `User` row defined in `prisma/schema.prisma`, and `invoice.payment_succeeded`, which refreshes the price and the period end. `lib/subscription.ts` decides `isPro` from `stripePriceId` being set and `stripeCurrentPeriodEnd` plus one day being in the future. `package.json` pins `stripe` at `^11.18.0` with `apiVersion: "2022-11-15"` in `lib/stripe.ts`, `@prisma/client` at `^4.13.0` and `next-auth` at `4.22.1`.

Nothing listens for the subscription ending. A customer who cancels in the billing portal that `app/api/users/stripe/route.ts` opens for a pro user, or whose subscription Stripe cancels after failed payments, keeps `stripePriceId` on their row, and `isPro` stays true until a day past the period end, which is right for cancel-at-period-end and wrong for an immediate cancellation. After that day `getUserSubscriptionPlan` reports the free plan while the row still carries the old subscription id and customer id, so the next click on the billing form reaches the free-plan branch of the route and creates a checkout session with `customer_email` instead of the existing customer, which makes a second Stripe customer for the same person. `app/(dashboard)/dashboard/billing/page.tsx` reads `cancel_at_period_end` live from Stripe on every render for a pro user, a call that the stored row could answer.

The agent adds two branches to the webhook. On `customer.subscription.updated` it finds the user by `stripeSubscriptionId` and stores the current `stripePriceId`, `current_period_end` and a new `stripeCancelAtPeriodEnd` boolean added to `User` in `prisma/schema.prisma` with a migration, so a downgrade, an upgrade and a scheduled cancellation all land in the row. On `customer.subscription.deleted` it clears `stripeSubscriptionId`, `stripePriceId`, `stripeCurrentPeriodEnd` and the new flag, and keeps `stripeCustomerId`, which is the fix for the duplicate: the checkout branch of `app/api/users/stripe/route.ts` passes `customer` when the row has one and `customer_email` only when it does not. The webhook also answers `200` for the event types it ignores, as it does now, and the billing page reads `isCanceled` from the row instead of calling `stripe.subscriptions.retrieve` on every load. `getUserSubscriptionPlan` returns the flag so the form can say when the plan ends.

The repository has no test runner, so the agent adds Vitest with one file for the webhook and one for the plan helper. The webhook tests build each event with `stripe.webhooks.generateTestHeaderString` and the secret from `env.mjs`, post it to the route handler with a Prisma client pointed at a MySQL the agent installs in the sandbox, and assert the row after each event: set after `checkout.session.completed`, flagged after an `updated` event with `cancel_at_period_end`, cleared except for the customer id after `deleted`. The helper tests cover `isPro` before and after the period end with and without the flag. It runs the tests, `pnpm lint`, which is `next lint`, and `tsc --noEmit`, since `package.json` has no type-check script, then replays the three events once more with `stripe trigger` from the Stripe CLI against the dev server, and opens the pull request with the output.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Handle Stripe subscription cancellations and plan changes in this Next.js app. Read package.json, env.mjs, .env.example, lib/stripe.ts, lib/subscription.ts, lib/db.ts, config/subscriptions.ts, types/index.d.ts, prisma/schema.prisma, app/api/webhooks/stripe/route.ts, app/api/users/stripe/route.ts, app/(dashboard)/dashboard/billing/page.tsx and components/billing-form.tsx first. Add a stripeCancelAtPeriodEnd boolean to User with a Prisma migration. In the webhook, handle customer.subscription.updated by storing the current price id, period end and cancel_at_period_end on the user found by stripeSubscriptionId, and customer.subscription.deleted by clearing the subscription id, price id, period end and flag while keeping stripeCustomerId. In the checkout branch of app/api/users/stripe/route.ts pass customer when the row has a customer id and customer_email only when it does not. Make the billing page read isCanceled from the row instead of calling Stripe on each render, and return the flag from getUserSubscriptionPlan. Add Vitest with tests that post each event, signed with stripe.webhooks.generateTestHeaderString, to the route handler against a MySQL you install in the sandbox and assert the row after each, plus tests for isPro around the period end. Run the tests, pnpm lint and tsc --noEmit, replay the events with stripe trigger against the dev server, 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 `app/api/webhooks/stripe/route.ts`, `app/api/users/stripe/route.ts`, `lib/subscription.ts`, `types/index.d.ts`, `prisma/schema.prisma` with its migration, and the billing page, and adds the Vitest setup with two test files. The description lists the event types the webhook now handles and what each writes to the row, and quotes the test, lint and tsc output and the `stripe trigger` replay.

The run's record keeps the test in which a `deleted` event clears the row and a following checkout call carries `customer` rather than `customer_email`, so a reviewer sees the duplicate-customer path closed rather than reads that it is.

Before merging, a reviewer adds the two event types to the webhook endpoint in the Stripe dashboard, which the pull request names as the step that is not in the code, and decides whether a user whose subscription was deleted keeps pro access until the stored period end or loses it at once; the pull request implements the latter and marks the line to change.

## Run it on every Linear issue labelled agent

Billing gaps are reported as issues: a cancelled customer still on pro, a person with two Stripe customers. With Linear connected under Settings → Connections in the console, add an automation to the Project with a `linear` trigger on `linear.issue.labeled` and the label `agent`. Its saved prompt asks for what this one asks for, without the event names: read the webhook and the plan helper, handle the lifecycle events the issue describes, keep the customer id, test each event against a real database and open a pull request. The trigger adds the issue after the prompt and fills in no placeholder, so which event comes from the issue text.

The trigger fires only when someone in your Rush org adds the label, and a change made by an app integration never fires it. A burst of labels is held to the automation's `max_runs_per_hour`. From your own server, the same run starts with this request and the issue URL in `resources`, with a `request_id` that is a UUID v5 of the issue id so a retried start returns the run already begun.

## Why run it on Rush?

A webhook bug is a bug in a conversation between two systems, and proving the fix means sending the real event shapes, signed, at the real handler with a real database behind it. The agent does all of that in its own sandbox, with the Stripe CLI replaying the events against the dev server, and the record keeps each request and the row it left, so the pull request carries evidence rather than a description of the happy path.

A company with several Next.js products on the same billing layout runs this once per repository, each in its own sandbox with its own database and its own pull request, and reviews the same two webhook branches and the same customer-id fix in each.

## Frequently asked questions

### Why keep stripeCustomerId after a cancellation?

Because the customer still exists in Stripe with their payment history, and a resubscribe should attach to it. The duplicate-customer bug comes from forgetting the id and letting checkout create a new one from an email; keeping it and passing `customer` to the checkout session is the whole fix.

### Will existing subscriptions get the new flag?

The migration adds the column with a default of false. The next `customer.subscription.updated` event for each subscription sets it correctly, and the pull request includes a one-off script that reads each stored subscription from Stripe and backfills the flag for anyone who cancelled before the webhook learned the event.

### Does the webhook need to be re-registered?

The endpoint stays the same, but the Stripe dashboard sends only the event types an endpoint subscribes to, so `customer.subscription.updated` and `customer.subscription.deleted` have to be added there. The pull request names that step because it cannot be done from the repository.

### What about invoice.payment_failed?

It is left alone. Stripe retries a failed payment on its own schedule and cancels the subscription itself when retries run out, which arrives as `customer.subscription.deleted` and is now handled. Reacting to the failure earlier, such as warning the user, is a separate change the pull request mentions.

## More Stripe jobs

- [Make a Stripe Webhook Handler Idempotent](https://getrush.ai/run/add-webhook-idempotency/stripe/)
- [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/)

## More jobs like this: Turn a Linear label into a PR

- [Add a Table of Contents to Eleventy Blog Posts](https://getrush.ai/run/add-table-of-contents/eleventy/)
- [Add a Table of Contents to Gatsby Blog Posts from a Linear Issue](https://getrush.ai/run/add-table-of-contents/gatsby/)
- [Add Tag Pages to a Gatsby Blog from a Linear Issue](https://getrush.ai/run/add-tag-pages/gatsby/)

## 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/)
