Repository navigation
feat(flutterwave): Flutterwave payment provider package - #107
Conversation
…able Real test-mode run (24 Nov 2026): GET /v3/refunds answers 400 unauthorized on a key that can create refunds. Degrade the duplicate check to a logged warning for that case, log a failed disbursement, and add fixtures from the real verify and refund responses.
|
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 |
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.
|
@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.
|
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. |
|
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 |
|
Thanks for the review, @cavewebs. Commit When you have a chance, could you take another look and merge if everything looks good? |
cavewebs
left a comment
There was a problem hiding this comment.
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.
## 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).
…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.
#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.
#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.
## 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.
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>
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
mainbefore 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 withmainand 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: aPaymentProviderfor Flutterwave v3. It registers itself onimport "@dashcommerce/flutterwave"../checkout-client;v3.jsloads only on Pay; orders still come only from the webhookpayment_planon hosted and Inline; record verified renewals once after matching transaction, plan, amount, and currency; late payments preserve cancellation; cancel/resume through the planverif-hash, event deduplication, and provider verification before settling. Preserve the customer email saved at checkout when it is presentsubaccountswithflat_subaccount+ the exact amount, hosted and Inlinecapabilities.coupons: true; the discount is applied to the amount Flutterwave chargesmeta.split_settlement_info+app_feeinto core'ssplitSettlement; the order records what each subaccount earnedGET /v3/balances, test/live modeCurrencies: NGN, USD, GBP, EUR, KES, GHS, ZAR, UGX, TZS, RWF, XOF, XAF, ZMW, MWK, EGP.
API facts checked, not assumed
split_typeispercentageorflat; the transaction override supportsflat_subaccount,flatandpercentage. DashCommerce usesflat_subaccountwith 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/subaccountsrequires the bank, account, business name, country, mobile andsplit_value(and email in practice).type: percentage|flatandsharebut not the flat share unit; that remains an open question for its own PR.POST /v3/payment-planswithinterval(monthly,every 3 months, …),amount,currencyandduration: 0; passpayment_planon the first charge.verifyreturnsplan, which is how a charge is tied to the plan.GET /v3/subscriptionsanswered400 "Service error"on the test account, so the package uses the plan id and cancels viaPUT /v3/payment-plans/{id}/cancel.Live test-mode evidence (24 Nov 2026)
10633614;callback→finishedtx_refsucceeded,150000minor, KESRS_CD57…, 450 toRS_A075…, 76.5 platform after the 73.5 fee; confirmed inmeta.split_settlement_info0690000033resolved toBale Gary; createdRS_043B…, then deleted the probesuccessful(documented)400withRefund request successfully loggedand no id; treated as a failure and surfaced, not claimed as success254811(KES 100/month); real test-card payment10634465through Inline;verifyreturnedplan: 254811initCheckoutcreated plan254812and opened Inline withpayment_plan; plan cancelled after the probeValidation
The Flutterwave test-mode results above are historical. The refund-retry and renewal edge cases use fixtures.
Review fixes included
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'sis_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
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.