Skip to content

fix(core): confirm Stripe subscription checkouts and keep the customer - #138

Open
moset15 wants to merge 2 commits into
emdashCommerce:mainfrom
FIKANOVA:fix/stripe-subscription-confirm
Open

moset15 wants to merge 2 commits into
emdashCommerce:mainfrom
FIKANOVA:fix/stripe-subscription-confirm

Conversation

@moset15

@moset15 moset15 commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Builds on #127. It needs #127's index on customers.stripeCustomerId (without it, every customer.subscription.* webhook fails on a real store), so it includes #127's commit until that merges. Only the last commit is this PR.

Bugs

Found while testing a shop end to end with Stripe subscription products.

  1. The thank-you page fails after every Stripe subscription checkout.
    • In subscription mode checkout.session.completed creates no order and deletes the checkout draft.
    • So orders/by-draft answers { status: "failed" }, and the page says "We couldn't confirm your payment" though the customer has paid.
    • No order also means no stock decrement, no coupon usage, no lock release, no receipt and no download grants.
  2. A free-trial checkout fails the same way. Stripe reports a trial that collected a card as paid with amount_total: 0, not as no_payment_required. A paid-path order would then be put on hold for an amount mismatch.
  3. An early customer.subscription.created leaves the customer blank for good.
    • Stripe doesn't guarantee event order. If the subscription event lands before checkout.session.completed, no customer carries the Stripe customer id yet, so the row stores customerId: "".
    • upsertFromStripe uses existing?.customerId ?? …, and "" isn't nullish, so no later event fills it in.

They're in one PR because the order the session creates is also what confirms the checkout and fills in the customer when the session lands second.

Fix

The first-period order. A subscription-mode session goes through createOrderFromPaymentIntent, the same path as a payment-mode session.

  • Keying: a subscription session has no PaymentIntent, so the order is keyed on the Stripe subscription id: one checkout, one subscription, one first-period order. Retries and replays find the order by it.
  • Linking: whichever of the session and customer.subscription.* lands second links the order and the subscription (order.subscriptionIds), and fills a blank subscription customer from the order. The helper, linkFirstPeriodOrder, lives in subscriptions/create.ts.
  • No second order: invoice.paid and payment_intent.succeeded for the first invoice carry no orderDraftId, so they never create one, whatever the order of events.
  • Amounts: amount and currency come from the signed session (amount_total, currency) and are reconciled against the cart as usual, so a mismatch is put on hold.
  • Concurrent deliveries: if order creation throws but a concurrent delivery already stored the order, it's treated as a duplicate, like the payment-mode path.
  • Address merge: the session-to-cart address merge moves into cartWithSessionDetails, shared by both session kinds. Payment mode behaves exactly as before.

Refunds of that order.

  • The order records the PaymentIntent that paid the first invoice as its paymentReference, so an admin refund works. Stripe refuses a refund against the subscription id.
  • The PaymentIntent comes from /v1/invoice_payments?invoice=… (API version 2025-03-31 and later), falling back to the invoice's payment_intent on older versions.
  • The order stays keyed on the subscription id.
  • If the lookup fails, the order is left as it was, since it's already paid.

Free trials.

  • no_payment_required, or paid with amount_total: 0 for a cart that costs something, creates an order for 0: the items, a trial discount equal to the subtotal, and no shipping or tax until the first paid period.
  • The thank-you page confirms it, and stock, receipt and downloads take the normal path.
  • A cart a coupon makes free costs 0 and is unaffected.

The blank customer. upsertFromStripe uses ||, so a blank stored customer counts as missing and the next event resolves it.

Tests

Extends packages/core/test/stripe-subscription-webhook.test.ts, all through the real checkout, webhook and orders/by-draft routes with signed Stripe webhooks:

  • Usual order of events (session, then subscription.created, invoice.paid, payment_intent.succeeded): by-draft ready, exactly one order, linked to the subscription, same customer.
  • Everything before the session (subscription.created, invoice.paid and payment_intent.succeeded): one order, customer filled in, linked.
  • Redelivery: the session event redelivered, and replayed under a new event id, still gives one order.
  • Refund reference: the first order's payment reference is the first invoice's PaymentIntent, and it's still keyed on the subscription.
  • Free trial, no_payment_required: an order for 0, not on hold, linked, with the customer filled in.
  • Free trial, paid with 0: an order for 0, not on hold.

The tests fail without the change. Full suite: core 442 pass, plus the 4 local routing-response-adapter failures that need the EmDash patch and pass on CI. Core typecheck and Biome clean.

Also tested by hand on a running shop (EmDash 1.6, Stripe test mode, test card):

  • Paid subscription: the thank-you page confirmed it, and a full admin refund of the first order succeeded at Stripe against the PaymentIntent.
  • 7-day free trial: the thank-you page confirmed an order for 0, linked to its subscription.

Compatibility

  • Shops get an order for the first period of every Stripe subscription, as for any other purchase: for 0 on a free trial. Merchants who relied on there being no order will now see one; we know of none, since the thank-you page failed.
  • Renewals are unchanged: they stay subscription invoices, not orders.

Review points

@moset15
moset15 force-pushed the fix/stripe-subscription-confirm branch from c491be0 to a469db2 Compare December 3, 2026 07:35
cavewebs added a commit that referenced this pull request Dec 3, 2026
This PR brings the Flutterwave adapter and the Core changes it needs
into one review.

- Integration roadmap in #97

## Superseded package PRs

The changes from these five stacked PRs are included here.

- #98
- #100
- #102
- #104
- #106

## Review and merge order

Core support for provider public keys, split allocations, and checkout
and refund safety has merged in the following PRs.

- #99
- #101
- #115

This branch also includes the current heads of the following PRs. Review
their changes here if we merge the combined PR. Keep the original
threads open until the changes are confirmed on `main`.

- #103
- #105
- #114

A merge commit can preserve those PR heads and let GitHub mark them
merged indirectly. If this PR is squash-merged and any companions remain
open, verify their changes on `main` before closing them with a link
here.

moset15’s earlier draft [Stripe subscription checkout and customer
linking #138](#138)
overlaps with this PR in `storage-collections.ts`. When either PR lands,
bring the other up to date with `main` and preserve the draft’s customer
lookup index alongside this PR’s refund dispatch storage.

## Release

Changesets plans Flutterwave 0.1.0 with Core 0.6.0 when this PR is
included in the release. Flutterwave declares a Core peer range of
`>=0.6.0 <1.0.0`. The minimum release must contain its provider
interfaces and currency helper. If the release in [Core release PR
#120](#120) ships
before these changes land, update the Flutterwave peer floor to the next
Core release that actually includes them.

## What

`packages/flutterwave`: a `PaymentProvider` for Flutterwave v3. It
registers itself on `import "@dashcommerce/flutterwave"`.

| Area | Behaviour |
|---|---|
| Hosted checkout | Validate the hosted redirect URL, allow the sandbox
host with test credentials, and return the verified checkout reference
alongside the charge ID for [Verify hosted payments on return
#126](#126) |
| On-page | Flutterwave Inline over the store's checkout via
`./checkout-client`; `v3.js` loads only on Pay; orders still come only
from the webhook |
| Subscriptions | Payment Plans, card-only. One plan per checkout (the
plan id is the subscription key); `payment_plan` on hosted and Inline;
record verified renewals once after matching transaction, plan, amount,
and currency; late payments preserve cancellation; cancel/resume through
the plan |
| Amounts | Core minor units ↔ Flutterwave major units, converted once
at the boundary |
| Webhooks | Constant-time `verif-hash`, event deduplication, and
provider verification before settling. Preserve the customer email saved
at checkout when it is present |
| Refunds | Reserve the request before dispatch, reconcile retries by
the request tag and verified original charge, and keep acceptance
pending until Flutterwave reports disbursement or failure |
| Splits | Core allocations → `subaccounts` with `flat_subaccount` + the
exact amount, hosted and Inline |
| Vendor onboarding | List banks, verify the account name, create the
subaccount, store the masked result |
| Discounts | `capabilities.coupons: true`; the discount is applied to
the amount Flutterwave charges |
| Reconciliation | Parses `meta.split_settlement_info` + `app_fee` into
core's `splitSettlement`; the order records what each subaccount earned
|
| Connection check | Read-only `GET /v3/balances`, test/live mode |

Currencies: NGN, USD, GBP, EUR, KES, GHS, ZAR, UGX, TZS, RWF, XOF, XAF,
ZMW, MWK, EGP.

## API facts checked, not assumed

- Flutterwave subaccounts: default `split_type` is `percentage` or
`flat`; the transaction override supports `flat_subaccount`, `flat` and
`percentage`. DashCommerce uses `flat_subaccount` with the exact vendor
amount so the shares never drift; the default is only a fallback.
- `GET /v3/banks/{country}` → `{ code, name }`; `POST
/v3/accounts/resolve` → `account_name`; `POST /v3/subaccounts` requires
the bank, account, business name, country, mobile and `split_value` (and
email in practice).
- Paystack's docs define `type: percentage|flat` and `share` but not the
flat share unit; that remains an open question for its own PR.
- Payment Plans: `POST /v3/payment-plans` with `interval` (`monthly`,
`every 3 months`, …), `amount`, `currency` and `duration: 0`; pass
`payment_plan` on the first charge. `verify` returns `plan`, which is
how a charge is tied to the plan. `GET /v3/subscriptions` answered `400
"Service error"` on the test account, so the package uses the plan id
and cancels via `PUT /v3/payment-plans/{id}/cancel`.

## Live test-mode evidence (24 Nov 2026)

| Check | Result |
|---|---|
| Hosted link creation | 200, real link |
| Real KES 1,500 M-Pesa payment via Inline | Succeeded, transaction
`10633614`; `callback` → `finished` |
| Verify by id and `tx_ref` | `succeeded`, `150000` minor, KES |
| Two-vendor split (KES 1,500) | 900 to `RS_CD57…`, 450 to `RS_A075…`,
76.5 platform after the 73.5 fee; confirmed in
`meta.split_settlement_info` |
| Payout onboarding | 598 NG banks; `0690000033` resolved to `Bale
Gary`; created `RS_043B…`, then deleted the probe |
| Partial + settled-max refunds | Succeeded; verify still reports
`successful` (documented) |
| Split refund | Flutterwave returned `400` with `Refund request
successfully logged` and no id; treated as a failure and surfaced, not
claimed as success |
| Subscription plan + first charge | Plan `254811` (KES 100/month); real
test-card payment `10634465` through Inline; `verify` returned `plan:
254811` |
| Package-level plan creation | `initCheckout` created plan `254812` and
opened Inline with `payment_plan`; plan cancelled after the probe |

## Validation

- Frozen install, workspace typecheck, and workspace build passed
locally. All 789 workspace tests passed, including 398 Core and 137
Flutterwave tests.
- An isolated merge preview with #126 passed 14 focused tests, including
a verified Flutterwave checkout reference with a distinct numeric
capture ID.
- [GitHub checks for the review follow-up
commit](https://github.com/emdashCommerce/dashcommerce/actions/runs/47085699551).

The Flutterwave test-mode results above are historical. The refund-retry
and renewal edge cases use fixtures.

## Review fixes included

- The Flutterwave peer range covers Core 0.6.0 through the rest of the
0.x series, matching Paystack’s range pattern. The lockfile mirrors the
current workspace versions and peer declarations.
- The subscriptions table uses labels from the provider registry. Legacy
Stripe rows still show Stripe, and rows for removed providers show their
stored provider ID.
- Removed the duplicated provider doc-comment opener and kept a single
checkout guard for subscription carts with vendor-owned items.

This branch includes the changes requested on [Provider-managed payout
onboarding
#103](#103):
verification is optional when a provider cannot resolve names, an
active-but-unverified account is stored with `verified: false`
(Paystack's `is_verified: false`), the onboarding form starts on the
store's default-currency country, and the bank picker accepts
mobile-money channels such as M-PESA. Onboarding is also idempotent
here: re-adding the same bank account returns Flutterwave's existing
subaccount, matched by account number and bank rather than the error
text.

## Deliberately not included

- Country-specific subaccount `meta` (SWIFT/routing/branch) in the form.
The docs conflict between the create reference and the split guide, and
there are no test accounts for those countries; the README says to
create those accounts in the dashboard/API for now.
- API-driven split refunds: Flutterwave's split-refund response has no
refund id, so the package surfaces the message and points to the
dashboard.
- Subscription trials, pausing, in-place upgrades and multiple
subscription lines per checkout. All fail loudly; cancel and resume are
supported.
cavewebs added a commit that referenced this pull request Dec 3, 2026
#150)

## Bug

From Stripe API version 2025-03-31, an invoice no longer has a top-level
`subscription`: it names its subscription under
`parent.subscription_details.subscription`. `upsertInvoiceFromStripe`
starts with `if (!inv.subscription) return null`, so on current API
versions **every subscription invoice is ignored**:

- `invoice.paid` stores no invoice row, so the renewal email never goes
out.
- `invoice.payment_failed` (dunning) never marks the subscription past
due from the invoice.

Found while testing a shop end to end: after several paid Stripe
subscriptions, the shop had no subscription invoices at all.

There's a second problem on the same path. When an invoice was recorded,
the subscription period was taken from the invoice's own
`period_start`/`period_end`. Those aren't the subscription period: on
the first invoice they're both the creation time.

## Fix

- `invoiceSubscriptionId(inv)` reads `inv.subscription`, or
`inv.parent.subscription_details.subscription`.
- `invoiceSubscriptionPeriod(inv)` takes the period from the invoice's
subscription lines (`lines.data[].period`). It falls back to the
invoice's own dates when there are no line periods and they span
something.
- The `StripeInvoice` type gains the optional `parent` and `lines`
fields.

That's all of it: `upsertInvoiceFromStripe` uses the two helpers, and
`invoice.payment_failed` goes through it too. No change to `webhook.ts`
or `checkout.ts`.

## Tests

New `packages/core/test/stripe-invoice-parent.test.ts`, 4 tests:
- **Both shapes:** the subscription is found under `parent`, or at the
top level.
- **The period:** it comes from the subscription line, not the invoice's
own dates.
- **A current-shape renewal invoice** is recorded, and it moves the
subscription's period.
- **An older-shape invoice** is still recorded.

The recording test fails without the change. Core 364 pass; the 4 local
`routing-response-adapter` failures pass on CI. Typecheck and Biome
clean.

Also tested by hand on a running shop (EmDash 1.6, Stripe test mode):
paid subscription checkouts now record their invoices, with the period
running one interval from the payment.

## Review points

- **#147** reads `inv.payment_intent`, which current API versions don't
send either. #138 adds an Invoice Payments lookup that could serve it.
This PR doesn't touch `payment_intent`, and it merges cleanly with #147,
#138 and #107.
- Older API versions behave as before, apart from the period now coming
from the lines when they carry one.
moset15 and others added 2 commits December 4, 2026 21:56
EmDash refuses a where on a field the collection doesn't index.
customer.subscription.* webhooks find the local customer by
stripeCustomerId, which wasn't indexed, so every paid Stripe subscription
answered 500 and was never recorded. (refunds.refundRequestId had the
same gap; emdashCommerce#107 indexed it.)

An audit of every storage query, count and orderBy in core found no other
gaps. The route harness now refuses non-indexed where, orderBy and count
fields like EmDash does, so the refund tests and a new Stripe
subscription webhook test catch these.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Two bugs in the Stripe subscription checkout path:

1. The thank-you page failed after every Stripe subscription checkout.
   In subscription mode `checkout.session.completed` created no order
   and deleted the checkout draft, so `orders/by-draft` answered
   `{ status: "failed" }` and the page said "We couldn't confirm your
   payment" though the customer had paid.

2. An early `customer.subscription.created` left the customer blank for
   good. Stripe doesn't guarantee event order; if the subscription event
   lands before the session, no customer carries the Stripe customer id
   yet and the row stores `customerId: ""`. `upsertFromStripe` used
   `existing?.customerId ?? …`, and "" isn't nullish, so no later event
   filled it in.

A paid subscription-mode session now creates the first-period order
through `createOrderFromPaymentIntent`, like a payment-mode session:
stock, coupon usage, lock release, receipt and download grants all take
the one order path. The session has no PaymentIntent, so the order is
keyed on the Stripe subscription id (one checkout, one subscription,
one first-period order); retries find it by that id. Whichever of the
session and `customer.subscription.*` lands second links the order and
the subscription, and fills a blank subscription customer from the
order. `invoice.paid` and `payment_intent.succeeded` for the first
invoice carry no draft id and never create an order.

The first order records the PaymentIntent that paid the first invoice
(from /v1/invoice_payments, or the invoice's payment_intent on older API
versions) as its payment reference, so an admin refund works; Stripe
refuses a refund against the subscription id. A free trial creates an
order for 0: the items, a trial discount, no shipping or tax yet. Stripe
reports a trial that collected a card as "paid" with an amount of 0, so
nothing paid for a cart that costs something counts as a trial.

The session-to-cart address merge moves into `cartWithSessionDetails`,
shared by payment and subscription sessions, with no change for
payment mode. `upsertFromStripe` now treats a blank stored customer as
missing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@moset15
moset15 force-pushed the fix/stripe-subscription-confirm branch from a469db2 to 5183bee Compare December 5, 2026 22:53
@moset15
moset15 marked this pull request as ready for review December 5, 2026 22:53
@moset15

moset15 commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

#107 has landed, so this is rebased onto main and ready for review. It still carries #127's commit until that merges; then it's one commit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant