Skip to content

feat(flutterwave): Flutterwave payment provider package - #107

Merged
cavewebs merged 81 commits into
emdashCommerce:mainfrom
alexasomba:feat/flutterwave-provider
Dec 3, 2026
Merged

cavewebs merged 81 commits into
emdashCommerce:mainfrom
alexasomba:feat/flutterwave-provider

Conversation

@alexasomba

@alexasomba alexasomba commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

This PR brings the Flutterwave adapter and the Core changes it needs into one review.

Superseded package PRs

The changes from these five stacked PRs are included here.

Review and merge order

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

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.

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 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 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
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

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: 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.

@moset15

moset15 commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

One gap that shows up next to this PR's Resume change: on Stripe rows, "Cancel at period end" can't be undone from the admin, because Stripe's resume only clears pause_collection. Provider-managed cancellations can be reversed through Resume after this PR. Would you rather Stripe's Resume also send cancel_at_period_end=false when the row is cancelling, or a separate Keep action for all providers? Happy to send the follow-up either way once this lands.

Reserve a refund against its order before dispatch. Recover the same request from provider history or a saved provider response without another POST when the outcome is uncertain.

Require Flutterwave renewal verification to match the payment, plan, amount, and currency. Preserve cancellation while recording payments that arrive after the subscription ends.
Return the verified tx_ref alongside the charge ID for hosted return verification. Preserve the saved checkout email and accept Flutterwave's sandbox checkout host only with test credentials.
@alexasomba

alexasomba commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor Author

@moset15 Thanks for spotting the Stripe scheduled-cancellation gap. A separate Keep subscription action makes sense for rows with a period-end cancellation, while Resume can continue to clear paused collection. I'd welcome that follow-up after this PR lands. If a row has both settings, each action should change only its own setting.

This PR now also carries the verified Flutterwave checkout reference needed by Hosted payment verification on return #126, preserves the checkout email during settlement, and can reconcile a refund whose provider transaction ID differs when the verified original charge reference matches.

Target Core 0.6.0, as planned by Changesets when this PR ships with Core's provider interfaces. Require that release to contain the adapter's interfaces and currency conversion support.
@alexasomba

Copy link
Copy Markdown
Contributor Author

Hi @cavewebs, when you have a review window, could you take another look at the Flutterwave PR? The currency fix now has regression tests for UGX, RWF, XAF, and XOF. The branch includes the checkout and refund changes you asked us to pick up, and all 11 checks pass. The stock follow-up #141 is waiting on this one. Is there anything else you’d like changed before it can land?

Two other checkout PRs are ready for independent review whenever you have time.

Thanks for your time.

@cavewebs

cavewebs commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

Thanks for the follow-up commits and for pointing the peer at 0.6. CI is still green on this head. Before I approve, please widen the peer from ^0.6.0 to >=0.6.0 <1.0.0, the same shape as Paystack, so the next core minor does not major-bump the package. The doubled comment opener in payment-provider/types.ts, the hard-coded Flutterwave label on SubscriptionsPage, the duplicated vendor-items check in checkout.ts, and the stale bun.lock workspace versions are still there. I'll review again once those are in.

@alexasomba
alexasomba requested a review from cavewebs December 3, 2026 10:32
@alexasomba

Copy link
Copy Markdown
Contributor Author

Thanks for the review, @cavewebs. Commit 1e999ec widens the Core peer to >=0.6.0 <1.0.0 and addresses the other four items you flagged. All 11 checks passed on that commit.

When you have a chance, could you take another look and merge if everything looks good?

@cavewebs cavewebs left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the fixes. The peer is now >=0.6.0 <1.0.0, the comment typo, provider label, duplicate checkout check and bun.lock all look right, and CI is green on this head. I'll merge this with a merge commit.

@cavewebs
cavewebs merged commit ba7c7fc into emdashCommerce:main Dec 3, 2026
11 checks passed
cavewebs added a commit that referenced this pull request Dec 3, 2026
## Bug

The demo catalogue and the starter seed write

```json
"subscription_config": { "interval": "month", "interval_count": 1 }
```

and hand-written product JSON often uses snake_case too.
`products/normalize.ts` passes `subscription_config` through unchanged,
while checkout reads `intervalCount` and `trialDays`. So the count and
trial are dropped:

- a product set to bill every 3 months is billed **monthly** on Stripe:
the count is `undefined`, the form encoder leaves it out, and Stripe
defaults it to 1;
- a snake_case trial is ignored.

The demo product only works today because its count is 1, which happens
to be Stripe's default. Found while testing a shop end to end with the
demo catalogue.

## Fix

The normaliser accepts `interval_count`, `trial_days` and
`stripe_price_id` as well as the camelCase keys (camelCase wins if both
are present) and hands checkout camelCase. The demo catalogue and
starter seed now use camelCase.

## Tests

New `packages/core/test/subscription-config-keys.test.ts`, 4 tests:

- snake_case `interval_count` and `trial_days` are read;
- the same from a JSON string;
- camelCase is kept as it is;
- through the real `cart/items` route, a product with `interval_count:
3, trial_days: 14` lands in the cart with `intervalCount: 3, trialDays:
14`.

3 fail without the fix; the camelCase test passes both ways, as
intended. Full suite: core 364 pass (plus the 4 local
`routing-response-adapter` failures: the EmDash patch isn't applied in a
fresh worktree; they pass on CI), paystack 105, lite 144. Core typecheck
and Biome lint clean on the changed lines (`normalize.ts` and
`demo-catalog.ts` have older formatting drift elsewhere that I left
alone).

Also tested by hand on a running shop (EmDash 1.6, Stripe test mode): a
product saved with `"interval_count": 3` in snake_case. Stripe's
checkout page showed "every 3 months", and after paying with a test card
the Stripe subscription's price is monthly × 3, with the first period
running three months. The admin's Subscriptions page shows the same
period.

## Compatibility

camelCase settings behave exactly as before. Existing snake_case
products start billing on the interval they were set to, which is the
intent but is a change for any shop that has one: worth a line in the
release notes.

## Review points

- Why accept both rather than only fix the seed? The other commerce
fields on a product are snake_case (`manage_stock`,
`low_stock_threshold`, `subscription_config` itself), so snake_case
inside it is an easy mistake to make, and the failure is silent.
- #107's provider-neutral subscriptions also read
`config.intervalCount`, so this also stops a snake_case product reaching
them with no count.
- Changeset covers `@dashcommerce/core` and `@dashcommerce/starter`
(seed).
cavewebs added a commit that referenced this pull request Dec 3, 2026
…130)

## Bug

A subscription cart with any shipping method chosen, even free local
pickup, can't start Stripe hosted checkout. `checkout/create-session`
gets a 400 from Stripe ("`shipping_options` can only be used in payment
mode."), and the shopper sees "Payment couldn't start".

`checkout.ts` passes `shippingOptions` whatever the mode, and
`toCreateCheckoutSessionInput` in `stripe-provider.ts` maps them to
Stripe `shipping_options` in subscription mode too. Found while testing
a shop end to end with a physical monthly box.

## Fix

The fix is only in the Stripe mapping, so every caller is covered. For
`mode: "subscription"`:

- `shipping_options` is never sent.
- Paid shipping (amount > 0) becomes a line item named `Shipping ·
<method>`, with metadata `kind: "shipping"` plus the option's own
metadata. It **recurs on the product's interval**, because a delivered
subscription ships every period.
- Free shipping and pickup are left out.
- `shipping_address_collection` is kept; Stripe allows it in
subscription mode.
- Under Stripe Tax the shipping line is `tax_behavior: exclusive`, like
the product lines.

Only the first option is used. It is the method already chosen in the
cart, and a shopper can't choose between rates in a subscription session
anyway.

## Tests

New `packages/core/test/stripe-subscription-shipping.test.ts`, 6 tests:

- **Mapping:**
  - free pickup is left out and address collection is kept;
  - paid shipping becomes a line that recurs with the product;
  - Stripe Tax marks it exclusive;
  - payment mode still sends `shipping_options`.
- **Route:** `checkout/create-session` with the real Stripe provider,
against a stand-in that answers like Stripe (400 when `shipping_options`
reach a non-payment session).
  - Pickup gives 200 with no `shipping_options`.
- A paid courier rate gives 200, with `line_items[1]` "Shipping ·
Courier" recurring monthly.

5 of the 6 fail without the fix; the payment-mode test passes both ways,
as intended. Full suite: core 366 pass. The 4 `routing-response-adapter`
failures are local only: the EmDash patch isn't applied in a fresh
worktree, and they pass on CI. Core typecheck and Biome are clean on the
changed files.

Also tested by hand on a running shop (EmDash 1.6, Stripe test mode, a
KES 3,000 monthly box with KES 500 delivery):
- pickup starts a session with no shipping line;
- with delivery, Stripe's page lists the box and "Shipping · …", each
billed monthly.

## Compatibility

- Payment-mode sessions and other providers are unchanged.
- No change to `checkout.ts`, so this doesn't touch the file #107 is
changing.

## Review points

- **Why a line item?** Stripe has no shipping rate for subscription
sessions; a price on the subscription is the documented way to charge
it.
- **Why recurring?** A physical subscription is delivered every period,
so each renewal charges delivery. Pickup stays free.
- **Tax on renewals is a separate fix.** Flat/table tax is sent as a
one-time line today, so renewals are charged without it; coupons on
subscription checkouts are ignored too. Both live in `checkout.ts`, so
I've proposed that fix on #108 and will send it after #107.
- **Tax on shipping under Stripe Tax:** the shipping line is taxed with
the account's default product tax code, not Stripe's shipping tax code,
so tax on shipping can differ slightly from a payment-mode session. This
is noted in a code comment.
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.
cavewebs added a commit that referenced this pull request Dec 3, 2026
#137)

## Bug

The admin's Pause sets `pause_collection` at Stripe, but Stripe keeps
the subscription's status `active`. `upsertFromStripe` stores Stripe's
status as it is, so the row stays Active after the
`customer.subscription.updated` webhook, and Resume, which the admin
offers only for `paused` rows, never appears. Found while testing a shop
end to end: once paused, a subscription couldn't be resumed from the
admin.

## Fix

An `active` or `trialing` subscription with `pause_collection` set is
stored as `paused`. When collection resumes, Stripe clears
`pause_collection` and the row goes back to Stripe's status. Other
statuses (`past_due`, `unpaid`, `canceled`, …) are kept as Stripe sends
them, so a payment problem isn't hidden behind "paused".

## Tests

New `packages/core/test/stripe-subscription-paused.test.ts`, 4 tests,
each through the real webhook route with a signed
`customer.subscription.updated`:

- active with `pause_collection` is stored as `paused`;
- the same during a trial;
- after a pause, an event with `pause_collection: null` sets it back to
`active`;
- `past_due` with `pause_collection` stays `past_due`.

3 fail without the fix; the `past_due` test passes both ways, as
intended. Full suite: core 364 pass (plus the 4 local
`routing-response-adapter` failures noted in the other PRs), paystack
105, lite 144. Core typecheck and Biome lint clean.

## Compatibility

Only rows for paused Stripe subscriptions change. `paused` is already a
`SubscriptionStatus` and the admin already offers Resume for it.

## Review points

- Stripe's own `paused` status (a trial that ended with no payment
method) is unchanged and still comes through as `paused`.
- The admin list updates when the webhook arrives, not the instant Pause
is clicked. Making it instant means storing Stripe's reply in
`lifecycle.ts`, which #107 is changing, so it's left for later.

**Works on a real store once #127 merges:** until
`customers.stripeCustomerId` is indexed, `customer.subscription.*`
webhooks fail before they reach this code. The code doesn't depend on
#127 and merges on its own.
cavewebs added a commit that referenced this pull request Dec 3, 2026
## What and why

Checkout's country field always starts on `US` (`value="US"` in
`HostedCheckoutForm` and in the starter's embedded form), and core has
no setting for where the shop is based. A shopper on a shop outside the
US changes it on every order.

#103 (now carried in #107) works around the same gap in its payout form
by guessing the country from the default currency, and mentions a
shop-country setting as a follow-up. Once both land, that form can start
from this setting.

Part of the roadmap in #108.

## Behaviour

- **Before:** the ship-to country starts on `US`; a digital order's
country starts empty.
- **After, with the setting:** both start on the shop's country.
Customers can still change it.
- **Without the setting nothing changes.**

## Changes

- **New optional setting `storeCountry`** in `settings/schema.ts`:
checked against core's country list (`isValidCountryCode`), trimmed and
upper-cased. A country name or an unknown code is refused; `null` clears
it.
- **Settings → Store → Shop country:** a searchable country picker (the
kit's `Combobox` with `countryOptions()`) above the currency fields. The
card's description now mentions it.
- **`HostedCheckoutForm`:** a new optional `defaultCountry` prop. The
ship-to country starts on it (else `US`), and a digital order's country
is prefilled with it (else empty).
- **Starter:** reads the setting and passes it to the hosted form, and
to the embedded form's shipping and billing country.
- Changeset: minor for core (a new setting and prop), patch for the
starter.

No change to `routes/checkout.ts` or to currencies.

## Tests

`packages/core/test/store-country.test.ts`:

- through the real `admin/settings` route: saves `" ke "` as `KE` and
returns it; can be cleared with `null`; is `null` on a new shop; refuses
`"Kenya"`, `"XX"` and a number with a 400 naming the field;
- source checks on both forms' country inputs and the starter's wiring.

Five of the six fail without the change (the refusal test passes either
way, since an unknown key is refused too). Full suite: core 370 (364
before), paystack 105, lite 144, registry-setup 5, all passing. `tsc
--noEmit` passes for core, `astro check` for the starter, Biome is clean
on the new and changed lines; `bun.lock` is unchanged.

## Review points

- **Why not infer it from the currency?** Several countries share a
currency (USD, EUR), and a shop can sell in a currency that isn't its
own. An explicit setting is cheap and exact.
- **Payout form in #103:** not changed here, to keep this PR off #107's
files. A one-line follow-up after both merge.
- **No formatting churn:** Biome reports some older lines in
`SettingsPage.tsx` on `main`; they're left as they are.

**Next to #122:** both add props near the top of
`HostedCheckoutForm.astro`. If #122 merges first I'll rebase this; the
change itself doesn't overlap.
moset15 added a commit to FIKANOVA/dashcommerce that referenced this pull request Dec 5, 2026
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>
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.

3 participants