Skip to content

fix(core): harden checkout and refund safety - #115

Merged
cavewebs merged 6 commits into
emdashCommerce:mainfrom
alexasomba:feat/core-checkout-refund-hardening
Nov 30, 2026
Merged

cavewebs merged 6 commits into
emdashCommerce:mainfrom
alexasomba:feat/core-checkout-refund-hardening

Conversation

@alexasomba

@alexasomba alexasomba commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Core checkout and refund hardening from the Flutterwave parity review and AutomaticPallet integration.

1. Refuse stripe_tax with a non-Stripe provider

taxMode: "stripe_tax" defers tax calculation to Stripe: core returns zero tax and sends automaticTax: true. A provider that ignores automatic_tax would charge the pre-tax total. checkout/create-session now returns 409 stripe_tax_requires_stripe and asks the merchant to switch to flat/table or to Stripe.

2. Harden refund idempotency

The admin refund route generated a fresh refund:${orderId}:${randomId()} on every click. If the provider accepted the refund but the response was lost, a retry could refund twice.

  • admin/orders/refund accepts a refundRequestId; the UI generates one per attempt and reuses it if the request throws.
  • refundOrder returns the recorded refund for a repeated request id instead of calling the provider again.
  • The refund confirmation says “the payment provider” instead of “Stripe”, and a failed provider refund shows an error rather than “Refund issued”.

3. Bind payment events to checkout drafts

  • Require POST on checkout/create-session. Record the provider before creating the session and save the checkout reference before returning it to the storefront.
  • Check the draft's provider and reference before fulfilling an order or releasing a stock lock. Cross-check the checkout reference returned by live provider verification when available.
  • An early webhook can retry once the checkout reference is saved. Drafts written before provider and reference fields existed can still settle.

Tests

  • bun test packages/core passed all 329 tests, including non-POST requests, early deliveries, provider and reference mismatches, stock-lock release, retry deduplication, and legacy drafts.
  • Workspace typecheck, Core build, and Biome checks on the changed TypeScript files passed.
  • Changesets cover the tax guard, refund idempotency, and checkout draft binding.

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

The tax guard and the refund idempotency ledger look great.

One change before I merge it: please do not mint a new refundRequestId on every amount or reason keystroke. If the first response is dropped and the merchant then edits the reason, the next submit is a new id and can create a second refund. Keep the same id until the attempt succeeds or the provider has definitely failed, so a retry stays idempotent.

Once that is in, I'll merge this before #107.

@alexasomba

Copy link
Copy Markdown
Contributor Author

@cavewebs, could you take another look at #115 when you have a chance? Commit f347de1 keeps the same refund request ID and original details through retries, and adds a regression test for a lost full-refund response. All 11 GitHub checks passed.

The requested Flutterwave currency fix is also up on #107 in e586f1c, with coverage for UGX, RWF, XAF, and XOF. All 11 checks passed there too. I’ll rebase #107 after #115 lands and bring it back for review. The current #107 branch also includes #103, #105, and #114, so those Core changes can go through #107 as you suggested.

@alexasomba

Copy link
Copy Markdown
Contributor Author

@cavewebs, could you take a fresh look at the latest #115 commit (8ef87f8)? The refund retry fix keeps the original request ID and details after a lost response. The latest commit also checks that payment events match the checkout draft before settling an order or releasing its stock lock. All 11 GitHub checks passed.

@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, the refund id is now minted once per confirmed attempt and reused on retry, and the fields stay locked until that attempt succeeds or the provider has definitely failed.

The webhook binding to the checkout draft looks right too. I ran the core tests locally and they all passed.

This is still behind main. A local merge was clean, but I'd update the branch and let CI run on that before I merge it, then take #107.

@cavewebs
cavewebs merged commit 9d2bfe2 into emdashCommerce:main Nov 30, 2026
11 checks passed
alexasomba added a commit to alexasomba/dashcommerce that referenced this pull request Nov 30, 2026
Integrates checkout draft binding, refund idempotency, and tax guard from
main with Flutterwave split settlement UI and provider charge handling.

Co-authored-by: Cursor <cursoragent@cursor.com>
alexasomba added a commit to alexasomba/dashcommerce that referenced this pull request Nov 30, 2026
…rce#115 merge

Remove duplicate getPaymentStatus before order creation; fold checkout
reference checks into the first live verification. Uses ConfirmationFailure
for draft-bound charges (Paystack overlap dedupe) while keeping
RetryableWebhookError for subscription paths.

Co-authored-by: Cursor <cursoragent@cursor.com>
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.
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.

2 participants