Writing Subscription Billing Code With LLMs in November 2026: Let Webhooks Decide Access, Store the Provider's IDs, and Plan for Failed Payments

Subscription billing looks like a weekend task. You add a checkout button, the payment provider takes the card, and you flip a flag that says the user is on the paid plan. Ask an LLM for "Stripe subscription code" and it will give you exactly that in a few seconds. The trouble is that the first version almost always treats billing as a single moment, the checkout, when it is really a long-running relationship with renewals, failed cards, upgrades, cancellations, refunds, and events that arrive late or twice.

This post walks through how to get useful subscription code out of an LLM without shipping the usual mistakes. The examples use Stripe because it is common and well documented, but the same ideas apply to Paddle, Lemon Squeezy, Chargebee, and app store billing: the provider owns the money, and your app has to keep a faithful copy of what the provider says.

A Nagoya subway commuter pass

A subscription is like a commuter pass: it is valid for a period, it has to be renewed, and the system that issued it decides whether it still works. Image: Train pass for commuter pass purchase of Nagoya subway by 愛知特区, CC0, via Wikimedia Commons.

Why LLM-written billing code goes wrong

Most generated billing code fails in a few predictable ways:

  • It grants access from the browser redirect. The model writes a /success page that marks the user as paid. Anyone can open that URL, and a user who closes the tab before the redirect never gets upgraded.
  • It keeps a single is_paid boolean. That can't represent a trial, a card that failed yesterday, or a plan that ends at the end of the month.
  • It handles only the happy-path events. You get code for "checkout completed" and nothing for renewals that fail, subscriptions that are canceled from the provider's dashboard, or refunds.
  • It assumes events arrive once and in order. Payment providers retry webhook deliveries and do not promise ordering, so naive handlers double-apply changes or let an old event overwrite a newer state.
  • It mixes in plan prices from memory. The model may hardcode a price ID or an amount that doesn't exist in your account.

None of these show up in a quick demo. They show up a month later when the first renewal fails.

Step 1: Give the model your real setup before asking for code

Start the conversation with facts, not a request for "subscription code." Paste or describe:

  • Your provider and the SDK version you have installed (copy it from your lockfile).
  • Your plans and the real price IDs from your provider dashboard, in test mode.
  • Your users table schema and the language and framework you use.
  • What each plan unlocks, written as a short list of features or limits.
  • Whether you offer trials, and what should happen when a payment fails.

Then ask for a design before code: "List the tables, the webhook events you plan to handle, and what each event changes. Don't write code yet." Reviewing a ten-line plan is much easier than reviewing four hundred lines of handlers, and it is where you catch a missing event.

Step 2: Store the provider's IDs and status, not a boolean

Your database should mirror the provider's view of each subscription closely enough that you can answer "what is this customer entitled to right now?" without calling the provider on every request. A minimal table looks like this:

CREATE TABLE subscriptions (
  id                      BIGSERIAL PRIMARY KEY,
  user_id                 BIGINT NOT NULL REFERENCES users(id),
  provider_customer_id    TEXT NOT NULL,
  provider_subscription_id TEXT NOT NULL UNIQUE,
  price_id                TEXT NOT NULL,
  status                  TEXT NOT NULL,      -- e.g. trialing, active, past_due, canceled
  current_period_end      TIMESTAMPTZ,
  cancel_at_period_end    BOOLEAN NOT NULL DEFAULT FALSE,
  provider_updated_at     TIMESTAMPTZ NOT NULL,
  created_at              TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at              TIMESTAMPTZ NOT NULL DEFAULT now()
);

A few points to insist on when the model drafts this:

  • Save the customer ID on the user as soon as you create it. Every later event refers to the provider's customer and subscription IDs, so you need a reliable way back to your user. Pass your own user ID in the provider's metadata field as well, as a second link.
  • Keep the provider's status string as-is. Stripe, for example, uses statuses such as trialing, active, past_due, unpaid, canceled, incomplete, and paused. Check the current list in your provider's docs rather than trusting the model's memory, and store whatever arrives.
  • Decide access in one function. Write a single hasPaidAccess(subscription) helper that turns status and dates into a yes or no, and use it everywhere. When you later decide that past_due gets a grace period, you change one place.
function hasPaidAccess(sub) {
  if (!sub) return false;
  if (sub.status === "active" || sub.status === "trialing") return true;
  // Grace period while the provider retries a failed card
  if (sub.status === "past_due") return true;
  return false;
}

Whether past_due keeps access is a business decision, not a technical one. Make it on purpose and write it down.

Step 3: Let webhooks decide access, not the success page

The rule to give the model is simple: the success page only shows a message; webhooks change the database. The user's browser is not a trusted source of payment information, and it may never reach your success page at all.

A typical flow with a hosted checkout:

  1. Your server creates a checkout session for the logged-in user, with the price ID chosen on the server and the user's ID in metadata.
  2. The user pays on the provider's page and is redirected to your success page, which says "Thanks, your account is being upgraded" and polls your own API for the subscription status.
  3. The provider sends webhook events to your server. Your handler verifies them and updates the subscriptions table.
  4. The success page sees the new status and moves on.

Never let the client send a price or an amount. If the request body includes a price ID, check it against an allowlist of your own plans on the server.

Verify every webhook on the raw body

Webhook endpoints are public URLs. Without signature checks, anyone can post a fake "subscription active" event. Providers sign each delivery, and their SDKs include a verify helper. In Node with Stripe it looks like this:

app.post("/webhooks/stripe",
  express.raw({ type: "application/json" }),
  async (req, res) => {
    let event;
    try {
      event = stripe.webhooks.constructEvent(
        req.body,                               // raw Buffer, not parsed JSON
        req.headers["stripe-signature"],
        process.env.STRIPE_WEBHOOK_SECRET
      );
    } catch (err) {
      return res.status(400).send("Invalid signature");
    }
    await enqueueBillingEvent(event);           // store, then process
    res.sendStatus(200);
  });

A common bug in generated code is placing a global JSON body parser before this route, which changes the bytes and makes every signature check fail. Tell the model the route must receive the raw body and ask it to explain how your framework does that.

Step 4: Handle the events that actually change money

Ask the model to list every event your design needs and what each does. For a Stripe subscription app, a reasonable starting set is:

  • checkout.session.completed: link the new customer and subscription to your user.
  • customer.subscription.created, customer.subscription.updated, customer.subscription.deleted: copy status, price, period end, and cancel flags into your table.
  • invoice.paid: a renewal went through; good place to extend usage quotas or send a receipt.
  • invoice.payment_failed: a renewal failed; tell the user and point them to update their card.

Check event names against the provider's current docs before you ship. Models sometimes invent plausible event names that don't exist.

A New York City subway turnstile with an OMNY contactless reader

Your access check is the turnstile: it should open based on what the payment system confirmed, not on what the rider says. Image: NYC Subway turnstile equipt with OMNY by GK tramrunner RU, CC BY-SA 4.0, via Wikimedia Commons.

Make handlers safe to run twice and out of order

Providers retry deliveries when your endpoint is slow or returns an error, so the same event can arrive more than once. Events can also arrive in a different order than they happened. Two habits fix most of this:

  1. Record processed event IDs. Keep a processed_events table with the provider's event ID as the primary key. Insert it in the same transaction as your update; if the insert conflicts, skip the event.
  2. Sync from the source instead of applying deltas. When a subscription event arrives, fetch the current subscription from the provider's API (or use the full object in the event) and write the whole state. "Set status to whatever the provider says now" is safe to repeat. "Add one month to the end date" is not.
async function syncSubscription(providerSubId) {
  const sub = await stripe.subscriptions.retrieve(providerSubId);
  await db.query(
    `INSERT INTO subscriptions (user_id, provider_customer_id,
       provider_subscription_id, price_id, status,
       current_period_end, cancel_at_period_end, provider_updated_at)
     VALUES ($1,$2,$3,$4,$5,$6,$7, now())
     ON CONFLICT (provider_subscription_id) DO UPDATE SET
       price_id = EXCLUDED.price_id,
       status = EXCLUDED.status,
       current_period_end = EXCLUDED.current_period_end,
       cancel_at_period_end = EXCLUDED.cancel_at_period_end,
       provider_updated_at = now(),
       updated_at = now()`,
    [userIdFor(sub), sub.customer, sub.id,
     sub.items.data[0].price.id, sub.status,
     periodEnd(sub), sub.cancel_at_period_end]
  );
}

Field names such as where the current period end lives have moved between API versions, so the periodEnd helper here is deliberately a placeholder. Have the model look it up for the API version pinned in your account and confirm by printing a real test-mode object.

Step 5: Plan for failed payments and cancellations

Cards expire, get replaced, or hit limits. Your code needs a clear answer for each of these situations before the first one happens:

  • Renewal fails: the provider usually retries on a schedule you configure. Decide whether the user keeps access during retries, show a banner with a link to update the card, and send an email.
  • Retries run out: the subscription moves to a final state such as canceled or unpaid, depending on your settings. Your sync code picks that up and hasPaidAccess returns false.
  • User cancels: most apps cancel at period end, so the user keeps what they paid for. Show "Your plan ends on date" using cancel_at_period_end and the stored period end.
  • Plan change: let the provider calculate proration rather than asking the model to write that math. Update the subscription through the API and let the webhook sync the result.

Most providers offer a hosted customer portal for updating cards, switching plans, and canceling. Using it removes a lot of code you would otherwise have to write and secure yourself.

Step 6: Test with the provider's tools, not just unit tests

Billing bugs live in the gaps between your app and the provider, so test across that gap:

  • Use test mode and the provider's test cards, including the ones that simulate declines and cards that require extra authentication.
  • Forward real webhooks to your laptop. The Stripe CLI can forward events to a local URL (stripe listen --forward-to localhost:3000/webhooks/stripe) and trigger sample events (stripe trigger invoice.payment_failed).
  • Replay the same event twice and confirm nothing changes the second time.
  • Simulate time passing with the provider's test clocks, if available, to see a trial end and a renewal fail without waiting a month.
  • Write a nightly reconciliation job that lists active subscriptions from the provider and compares them with your table. Any mismatch is a bug in your webhook handling, and you want to find it before a customer does.

A prompt that gets better results

Here is a prompt pattern that works well once you have shared your schema and plans:

Write the webhook handler for our Stripe subscriptions in [language/framework].
Requirements:
- Verify the signature on the raw request body.
- Store each event ID and skip events we've already processed.
- For subscription events, fetch the current subscription and upsert
  our subscriptions table (schema above). Never apply deltas.
- Handle: checkout.session.completed, customer.subscription.created,
  customer.subscription.updated, customer.subscription.deleted,
  invoice.paid, invoice.payment_failed. Log and ignore anything else.
- Return 200 quickly; do slow work (emails) in a background job.
- Do not hardcode prices or amounts.
After the code, list every assumption you made about Stripe's API
fields so I can check them against the docs.

The last line matters most. It turns the model's guesses into a checklist you can verify in a few minutes.

Checklist before you go live

  • Access is granted only by verified webhooks, never by the success redirect.
  • Prices are chosen on the server from an allowlist.
  • The database stores provider IDs, raw status, and period end, not a boolean.
  • One helper decides access, and the past_due policy is a deliberate choice.
  • Webhook handlers are idempotent and sync full state.
  • Failed payments trigger a visible banner and an email.
  • You've tested declines, duplicate events, and a renewal with the provider's test tools.
  • A reconciliation job compares your table with the provider every day.
  • Live-mode keys and webhook secrets are separate from test mode and kept out of the repo.

An LLM can write most of this code quickly. Your job is to give it the real setup, insist that the provider is the source of truth, and check every API detail it claims before money depends on it.

Comments

Popular posts from this blog

Grok Bot - a step closer to AGI

Tencent Hy4 Preview: Open 770B MoE Built for Real Work

Structured Outputs and Constrained Decoding for Reliable LLM APIs in Production (September 2026)