From f8a15c8fcd7359f51cf93fc033f5f580c2ad1bc0 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:28:00 +0100 Subject: [PATCH 01/50] feat(flutterwave): Flutterwave payment provider package --- .changeset/flutterwave-provider.md | 14 + bun.lock | 14 + packages/flutterwave/README.md | 90 ++ packages/flutterwave/package.json | 48 ++ packages/flutterwave/src/client.ts | 106 +++ packages/flutterwave/src/index.ts | 49 ++ packages/flutterwave/src/provider.ts | 762 +++++++++++++++++ packages/flutterwave/src/webhook-verify.ts | 58 ++ .../flutterwave/test/core-integration.test.ts | 708 ++++++++++++++++ .../test/flutterwave-provider.test.ts | 779 ++++++++++++++++++ .../flutterwave/test/webhook-verify.test.ts | 55 ++ packages/flutterwave/tsconfig.json | 11 + packages/flutterwave/tsdown.config.ts | 8 + 13 files changed, 2702 insertions(+) create mode 100644 .changeset/flutterwave-provider.md create mode 100644 packages/flutterwave/README.md create mode 100644 packages/flutterwave/package.json create mode 100644 packages/flutterwave/src/client.ts create mode 100644 packages/flutterwave/src/index.ts create mode 100644 packages/flutterwave/src/provider.ts create mode 100644 packages/flutterwave/src/webhook-verify.ts create mode 100644 packages/flutterwave/test/core-integration.test.ts create mode 100644 packages/flutterwave/test/flutterwave-provider.test.ts create mode 100644 packages/flutterwave/test/webhook-verify.test.ts create mode 100644 packages/flutterwave/tsconfig.json create mode 100644 packages/flutterwave/tsdown.config.ts diff --git a/.changeset/flutterwave-provider.md b/.changeset/flutterwave-provider.md new file mode 100644 index 0000000..2e58007 --- /dev/null +++ b/.changeset/flutterwave-provider.md @@ -0,0 +1,14 @@ +--- +"@dashcommerce/flutterwave": minor +--- + +New package: a Flutterwave payment provider for DashCommerce, built on core's PaymentProvider interface. + +- Card, M-Pesa and mobile money through Flutterwave's hosted checkout. Currencies: NGN, USD, GBP, EUR, KES, GHS, ZAR, UGX, TZS, RWF, XOF, XAF, ZMW, MWK and EGP. +- Amounts are converted at the boundary: core keeps minor units, Flutterwave's v3 API charges major units. +- Orders are created only from a signed `charge.completed`, confirmed against Flutterwave before the order is written. `verif-hash` is checked in constant time against the secret hash saved in Settings → Webhooks. +- Repeat and overlapping webhook deliveries run once: each charge and refund event carries an event id core can deduplicate on. +- Refunds by transaction id or `tx_ref`, guarded against duplicates on retry, with Flutterwave's refund webhook moving each refund to succeeded or failed. +- "Test Flutterwave connection" in Settings checks the saved key in test or live mode with a read-only balances call. + +Needs `@dashcommerce/core` 0.4.0 or later. Register it with `import "@dashcommerce/flutterwave"` in a server module, add `api.flutterwave.com` to `allowedHosts`, and point Flutterwave's webhook at `…/checkout/webhook?provider=flutterwave`; see the package README. diff --git a/bun.lock b/bun.lock index ab110bf..c7ed707 100644 --- a/bun.lock +++ b/bun.lock @@ -57,6 +57,18 @@ "typescript": "^5.9.0", }, }, + "packages/flutterwave": { + "name": "@dashcommerce/flutterwave", + "version": "0.0.0", + "devDependencies": { + "@dashcommerce/core": "workspace:*", + "tsdown": "^0.20.0", + "typescript": "^5.9.3", + }, + "peerDependencies": { + "@dashcommerce/core": "^0.4.0", + }, + }, "packages/lite": { "name": "@dashcommerce/lite", "version": "0.2.0", @@ -339,6 +351,8 @@ "@dashcommerce/create": ["@dashcommerce/create@workspace:packages/create"], + "@dashcommerce/flutterwave": ["@dashcommerce/flutterwave@workspace:packages/flutterwave"], + "@dashcommerce/lite": ["@dashcommerce/lite@workspace:packages/lite"], "@dashcommerce/registry-setup": ["@dashcommerce/registry-setup@workspace:packages/registry-setup"], diff --git a/packages/flutterwave/README.md b/packages/flutterwave/README.md new file mode 100644 index 0000000..73b6e51 --- /dev/null +++ b/packages/flutterwave/README.md @@ -0,0 +1,90 @@ +# @dashcommerce/flutterwave + +A Flutterwave `PaymentProvider` for DashCommerce. Customers pay on Flutterwave's hosted checkout by card, M-Pesa or mobile money. DashCommerce creates the order when Flutterwave's signed `charge.completed` webhook arrives and the transaction is confirmed with Flutterwave. + +> **Needs `@dashcommerce/core` 0.4.0 or later.** 0.4.0 is the first core release that can call `api.flutterwave.com`, save a second provider's keys, pass its webhook header to the provider and take refund updates. This package's first release, 0.1.0, goes out with it. + +## What it does + +| Area | Behaviour | +|---|---| +| Checkout | `POST /v3/payments`, then a redirect to the hosted link in `data.link`. The reference is `dc-`, so the draft can be recovered from `tx_ref` even without metadata | +| Amounts | Core works in integer minor units; Flutterwave's v3 API works in major units. The provider converts at the boundary: a KES 1,500.00 cart is sent as `1500`, and Flutterwave's `1500` comes back as `150000` | +| Webhook | Compares the `verif-hash` header with the secret hash saved in Settings → Webhooks, in constant time. See [Webhook verification](#webhook-verification) | +| Confirmation | Core calls `getPaymentStatus` before creating the order. A numeric reference is verified with `GET /v3/transactions/:id/verify`; anything else through `GET /v3/transactions/verify_by_reference?tx_ref=…`. The amount and currency come from Flutterwave's record, not the webhook body. `successful` counts as paid, `failed`/`cancelled` as failed, `pending` as pending. An unknown status is reported as pending, never as paid | +| Duplicates | Flutterwave webhooks carry no event id, so the provider builds one: `charge.completed::successful`, `charge.completed::failed`, and `refund::`. Core records it before the handler runs, so a repeat or overlapping delivery is skipped, and a failed refund is reversed once. If confirming with Flutterwave fails (Flutterwave down, or the payment not yet successful), core releases the record, so Flutterwave's retry still creates the order. Any other failure keeps the record, as it does for Stripe | +| Draft lookup | From `meta.orderDraftId` (object or JSON string), or from the `dc-` reference | +| Return URL | Core's success URL minus Stripe's `{CHECKOUT_SESSION_ID}` placeholder; Flutterwave appends `status`, `tx_ref` and `transaction_id` | +| Refunds | `POST /v3/transactions/:id/refund`, with `(refundRequestId=)` at the end of `comments`. Flutterwave takes no idempotency key for refunds, so the provider lists refunds and returns any non-failed refund already tagged with this `refundRequestId` instead of creating another. The tag is read only from the end of the comment, and brackets are stripped from the reason, so a reason cannot pose as another request. This guards retries, not two simultaneous calls with the same id: both could pass the check before either refund exists, so core must not run the same refund request concurrently | +| Refund statuses | `completed`, `completed-bank-transfer`, `completed-momo`, `completed-mpgs`, `completed-offline` and `completed-preauth` → succeeded; `pending`, `pending-momo`, `pending-bank-transfer`, `pending-mpgs` and `processing` → pending; `failed` → failed. Flutterwave's minimum refund is NGN 100 / KES 10; a smaller request is refused by Flutterwave with a 400 | +| Refund webhooks | Flutterwave posts the refund object itself, with no `event` field and capitalised `AmountRefunded`, `FlwRef` and `TransactionId`. The provider turns it into core's `refund.updated`, matched by the refund id | +| Currencies | NGN, USD, GBP, EUR, KES, GHS, ZAR, UGX, TZS, RWF, XOF, XAF, ZMW, MWK and EGP. Your Flutterwave account must be enabled for the currency you sell in | +| Payment options | With no channel hint, Flutterwave shows every method enabled on the account. A hint is mapped to Flutterwave's option names, and generic `mobile_money` is resolved by currency (`KES` → `mpesa`, `GHS` → `mobilemoneyghana`, …) | +| Customer details | Flutterwave's hosted page collects neither a shipping address nor a name for the store, so the provider leaves `collectsCustomerDetails` unset and DashCommerce's checkout asks for email and address before payment. The email is also required by `POST /v3/payments` | +| Not supported | Coupons, split payments and subscriptions. `capabilities` declares all three as `false` | +| On-page checkout | Not offered. Flutterwave Inline needs the account's public key (`FLWPUBK-…`), which core's provider settings do not store; hosted checkout is the equivalent flow today | + +## Webhook verification + +Flutterwave authenticates v3 webhooks with a shared secret, not an HMAC ([docs](https://developer.flutterwave.com/docs/webhooks)): + +1. Set a **secret hash** under Settings → Webhooks in the Flutterwave dashboard. Any random value works. +2. Flutterwave sends it back verbatim in the `verif-hash` header on every delivery. +3. The provider compares the two in constant time and rejects a missing or different value. + +There is no timestamp and no signature over the body, so a captured delivery can be replayed. That cannot create a second order: core deduplicates on the event id above, its unique index on the payment reference refuses a second order for the same transaction, and every order is confirmed against Flutterwave before it is written. A replay also cannot create an order for money that was never captured. + +Enable **webhook retries** in the Flutterwave dashboard. Flutterwave retries a failed delivery three times, 30 minutes apart. A delivery refused with a 400 (wrong secret hash) is also retried, so fixing the setting recovers it. + +Flutterwave sends `charge.completed` for failed attempts too, with `data.status` of `failed`. Those events release the checkout's stock lock; they never create an order. + +## Use + +1. **Install** both packages: + + ```sh + npm install @dashcommerce/core@^0.4.0 @dashcommerce/flutterwave + ``` + +2. **Register the provider at runtime.** Import the package in a module the server loads before any request, such as `src/middleware.ts`: + + ```ts + import "@dashcommerce/flutterwave"; // registers the "flutterwave" provider + ``` + + Importing it in `astro.config.mjs` is not enough: that file runs only at build time. Importing twice is harmless. If a different provider already holds the `flutterwave` id, the import throws instead of silently replacing it. + +3. **Allow Flutterwave's API host:** + + ```ts + emdash({ plugins: [dashcommerce({ allowedHosts: ["api.flutterwave.com"] })] }); + ``` + +4. **Choose Flutterwave and enter its keys** in Settings → Payment provider: + + | Field | Value | + |---|---| + | Secret key | Settings → API Keys. Test keys start `FLWSECK_TEST-`; live keys start `FLWSECK-` | + | Secret hash | The secret hash you set under Settings → Webhooks. Flutterwave sends it back in `verif-hash` | + + Save, then press **Test Flutterwave connection**. It makes one read-only call (`GET /v3/balances`) and says whether Flutterwave accepts the key, in test or live mode. + +5. **Set the webhook URL** in the Flutterwave dashboard, including `?provider=flutterwave`: + + ``` + https:///_emdash/api/plugins/dashcommerce/checkout/webhook?provider=flutterwave + ``` + + Without the query, core picks the provider from the `verif-hash` header. That works today, but the query keeps Flutterwave's webhooks going to Flutterwave even if another provider later uses the same header. Enable **refund** webhooks as well, so `refund.updated` reaches the store. + +6. **Use the same secret hash for every environment you point at the same site.** Flutterwave's dashboard has one webhook configuration; a test-mode delivery and a live-mode delivery both carry that value. + +## Develop + +```sh +bun test # unit tests, plus checkout → webhook → order → refund through core's real routes +bun run typecheck +bun run build +``` + +The integration tests use a Flutterwave stand-in that only answers verification for transactions it created, and that enforces the major/minor conversion in both directions. A provider that verifies by the wrong identifier or sends cents to Flutterwave fails there. diff --git a/packages/flutterwave/package.json b/packages/flutterwave/package.json new file mode 100644 index 0000000..61cda9a --- /dev/null +++ b/packages/flutterwave/package.json @@ -0,0 +1,48 @@ +{ + "name": "@dashcommerce/flutterwave", + "version": "0.0.0", + "description": "Flutterwave payment provider for @dashcommerce/core: card, M-Pesa and mobile money through Flutterwave's hosted checkout, verified webhooks, live status checks and refunds.", + "type": "module", + "main": "dist/index.mjs", + "module": "dist/index.mjs", + "types": "dist/index.d.mts", + "exports": { + ".": { + "import": "./dist/index.mjs", + "types": "./dist/index.d.mts" + } + }, + "files": ["dist", "README.md"], + "engines": { + "node": ">=20" + }, + "keywords": ["dashcommerce", "flutterwave", "payments", "mpesa", "mobile-money", "africa"], + "author": "DashCommerce contributors", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/emdashCommerce/dashcommerce.git", + "directory": "packages/flutterwave" + }, + "homepage": "https://dashcommerce.dev", + "bugs": { + "url": "https://github.com/emdashCommerce/dashcommerce/issues" + }, + "publishConfig": { + "access": "public" + }, + "scripts": { + "build": "tsdown", + "dev": "tsdown --watch", + "typecheck": "tsc --noEmit", + "test": "bun test" + }, + "peerDependencies": { + "@dashcommerce/core": "^0.4.0" + }, + "devDependencies": { + "@dashcommerce/core": "workspace:*", + "tsdown": "^0.20.0", + "typescript": "^5.9.3" + } +} diff --git a/packages/flutterwave/src/client.ts b/packages/flutterwave/src/client.ts new file mode 100644 index 0000000..20f7297 --- /dev/null +++ b/packages/flutterwave/src/client.ts @@ -0,0 +1,106 @@ +/** + * Flutterwave API client — sandbox-safe, mirrors the calling convention + * established by @dashcommerce/core: + * + * - Uses the runtime context's `http.fetch` (not global fetch) so + * `allowedHosts` is honoured when this runs inside an EmDash sandbox. + * - JSON request/response bodies (Flutterwave REST API v3). + * - Auto-injects `Authorization: Bearer {secretKey}`. + * - Throws `FlutterwaveApiError` on a non-2xx or a body whose + * `status` is not `"success"`. + */ + +import type { PaymentProviderRuntimeContext } from "@dashcommerce/core/payment-provider"; + +export const FLUTTERWAVE_API_BASE = "https://api.flutterwave.com/v3"; + +export class FlutterwaveApiError extends Error { + readonly status: number; + readonly body: Record; + constructor(status: number, body: Record, message: string) { + super(message); + this.name = "FlutterwaveApiError"; + this.status = status; + this.body = body; + } +} + +export interface FlutterwaveClientOptions { + secretKey: string; + /** Override for tests. */ + apiBase?: string; +} + +export interface FlutterwaveCallOptions { + method?: "GET" | "POST"; + path: string; // leading slash, e.g. /payments + body?: Record; + client: FlutterwaveClientOptions; +} + +export interface FlutterwavePageInfo { + total?: number; + current_page?: number; + total_pages?: number; + page_size?: number; +} + +export interface FlutterwaveResponse { + status: "success" | "error"; + message: string; + data: T; + meta?: { page_info?: FlutterwavePageInfo }; +} + +export async function call>( + ctx: PaymentProviderRuntimeContext, + opts: FlutterwaveCallOptions, +): Promise { + return (await callEnvelope(ctx, opts)).data; +} + +/** As `call`, but returns the whole response, including list `meta`. */ +export async function callEnvelope>( + ctx: PaymentProviderRuntimeContext, + opts: FlutterwaveCallOptions, +): Promise> { + const method = opts.method ?? "POST"; + const base = opts.client.apiBase ?? FLUTTERWAVE_API_BASE; + const headers: Record = { + Authorization: `Bearer ${opts.client.secretKey}`, + "Content-Type": "application/json", + }; + + // Only the runtime's fetch, which enforces the plugin's allowedHosts. + // Never fall back to global fetch: that would bypass the sandbox. + if (!ctx.http?.fetch) { + throw new Error("Flutterwave provider needs ctx.http.fetch (network:request capability)"); + } + const res = await ctx.http.fetch(`${base}${opts.path}`, { + method, + headers, + ...(opts.body ? { body: JSON.stringify(opts.body) } : {}), + }); + + const rawText = await res.text(); + let parsed: FlutterwaveResponse; + try { + parsed = JSON.parse(rawText) as FlutterwaveResponse; + } catch { + throw new FlutterwaveApiError( + res.status, + { raw: rawText }, + `Flutterwave returned unparseable response (${res.status})`, + ); + } + + if (!res.ok || parsed.status !== "success") { + const msg = + parsed.message || + (typeof parsed.data === "string" ? parsed.data : undefined) || + `Flutterwave API error (${res.status})`; + throw new FlutterwaveApiError(res.status, parsed as unknown as Record, msg); + } + + return parsed; +} diff --git a/packages/flutterwave/src/index.ts b/packages/flutterwave/src/index.ts new file mode 100644 index 0000000..e4bafc0 --- /dev/null +++ b/packages/flutterwave/src/index.ts @@ -0,0 +1,49 @@ +/** + * @dashcommerce/flutterwave + * + * Flutterwave PaymentProvider for DashCommerce: hosted checkout (card, + * M-Pesa and mobile money), `verif-hash` webhook verification, live status + * checks and refunds. + * + * Importing this module registers the provider with core's registry. + */ + +import { getPaymentProvider, registerPaymentProvider } from "@dashcommerce/core/payment-provider"; +import { flutterwavePaymentProvider } from "./provider"; + +export { + flutterwavePaymentProvider, + flutterwaveReferenceFor, + toMajorUnits, + toMinorUnits, +} from "./provider"; +export { + verifyFlutterwaveSecretHash, + type VerifyInput, + type VerifyResult, +} from "./webhook-verify"; +export { + call as callFlutterwave, + FlutterwaveApiError, + FLUTTERWAVE_API_BASE, + type FlutterwaveClientOptions, + type FlutterwaveCallOptions, + type FlutterwaveResponse, +} from "./client"; + +/** + * Register the Flutterwave provider. Safe to call more than once. If a + * different provider already holds the `flutterwave` id this throws, unless + * `{ override: true }` is passed, so a clash is never silent. + */ +export function registerFlutterwaveProvider(opts: { override?: boolean } = {}): void { + if ( + !opts.override && + getPaymentProvider(flutterwavePaymentProvider.id) === flutterwavePaymentProvider + ) { + return; + } + registerPaymentProvider(flutterwavePaymentProvider, opts); +} + +registerFlutterwaveProvider(); diff --git a/packages/flutterwave/src/provider.ts b/packages/flutterwave/src/provider.ts new file mode 100644 index 0000000..74094fb --- /dev/null +++ b/packages/flutterwave/src/provider.ts @@ -0,0 +1,762 @@ +/** + * FlutterwavePaymentProvider — Flutterwave implementing @dashcommerce/core's + * PaymentProvider interface. + * + * Amounts: core works in integer minor units; Flutterwave's v3 API works in + * major units (100 NGN is `100`, not `10000`). This adapter converts at the + * boundary and nowhere else. + * + * Checkout is Flutterwave's hosted page. Flutterwave Inline, the on-page + * option, needs the account's public key, which core's provider settings do + * not store; the hosted page is the equivalent flow today. + */ + +import type { + ConnectionCheckResult, + CreateRefundInput, + InitCheckoutInput, + InitCheckoutResult, + NormalizedPaymentEvent, + PaymentProvider, + PaymentProviderCredentials, + PaymentProviderRuntimeContext, + RefundResult, + VerifyWebhookInput, + VerifyWebhookResult, +} from "@dashcommerce/core/payment-provider"; +import { + FlutterwaveApiError, + type FlutterwaveCallOptions, + type FlutterwaveResponse, + call, + callEnvelope, +} from "./client"; +import { verifyFlutterwaveSecretHash } from "./webhook-verify"; + +const SUPPORTED_CURRENCIES = new Set([ + "NGN", + "USD", + "GBP", + "EUR", + "KES", + "GHS", + "ZAR", + "UGX", + "TZS", + "RWF", + "XOF", + "XAF", + "ZMW", + "MWK", + "EGP", +]); + +const REFERENCE_PREFIX = "dc-"; + +/** + * Flutterwave requires a unique `tx_ref` per transaction. Core's draft ids are + * hex, so this is normally `dc-`; anything else is replaced rather + * than sent and rejected. + */ +export function flutterwaveReferenceFor(orderDraftId: string): string { + return `${REFERENCE_PREFIX}${orderDraftId.replace(/[^A-Za-z0-9.=-]/g, "-")}`; +} + +/** Recover a core draft id from a reference this provider issued. */ +function draftIdFromReference(reference: string): string | undefined { + if (!reference.startsWith(REFERENCE_PREFIX)) return undefined; + const id = reference.slice(REFERENCE_PREFIX.length); + return /^[0-9a-f]{32}$/.test(id) ? id : undefined; +} + +/** + * Core builds the success URL for Stripe, with a `{CHECKOUT_SESSION_ID}` + * placeholder that Stripe fills in. Flutterwave appends `status`, `tx_ref` + * and `transaction_id`, so drop the placeholder. + */ +function flutterwaveCallbackUrl(successUrl: string): string { + const url = new URL(successUrl); + for (const [key, value] of [...url.searchParams]) { + if (value === "{CHECKOUT_SESSION_ID}") url.searchParams.delete(key); + } + return url.toString(); +} + +/** Flutterwave documents `meta` as an object, but some deliveries carry a string. */ +function metadataOf(raw: unknown): Record | undefined { + if (typeof raw === "string") { + try { + const parsed = JSON.parse(raw) as unknown; + return parsed && typeof parsed === "object" ? (parsed as Record) : undefined; + } catch { + return undefined; + } + } + return raw && typeof raw === "object" ? (raw as Record) : undefined; +} + +/** Core minor units → Flutterwave major units, e.g. 250000 → 2500. */ +export function toMajorUnits(amount: number): number { + if (!Number.isSafeInteger(amount) || amount < 0) { + throw new Error("Flutterwave amount must be a non-negative integer in minor units"); + } + return Number((amount / 100).toFixed(2)); +} + +/** Flutterwave major units → core minor units, e.g. 2500 → 250000. */ +export function toMinorUnits(amount: unknown): number | undefined { + const value = typeof amount === "string" ? Number(amount) : amount; + if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return undefined; + return Math.round(value * 100); +} + +function toFlutterwaveClient(credentials: PaymentProviderCredentials) { + return { secretKey: credentials.secretKey }; +} + +/** + * Flutterwave's mobile-money option differs by country, and `mpesa` is only + * valid for KES. A generic `mobile_money` hint is resolved with the cart's + * currency so the right option reaches the hosted page. + */ +const MOBILE_MONEY_BY_CURRENCY: Record = { + KES: "mpesa", + GHS: "mobilemoneyghana", + UGX: "mobilemoneyuganda", + RWF: "mobilemoneyrwanda", + TZS: "mobilemoneytanzania", + ZMW: "mobilemoneyzambia", + MWK: "mobilemoneymalawi", + XOF: "mobilemoneyxof", + XAF: "mobilemoneyxaf", +}; + +function mapChannel(channel: string, currency: string): string | undefined { + switch (channel.toLowerCase()) { + case "card": + return "card"; + case "mpesa": + case "m-pesa": + return "mpesa"; + case "mobile_money": + case "mobilemoney": + return MOBILE_MONEY_BY_CURRENCY[currency] ?? "mpesa"; + case "bank_transfer": + case "banktransfer": + return "banktransfer"; + case "ussd": + return "ussd"; + case "account": + return "account"; + case "opay": + return "opay"; + default: + return undefined; + } +} + +function mapPaymentOptions( + preferred: string[] | undefined, + currency: string, +): string[] | undefined { + if (!preferred || preferred.length === 0) return undefined; + const mapped = new Set(); + for (const channel of preferred) { + const option = mapChannel(channel, currency); + if (option) mapped.add(option); + } + return mapped.size > 0 ? Array.from(mapped) : undefined; +} + +function channelLabel(type: string | undefined): string | undefined { + if (!type) return undefined; + const value = type.toLowerCase(); + if (value === "card") return "Card"; + if (value === "mpesa") return "M-Pesa"; + if (value === "banktransfer" || value === "bank_transfer") return "Bank transfer"; + if (value === "ussd") return "USSD"; + if (value === "account") return "Bank account"; + if (value.startsWith("mobilemoney") || value === "mobile_money") return "Mobile money"; + return type; +} + +interface FlutterwaveCustomer { + id?: number; + name?: string | null; + phone_number?: string | null; + email?: string; +} + +interface FlutterwaveChargeData { + id: number | string; + tx_ref?: string; + flw_ref?: string; + amount?: number | string; + currency?: string; + charged_amount?: number | string; + status?: string; + payment_type?: string; + processor_response?: string; + customer?: FlutterwaveCustomer; + meta?: unknown; +} + +interface FlutterwaveWebhookEvent { + event: string; + data: FlutterwaveChargeData; + "event.type"?: string; +} + +interface FlutterwaveVerifyData extends FlutterwaveChargeData { + amount_settled?: number | string; +} + +interface FlutterwaveRefundData { + id: number; + amount_refunded?: number | string; + status?: string; + comment?: string | null; + comments?: string | null; + flw_ref?: string; + created_at?: string; + createdAt?: string; + transaction_id?: number; + TransactionId?: number; +} + +/** + * Transaction statuses from + * https://developer.flutterwave.com/docs/transaction-verification. + * `successful` is paid; `failed` and `cancelled` are final failures; + * `pending` is not final, the customer may still complete it. + */ +const TRANSACTION_STATUS: Record = { + successful: "succeeded", + success: "succeeded", + failed: "failed", + cancelled: "failed", + canceled: "failed", + pending: "pending", + processing: "pending", +}; + +/** + * Refund statuses from + * https://developer.flutterwave.com/docs/payment-operations/refunds. + * Every `completed*` value is a completed refund; `pending-*` and + * `processing` are still on their way. + */ +function refundStatus(raw: string | undefined): RefundResult["status"] { + const value = raw?.toLowerCase() ?? ""; + if (value.startsWith("completed")) return "succeeded"; + if (value === "failed" || value === "declined" || value === "cancelled") return "failed"; + return "pending"; +} + +function isFailedRefund(raw: string | undefined): boolean { + return refundStatus(raw) === "failed"; +} + +/** + * Flutterwave keeps no idempotency key for refunds. `comments` is the only + * field that keeps ours, so the request id goes there in a form that can be + * read back exactly. + */ +const REFUND_REQUEST_ID = /^[^\s()]+$/; +// Anchored at the end, so text in the reason cannot pose as the tag. +const COMMENT_REQUEST_ID = /\(refundRequestId=([^\s()]+)\)\s*$/; + +function refundCommentFor(refundRequestId: string, reason?: string): string { + const tag = `(refundRequestId=${refundRequestId})`; + const text = reason?.replace(/[()]/g, "").trim(); + return text ? `${text} ${tag}` : tag; +} + +const MAX_REFUND_PAGES = 20; + +async function listRefundPage( + ctx: PaymentProviderRuntimeContext, + client: FlutterwaveCallOptions["client"], + page: number, +): Promise<{ data: FlutterwaveRefundData[]; totalPages: number }> { + const result: FlutterwaveResponse = await callEnvelope(ctx, { + client, + method: "GET", + path: `/refunds?page=${page}`, + }); + if (!Array.isArray(result.data)) { + throw new Error("Flutterwave refund list returned no data array"); + } + const totalPages = result.meta?.page_info?.total_pages; + return { + data: result.data, + totalPages: typeof totalPages === "number" ? totalPages : 1, + }; +} + +function refundTransactionId(refund: FlutterwaveRefundData): number | undefined { + const id = refund.transaction_id ?? refund.TransactionId; + return typeof id === "number" ? id : undefined; +} + +/** + * Find a refund on this transaction already made for `refundRequestId`. + * Flutterwave's refund list is not filterable by transaction, so this walks + * recent pages and matches the id and the tag. A failed refund does not + * count, so it can be retried. The earliest match wins. + */ +async function findRefundForRequest( + ctx: PaymentProviderRuntimeContext, + client: FlutterwaveCallOptions["client"], + transactionId: number, + refundRequestId: string, +): Promise { + const matches: FlutterwaveRefundData[] = []; + for (let page = 1, totalPages = 1; page <= totalPages; page += 1) { + if (page > MAX_REFUND_PAGES) { + // Refunds are rare and the newest ones are listed first, so the + // retry that matters is almost always in range. Say so rather than + // blocking every refund on a store with a long refund history. + ctx.log.warn("Flutterwave refund list exceeded the lookup window", { + pagesScanned: MAX_REFUND_PAGES, + refundRequestId, + }); + break; + } + const result = await listRefundPage(ctx, client, page); + for (const refund of result.data) { + if (refundTransactionId(refund) !== transactionId) continue; + const note = refund.comment ?? refund.comments ?? ""; + if (COMMENT_REQUEST_ID.exec(note)?.[1] !== refundRequestId) continue; + if (!isFailedRefund(refund.status)) matches.push(refund); + } + totalPages = result.totalPages; + } + + matches.sort( + (a, b) => + (a.created_at ?? a.createdAt ?? "").localeCompare(b.created_at ?? b.createdAt ?? "") || + a.id - b.id, + ); + return matches[0]; +} + +/** Resolve a transaction id from either a numeric id or a `tx_ref`. */ +async function resolveTransactionId( + ctx: PaymentProviderRuntimeContext, + client: FlutterwaveCallOptions["client"], + reference: string, +): Promise { + if (/^\d+$/.test(reference)) { + const id = Number(reference); + if (Number.isSafeInteger(id)) return id; + } + const data = await call(ctx, { + client, + method: "GET", + path: `/transactions/verify_by_reference?tx_ref=${encodeURIComponent(reference)}`, + }); + const id = Number(data.id); + if (!Number.isSafeInteger(id) || id <= 0) { + throw new Error( + "Flutterwave verify returned no numeric transaction id; refusing to refund blind", + ); + } + return id; +} + +/** + * A refund webhook has no `event` field: Flutterwave posts the refund object + * itself, with capitalised `AmountRefunded`, `FlwRef` and `TransactionId`. + */ +function isRefundWebhook(payload: Record): boolean { + if (typeof payload.event === "string") return false; + const hasAmount = "AmountRefunded" in payload || "amount_refunded" in payload; + const id = payload.id; + return ( + (typeof id === "number" || typeof id === "string") && + id !== "" && + typeof payload.status === "string" && + hasAmount + ); +} + +function refundEvent(payload: Record): NormalizedPaymentEvent { + const rawId = payload.id; + const id = + typeof rawId === "number" || (typeof rawId === "string" && rawId !== "") + ? String(rawId) + : undefined; + const status = refundStatus(typeof payload.status === "string" ? payload.status : undefined); + if (!id) { + return { type: "unhandled", providerEventType: "refund", raw: payload }; + } + return { + type: "refund.updated", + providerId: "flutterwave", + // Flutterwave sends no event id, so the refund id plus its status + // stands in for one. Core records it before the handler runs, so a + // repeat of the same status is skipped instead of reversing a failed + // refund twice. Each status keeps its own id, so `pending` never + // blocks the later `completed`. + providerEventId: `refund:${id}:${status}`, + providerRefundId: id, + status, + raw: payload, + }; +} + +export const flutterwavePaymentProvider: PaymentProvider = { + id: "flutterwave", + label: "Flutterwave", + capabilities: { + coupons: false, + connect: false, + subscriptions: false, + }, + + brandColour: "#f5a623", + description: "Card, M-Pesa and mobile money across Africa, settled in your local currency.", + // Hosted page only; Flutterwave Inline needs a public key core does not store. + checkoutStyles: ["hosted"], + + webhookHeaders: ["verif-hash"], + + credentialFields: { + secretKey: { + label: "Flutterwave secret key", + prefixes: ["FLWSECK_TEST-", "FLWSECK-"], + help: "Settings → API Keys. Test keys start FLWSECK_TEST-; live keys start FLWSECK-.", + }, + webhookSecret: { + label: "Flutterwave secret hash", + prefixes: [], + help: "The secret hash you set under Settings → Webhooks. Flutterwave sends it back in the verif-hash header on every delivery.", + }, + }, + + supportsCurrency(currency: string): boolean { + if (!currency || typeof currency !== "string") return false; + return SUPPORTED_CURRENCIES.has(currency.trim().toUpperCase()); + }, + + async initCheckout( + ctx: PaymentProviderRuntimeContext, + input: InitCheckoutInput, + credentials: PaymentProviderCredentials, + ): Promise { + const email = input.customer.email?.trim(); + if (!email) { + throw new Error("Flutterwave requires customer email to initialize checkout"); + } + if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { + throw new Error("Flutterwave requires a valid customer email to initialize checkout"); + } + + const currency = input.currency.trim().toUpperCase(); + if (!SUPPORTED_CURRENCIES.has(currency)) { + throw new Error(`Flutterwave does not support currency ${input.currency}`); + } + if (input.mode === "subscription") { + throw new Error("Flutterwave provider does not support subscription checkout"); + } + + const client = toFlutterwaveClient(credentials); + const checkoutRef = flutterwaveReferenceFor(input.orderDraftId); + const address = input.shippingAddress ?? input.billingAddress; + const addressName = [address?.firstName, address?.lastName].filter(Boolean).join(" "); + const name = input.customer.name ?? (addressName || undefined); + const phone = input.customer.phone ?? address?.phone; + const paymentOptions = mapPaymentOptions(input.preferredChannels, currency); + + const data = await call<{ link?: string }>(ctx, { + client, + path: "/payments", + body: { + tx_ref: checkoutRef, + amount: toMajorUnits(input.amount), + currency, + redirect_url: flutterwaveCallbackUrl(input.successUrl), + customer: { + email, + ...(name ? { name } : {}), + ...(phone ? { phonenumber: phone } : {}), + }, + meta: { + ...input.metadata, + orderDraftId: input.orderDraftId, + }, + ...(paymentOptions ? { payment_options: paymentOptions.join(",") } : {}), + }, + }); + + if (!data?.link) { + throw new Error("Flutterwave did not return a hosted checkout link"); + } + return { + kind: "redirect", + redirectUrl: data.link, + checkoutReference: checkoutRef, + }; + }, + + async verifyWebhook(input: VerifyWebhookInput): Promise { + return verifyFlutterwaveSecretHash({ + signatureHeader: input.signatureHeader, + secret: input.secret, + }); + }, + + parseWebhookEvent(rawBody: string): NormalizedPaymentEvent { + let payload: unknown; + try { + payload = JSON.parse(rawBody); + } catch { + return { + type: "unhandled", + providerEventType: "unparseable", + raw: rawBody, + }; + } + + if (!payload || typeof payload !== "object") { + return { + type: "unhandled", + providerEventType: "malformed", + raw: payload, + }; + } + + const record = payload as Record; + if (isRefundWebhook(record)) { + return refundEvent(record); + } + + const event = payload as FlutterwaveWebhookEvent; + if (typeof event.event !== "string") { + return { + type: "unhandled", + providerEventType: "malformed", + raw: payload, + }; + } + + // The documented refund webhook is a bare refund object (handled + // above), but accept an event wrapper if Flutterwave adds one. + if (event.event.startsWith("refund.")) { + return refundEvent((event.data ?? {}) as unknown as Record); + } + + // Flutterwave sends `charge.completed` for both outcomes; `data.status` + // decides which. There is no separate refund event name. + if (event.event !== "charge.completed") { + return { + type: "unhandled", + providerEventType: event.event, + raw: payload, + }; + } + + const d = event.data; + const status = d?.status?.toLowerCase(); + const transactionId = d?.id === undefined ? undefined : String(d.id); + const metaDraftId = metadataOf(d?.meta)?.orderDraftId; + const orderDraftId = + typeof metaDraftId === "string" && metaDraftId + ? metaDraftId + : draftIdFromReference(d?.tx_ref ?? ""); + + if (!transactionId || !orderDraftId || !d.tx_ref) { + return { + type: "unhandled", + providerEventType: event.event, + raw: payload, + }; + } + + if (status === "failed" || status === "cancelled" || status === "canceled") { + return { + type: "charge.failed", + orderDraftId, + providerId: "flutterwave", + providerEventId: `charge.completed:${transactionId}:failed`, + checkoutReference: d.tx_ref, + paymentReference: transactionId, + ...(d.processor_response ? { reason: d.processor_response } : {}), + raw: payload, + }; + } + + if (status !== "successful" && status !== "success") { + return { + type: "unhandled", + providerEventType: event.event, + raw: payload, + }; + } + + const amount = toMinorUnits(d.amount); + const currency = d.currency?.toUpperCase(); + if (amount === undefined || !currency) { + return { + type: "unhandled", + providerEventType: event.event, + raw: payload, + }; + } + + const channel = channelLabel(d.payment_type); + return { + type: "charge.succeeded", + orderDraftId, + providerId: "flutterwave", + // The numeric transaction id, not the reference: refunds are made + // against /transactions/:id/refund. + paymentReference: transactionId, + checkoutReference: d.tx_ref, + // Flutterwave webhooks carry no event id (`data.id` is the + // transaction), so the id plus status stands in for one. Core + // records it before the handler runs, so two overlapping deliveries + // never both run it. When confirming with Flutterwave fails, core + // releases the record, so Flutterwave's retry still creates the order. + providerEventId: `charge.completed:${transactionId}:successful`, + amount, + currency, + customer: { + email: d.customer?.email ?? "", + ...(d.customer?.name ? { name: d.customer.name } : {}), + ...(d.customer?.phone_number ? { phone: d.customer.phone_number } : {}), + }, + ...(channel ? { channel } : {}), + raw: payload, + }; + }, + + async checkConnection( + ctx: PaymentProviderRuntimeContext, + credentials: PaymentProviderCredentials, + ): Promise { + const mode: ConnectionCheckResult["mode"] = /^FLWSECK_TEST-/i.test(credentials.secretKey) + ? "test" + : /^FLWSECK-/i.test(credentials.secretKey) + ? "live" + : undefined; + const modeResult = mode ? { mode } : {}; + try { + await call(ctx, { + client: toFlutterwaveClient(credentials), + method: "GET", + path: "/balances", + }); + } catch (err) { + if (!(err instanceof FlutterwaveApiError)) throw err; + if (err.status === 401 || err.status === 403) { + return { ok: false, ...modeResult, message: `Flutterwave refused the key: ${err.message}` }; + } + return { + ok: false, + ...modeResult, + message: `Flutterwave answered ${err.status}: ${err.message}`, + }; + } + return { + ok: true, + ...modeResult, + message: `Connected${mode ? ` in ${mode} mode` : ""}. The key can read account balances.`, + }; + }, + + async getPaymentStatus( + ctx: PaymentProviderRuntimeContext, + paymentOrCheckoutReference: string, + credentials: PaymentProviderCredentials, + ): Promise<{ + status: "pending" | "succeeded" | "failed"; + paymentReference?: string; + amount?: number; + currency?: string; + reason?: string; + }> { + const client = toFlutterwaveClient(credentials); + const reference = paymentOrCheckoutReference?.trim(); + if (!reference) { + return { + status: "failed", + reason: "No reference provided for payment status lookup", + }; + } + + const path = /^\d+$/.test(reference) + ? `/transactions/${encodeURIComponent(reference)}/verify` + : `/transactions/verify_by_reference?tx_ref=${encodeURIComponent(reference)}`; + const data = await call(ctx, { client, method: "GET", path }); + + const rawStatus = data.status?.toLowerCase() ?? ""; + const status = TRANSACTION_STATUS[rawStatus]; + const amount = toMinorUnits(data.amount); + const id = data.id === undefined ? undefined : String(data.id); + return { + status: status ?? "pending", + ...(id ? { paymentReference: id } : {}), + ...(amount !== undefined ? { amount } : {}), + ...(data.currency ? { currency: data.currency.toUpperCase() } : {}), + reason: status + ? data.processor_response + : `Unrecognised Flutterwave status: ${data.status ?? "(missing)"}`, + }; + }, + + async refund( + ctx: PaymentProviderRuntimeContext, + input: CreateRefundInput, + credentials: PaymentProviderCredentials, + ): Promise { + if (!input.refundRequestId || !input.refundRequestId.trim()) { + throw new Error( + "Flutterwave refund requires a non-empty refundRequestId for operation idempotency", + ); + } + + if (!REFUND_REQUEST_ID.test(input.refundRequestId)) { + throw new Error( + "Flutterwave refund needs a refundRequestId without spaces or brackets, so the refund comment can carry it", + ); + } + + const client = toFlutterwaveClient(credentials); + if (!input.paymentReference) { + throw new Error("Flutterwave refund requires paymentReference"); + } + + const transactionId = await resolveTransactionId(ctx, client, input.paymentReference); + + // Flutterwave accepts an identical second refund as a new one, so a + // retry with the same refundRequestId must find the first refund + // rather than create another. + const existing = await findRefundForRequest(ctx, client, transactionId, input.refundRequestId); + const data = + existing ?? + (await call(ctx, { + client, + path: `/transactions/${transactionId}/refund`, + body: { + ...(input.amount !== undefined ? { amount: toMajorUnits(input.amount) } : {}), + comments: refundCommentFor(input.refundRequestId, input.reason), + }, + })); + + const amount = toMinorUnits(data.amount_refunded) ?? input.amount ?? 0; + return { + providerRefundId: String(data.id), + refundRequestId: input.refundRequestId, + status: refundStatus(data.status), + amount, + currency: input.currency.toUpperCase(), + }; + }, + + formatAmount(amount: number, currency: string): string { + const major = (amount / 100).toFixed(2); + return `${currency.toUpperCase()} ${major}`; + }, +}; diff --git a/packages/flutterwave/src/webhook-verify.ts b/packages/flutterwave/src/webhook-verify.ts new file mode 100644 index 0000000..fd1cc49 --- /dev/null +++ b/packages/flutterwave/src/webhook-verify.ts @@ -0,0 +1,58 @@ +/** + * Flutterwave webhook verification. Web Crypto is not needed: Flutterwave's + * v3 webhooks are authenticated with a shared secret, not an HMAC. + * + * From https://developer.flutterwave.com/docs/webhooks: when a merchant sets + * a secret hash under Settings → Webhooks, Flutterwave sends it back verbatim + * in the `verif-hash` header. The endpoint compares the two in constant time. + * A missing header, a missing secret or a different value is a rejection. + * + * There is no timestamp and no signature over the body, so a captured + * delivery can be replayed. Core's event-id dedupe and the live + * `getPaymentStatus` check are what stop a replay from creating a second + * order or an order Flutterwave's own records do not confirm. + */ + +function constantTimeEqualStrings(a: string, b: string): boolean { + const encoder = new TextEncoder(); + const left = encoder.encode(a); + const right = encoder.encode(b); + // Length is not secret: a different-length hash can never match. + if (left.length !== right.length) return false; + let diff = 0; + for (let i = 0; i < left.length; i += 1) { + diff |= (left[i] ?? 0) ^ (right[i] ?? 0); + } + return diff === 0; +} + +export interface VerifyInput { + /** The `verif-hash` header, exactly as received. */ + signatureHeader: string; + /** The secret hash saved in Settings → Webhooks. */ + secret: string; +} + +export interface VerifyResult { + ok: boolean; + reason?: string; +} + +export function verifyFlutterwaveSecretHash(input: VerifyInput): VerifyResult { + const header = input.signatureHeader?.trim() ?? ""; + if (!header) { + return { ok: false, reason: "Missing verif-hash header" }; + } + const secret = input.secret?.trim() ?? ""; + if (!secret) { + return { ok: false, reason: "Missing Flutterwave secret hash for verification" }; + } + if (!constantTimeEqualStrings(header, secret)) { + return { + ok: false, + reason: + "verif-hash does not match the secret hash saved for Flutterwave; copy it from Settings → Webhooks", + }; + } + return { ok: true }; +} diff --git a/packages/flutterwave/test/core-integration.test.ts b/packages/flutterwave/test/core-integration.test.ts new file mode 100644 index 0000000..2ea3ec5 --- /dev/null +++ b/packages/flutterwave/test/core-integration.test.ts @@ -0,0 +1,708 @@ +/** + * Runs @dashcommerce/flutterwave through @dashcommerce/core's own route + * handlers (create-session → webhook → order → refund). + * + * The HTTP stub behaves like Flutterwave where it matters: the hosted link + * is issued for the `tx_ref` it was given, verification answers only for a + * transaction it issued, and amounts cross the boundary in major units while + * core keeps minor units. + */ + +import { describe, expect, it } from "bun:test"; +import { type CartState, type Order, dashcommerce } from "@dashcommerce/core"; +import { + getPaymentProvider, + registerPaymentProvider, + resolveProvider, +} from "@dashcommerce/core/payment-provider"; +import sandbox from "@dashcommerce/core/sandbox"; +import { registerFlutterwaveProvider } from "../src/index"; +import { flutterwavePaymentProvider } from "../src/provider"; + +const SECRET_KEY = "FLWSECK_TEST-1234567890abcdef-X"; +const SECRET_HASH = "flw-test-secret-hash"; + +function json(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { "Content-Type": "application/json" }, + }); +} + +interface FakeFlutterwaveOptions { + /** Minor units Flutterwave records as charged. Defaults to what checkout was asked for. */ + chargedAmountMinor?: number; + /** Status verify reports. Defaults to "successful". */ + verifyStatus?: string; + /** Number of verify calls that fail with a 503 before Flutterwave recovers. */ + verifyOutages?: number; + /** Milliseconds verify takes to answer, so two deliveries can overlap. */ + verifyDelayMs?: number; +} + +interface FakeTransaction { + id: number; + amountMinor: number; + currency: string; + status: string; +} + +/** + * A Flutterwave stand-in that only knows the transactions it created, + * requires the secret key on every call, and records amounts in both + * directions. + */ +function fakeFlutterwave(options: FakeFlutterwaveOptions = {}) { + const transactions = new Map(); + const refunds: Array> = []; + let nextId = 908790; + let lastInit: Record | null = null; + let outagesLeft = options.verifyOutages ?? 0; + let verifyCalls = 0; + + function verifyResponse(txRef: string, tx: FakeTransaction): Response { + return json({ + status: "success", + message: "Transaction fetched successfully", + data: { + id: tx.id, + tx_ref: txRef, + flw_ref: `FLW-MOCK-${tx.id}`, + amount: tx.amountMinor / 100, + currency: tx.currency, + charged_amount: tx.amountMinor / 100, + status: options.verifyStatus ?? tx.status, + processor_response: "Approved", + payment_type: "mpesa", + customer: { + id: 215604089, + name: "Aidi Onyango", + phone_number: "+254700000000", + email: "supporter@example.com", + }, + }, + }); + } + + async function fetch(url: string, init?: RequestInit): Promise { + const headers = new Headers(init?.headers); + if (headers.get("Authorization") !== `Bearer ${SECRET_KEY}`) { + return json({ status: "error", message: "Authorization required", data: null }, 401); + } + const { pathname, searchParams } = new URL(url); + const method = init?.method ?? "GET"; + + if (pathname === "/v3/payments" && method === "POST") { + const body = JSON.parse(String(init?.body)) as Record; + lastInit = body; + const txRef = String(body.tx_ref); + if (!/^[A-Za-z0-9.=-]+$/.test(txRef)) { + return json({ status: "error", message: "Invalid transaction reference", data: null }, 400); + } + if (typeof body.amount !== "number" || body.amount <= 0) { + return json({ status: "error", message: "Invalid amount", data: null }, 400); + } + transactions.set(txRef, { + id: nextId++, + amountMinor: options.chargedAmountMinor ?? Math.round(body.amount * 100), + currency: String(body.currency), + status: "successful", + }); + return json({ + status: "success", + message: "Hosted Link", + data: { link: "https://checkout.flutterwave.com/v3/hosted/pay/test-link" }, + }); + } + + if (pathname === "/v3/balances") { + return json({ status: "success", message: "Balances fetched", data: { KES: 1000 } }); + } + + if (pathname === "/v3/transactions/verify_by_reference") { + verifyCalls++; + if (options.verifyDelayMs) + await new Promise((resolve) => setTimeout(resolve, options.verifyDelayMs)); + if (outagesLeft > 0) { + outagesLeft--; + return json({ status: "error", message: "Service unavailable", data: null }, 503); + } + const txRef = searchParams.get("tx_ref") ?? ""; + const tx = transactions.get(txRef); + if (!tx) { + return json( + { status: "error", message: "No transaction was found for this id", data: null }, + 400, + ); + } + return verifyResponse(txRef, tx); + } + + const verifyById = /^\/v3\/transactions\/(\d+)\/verify$/.exec(pathname); + if (verifyById) { + verifyCalls++; + if (options.verifyDelayMs) + await new Promise((resolve) => setTimeout(resolve, options.verifyDelayMs)); + if (outagesLeft > 0) { + outagesLeft--; + return json({ status: "error", message: "Service unavailable", data: null }, 503); + } + const id = Number(verifyById[1]); + const entry = [...transactions.entries()].find(([, tx]) => tx.id === id); + if (!entry) { + return json( + { status: "error", message: "No transaction was found for this id", data: null }, + 400, + ); + } + return verifyResponse(entry[0], entry[1]); + } + + if (pathname === "/v3/refunds" && method === "GET") { + return json({ + status: "success", + message: "Refunds fetched", + data: refunds, + meta: { + page_info: { total: refunds.length, current_page: 1, total_pages: 1, page_size: 20 }, + }, + }); + } + + const refund = /^\/v3\/transactions\/(\d+)\/refund$/.exec(pathname); + if (refund && method === "POST") { + const body = JSON.parse(String(init?.body)) as Record; + const transactionId = Number(refund[1]); + const tx = [...transactions.values()].find((entry) => entry.id === transactionId); + if (!tx) return json({ status: "error", message: "Transaction not found", data: null }, 404); + const row = { + id: 8612 + refunds.length, + account_id: 73362, + transaction_id: transactionId, + amount_refunded: typeof body.amount === "number" ? body.amount : tx.amountMinor / 100, + status: "completed", + comment: body.comments ?? null, + flw_ref: `URF_${transactionId}`, + created_at: new Date(Date.UTC(2026, 10, 19, 2, refunds.length)).toISOString(), + }; + refunds.push(row); + return json({ status: "success", message: "Transaction refund initiated", data: row }); + } + + return json({ status: "error", message: "Not found", data: null }, 404); + } + + return { + fetch, + transactions, + refunds, + getLastInit: () => lastInit, + getVerifyCalls: () => verifyCalls, + }; +} + +// Core's real storage config, so the stub enforces the same unique indexes +// the database does (dedup relies on them). +const CORE_STORAGE = dashcommerce().storage as Record; + +function makeContext( + initialKv: Record, + fetchImpl: typeof fetch | ((url: string, init?: RequestInit) => Promise), +) { + const kvStore = new Map(Object.entries(initialKv)); + const collections = new Map>(); + const getCol = (name: string) => { + let col = collections.get(name); + if (!col) { + col = new Map(); + collections.set(name, col); + } + return col; + }; + + const storage = new Proxy( + {}, + { + get(_target, prop: string) { + const col = getCol(prop); + return { + async get(id: string) { + return col.get(id) ?? null; + }, + async put(id: string, data: unknown) { + const row = data as Record; + for (const field of CORE_STORAGE[prop]?.uniqueIndexes ?? []) { + if (row[field] === undefined || row[field] === null) continue; + for (const [otherId, other] of col) { + if (otherId !== id && (other as Record)[field] === row[field]) { + throw new Error(`UNIQUE constraint failed: ${prop}.${field}`); + } + } + } + col.set(id, data); + }, + async putMany(items: Array<{ id: string; data: unknown }>) { + for (const item of items) col.set(item.id, item.data); + }, + async delete(id: string) { + col.delete(id); + }, + async query(opts?: { where?: Record; limit?: number }) { + const all = Array.from(col.entries()).map(([id, data]) => ({ id, data })); + const where = opts?.where; + if (!where) return { items: all, hasMore: false }; + const items = all.filter((item) => { + const d = item.data as Record; + return Object.entries(where).every(([k, v]) => d[k] === v); + }); + return { items, hasMore: false }; + }, + async count() { + return col.size; + }, + }; + }, + }, + ); + + const products = new Map([ + [ + "prod_ticket", + { + id: "prod_ticket", + status: "published", + data: { + title: "Matchday ticket", + type: "simple", + prices: { KES: { amount: 150000 } }, + virtual: true, + manage_stock: false, + }, + }, + ], + ]); + + const ctx = { + kv: { + async get(key: string): Promise { + return (kvStore.get(key) as T) ?? null; + }, + async set(key: string, value: unknown) { + kvStore.set(key, value); + }, + async delete(key: string) { + kvStore.delete(key); + }, + }, + storage, + content: { + async get(collection: string, id: string) { + return collection === "products" ? (products.get(id) ?? null) : null; + }, + }, + http: { fetch: fetchImpl }, + site: { url: "https://test.dashcommerce.dev" }, + log: { debug() {}, info() {}, warn() {}, error() {} }, + } as unknown as import("emdash").PluginContext; + + return { ctx, getCol }; +} + +function ticketCart(sessionId: string): CartState { + const kes = (amount: number) => ({ amount, currency: "KES" }); + const address = { line1: "Ngong Road", city: "Nairobi", country: "KE" }; + return { + sessionId, + currency: "KES", + customerEmail: "supporter@example.com", + billingAddress: address, + shippingAddress: address, + items: [ + { + lineId: "line_1", + productId: "prod_ticket", + quantity: 1, + title: "Matchday ticket", + isDigital: true, + unitPrice: kes(150000), + lineSubtotal: kes(150000), + }, + ], + coupons: [], + taxLines: [], + subtotal: kes(150000), + discountTotal: kes(0), + shippingTotal: kes(0), + taxTotal: kes(0), + total: kes(150000), + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + } as unknown as CartState; +} + +const flutterwaveSettings = { + "settings:paymentProvider": "flutterwave", + "settings:flutterwaveSecretKey": SECRET_KEY, + "settings:flutterwaveWebhookSecret": SECRET_HASH, +}; + +async function startCheckout(ctx: import("emdash").PluginContext, sessionId: string) { + await ctx.kv.set(`cart:${sessionId}`, ticketCart(sessionId)); + const request = new Request("http://test/checkout/create-session", { + method: "POST", + headers: { "Content-Type": "application/json", Cookie: `dashcommerce_sid=${sessionId}` }, + body: JSON.stringify({ customerEmail: "supporter@example.com" }), + }); + const routeCtx = { + ...ctx, + request, + input: { customerEmail: "supporter@example.com" }, + } as unknown as import("emdash").RouteContext; + return (await sandbox.routes["checkout/create-session"].handler(routeCtx, ctx)) as Response; +} + +async function deliverWebhook( + ctx: import("emdash").PluginContext, + payload: string, + hash: string | Record, + url = "http://test/checkout/webhook", +) { + const request = new Request(url, { + method: "POST", + headers: typeof hash === "string" ? { "verif-hash": hash } : hash, + body: payload, + }); + const routeCtx = { ...ctx, request } as unknown as import("emdash").RouteContext; + try { + return (await sandbox.routes["checkout/webhook"].handler(routeCtx, ctx)) as Response; + } catch (err) { + // EmDash turns a thrown route error into a 500. + return json({ error: err instanceof Error ? err.message : String(err) }, 500); + } +} + +function chargeCompleted( + txRef: string, + orderDraftId: string, + id: number, + amountMajor = 1500, + status = "successful", +) { + return JSON.stringify({ + event: "charge.completed", + "event.type": "CARD_TRANSACTION", + data: { + id, + tx_ref: txRef, + flw_ref: `FLW-MOCK-${id}`, + amount: amountMajor, + currency: "KES", + charged_amount: amountMajor, + status, + payment_type: "mpesa", + processor_response: "Approved", + customer: { + id: 215604089, + name: "Aidi Onyango", + phone_number: "+254700000000", + email: "supporter@example.com", + }, + meta: { orderDraftId }, + }, + }); +} + +describe("@dashcommerce/flutterwave through core", () => { + it("registers on import and resolves as the configured provider", async () => { + expect(getPaymentProvider("flutterwave")).toBe(flutterwavePaymentProvider); + const { ctx } = makeContext( + { "settings:paymentProvider": "flutterwave" }, + fakeFlutterwave().fetch, + ); + expect((await resolveProvider(ctx.kv)).id).toBe("flutterwave"); + }); + + it("registering again is a no-op, but a different provider under the same id fails loudly", () => { + expect(() => registerFlutterwaveProvider()).not.toThrow(); + expect(() => + registerPaymentProvider({ ...flutterwavePaymentProvider, label: "Impostor" }), + ).toThrow(/already registered/); + expect(getPaymentProvider("flutterwave")).toBe(flutterwavePaymentProvider); + }); + + it("runs checkout → signed webhook → verified order, and ignores a replay", async () => { + const flutterwave = fakeFlutterwave(); + const { ctx, getCol } = makeContext(flutterwaveSettings, flutterwave.fetch); + + const initRes = await startCheckout(ctx, "sess_flw_1"); + expect(initRes.status).toBe(200); + const { url, orderDraftId } = (await initRes.json()) as { url: string; orderDraftId: string }; + expect(url).toBe("https://checkout.flutterwave.com/v3/hosted/pay/test-link"); + + const txRef = String(flutterwave.getLastInit()?.tx_ref); + expect(txRef).toBe(`dc-${orderDraftId}`); + const tx = flutterwave.transactions.get(txRef); + if (!tx) throw new Error("checkout did not register a transaction"); + + const payload = chargeCompleted(txRef, orderDraftId, tx.id); + const webhookRes = await deliverWebhook(ctx, payload, SECRET_HASH); + expect(webhookRes.status).toBe(200); + + const orders = getCol("orders"); + expect(orders.size).toBe(1); + const order = Array.from(orders.values())[0] as Order; + expect(order.providerId).toBe("flutterwave"); + expect(order.paymentReference).toBe(String(tx.id)); + expect(order.checkoutReference).toBe(txRef); + expect(order.total.amount).toBe(150000); + expect(order.total.currency).toBe("KES"); + expect(order.paymentStatus).toBe("paid"); + + const replay = await deliverWebhook(ctx, payload, SECRET_HASH); + expect(replay.status).toBe(200); + expect(((await replay.json()) as { duplicate?: boolean }).duplicate).toBe(true); + expect(orders.size).toBe(1); + }); + + it("creates no order for a signed event whose transaction Flutterwave does not know", async () => { + const flutterwave = fakeFlutterwave(); + const { ctx, getCol } = makeContext(flutterwaveSettings, flutterwave.fetch); + const initRes = await startCheckout(ctx, "sess_flw_2"); + const { orderDraftId } = (await initRes.json()) as { orderDraftId: string }; + + const payload = chargeCompleted("dc-not-a-real-transaction", orderDraftId, 1); + const res = await deliverWebhook(ctx, payload, SECRET_HASH); + expect(res.status).not.toBe(200); + expect(getCol("orders").size).toBe(0); + }); + + it("rejects a webhook with the wrong verif-hash before any side effect", async () => { + const flutterwave = fakeFlutterwave(); + const { ctx, getCol } = makeContext(flutterwaveSettings, flutterwave.fetch); + const initRes = await startCheckout(ctx, "sess_flw_3"); + const { orderDraftId } = (await initRes.json()) as { orderDraftId: string }; + const txRef = String(flutterwave.getLastInit()?.tx_ref); + + const payload = chargeCompleted(txRef, orderDraftId, 1); + const res = await deliverWebhook(ctx, payload, "wrong-hash"); + expect(res.status).toBe(400); + expect(getCol("orders").size).toBe(0); + }); + + it("holds the order when Flutterwave confirms a different amount than the cart", async () => { + // The payload claims the full amount; Flutterwave's own record says less. + const flutterwave = fakeFlutterwave({ chargedAmountMinor: 100 }); + const { ctx, getCol } = makeContext(flutterwaveSettings, flutterwave.fetch); + const initRes = await startCheckout(ctx, "sess_flw_4"); + const { orderDraftId } = (await initRes.json()) as { orderDraftId: string }; + const txRef = String(flutterwave.getLastInit()?.tx_ref); + const tx = flutterwave.transactions.get(txRef); + if (!tx) throw new Error("checkout did not register a transaction"); + + const payload = chargeCompleted(txRef, orderDraftId, tx.id, 1500); + const res = await deliverWebhook(ctx, payload, SECRET_HASH); + expect(res.status).toBe(200); + + const order = Array.from(getCol("orders").values())[0] as Order & { + metadata?: Record; + }; + expect(order).toBeDefined(); + expect(order.status).toBe("on-hold"); + expect(order.metadata?.paymentAmountMismatch).toBe(true); + expect(order.metadata?.receivedAmount).toBe(100); + }); + + it("creates the order when Flutterwave's retry follows a failed first delivery", async () => { + // Flutterwave is briefly down when core confirms the first delivery, so + // core answers 500. Flutterwave's retry must still produce the order. + const flutterwave = fakeFlutterwave({ verifyOutages: 1 }); + const { ctx, getCol } = makeContext(flutterwaveSettings, flutterwave.fetch); + const initRes = await startCheckout(ctx, "sess_flw_5"); + const { orderDraftId } = (await initRes.json()) as { orderDraftId: string }; + const txRef = String(flutterwave.getLastInit()?.tx_ref); + const tx = flutterwave.transactions.get(txRef); + if (!tx) throw new Error("checkout did not register a transaction"); + + const payload = chargeCompleted(txRef, orderDraftId, tx.id); + + const first = await deliverWebhook(ctx, payload, SECRET_HASH); + expect(first.status).toBe(500); + expect(getCol("orders").size).toBe(0); + + const retry = await deliverWebhook(ctx, payload, SECRET_HASH); + expect(retry.status).toBe(200); + expect(getCol("orders").size).toBe(1); + }); + + it("creates no order when Flutterwave reports the transaction as pending", async () => { + const flutterwave = fakeFlutterwave({ verifyStatus: "pending" }); + const { ctx, getCol } = makeContext(flutterwaveSettings, flutterwave.fetch); + const initRes = await startCheckout(ctx, "sess_flw_6"); + const { orderDraftId } = (await initRes.json()) as { orderDraftId: string }; + const txRef = String(flutterwave.getLastInit()?.tx_ref); + const tx = flutterwave.transactions.get(txRef); + if (!tx) throw new Error("checkout did not register a transaction"); + + const payload = chargeCompleted(txRef, orderDraftId, tx.id); + const res = await deliverWebhook(ctx, payload, SECRET_HASH); + expect(res.status).not.toBe(200); + expect(getCol("orders").size).toBe(0); + }); + + it("finds the draft from the reference when Flutterwave returns no metadata", async () => { + const flutterwave = fakeFlutterwave(); + const { ctx, getCol } = makeContext(flutterwaveSettings, flutterwave.fetch); + const initRes = await startCheckout(ctx, "sess_flw_7"); + const { orderDraftId } = (await initRes.json()) as { orderDraftId: string }; + const txRef = String(flutterwave.getLastInit()?.tx_ref); + const tx = flutterwave.transactions.get(txRef); + if (!tx) throw new Error("checkout did not register a transaction"); + + const event = JSON.parse(chargeCompleted(txRef, orderDraftId, tx.id)); + const { meta: _meta, ...data } = event.data; + const payload = JSON.stringify({ ...event, data }); + const res = await deliverWebhook(ctx, payload, SECRET_HASH); + expect(res.status).toBe(200); + expect(getCol("orders").size).toBe(1); + }); + + it("sends Flutterwave a callback URL without Stripe's session placeholder", async () => { + const flutterwave = fakeFlutterwave(); + const { ctx } = makeContext(flutterwaveSettings, flutterwave.fetch); + const initRes = await startCheckout(ctx, "sess_flw_8"); + const { orderDraftId } = (await initRes.json()) as { orderDraftId: string }; + + const callback = new URL(String(flutterwave.getLastInit()?.redirect_url)); + expect(callback.pathname).toBe(`/thank-you/${orderDraftId}`); + expect(callback.search).toBe(""); + expect(String(flutterwave.getLastInit()?.redirect_url)).not.toContain("CHECKOUT_SESSION_ID"); + }); + + it("charges the cart total in major units and refunds the order's payment", async () => { + const flutterwave = fakeFlutterwave(); + const { ctx, getCol } = makeContext(flutterwaveSettings, flutterwave.fetch); + const initRes = await startCheckout(ctx, "sess_flw_9"); + const { orderDraftId } = (await initRes.json()) as { orderDraftId: string }; + expect(flutterwave.getLastInit()?.amount).toBe(1500); + expect(flutterwave.getLastInit()?.currency).toBe("KES"); + + const txRef = String(flutterwave.getLastInit()?.tx_ref); + const tx = flutterwave.transactions.get(txRef); + if (!tx) throw new Error("checkout did not register a transaction"); + const payload = chargeCompleted(txRef, orderDraftId, tx.id); + await deliverWebhook(ctx, payload, SECRET_HASH); + const order = Array.from(getCol("orders").values())[0] as Order; + + const refund = await flutterwavePaymentProvider.refund( + { http: ctx.http, log: ctx.log }, + { + refundRequestId: "refund-req-1", + paymentReference: order.paymentReference ?? "", + amount: 50000, + currency: "KES", + }, + { secretKey: SECRET_KEY }, + ); + expect(flutterwave.refunds).toHaveLength(1); + expect(flutterwave.refunds[0]?.transaction_id).toBe(tx.id); + expect(flutterwave.refunds[0]?.amount_refunded).toBe(500); + expect(refund.status).toBe("succeeded"); + expect(refund.amount).toBe(50000); + + // A retry with the same request id (say the first response timed out) + // returns the first refund; Flutterwave would accept a second one. + const retry = await flutterwavePaymentProvider.refund( + { http: ctx.http, log: ctx.log }, + { + refundRequestId: "refund-req-1", + paymentReference: order.paymentReference ?? "", + amount: 50000, + currency: "KES", + }, + { secretKey: SECRET_KEY }, + ); + expect(flutterwave.refunds).toHaveLength(1); + expect(retry.providerRefundId).toBe(refund.providerRefundId); + + // A different request for the same amount is a new, legitimate refund. + await flutterwavePaymentProvider.refund( + { http: ctx.http, log: ctx.log }, + { + refundRequestId: "refund-req-2", + paymentReference: order.paymentReference ?? "", + amount: 50000, + currency: "KES", + }, + { secretKey: SECRET_KEY }, + ); + expect(flutterwave.refunds).toHaveLength(2); + }); + + it("saves Flutterwave keys through the settings API and refuses a public key", async () => { + const { ctx } = makeContext({}, fakeFlutterwave().fetch); + const routeCtx = { + request: new Request("http://test/admin/settings", { method: "POST" }), + input: { + paymentProvider: "flutterwave", + flutterwaveSecretKey: SECRET_KEY, + flutterwaveWebhookSecret: SECRET_HASH, + }, + } as unknown as import("emdash").RouteContext; + const res = (await sandbox.routes["admin/settings"].handler(routeCtx, ctx)) as Response; + expect(res.status).toBe(200); + expect(await ctx.kv.get("settings:flutterwaveSecretKey")).toBe(SECRET_KEY); + + const bad = (await sandbox.routes["admin/settings"].handler( + { + request: new Request("http://test/admin/settings", { method: "POST" }), + input: { flutterwaveSecretKey: "FLWPUBK_TEST-1234567890abcdef-X" }, + } as unknown as import("emdash").RouteContext, + ctx, + )) as Response; + expect(bad.status).toBe(400); + }); + + it("moves a pending refund to succeeded on Flutterwave's refund webhook", async () => { + const flutterwave = fakeFlutterwave(); + const { ctx, getCol } = makeContext(flutterwaveSettings, flutterwave.fetch); + const initRes = await startCheckout(ctx, "sess_flw_10"); + const { orderDraftId } = (await initRes.json()) as { orderDraftId: string }; + const txRef = String(flutterwave.getLastInit()?.tx_ref); + const tx = flutterwave.transactions.get(txRef); + if (!tx) throw new Error("checkout did not register a transaction"); + await deliverWebhook(ctx, chargeCompleted(txRef, orderDraftId, tx.id), SECRET_HASH); + const order = Array.from(getCol("orders").values())[0] as Order; + + const refundRes = (await sandbox.routes["admin/orders/refund"].handler( + { + request: new Request(`http://test/admin/orders/refund?id=${order.id}`, { method: "POST" }), + input: { amount: 50000, currency: "KES" }, + } as unknown as import("emdash").RouteContext, + ctx, + )) as Response; + expect(refundRes.status).toBe(200); + + // Flutterwave's refund create response says "completed", so core stores + // the row as succeeded; force it back to pending so the webhook has + // something to move. + const refunds = getCol("refunds"); + const refundRow = Array.from(refunds.values())[0] as { + status: string; + stripeRefundId: string; + }; + refundRow.status = "pending"; + + const payload = JSON.stringify({ + id: Number(refundRow.stripeRefundId), + AmountRefunded: 500, + status: "completed", + FlwRef: `FLW-MOCK-${tx.id}`, + TransactionId: tx.id, + createdAt: "2026-11-19T02:00:00.000Z", + }); + const res = await deliverWebhook(ctx, payload, SECRET_HASH); + expect(res.status).toBe(200); + expect(((await res.json()) as { refund?: string }).refund).toBe("updated"); + expect((Array.from(refunds.values())[0] as { status: string }).status).toBe("succeeded"); + }); +}); diff --git a/packages/flutterwave/test/flutterwave-provider.test.ts b/packages/flutterwave/test/flutterwave-provider.test.ts new file mode 100644 index 0000000..31da409 --- /dev/null +++ b/packages/flutterwave/test/flutterwave-provider.test.ts @@ -0,0 +1,779 @@ +import { describe, expect, it } from "bun:test"; +import type { + InitCheckoutInput, + PaymentProviderRuntimeContext, +} from "@dashcommerce/core/payment-provider"; +import { + flutterwavePaymentProvider, + flutterwaveReferenceFor, + toMajorUnits, + toMinorUnits, +} from "../src/provider"; + +function makeMockRuntimeContext( + fetchHandler: (url: string, init?: RequestInit) => Promise, +): PaymentProviderRuntimeContext { + return { + http: { fetch: fetchHandler }, + log: { info() {}, warn() {}, error() {} }, + }; +} + +function checkoutInput(overrides: Partial = {}): InitCheckoutInput { + return { + orderDraftId: "0123456789abcdef0123456789abcdef", + amount: 250000, // KES 2,500.00 + currency: "KES", + customer: { email: "fan@example.com" }, + lineItems: [], + successUrl: "https://shop.example/thank-you", + cancelUrl: "https://shop.example/checkout", + ...overrides, + }; +} + +function flutterwaveOk(data: unknown, meta?: unknown): Response { + return new Response( + JSON.stringify({ status: "success", message: "ok", data, ...(meta ? { meta } : {}) }), + { + status: 200, + headers: { "Content-Type": "application/json" }, + }, + ); +} + +function flutterwaveError(message: string, status = 400): Response { + return new Response(JSON.stringify({ status: "error", message, data: null }), { + status, + headers: { "Content-Type": "application/json" }, + }); +} + +const TX_REFERENCE = /^[A-Za-z0-9.=-]+$/; + +describe("flutterwavePaymentProvider", () => { + const credentials = { secretKey: "FLWSECK_TEST-1234567890abcdef-X" }; + + describe("declared to core", () => { + it("is a hosted provider that claims the verif-hash header", () => { + expect(flutterwavePaymentProvider.id).toBe("flutterwave"); + expect(flutterwavePaymentProvider.checkoutStyles).toEqual(["hosted"]); + expect(flutterwavePaymentProvider.webhookHeaders).toEqual(["verif-hash"]); + expect(flutterwavePaymentProvider.collectsCustomerDetails).toBeUndefined(); + expect(flutterwavePaymentProvider.capabilities).toEqual({ + coupons: false, + connect: false, + subscriptions: false, + }); + }); + + it("accepts only Flutterwave secret keys and any secret hash", () => { + const fields = flutterwavePaymentProvider.credentialFields; + expect(fields?.secretKey?.prefixes).toEqual(["FLWSECK_TEST-", "FLWSECK-"]); + expect(fields?.webhookSecret?.prefixes).toEqual([]); + }); + }); + + describe("supportsCurrency", () => { + it("supports the currencies Flutterwave collects in", () => { + for (const currency of ["NGN", "KES", "GHS", "ZAR", "USD", "GBP", "EUR", "UGX", "TZS"]) { + expect(flutterwavePaymentProvider.supportsCurrency(currency)).toBe(true); + } + expect(flutterwavePaymentProvider.supportsCurrency("ngn")).toBe(true); + expect(flutterwavePaymentProvider.supportsCurrency(" KES ")).toBe(true); + }); + + it("rejects other currencies", () => { + expect(flutterwavePaymentProvider.supportsCurrency("JPY")).toBe(false); + expect(flutterwavePaymentProvider.supportsCurrency("")).toBe(false); + }); + }); + + describe("amount conversion", () => { + it("converts core minor units to Flutterwave major units", () => { + expect(toMajorUnits(250000)).toBe(2500); + expect(toMajorUnits(1)).toBe(0.01); + expect(toMajorUnits(0)).toBe(0); + }); + + it("converts Flutterwave major units back to core minor units", () => { + expect(toMinorUnits(2500)).toBe(250000); + expect(toMinorUnits("0.01")).toBe(1); + expect(toMinorUnits(12.345)).toBe(1235); + }); + + it("refuses a negative or fractional minor amount", () => { + expect(() => toMajorUnits(-1)).toThrow(/non-negative integer/); + expect(() => toMajorUnits(1.5)).toThrow(/non-negative integer/); + }); + + it("ignores a missing or malformed major amount", () => { + expect(toMinorUnits(undefined)).toBeUndefined(); + expect(toMinorUnits("abc")).toBeUndefined(); + expect(toMinorUnits(-1)).toBeUndefined(); + }); + }); + + describe("flutterwaveReferenceFor", () => { + it("produces a reference Flutterwave accepts from a core draft id", () => { + const ref = flutterwaveReferenceFor("0123456789abcdef0123456789abcdef"); + expect(ref).toBe("dc-0123456789abcdef0123456789abcdef"); + expect(ref).toMatch(TX_REFERENCE); + }); + + it("replaces characters Flutterwave rejects", () => { + expect(flutterwaveReferenceFor("draft_flw_1")).toMatch(TX_REFERENCE); + }); + }); + + describe("initCheckout", () => { + it("creates a hosted payment in major units and returns the link", async () => { + let capturedUrl = ""; + let capturedBody: Record = {}; + const ctx = makeMockRuntimeContext(async (url, init) => { + capturedUrl = url; + capturedBody = JSON.parse(String(init?.body)); + return flutterwaveOk({ + link: "https://checkout.flutterwave.com/v3/hosted/pay/test-link", + }); + }); + + const result = await flutterwavePaymentProvider.initCheckout( + ctx, + checkoutInput({ preferredChannels: ["card", "mpesa"] }), + credentials, + ); + + expect(capturedUrl).toBe("https://api.flutterwave.com/v3/payments"); + expect(capturedBody.tx_ref).toBe("dc-0123456789abcdef0123456789abcdef"); + expect(String(capturedBody.tx_ref)).toMatch(TX_REFERENCE); + expect(capturedBody.amount).toBe(2500); + expect(capturedBody.currency).toBe("KES"); + expect(capturedBody.redirect_url).toBe("https://shop.example/thank-you"); + expect(capturedBody.payment_options).toBe("card,mpesa"); + expect((capturedBody.customer as Record).email).toBe("fan@example.com"); + expect((capturedBody.meta as Record).orderDraftId).toBe( + "0123456789abcdef0123456789abcdef", + ); + + expect(result.kind).toBe("redirect"); + if (result.kind !== "redirect") throw new Error("expected redirect"); + expect(result.redirectUrl).toBe("https://checkout.flutterwave.com/v3/hosted/pay/test-link"); + expect(result.checkoutReference).toBe("dc-0123456789abcdef0123456789abcdef"); + }); + + it("resolves a generic mobile-money hint with the cart's currency", async () => { + let body: Record = {}; + const ctx = makeMockRuntimeContext(async (_url, init) => { + body = JSON.parse(String(init?.body)); + return flutterwaveOk({ link: "https://checkout.flutterwave.com/v3/hosted/pay/x" }); + }); + await flutterwavePaymentProvider.initCheckout( + ctx, + checkoutInput({ currency: "GHS", preferredChannels: ["mobile_money"] }), + credentials, + ); + expect(body.payment_options).toBe("mobilemoneyghana"); + }); + + it("passes the customer's name and phone when the cart has them", async () => { + let body: Record = {}; + const ctx = makeMockRuntimeContext(async (_url, init) => { + body = JSON.parse(String(init?.body)); + return flutterwaveOk({ link: "https://checkout.flutterwave.com/v3/hosted/pay/x" }); + }); + await flutterwavePaymentProvider.initCheckout( + ctx, + checkoutInput({ + customer: { email: "fan@example.com", phone: "+254700000000" }, + shippingAddress: { firstName: "Aidi", lastName: "Onyango" }, + }), + credentials, + ); + expect(body.customer).toEqual({ + email: "fan@example.com", + name: "Aidi Onyango", + phonenumber: "+254700000000", + }); + }); + + it("strips Stripe's session placeholder from the return URL", async () => { + let body: Record = {}; + const ctx = makeMockRuntimeContext(async (_url, init) => { + body = JSON.parse(String(init?.body)); + return flutterwaveOk({ link: "https://checkout.flutterwave.com/v3/hosted/pay/x" }); + }); + await flutterwavePaymentProvider.initCheckout( + ctx, + checkoutInput({ + successUrl: "https://shop.example/thank-you?session_id={CHECKOUT_SESSION_ID}&utm=email", + }), + credentials, + ); + const callback = new URL(String(body.redirect_url)); + expect(callback.searchParams.get("session_id")).toBeNull(); + expect(callback.searchParams.get("utm")).toBe("email"); + }); + + it("throws before calling Flutterwave when the email is missing", async () => { + let calls = 0; + const ctx = makeMockRuntimeContext(async () => { + calls++; + return new Response("{}"); + }); + await expect( + flutterwavePaymentProvider.initCheckout( + ctx, + checkoutInput({ customer: { email: "" } }), + credentials, + ), + ).rejects.toThrow("Flutterwave requires customer email to initialize checkout"); + expect(calls).toBe(0); + }); + + it("throws before calling Flutterwave when the email is malformed", async () => { + let calls = 0; + const ctx = makeMockRuntimeContext(async () => { + calls++; + return new Response("{}"); + }); + await expect( + flutterwavePaymentProvider.initCheckout( + ctx, + checkoutInput({ customer: { email: "invalid-email" } }), + credentials, + ), + ).rejects.toThrow("Flutterwave requires a valid customer email to initialize checkout"); + expect(calls).toBe(0); + }); + + it("throws before calling Flutterwave for an unsupported currency", async () => { + let calls = 0; + const ctx = makeMockRuntimeContext(async () => { + calls++; + return new Response("{}"); + }); + await expect( + flutterwavePaymentProvider.initCheckout( + ctx, + checkoutInput({ currency: "JPY" }), + credentials, + ), + ).rejects.toThrow(/does not support currency JPY/); + expect(calls).toBe(0); + }); + + it("throws before calling Flutterwave for subscription mode", async () => { + let calls = 0; + const ctx = makeMockRuntimeContext(async () => { + calls++; + return new Response("{}"); + }); + await expect( + flutterwavePaymentProvider.initCheckout( + ctx, + checkoutInput({ mode: "subscription" }), + credentials, + ), + ).rejects.toThrow(/does not support subscription checkout/); + expect(calls).toBe(0); + }); + + it("fails when Flutterwave returns no link", async () => { + const ctx = makeMockRuntimeContext(async () => flutterwaveOk({})); + await expect( + flutterwavePaymentProvider.initCheckout(ctx, checkoutInput(), credentials), + ).rejects.toThrow("Flutterwave did not return a hosted checkout link"); + }); + }); + + describe("verifyWebhook", () => { + it("accepts the configured secret hash", async () => { + const result = await flutterwavePaymentProvider.verifyWebhook({ + rawBody: "{}", + signatureHeader: "my-secret-hash", + secret: "my-secret-hash", + }); + expect(result.ok).toBe(true); + }); + + it("refuses a different hash", async () => { + const result = await flutterwavePaymentProvider.verifyWebhook({ + rawBody: "{}", + signatureHeader: "not-the-hash", + secret: "my-secret-hash", + }); + expect(result.ok).toBe(false); + expect(result.reason).toContain("verif-hash"); + }); + + it("refuses a missing header or a missing secret", async () => { + expect( + ( + await flutterwavePaymentProvider.verifyWebhook({ + rawBody: "{}", + signatureHeader: "", + secret: "my-secret-hash", + }) + ).ok, + ).toBe(false); + expect( + ( + await flutterwavePaymentProvider.verifyWebhook({ + rawBody: "{}", + signatureHeader: "my-secret-hash", + secret: "", + }) + ).ok, + ).toBe(false); + }); + }); + + describe("parseWebhookEvent", () => { + const draftId = "0123456789abcdef0123456789abcdef"; + + function chargeEvent(overrides: Record = {}) { + return { + event: "charge.completed", + "event.type": "CARD_TRANSACTION", + data: { + id: 285959875, + tx_ref: `dc-${draftId}`, + flw_ref: "FLW-MOCK-123", + amount: 1500, + currency: "KES", + charged_amount: 1500, + status: "successful", + payment_type: "mpesa", + processor_response: "Approved", + customer: { + id: 1, + name: "Aidi Onyango", + phone_number: "+254700000000", + email: "fan@example.com", + }, + meta: { orderDraftId: draftId }, + ...overrides, + }, + }; + } + + it("normalises a successful charge, converting the amount to minor units", () => { + const event = flutterwavePaymentProvider.parseWebhookEvent(JSON.stringify(chargeEvent())); + expect(event.type).toBe("charge.succeeded"); + if (event.type !== "charge.succeeded") throw new Error("expected charge.succeeded"); + expect(event.orderDraftId).toBe(draftId); + expect(event.providerId).toBe("flutterwave"); + expect(event.providerEventId).toBe("charge.completed:285959875:successful"); + expect(event.paymentReference).toBe("285959875"); + expect(event.checkoutReference).toBe(`dc-${draftId}`); + expect(event.amount).toBe(150000); + expect(event.currency).toBe("KES"); + expect(event.channel).toBe("M-Pesa"); + expect(event.customer).toEqual({ + email: "fan@example.com", + name: "Aidi Onyango", + phone: "+254700000000", + }); + }); + + it("reads meta when Flutterwave sends it as a JSON string", () => { + const event = flutterwavePaymentProvider.parseWebhookEvent( + JSON.stringify(chargeEvent({ meta: JSON.stringify({ orderDraftId: draftId }) })), + ); + expect(event.type).toBe("charge.succeeded"); + }); + + it("finds the draft from the reference when meta is absent", () => { + const payload = chargeEvent(); + const { meta: _meta, ...data } = payload.data as Record; + const event = flutterwavePaymentProvider.parseWebhookEvent( + JSON.stringify({ ...payload, data }), + ); + expect(event.type).toBe("charge.succeeded"); + if (event.type !== "charge.succeeded") throw new Error("expected charge.succeeded"); + expect(event.orderDraftId).toBe(draftId); + }); + + it("normalises a failed charge", () => { + const event = flutterwavePaymentProvider.parseWebhookEvent( + JSON.stringify(chargeEvent({ status: "failed", processor_response: "insufficient funds" })), + ); + expect(event.type).toBe("charge.failed"); + if (event.type !== "charge.failed") throw new Error("expected charge.failed"); + expect(event.orderDraftId).toBe(draftId); + expect(event.providerEventId).toBe("charge.completed:285959875:failed"); + expect(event.reason).toBe("insufficient funds"); + }); + + it("leaves a pending charge unhandled", () => { + const event = flutterwavePaymentProvider.parseWebhookEvent( + JSON.stringify(chargeEvent({ status: "pending" })), + ); + expect(event.type).toBe("unhandled"); + }); + + it("normalises the refund webhook, which has no event field", () => { + const event = flutterwavePaymentProvider.parseWebhookEvent( + JSON.stringify({ + id: 99025, + AmountRefunded: 100, + status: "completed", + FlwRef: "4687213286", + TransactionId: 9231836, + createdAt: "2026-01-30T08:35:45.000Z", + }), + ); + expect(event.type).toBe("refund.updated"); + if (event.type !== "refund.updated") throw new Error("expected refund.updated"); + expect(event.providerId).toBe("flutterwave"); + expect(event.providerRefundId).toBe("99025"); + expect(event.providerEventId).toBe("refund:99025:succeeded"); + expect(event.status).toBe("succeeded"); + }); + + it("maps a pending refund and keeps each status a separate event", () => { + const event = flutterwavePaymentProvider.parseWebhookEvent( + JSON.stringify({ + id: 99025, + AmountRefunded: 100, + status: "pending-momo", + TransactionId: 9231836, + }), + ); + if (event.type !== "refund.updated") throw new Error("expected refund.updated"); + expect(event.status).toBe("pending"); + expect(event.providerEventId).toBe("refund:99025:pending"); + }); + + it("accepts a string refund id and an event wrapper", () => { + const bare = flutterwavePaymentProvider.parseWebhookEvent( + JSON.stringify({ id: "99025", AmountRefunded: 100, status: "completed" }), + ); + if (bare.type !== "refund.updated") throw new Error("expected refund.updated"); + expect(bare.providerRefundId).toBe("99025"); + + const wrapped = flutterwavePaymentProvider.parseWebhookEvent( + JSON.stringify({ event: "refund.completed", data: { id: 99025, status: "completed" } }), + ); + if (wrapped.type !== "refund.updated") throw new Error("expected refund.updated"); + expect(wrapped.providerRefundId).toBe("99025"); + expect(wrapped.status).toBe("succeeded"); + }); + + it("leaves malformed, unparseable and unknown events unhandled", () => { + expect(flutterwavePaymentProvider.parseWebhookEvent("not json").type).toBe("unhandled"); + expect(flutterwavePaymentProvider.parseWebhookEvent("null").type).toBe("unhandled"); + expect(flutterwavePaymentProvider.parseWebhookEvent("{}").type).toBe("unhandled"); + expect( + flutterwavePaymentProvider.parseWebhookEvent( + JSON.stringify({ event: "transfer.completed", data: {} }), + ).type, + ).toBe("unhandled"); + }); + }); + + describe("getPaymentStatus", () => { + it("verifies by numeric transaction id", async () => { + let requested = ""; + const ctx = makeMockRuntimeContext(async (url) => { + requested = url; + return flutterwaveOk({ + id: 285959875, + tx_ref: "dc-abc", + amount: 1500, + currency: "KES", + status: "successful", + processor_response: "Approved", + }); + }); + + const result = await flutterwavePaymentProvider.getPaymentStatus?.( + ctx, + "285959875", + credentials, + ); + expect(requested).toBe("https://api.flutterwave.com/v3/transactions/285959875/verify"); + expect(result).toEqual({ + status: "succeeded", + paymentReference: "285959875", + amount: 150000, + currency: "KES", + reason: "Approved", + }); + }); + + it("verifies a reference through verify_by_reference", async () => { + let requested = ""; + const ctx = makeMockRuntimeContext(async (url) => { + requested = url; + return flutterwaveOk({ + id: 285959875, + tx_ref: "dc-abc", + amount: "1500", + currency: "kes", + status: "failed", + }); + }); + + const result = await flutterwavePaymentProvider.getPaymentStatus?.( + ctx, + "dc-abc", + credentials, + ); + expect(requested).toBe( + "https://api.flutterwave.com/v3/transactions/verify_by_reference?tx_ref=dc-abc", + ); + expect(result?.status).toBe("failed"); + expect(result?.amount).toBe(150000); + expect(result?.currency).toBe("KES"); + }); + + it("treats an unknown status as pending, never as paid", async () => { + const ctx = makeMockRuntimeContext(async () => + flutterwaveOk({ id: 1, status: "weird", amount: 10, currency: "NGN" }), + ); + const result = await flutterwavePaymentProvider.getPaymentStatus?.(ctx, "1", credentials); + expect(result?.status).toBe("pending"); + expect(result?.reason).toContain("Unrecognised Flutterwave status"); + }); + + it("fails without a reference and does not call Flutterwave", async () => { + let calls = 0; + const ctx = makeMockRuntimeContext(async () => { + calls++; + return flutterwaveOk({}); + }); + const result = await flutterwavePaymentProvider.getPaymentStatus?.(ctx, " ", credentials); + expect(result?.status).toBe("failed"); + expect(calls).toBe(0); + }); + }); + + describe("refund", () => { + function refundRuntime() { + const refunds: Array> = []; + let nextId = 8612; + const calls: Array<{ method: string; path: string; body?: Record }> = []; + + const ctx = makeMockRuntimeContext(async (url, init) => { + const { pathname, searchParams } = new URL(url); + const method = init?.method ?? "GET"; + const body = init?.body + ? (JSON.parse(String(init.body)) as Record) + : undefined; + calls.push({ method, path: pathname, ...(body ? { body } : {}) }); + + if (pathname === "/v3/refunds") { + const page = Number(searchParams.get("page") ?? "1"); + return flutterwaveOk(page === 1 ? refunds : [], { + page_info: { current_page: page, total_pages: 1, page_size: 20 }, + }); + } + const match = /^\/v3\/transactions\/(\d+)\/refund$/.exec(pathname); + if (match) { + const transactionId = Number(match[1]); + const refund = { + id: nextId++, + transaction_id: transactionId, + amount_refunded: body?.amount, + status: "completed", + comment: body?.comments ?? null, + created_at: new Date(Date.UTC(2026, 10, 19, 2, refunds.length)).toISOString(), + }; + refunds.push(refund); + return flutterwaveOk(refund); + } + return flutterwaveError("Not found", 404); + }); + + return { ctx, refunds, calls }; + } + + it("refunds in major units and tags the comment with the request id", async () => { + const { ctx, refunds, calls } = refundRuntime(); + const result = await flutterwavePaymentProvider.refund( + ctx, + { + paymentReference: "908790", + refundRequestId: "refund-req-1", + amount: 50000, + currency: "KES", + reason: "out of stock", + }, + credentials, + ); + + const create = calls.find((c) => c.method === "POST"); + expect(create?.path).toBe("/v3/transactions/908790/refund"); + expect(create?.body?.amount).toBe(500); + expect(create?.body?.comments).toBe("out of stock (refundRequestId=refund-req-1)"); + expect(refunds).toHaveLength(1); + expect(result).toEqual({ + providerRefundId: "8612", + refundRequestId: "refund-req-1", + status: "succeeded", + amount: 50000, + currency: "KES", + }); + }); + + it("returns the first refund on a retry instead of creating another", async () => { + const { ctx, refunds, calls } = refundRuntime(); + const input = { + paymentReference: "908790", + refundRequestId: "refund-req-1", + amount: 50000, + currency: "KES", + }; + const first = await flutterwavePaymentProvider.refund(ctx, input, credentials); + const retry = await flutterwavePaymentProvider.refund(ctx, input, credentials); + + expect(retry.providerRefundId).toBe(first.providerRefundId); + expect(refunds).toHaveLength(1); + expect(calls.filter((c) => c.method === "POST")).toHaveLength(1); + }); + + it("creates a new refund for a different request id", async () => { + const { ctx, refunds } = refundRuntime(); + await flutterwavePaymentProvider.refund( + ctx, + { + paymentReference: "908790", + refundRequestId: "refund-req-1", + amount: 50000, + currency: "KES", + }, + credentials, + ); + await flutterwavePaymentProvider.refund( + ctx, + { + paymentReference: "908790", + refundRequestId: "refund-req-2", + amount: 50000, + currency: "KES", + }, + credentials, + ); + expect(refunds).toHaveLength(2); + }); + + it("retries a request whose earlier refund failed", async () => { + const { ctx, refunds, calls } = refundRuntime(); + refunds.push({ + id: 7000, + transaction_id: 908790, + amount_refunded: 500, + status: "failed", + comment: "(refundRequestId=refund-req-1)", + created_at: "2026-11-19T01:00:00.000Z", + }); + + await flutterwavePaymentProvider.refund( + ctx, + { + paymentReference: "908790", + refundRequestId: "refund-req-1", + amount: 50000, + currency: "KES", + }, + credentials, + ); + expect(refunds).toHaveLength(2); + expect(calls.filter((c) => c.method === "POST")).toHaveLength(1); + }); + + it("resolves a tx_ref to the numeric id before refunding", async () => { + const paths: string[] = []; + const ctx = makeMockRuntimeContext(async (url) => { + const { pathname } = new URL(url); + paths.push(pathname); + if (pathname === "/v3/transactions/verify_by_reference") { + return flutterwaveOk({ id: 908790, tx_ref: "dc-abc", status: "successful" }); + } + if (pathname === "/v3/refunds") { + return flutterwaveOk([], { page_info: { total_pages: 1 } }); + } + if (pathname === "/v3/transactions/908790/refund") { + return flutterwaveOk({ id: 8612, amount_refunded: 1500, status: "completed" }); + } + return flutterwaveError("Not found", 404); + }); + + await flutterwavePaymentProvider.refund( + ctx, + { + paymentReference: "dc-abc", + refundRequestId: "refund-req-1", + currency: "KES", + }, + credentials, + ); + expect(paths).toContain("/v3/transactions/verify_by_reference"); + expect(paths).toContain("/v3/transactions/908790/refund"); + }); + + it("requires a usable refundRequestId and a payment reference", async () => { + const ctx = makeMockRuntimeContext(async () => flutterwaveOk({})); + await expect( + flutterwavePaymentProvider.refund( + ctx, + { paymentReference: "1", refundRequestId: "", currency: "KES" }, + credentials, + ), + ).rejects.toThrow(/non-empty refundRequestId/); + await expect( + flutterwavePaymentProvider.refund( + ctx, + { paymentReference: "1", refundRequestId: "has space", currency: "KES" }, + credentials, + ), + ).rejects.toThrow(/without spaces or brackets/); + await expect( + flutterwavePaymentProvider.refund( + ctx, + { paymentReference: "", refundRequestId: "ok", currency: "KES" }, + credentials, + ), + ).rejects.toThrow(/requires paymentReference/); + }); + }); + + describe("checkConnection", () => { + it("reports test mode and a readable key", async () => { + let requested = ""; + const ctx = makeMockRuntimeContext(async (url) => { + requested = url; + return flutterwaveOk({ NGN: 1000 }); + }); + const result = await flutterwavePaymentProvider.checkConnection?.(ctx, credentials); + expect(requested).toBe("https://api.flutterwave.com/v3/balances"); + expect(result?.ok).toBe(true); + expect(result?.mode).toBe("test"); + }); + + it("reports live mode for a live key", async () => { + const ctx = makeMockRuntimeContext(async () => flutterwaveOk({})); + const result = await flutterwavePaymentProvider.checkConnection?.(ctx, { + secretKey: "FLWSECK-1234567890abcdef-X", + }); + expect(result?.mode).toBe("live"); + }); + + it("reports a refused key instead of throwing", async () => { + const ctx = makeMockRuntimeContext(async () => + flutterwaveError("Authorization required", 401), + ); + const result = await flutterwavePaymentProvider.checkConnection?.(ctx, credentials); + expect(result?.ok).toBe(false); + expect(result?.message).toContain("refused the key"); + }); + }); + + describe("formatAmount", () => { + it("shows major units", () => { + expect(flutterwavePaymentProvider.formatAmount(250000, "kes")).toBe("KES 2500.00"); + }); + }); +}); diff --git a/packages/flutterwave/test/webhook-verify.test.ts b/packages/flutterwave/test/webhook-verify.test.ts new file mode 100644 index 0000000..440fd30 --- /dev/null +++ b/packages/flutterwave/test/webhook-verify.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from "bun:test"; +import { verifyFlutterwaveSecretHash } from "../src/webhook-verify"; + +describe("verifyFlutterwaveSecretHash", () => { + it("accepts the exact secret hash", () => { + expect( + verifyFlutterwaveSecretHash({ + signatureHeader: "s3cr3t-h4sh", + secret: "s3cr3t-h4sh", + }), + ).toEqual({ ok: true }); + }); + + it("trims surrounding whitespace from the header and the secret", () => { + expect( + verifyFlutterwaveSecretHash({ + signatureHeader: " s3cr3t-h4sh\n", + secret: "s3cr3t-h4sh ", + }).ok, + ).toBe(true); + }); + + it("refuses a different hash", () => { + const result = verifyFlutterwaveSecretHash({ + signatureHeader: "wrong", + secret: "s3cr3t-h4sh", + }); + expect(result.ok).toBe(false); + expect(result.reason).toContain("does not match"); + }); + + it("refuses a different length without throwing", () => { + expect( + verifyFlutterwaveSecretHash({ + signatureHeader: "s3cr3t-h4sh-and-more", + secret: "s3cr3t-h4sh", + }).ok, + ).toBe(false); + }); + + it("refuses a missing header", () => { + const result = verifyFlutterwaveSecretHash({ signatureHeader: "", secret: "s3cr3t-h4sh" }); + expect(result.ok).toBe(false); + expect(result.reason).toContain("Missing verif-hash header"); + }); + + it("refuses a missing secret", () => { + const result = verifyFlutterwaveSecretHash({ + signatureHeader: "s3cr3t-h4sh", + secret: " ", + }); + expect(result.ok).toBe(false); + expect(result.reason).toContain("Missing Flutterwave secret hash"); + }); +}); diff --git a/packages/flutterwave/tsconfig.json b/packages/flutterwave/tsconfig.json new file mode 100644 index 0000000..82829f9 --- /dev/null +++ b/packages/flutterwave/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "dist", + "noEmit": true, + "types": [] + }, + "include": ["src/**/*.ts"], + "exclude": ["dist", "node_modules"] +} diff --git a/packages/flutterwave/tsdown.config.ts b/packages/flutterwave/tsdown.config.ts new file mode 100644 index 0000000..5353ebc --- /dev/null +++ b/packages/flutterwave/tsdown.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from "tsdown"; + +export default defineConfig({ + entry: ["src/index.ts"], + format: ["esm"], + dts: true, + clean: true, +}); From 82e9a32c35ad7c059f4a9a322bc64c4eaef92fa6 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:00:57 +0100 Subject: [PATCH 02/50] fix(flutterwave): keep refunds working when refund history is unavailable 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. --- packages/flutterwave/README.md | 16 +++- packages/flutterwave/src/provider.ts | 81 +++++++++++++---- .../test/fixtures/refund-completed.json | 18 ++++ .../fixtures/verify-successful-mpesa.json | 30 ++++++ .../test/flutterwave-provider.test.ts | 91 +++++++++++++++++++ 5 files changed, 215 insertions(+), 21 deletions(-) create mode 100644 packages/flutterwave/test/fixtures/refund-completed.json create mode 100644 packages/flutterwave/test/fixtures/verify-successful-mpesa.json diff --git a/packages/flutterwave/README.md b/packages/flutterwave/README.md index 73b6e51..b1d0b18 100644 --- a/packages/flutterwave/README.md +++ b/packages/flutterwave/README.md @@ -11,12 +11,12 @@ A Flutterwave `PaymentProvider` for DashCommerce. Customers pay on Flutterwave's | Checkout | `POST /v3/payments`, then a redirect to the hosted link in `data.link`. The reference is `dc-`, so the draft can be recovered from `tx_ref` even without metadata | | Amounts | Core works in integer minor units; Flutterwave's v3 API works in major units. The provider converts at the boundary: a KES 1,500.00 cart is sent as `1500`, and Flutterwave's `1500` comes back as `150000` | | Webhook | Compares the `verif-hash` header with the secret hash saved in Settings → Webhooks, in constant time. See [Webhook verification](#webhook-verification) | -| Confirmation | Core calls `getPaymentStatus` before creating the order. A numeric reference is verified with `GET /v3/transactions/:id/verify`; anything else through `GET /v3/transactions/verify_by_reference?tx_ref=…`. The amount and currency come from Flutterwave's record, not the webhook body. `successful` counts as paid, `failed`/`cancelled` as failed, `pending` as pending. An unknown status is reported as pending, never as paid | +| Confirmation | Core calls `getPaymentStatus` before creating the order. A numeric reference is verified with `GET /v3/transactions/:id/verify`; anything else through `GET /v3/transactions/verify_by_reference?tx_ref=…`. The amount and currency come from Flutterwave's record, not the webhook body. `successful` counts as paid, `failed`/`cancelled` as failed, `pending` as pending. An unknown status is reported as pending, never as paid. Flutterwave keeps reporting `successful` after a refund (there is no `reversed` state), so a payment refunded in full before its order exists cannot be told apart from an unrefunded one; core's unique index on the payment reference still refuses a second order | | Duplicates | Flutterwave webhooks carry no event id, so the provider builds one: `charge.completed::successful`, `charge.completed::failed`, and `refund::`. Core records it before the handler runs, so a repeat or overlapping delivery is skipped, and a failed refund is reversed once. If confirming with Flutterwave fails (Flutterwave down, or the payment not yet successful), core releases the record, so Flutterwave's retry still creates the order. Any other failure keeps the record, as it does for Stripe | | Draft lookup | From `meta.orderDraftId` (object or JSON string), or from the `dc-` reference | | Return URL | Core's success URL minus Stripe's `{CHECKOUT_SESSION_ID}` placeholder; Flutterwave appends `status`, `tx_ref` and `transaction_id` | -| Refunds | `POST /v3/transactions/:id/refund`, with `(refundRequestId=)` at the end of `comments`. Flutterwave takes no idempotency key for refunds, so the provider lists refunds and returns any non-failed refund already tagged with this `refundRequestId` instead of creating another. The tag is read only from the end of the comment, and brackets are stripped from the reason, so a reason cannot pose as another request. This guards retries, not two simultaneous calls with the same id: both could pass the check before either refund exists, so core must not run the same refund request concurrently | -| Refund statuses | `completed`, `completed-bank-transfer`, `completed-momo`, `completed-mpgs`, `completed-offline` and `completed-preauth` → succeeded; `pending`, `pending-momo`, `pending-bank-transfer`, `pending-mpgs` and `processing` → pending; `failed` → failed. Flutterwave's minimum refund is NGN 100 / KES 10; a smaller request is refused by Flutterwave with a 400 | +| Refunds | `POST /v3/transactions/:id/refund`, with `(refundRequestId=)` at the end of `comments`. Flutterwave takes no idempotency key for refunds, so the provider lists refunds and returns any non-failed refund already tagged with this `refundRequestId` instead of creating another. The tag is read only from the end of the comment, and brackets are stripped from the reason, so a reason cannot pose as another request. This guards retries, not two simultaneous calls with the same id: both could pass the check before either refund exists, so core must not run the same refund request concurrently. Flutterwave allows one partial refund to process per transaction at a time; a second answers `400 "A partial refund is currently processing on this transaction"`. `GET /v3/refunds` is not available to every key: a real test-mode key answered `400 {"message":"unauthorized"}` while it could create refunds. The provider logs that the retry check is unavailable and continues, so on such an account a retried refund can duplicate | +| Refund statuses | `completed`, `completed-bank-transfer`, `completed-momo`, `completed-mpgs`, `completed-offline` and `completed-preauth` → succeeded; `pending`, `pending-momo`, `pending-bank-transfer`, `pending-mpgs` and `processing` → pending; `failed` → failed. Flutterwave's minimum refund is NGN 100 / KES 10; a smaller request is refused by Flutterwave with a 400. `completed` can arrive while `meta.disburse_status` is `failed`, meaning Flutterwave accepted the refund but the customer has not been paid yet; the provider logs a warning in that case | | Refund webhooks | Flutterwave posts the refund object itself, with no `event` field and capitalised `AmountRefunded`, `FlwRef` and `TransactionId`. The provider turns it into core's `refund.updated`, matched by the refund id | | Currencies | NGN, USD, GBP, EUR, KES, GHS, ZAR, UGX, TZS, RWF, XOF, XAF, ZMW, MWK and EGP. Your Flutterwave account must be enabled for the currency you sell in | | Payment options | With no channel hint, Flutterwave shows every method enabled on the account. A hint is mapped to Flutterwave's option names, and generic `mobile_money` is resolved by currency (`KES` → `mpesa`, `GHS` → `mobilemoneyghana`, …) | @@ -38,6 +38,16 @@ Enable **webhook retries** in the Flutterwave dashboard. Flutterwave retries a f Flutterwave sends `charge.completed` for failed attempts too, with `data.status` of `failed`. Those events release the checkout's stock lock; they never create an order. +## Test-mode notes (24 Nov 2026) + +Verified against Flutterwave's real test API with a Nigerian test account (KES wallet): + +- `GET /v3/balances`, `POST /v3/payments` and a real KES 1,500 M-Pesa payment all worked. The payment was completed through Flutterwave Inline on `checkout-v3.flutterwave.com`, which proves the Inline path this package does not ship yet. +- `GET /v3/transactions/:id/verify` and `verify_by_reference?tx_ref=` both returned the payment, and the provider's `getPaymentStatus` reported `succeeded` with `150000` minor units for a `1500` KES charge. +- A KES 500 partial refund succeeded with `status: "completed"`, and the `comments` tag came back exactly as sent. `meta.disburse_status` was `failed` in test mode, which is why the provider logs it. +- The hosted link Flutterwave issued pointed at `checkout-v2.dev-flutterwave.com`, which Cloudflare blocked from this network. The production host `checkout.flutterwave.com` did not recognise that test link. If your test link is blocked too, use a different network or ask Flutterwave support; the API side is unaffected. +- The public key and the secret key do **not** share their hash segment, so the public key cannot be derived from the secret key. Inline needs the public key stored, which is the core change described in the issue. + ## Use 1. **Install** both packages: diff --git a/packages/flutterwave/src/provider.ts b/packages/flutterwave/src/provider.ts index 74094fb..3a8737e 100644 --- a/packages/flutterwave/src/provider.ts +++ b/packages/flutterwave/src/provider.ts @@ -218,6 +218,7 @@ interface FlutterwaveRefundData { comment?: string | null; comments?: string | null; flw_ref?: string; + meta?: unknown; created_at?: string; createdAt?: string; transaction_id?: number; @@ -257,6 +258,18 @@ function isFailedRefund(raw: string | undefined): boolean { return refundStatus(raw) === "failed"; } +/** + * Flutterwave reports `completed` as soon as it accepts a refund, while the + * payout to the customer is a separate step tracked in `meta.disburse_status` + * (a string in some deliveries, an object in others). A `failed` value does + * not change the refund's status, but it means the customer has not been paid + * yet, so it is worth a log line. + */ +function disburseStatusOf(meta: unknown): string | undefined { + const value = metadataOf(meta)?.disburse_status; + return typeof value === "string" ? value : undefined; +} + /** * Flutterwave keeps no idempotency key for refunds. `comments` is the only * field that keeps ours, so the request id goes there in a form that can be @@ -304,6 +317,14 @@ function refundTransactionId(refund: FlutterwaveRefundData): number | undefined * Flutterwave's refund list is not filterable by transaction, so this walks * recent pages and matches the id and the tag. A failed refund does not * count, so it can be retried. The earliest match wins. + * + * `GET /v3/refunds` is not available to every key: a real test-mode run + * (24 Nov 2026) answered `400 {"message":"unauthorized"}` on an account that + * could create refunds and verify payments. That is an account/permission + * limit, not a transient failure, so refunds continue without the duplicate + * check and say so in the log. Any other failure still throws: a refund that + * cannot be de-duplicated because the network is down is better retried than + * guessed at. */ async function findRefundForRequest( ctx: PaymentProviderRuntimeContext, @@ -312,25 +333,40 @@ async function findRefundForRequest( refundRequestId: string, ): Promise { const matches: FlutterwaveRefundData[] = []; - for (let page = 1, totalPages = 1; page <= totalPages; page += 1) { - if (page > MAX_REFUND_PAGES) { - // Refunds are rare and the newest ones are listed first, so the - // retry that matters is almost always in range. Say so rather than - // blocking every refund on a store with a long refund history. - ctx.log.warn("Flutterwave refund list exceeded the lookup window", { - pagesScanned: MAX_REFUND_PAGES, - refundRequestId, - }); - break; - } - const result = await listRefundPage(ctx, client, page); - for (const refund of result.data) { - if (refundTransactionId(refund) !== transactionId) continue; - const note = refund.comment ?? refund.comments ?? ""; - if (COMMENT_REQUEST_ID.exec(note)?.[1] !== refundRequestId) continue; - if (!isFailedRefund(refund.status)) matches.push(refund); + try { + for (let page = 1, totalPages = 1; page <= totalPages; page += 1) { + if (page > MAX_REFUND_PAGES) { + // Refunds are rare and the newest ones are listed first, so the + // retry that matters is almost always in range. Say so rather than + // blocking every refund on a store with a long refund history. + ctx.log.warn("Flutterwave refund list exceeded the lookup window", { + pagesScanned: MAX_REFUND_PAGES, + refundRequestId, + }); + break; + } + const result = await listRefundPage(ctx, client, page); + for (const refund of result.data) { + if (refundTransactionId(refund) !== transactionId) continue; + const note = refund.comment ?? refund.comments ?? ""; + if (COMMENT_REQUEST_ID.exec(note)?.[1] !== refundRequestId) continue; + if (!isFailedRefund(refund.status)) matches.push(refund); + } + totalPages = result.totalPages; } - totalPages = result.totalPages; + } catch (err) { + const unavailable = + err instanceof FlutterwaveApiError && + (err.status === 401 || err.status === 403 || /unauthori[sz]ed|not found/i.test(err.message)); + if (!unavailable) throw err; + ctx.log.warn( + "Flutterwave refund history is not available to this key; a retried refund cannot be de-duplicated", + { + refundRequestId, + reason: err.message, + }, + ); + return undefined; } matches.sort( @@ -746,6 +782,15 @@ export const flutterwavePaymentProvider: PaymentProvider = { })); const amount = toMinorUnits(data.amount_refunded) ?? input.amount ?? 0; + if (disburseStatusOf(data.meta) === "failed") { + ctx.log.warn( + "Flutterwave accepted the refund but its disbursement failed; the customer has not been paid yet", + { + providerRefundId: String(data.id), + refundRequestId: input.refundRequestId, + }, + ); + } return { providerRefundId: String(data.id), refundRequestId: input.refundRequestId, diff --git a/packages/flutterwave/test/fixtures/refund-completed.json b/packages/flutterwave/test/fixtures/refund-completed.json new file mode 100644 index 0000000..98bd6e6 --- /dev/null +++ b/packages/flutterwave/test/fixtures/refund-completed.json @@ -0,0 +1,18 @@ +{ + "id": 115037, + "amount_refunded": 500, + "status": "completed", + "flw_ref": "3294702781", + "destination": "payment_source", + "comments": "probe partial (refundRequestId=probe-refund-1)", + "meta": { + "source": "ledgerbalance", + "isPartialRefund": true, + "disburse_ref": "CC-REFD-31047843128-3294702781", + "disburse_status": "failed" + }, + "created_at": "2026-11-24T13:57:23.000Z", + "wallet_id": 2607410, + "account_id": 123456, + "tx_id": 9877019 +} diff --git a/packages/flutterwave/test/fixtures/verify-successful-mpesa.json b/packages/flutterwave/test/fixtures/verify-successful-mpesa.json new file mode 100644 index 0000000..ecf4143 --- /dev/null +++ b/packages/flutterwave/test/fixtures/verify-successful-mpesa.json @@ -0,0 +1,30 @@ +{ + "id": 10633588, + "tx_ref": "dc-0123456789abcdef0123456789abcdef", + "flw_ref": "3294702781", + "device_fingerprint": "sanitized", + "amount": 1500, + "currency": "KES", + "charged_amount": 1500, + "app_fee": 73.5, + "merchant_fee": 0, + "processor_response": "Transaction Successful", + "auth_model": "LIPA_MPESA", + "ip": "203.0.113.10", + "narration": "FLW-PBF MPESA Transaction ", + "status": "successful", + "payment_type": "mpesa", + "created_at": "2026-11-24T13:56:39.000Z", + "account_id": 123456, + "meta": { + "MOMO_NETWORK": "SAFARICOM" + }, + "amount_settled": 1426.5, + "customer": { + "id": 1234567, + "name": "Test Buyer", + "phone_number": "254700000000", + "email": "buyer@example.com", + "created_at": "2026-11-24T13:56:39.000Z" + } +} diff --git a/packages/flutterwave/test/flutterwave-provider.test.ts b/packages/flutterwave/test/flutterwave-provider.test.ts index 31da409..cf67282 100644 --- a/packages/flutterwave/test/flutterwave-provider.test.ts +++ b/packages/flutterwave/test/flutterwave-provider.test.ts @@ -1,4 +1,6 @@ import { describe, expect, it } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; import type { InitCheckoutInput, PaymentProviderRuntimeContext, @@ -10,6 +12,13 @@ import { toMinorUnits, } from "../src/provider"; +function fixture(name: string): Record { + return JSON.parse(readFileSync(join(import.meta.dir, "fixtures", name), "utf8")) as Record< + string, + unknown + >; +} + function makeMockRuntimeContext( fetchHandler: (url: string, init?: RequestInit) => Promise, ): PaymentProviderRuntimeContext { @@ -395,6 +404,35 @@ describe("flutterwavePaymentProvider", () => { expect(event.orderDraftId).toBe(draftId); }); + it("parses a charge.completed built from a real test-mode verify response", () => { + const event = flutterwavePaymentProvider.parseWebhookEvent( + JSON.stringify({ + event: "charge.completed", + "event.type": "M-PESA_TRANSACTION", + data: fixture("verify-successful-mpesa.json"), + }), + ); + expect(event.type).toBe("charge.succeeded"); + if (event.type !== "charge.succeeded") throw new Error("expected charge.succeeded"); + expect(event.amount).toBe(150000); + expect(event.currency).toBe("KES"); + expect(event.channel).toBe("M-Pesa"); + expect(event.paymentReference).toBe("10633588"); + expect(event.customer.email).toBe("buyer@example.com"); + expect(event.orderDraftId).toBe("0123456789abcdef0123456789abcdef"); + }); + + it("parses a refund object as Flutterwave really sends it", () => { + const event = flutterwavePaymentProvider.parseWebhookEvent( + JSON.stringify(fixture("refund-completed.json")), + ); + expect(event.type).toBe("refund.updated"); + if (event.type !== "refund.updated") throw new Error("expected refund.updated"); + expect(event.providerRefundId).toBe("115037"); + expect(event.providerEventId).toBe("refund:115037:succeeded"); + expect(event.status).toBe("succeeded"); + }); + it("normalises a failed charge", () => { const event = flutterwavePaymentProvider.parseWebhookEvent( JSON.stringify(chargeEvent({ status: "failed", processor_response: "insufficient funds" })), @@ -684,6 +722,59 @@ describe("flutterwavePaymentProvider", () => { expect(calls.filter((c) => c.method === "POST")).toHaveLength(1); }); + it("still refunds when the refund history is not available to the key", async () => { + // A real test-mode account (24 Nov 2026) answered + // 400 {"message":"unauthorized"} for GET /v3/refunds while it could + // create refunds. Refunds must not be blocked by that. + const paths: string[] = []; + const ctx = makeMockRuntimeContext(async (url) => { + const { pathname } = new URL(url); + paths.push(pathname); + if (pathname === "/v3/refunds") return flutterwaveError("unauthorized", 400); + if (pathname === "/v3/transactions/908790/refund") { + return flutterwaveOk({ id: 8612, amount_refunded: 500, status: "completed" }); + } + return flutterwaveError("Not found", 404); + }); + + const result = await flutterwavePaymentProvider.refund( + ctx, + { + paymentReference: "908790", + refundRequestId: "refund-req-1", + amount: 50000, + currency: "KES", + }, + credentials, + ); + expect(result.providerRefundId).toBe("8612"); + expect(paths).toContain("/v3/transactions/908790/refund"); + }); + + it("refuses to refund blind when the refund history is briefly unavailable", async () => { + const paths: string[] = []; + const ctx = makeMockRuntimeContext(async (url) => { + const { pathname } = new URL(url); + paths.push(pathname); + if (pathname === "/v3/refunds") return flutterwaveError("Service unavailable", 503); + return flutterwaveOk({ id: 8612, amount_refunded: 500, status: "completed" }); + }); + + await expect( + flutterwavePaymentProvider.refund( + ctx, + { + paymentReference: "908790", + refundRequestId: "refund-req-1", + amount: 50000, + currency: "KES", + }, + credentials, + ), + ).rejects.toThrow(/Service unavailable/); + expect(paths).not.toContain("/v3/transactions/908790/refund"); + }); + it("resolves a tx_ref to the numeric id before refunding", async () => { const paths: string[] = []; const ctx = makeMockRuntimeContext(async (url) => { From 6f81f05756a5dc97710b4dfc071a09925a4bc481 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:33:51 +0100 Subject: [PATCH 03/50] feat(core): a public-key credential for payment providers --- .changeset/provider-public-key.md | 9 ++++ packages/core/README.md | 4 +- .../core/src/admin/pages/SettingsPage.tsx | 34 +++++++++++-- .../core/src/payment-provider/credentials.ts | 30 ++++++++--- packages/core/src/payment-provider/types.ts | 14 +++++- packages/core/src/routes/admin-api.ts | 3 ++ .../provider-credentials-settings.test.ts | 50 ++++++++++++++++++- 7 files changed, 129 insertions(+), 15 deletions(-) create mode 100644 .changeset/provider-public-key.md diff --git a/.changeset/provider-public-key.md b/.changeset/provider-public-key.md new file mode 100644 index 0000000..a2bedb8 --- /dev/null +++ b/.changeset/provider-public-key.md @@ -0,0 +1,9 @@ +--- +"@dashcommerce/core": minor +--- + +Let a payment provider save a browser public key. + +- `PaymentProviderCredentials.publicKey` and `credentialFields.publicKey`, saved as `settings:PublicKey` and validated against the prefixes the provider declares. Providers that need it for on-page checkout (Flutterwave Inline) can hand it to their browser client; nothing else changes for providers that do not. +- Settings shows the field only for a provider that declares it, beside the secret key and webhook secret. A provider that does not declare one cannot have a public key saved, and its settings row is unchanged. +- `loadPaymentProviderCredentials` returns `publicKey` when one is set. diff --git a/packages/core/README.md b/packages/core/README.md index 5e9a141..558f77d 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -62,12 +62,12 @@ Stripe is built in. A gateway package (for example `@dashcommerce/paystack`) reg emdash({ plugins: [dashcommerce({ allowedHosts: ["api.paystack.co"] })] }); ``` -3. **Choose the provider and enter its keys** in Settings → Payment provider. They are saved as `settings:SecretKey` and `settings:WebhookSecret`, masked like Stripe's. +3. **Choose the provider and enter its keys** in Settings → Payment provider. They are saved as `settings:SecretKey` and `settings:WebhookSecret` (plus `settings:PublicKey` when the provider declares one), masked like Stripe's. 4. **Point the provider's webhooks** at `/_emdash/api/plugins/dashcommerce/checkout/webhook?provider=`. For provider authors, `PaymentProvider` can declare: -- `credentialFields`: the label, accepted prefixes and help text for the settings form. +- `credentialFields`: the label, accepted prefixes and help text for the settings form. A `publicKey` field is shown only when declared, for on-page checkout that needs the browser key (Flutterwave Inline); `credentials.publicKey` carries the saved value. - `webhookHeaders`: the headers that identify its webhooks, besides `x--signature`. `verifyWebhook` receives every request header, and `credentials` (the provider's saved secret key and webhook secret) for headers signed with the API key rather than the webhook secret. - `checkConnection`: one read-only call with the saved keys, behind a "Test connection" button in Settings. Return `{ ok, message }`, with `ok: false` and a message the merchant can act on for a wrong or under-permitted key. diff --git a/packages/core/src/admin/pages/SettingsPage.tsx b/packages/core/src/admin/pages/SettingsPage.tsx index cf623d0..031fa27 100644 --- a/packages/core/src/admin/pages/SettingsPage.tsx +++ b/packages/core/src/admin/pages/SettingsPage.tsx @@ -132,16 +132,25 @@ interface ProviderRow { description?: string | null; logo?: string | null; brandColour?: string | null; - credentialFields?: { secretKey?: CredentialField; webhookSecret?: CredentialField }; + credentialFields?: { + secretKey?: CredentialField; + webhookSecret?: CredentialField; + publicKey?: CredentialField; + }; canCheckConnection?: boolean; - secrets?: { secretKey: SecretMeta; webhookSecret: SecretMeta }; + secrets?: { + secretKey: SecretMeta; + webhookSecret: SecretMeta; + /** Present only when the provider declares a public key. */ + publicKey?: SecretMeta; + }; /** Absent from servers before on-page checkout: treat as hosted only. */ checkoutStyles?: Array<"hosted" | "on_page">; } /** - * Fixed settings, plus `SecretKey` / `WebhookSecret` - * for registered non-Stripe providers. + * Fixed settings, plus `SecretKey` / `WebhookSecret` / + * `PublicKey` for registered non-Stripe providers. */ type Draft = Partial> & { [providerCredential: string]: unknown; @@ -580,6 +589,21 @@ function GroupBody({ setField={setField} disabled={disabled} /> + {selected.credentialFields?.publicKey && ( + + )} {selected.canCheckConnection && ( )} @@ -831,7 +855,7 @@ function SecretField({ setField, disabled, }: { - /** `stripeSecretKey`, `stripeWebhookSecret`, or a provider's `SecretKey` / `WebhookSecret`. */ + /** `stripeSecretKey`, `stripeWebhookSecret`, or a provider's `SecretKey` / `WebhookSecret` / `PublicKey`. */ keyName: string; label: string; description?: string; diff --git a/packages/core/src/payment-provider/credentials.ts b/packages/core/src/payment-provider/credentials.ts index 2b98ba0..6d6d75c 100644 --- a/packages/core/src/payment-provider/credentials.ts +++ b/packages/core/src/payment-provider/credentials.ts @@ -3,7 +3,8 @@ * * Stripe keeps the existing key names (`settings:stripeSecretKey` / * `settings:stripeWebhookSecret`). Other providers use - * `settings:SecretKey` and `settings:WebhookSecret`. + * `settings:SecretKey`, `settings:WebhookSecret` and, when they + * declare one, `settings:PublicKey`. */ import { getPaymentProvider } from "./registry"; @@ -26,7 +27,12 @@ export async function loadPaymentProviderCredentials( const secretKey = await kv.get(`settings:${providerId}SecretKey`); if (!secretKey) return null; const webhookSecret = (await kv.get(`settings:${providerId}WebhookSecret`)) ?? undefined; - return { secretKey, webhookSecret }; + const publicKey = (await kv.get(`settings:${providerId}PublicKey`)) ?? undefined; + return { + secretKey, + ...(webhookSecret ? { webhookSecret } : {}), + ...(publicKey ? { publicKey } : {}), + }; } export function webhookSignatureHeader(headers: Headers, providerId: string): string | null { @@ -40,7 +46,7 @@ export function webhookSignatureHeader(headers: Headers, providerId: string): st ); } -export type ProviderCredentialName = "secretKey" | "webhookSecret"; +export type ProviderCredentialName = "secretKey" | "webhookSecret" | "publicKey"; export interface ProviderCredentialSetting { providerId: string; @@ -48,7 +54,13 @@ export interface ProviderCredentialSetting { spec: PaymentProviderCredentialField; } -const PROVIDER_CREDENTIAL_KEY = /^([a-z][a-z0-9_-]{0,63})(SecretKey|WebhookSecret)$/; +const PROVIDER_CREDENTIAL_KEY = /^([a-z][a-z0-9_-]{0,63})(SecretKey|WebhookSecret|PublicKey)$/; + +const CREDENTIAL_FIELD: Record = { + SecretKey: "secretKey", + WebhookSecret: "webhookSecret", + PublicKey: "publicKey", +}; /** * If `key` (without the `settings:` prefix) is a credential setting of a @@ -58,9 +70,15 @@ const PROVIDER_CREDENTIAL_KEY = /^([a-z][a-z0-9_-]{0,63})(SecretKey|WebhookSecre export function providerCredentialSetting(key: string): ProviderCredentialSetting | undefined { const match = PROVIDER_CREDENTIAL_KEY.exec(key); const providerId = match?.[1]; - if (!match || !providerId || providerId === "stripe") return undefined; + const suffix = match?.[2]; + if (!match || !providerId || !suffix || providerId === "stripe") return undefined; const provider = getPaymentProvider(providerId); if (!provider) return undefined; - const field: ProviderCredentialName = match[2] === "SecretKey" ? "secretKey" : "webhookSecret"; + const field = CREDENTIAL_FIELD[suffix]; + if (!field) return undefined; + // Secret key and webhook secret are offered for every provider (Settings + // falls back to a generic label). A public key is only meaningful when the + // provider declares one, so don't accept one for a provider that doesn't. + if (field === "publicKey" && !provider.credentialFields?.publicKey) return undefined; return { providerId, field, spec: provider.credentialFields?.[field] ?? {} }; } diff --git a/packages/core/src/payment-provider/types.ts b/packages/core/src/payment-provider/types.ts index 006dd4e..c38c92f 100644 --- a/packages/core/src/payment-provider/types.ts +++ b/packages/core/src/payment-provider/types.ts @@ -264,6 +264,12 @@ export interface RefundResult { export interface PaymentProviderCredentials { secretKey: string; webhookSecret?: string; + /** + * The provider's browser-side public key, when it has one. Used by + * providers whose on-page checkout needs it in the browser (Flutterwave + * Inline). Never a secret, but saved with the same settings plumbing. + */ + publicKey?: string; } /** Subset of PluginContext a provider may use. */ @@ -353,11 +359,17 @@ export interface PaymentProvider { /** * Credentials the merchant enters in admin settings, saved as - * `settings:SecretKey` and `settings:WebhookSecret`. + * `settings:SecretKey`, `settings:WebhookSecret` and + * `settings:PublicKey`. */ readonly credentialFields?: { secretKey?: PaymentProviderCredentialField; webhookSecret?: PaymentProviderCredentialField; + /** + * The browser-side public key, for on-page checkout that needs one + * (Flutterwave Inline). Settings shows the field only when declared. + */ + publicKey?: PaymentProviderCredentialField; }; /** True if this provider can charge `currency` (ISO-4217). */ diff --git a/packages/core/src/routes/admin-api.ts b/packages/core/src/routes/admin-api.ts index f45cce3..f91cb47 100644 --- a/packages/core/src/routes/admin-api.ts +++ b/packages/core/src/routes/admin-api.ts @@ -186,6 +186,9 @@ async function providerSettingsRows(ctx: PluginContext) { secrets: { secretKey: await secretStatus(ctx, `${provider.id}SecretKey`), webhookSecret: await secretStatus(ctx, `${provider.id}WebhookSecret`), + ...(provider.credentialFields?.publicKey + ? { publicKey: await secretStatus(ctx, `${provider.id}PublicKey`) } + : {}), }, }); } diff --git a/packages/core/test/provider-credentials-settings.test.ts b/packages/core/test/provider-credentials-settings.test.ts index 13fbb82..1a47285 100644 --- a/packages/core/test/provider-credentials-settings.test.ts +++ b/packages/core/test/provider-credentials-settings.test.ts @@ -8,9 +8,9 @@ import { afterEach, describe, expect, it } from "bun:test"; import type { PluginContext, RouteContext } from "emdash"; import { + type PaymentProvider, createMockPaymentProvider, loadPaymentProviderCredentials, - type PaymentProvider, registerPaymentProvider, resetPaymentProviders, } from "../src/payment-provider"; @@ -30,6 +30,11 @@ function acme(): PaymentProvider { prefixes: ["awh_"], help: "From the dashboard", }, + publicKey: { + label: "Browser public key", + prefixes: ["apk_test_", "apk_"], + help: "Used by on-page checkout", + }, }, }; } @@ -51,14 +56,33 @@ describe("provider credentials in the settings API", () => { paymentProvider: "acme", acmeSecretKey: "ark_test_1234567890", acmeWebhookSecret: "awh_1234567890", + acmePublicKey: "apk_test_1234567890", }); expect(res).toEqual({ status: 200, body: { ok: true } }); expect(await loadPaymentProviderCredentials(ctx.kv, "acme")).toEqual({ secretKey: "ark_test_1234567890", webhookSecret: "awh_1234567890", + publicKey: "apk_test_1234567890", }); }); + it("validates the public key against its declared prefixes", async () => { + registerPaymentProvider(acme()); + const { ctx, kvStore } = makeRouteContext({}); + const res = await call(ctx, "POST", { acmePublicKey: "sk_live_wrong" }); + expect(res.status).toBe(400); + expect(String((res.body.errors as Record).acmePublicKey)).toContain("apk_"); + expect(kvStore.has("settings:acmePublicKey")).toBe(false); + }); + + it("refuses a public key for a provider that does not declare one", async () => { + registerPaymentProvider(createMockPaymentProvider({ id: "plain" })); + const { ctx } = makeRouteContext({}); + const res = await call(ctx, "POST", { plainPublicKey: "pk_123" }); + expect(res.status).toBe(400); + expect(Object.keys(res.body.errors as object)).toEqual(["plainPublicKey"]); + }); + it("refuses a value without a declared prefix", async () => { registerPaymentProvider(acme()); const { ctx, kvStore } = makeRouteContext({}); @@ -95,9 +119,11 @@ describe("provider credentials in the settings API", () => { const { ctx } = makeRouteContext({ "settings:paymentProvider": "acme", "settings:acmeSecretKey": "ak_test_abcd1234", + "settings:acmePublicKey": "apk_test_public5678", }); const { body } = await call(ctx, "GET"); expect(JSON.stringify(body)).not.toContain("ak_test_abcd1234"); + expect(JSON.stringify(body)).not.toContain("apk_test_public5678"); const providers = body._providers as Array>; expect(providers.map((p) => p.id)).toEqual(["stripe", "acme"]); const acmeRow = providers.find((p) => p.id === "acme"); @@ -114,14 +140,36 @@ describe("provider credentials in the settings API", () => { prefixes: ["awh_"], help: "From the dashboard", }, + publicKey: { + label: "Browser public key", + prefixes: ["apk_test_", "apk_"], + help: "Used by on-page checkout", + }, }, checkoutStyles: ["hosted"], canCheckConnection: false, secrets: { secretKey: { isSet: true, hint: "••••1234" }, webhookSecret: { isSet: false, hint: null }, + publicKey: { isSet: true, hint: "••••5678" }, + }, + }); + }); + + it("omits the public key row for providers that do not declare one", async () => { + registerPaymentProvider(createMockPaymentProvider({ id: "plain" })); + const { ctx } = makeRouteContext({}); + const providers = (await call(ctx, "GET")).body._providers as Array>; + expect(providers.find((p) => p.id === "plain")).toMatchObject({ + secrets: { + secretKey: { isSet: false, hint: null }, + webhookSecret: { isSet: false, hint: null }, }, }); + const plain = providers.find((p) => p.id === "plain") as { + secrets: Record; + }; + expect(plain.secrets.publicKey).toBeUndefined(); }); it("leaves Stripe's keys exactly as before", async () => { From 5e071313761c79c9cf04da340272b743a17cc4d2 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:39:15 +0100 Subject: [PATCH 04/50] feat(flutterwave): on-page checkout with Flutterwave Inline --- .changeset/flutterwave-on-page.md | 10 + packages/flutterwave/README.md | 26 +- packages/flutterwave/package.json | 4 + packages/flutterwave/src/checkout-client.ts | 137 +++++++++++ packages/flutterwave/src/provider.ts | 37 ++- .../flutterwave/test/core-integration.test.ts | 56 ++++- .../test/flutterwave-provider.test.ts | 78 +++++- packages/flutterwave/test/on-page.test.ts | 225 ++++++++++++++++++ packages/flutterwave/tsdown.config.ts | 3 +- 9 files changed, 562 insertions(+), 14 deletions(-) create mode 100644 .changeset/flutterwave-on-page.md create mode 100644 packages/flutterwave/src/checkout-client.ts create mode 100644 packages/flutterwave/test/on-page.test.ts diff --git a/.changeset/flutterwave-on-page.md b/.changeset/flutterwave-on-page.md new file mode 100644 index 0000000..fe4e4c5 --- /dev/null +++ b/.changeset/flutterwave-on-page.md @@ -0,0 +1,10 @@ +--- +"@dashcommerce/flutterwave": minor +--- + +On-page checkout with Flutterwave Inline. + +- Declares `checkoutStyles: ["hosted", "on_page"]` and a `publicKey` credential (`FLWPUBK_…`), saved by core as `settings:flutterwavePublicKey`. +- With checkout set to "On your page", `initCheckout` returns `on_page` with the public key, `tx_ref`, amount in major units and customer details. No server-side payment is created; Inline creates the transaction in the browser. +- New `./checkout-client` entry registers Flutterwave Inline on `window.DashCommerceCheckoutClients.flutterwave`, loads `checkout.flutterwave.com/v3.js` only when the customer presses Pay, and maps `callback`/`onclose` to finished/closed. Orders still come only from the signed webhook and the live verify. +- On-page checkout refuses to start, with a message naming the setting, when the public key is missing. diff --git a/packages/flutterwave/README.md b/packages/flutterwave/README.md index b1d0b18..8694a61 100644 --- a/packages/flutterwave/README.md +++ b/packages/flutterwave/README.md @@ -1,6 +1,6 @@ # @dashcommerce/flutterwave -A Flutterwave `PaymentProvider` for DashCommerce. Customers pay on Flutterwave's hosted checkout by card, M-Pesa or mobile money. DashCommerce creates the order when Flutterwave's signed `charge.completed` webhook arrives and the transaction is confirmed with Flutterwave. +A Flutterwave `PaymentProvider` for DashCommerce. Customers pay on Flutterwave's hosted checkout, or in Flutterwave Inline over the store's own checkout, by card, M-Pesa or mobile money. DashCommerce creates the order when Flutterwave's signed `charge.completed` webhook arrives and the transaction is confirmed with Flutterwave. > **Needs `@dashcommerce/core` 0.4.0 or later.** 0.4.0 is the first core release that can call `api.flutterwave.com`, save a second provider's keys, pass its webhook header to the provider and take refund updates. This package's first release, 0.1.0, goes out with it. @@ -22,7 +22,7 @@ A Flutterwave `PaymentProvider` for DashCommerce. Customers pay on Flutterwave's | Payment options | With no channel hint, Flutterwave shows every method enabled on the account. A hint is mapped to Flutterwave's option names, and generic `mobile_money` is resolved by currency (`KES` → `mpesa`, `GHS` → `mobilemoneyghana`, …) | | Customer details | Flutterwave's hosted page collects neither a shipping address nor a name for the store, so the provider leaves `collectsCustomerDetails` unset and DashCommerce's checkout asks for email and address before payment. The email is also required by `POST /v3/payments` | | Not supported | Coupons, split payments and subscriptions. `capabilities` declares all three as `false` | -| On-page checkout | Not offered. Flutterwave Inline needs the account's public key (`FLWPUBK-…`), which core's provider settings do not store; hosted checkout is the equivalent flow today | +| On-page checkout | With checkout set to "On your page", Flutterwave Inline opens over the store's checkout using the public key and `tx_ref` from create-session. `checkout.flutterwave.com/v3.js` loads only when the customer presses Pay. The modal's `callback`/`onclose` only move the customer; the order still comes from the signed webhook and a live verify. `redirect_url` is deliberately not passed, because Inline gives it precedence over `callback` | ## Webhook verification @@ -42,11 +42,12 @@ Flutterwave sends `charge.completed` for failed attempts too, with `data.status` Verified against Flutterwave's real test API with a Nigerian test account (KES wallet): -- `GET /v3/balances`, `POST /v3/payments` and a real KES 1,500 M-Pesa payment all worked. The payment was completed through Flutterwave Inline on `checkout-v3.flutterwave.com`, which proves the Inline path this package does not ship yet. +- `GET /v3/balances`, `POST /v3/payments` and a real KES 1,500 M-Pesa payment all worked. The payment was completed through Flutterwave Inline on `checkout-v3.flutterwave.com`, which is the path `./checkout-client` now ships. +- On-page, through this package's `./checkout-client`: Inline loaded from `checkout.flutterwave.com/v3.js` on Pay, completed a real KES 1,500 M-Pesa payment (transaction `10633614`), and the `callback` moved the page to `onFinished`. `getPaymentStatus` reported `succeeded` with `150000` minor units, and a KES 100 partial refund succeeded (refund `115045`). - `GET /v3/transactions/:id/verify` and `verify_by_reference?tx_ref=` both returned the payment, and the provider's `getPaymentStatus` reported `succeeded` with `150000` minor units for a `1500` KES charge. - A KES 500 partial refund succeeded with `status: "completed"`, and the `comments` tag came back exactly as sent. `meta.disburse_status` was `failed` in test mode, which is why the provider logs it. - The hosted link Flutterwave issued pointed at `checkout-v2.dev-flutterwave.com`, which Cloudflare blocked from this network. The production host `checkout.flutterwave.com` did not recognise that test link. If your test link is blocked too, use a different network or ask Flutterwave support; the API side is unaffected. -- The public key and the secret key do **not** share their hash segment, so the public key cannot be derived from the secret key. Inline needs the public key stored, which is the core change described in the issue. +- The public key and the secret key do **not** share their hash segment, so the public key is stored separately (`settings:flutterwavePublicKey`) and handed to the Inline client by create-session; it cannot be derived. ## Use @@ -76,10 +77,23 @@ Verified against Flutterwave's real test API with a Nigerian test account (KES w |---|---| | Secret key | Settings → API Keys. Test keys start `FLWSECK_TEST-`; live keys start `FLWSECK-` | | Secret hash | The secret hash you set under Settings → Webhooks. Flutterwave sends it back in `verif-hash` | + | Public key | Settings → API Keys. Only for on-page checkout (Inline); test keys start `FLWPUBK_TEST-`, live keys `FLWPUBK-`. It is safe to expose to the browser | Save, then press **Test Flutterwave connection**. It makes one read-only call (`GET /v3/balances`) and says whether Flutterwave accepts the key, in test or live mode. -5. **Set the webhook URL** in the Flutterwave dashboard, including `?provider=flutterwave`: + Under **How customers pay**, choose hosted (Flutterwave's page) or on your page (Inline). On-page checkout refuses to start if the public key is not saved. + +5. **For on-page checkout, load the browser client** in your checkout page's client script, so Vite bundles it: + + ```astro + + ``` + + If your site sends a Content-Security-Policy, allow `https://checkout.flutterwave.com` for scripts and frames. + +6. **Set the webhook URL** in the Flutterwave dashboard, including `?provider=flutterwave`: ``` https:///_emdash/api/plugins/dashcommerce/checkout/webhook?provider=flutterwave @@ -87,7 +101,7 @@ Verified against Flutterwave's real test API with a Nigerian test account (KES w Without the query, core picks the provider from the `verif-hash` header. That works today, but the query keeps Flutterwave's webhooks going to Flutterwave even if another provider later uses the same header. Enable **refund** webhooks as well, so `refund.updated` reaches the store. -6. **Use the same secret hash for every environment you point at the same site.** Flutterwave's dashboard has one webhook configuration; a test-mode delivery and a live-mode delivery both carry that value. +7. **Use the same secret hash for every environment you point at the same site.** Flutterwave's dashboard has one webhook configuration; a test-mode delivery and a live-mode delivery both carry that value. ## Develop diff --git a/packages/flutterwave/package.json b/packages/flutterwave/package.json index 61cda9a..d88f128 100644 --- a/packages/flutterwave/package.json +++ b/packages/flutterwave/package.json @@ -10,6 +10,10 @@ ".": { "import": "./dist/index.mjs", "types": "./dist/index.d.mts" + }, + "./checkout-client": { + "import": "./dist/checkout-client.mjs", + "types": "./dist/checkout-client.d.mts" } }, "files": ["dist", "README.md"], diff --git a/packages/flutterwave/src/checkout-client.ts b/packages/flutterwave/src/checkout-client.ts new file mode 100644 index 0000000..ad6f2e2 --- /dev/null +++ b/packages/flutterwave/src/checkout-client.ts @@ -0,0 +1,137 @@ +/** + * Browser side of Flutterwave on-page checkout (Flutterwave Inline). + * + * A storefront imports this once, in its checkout page's client script: + * + * import "@dashcommerce/flutterwave/checkout-client"; + * + * which registers the client on `window.DashCommerceCheckoutClients.flutterwave`. + * DashCommerce's checkout form calls it with the details from create-session. + * `checkout.flutterwave.com/v3.js` is loaded only then, never on page load. + * The callbacks only move the customer along: the order is created by the + * signed webhook and a live verify, never by the browser. + * + * Runs in the browser only; nothing here may be imported by the provider. + */ + +import type { OnPageCheckoutClient } from "@dashcommerce/core/payment-provider"; + +export const FLUTTERWAVE_INLINE_SCRIPT = "https://checkout.flutterwave.com/v3.js"; + +interface FlutterwaveCheckoutOptions { + public_key: string; + tx_ref: string; + amount: number; + currency: string; + customer: { email: string; name?: string; phone_number?: string }; + meta?: Record; + payment_options?: string; + callback?: (payment: unknown) => void; + onclose?: (incomplete: boolean) => void; +} + +interface FlutterwaveCheckoutInstance { + close?: () => void; +} + +type WindowWithFlutterwave = Window & { + FlutterwaveCheckout?: ( + options: FlutterwaveCheckoutOptions, + ) => FlutterwaveCheckoutInstance | undefined; + DashCommerceCheckoutClients?: Record; +}; + +/** Build the client for a given window and document (tests pass stand-ins). */ +export function createFlutterwaveCheckoutClient(win: Window, doc: Document): OnPageCheckoutClient { + const w = win as WindowWithFlutterwave; + let loading: Promise | null = null; + + function loadScript(): Promise { + if (w.FlutterwaveCheckout) return Promise.resolve(); + if (!loading) { + loading = new Promise((resolve, reject) => { + const script = doc.createElement("script"); + script.src = FLUTTERWAVE_INLINE_SCRIPT; + script.async = true; + script.onload = () => resolve(); + script.onerror = () => reject(new Error("script failed")); + doc.head.appendChild(script); + }).catch((err) => { + loading = null; // let a retry load it again + throw err; + }); + } + return loading; + } + + return { + open(client, callbacks) { + const publicKey = client.publicKey; + const txRef = client.txRef; + const currency = client.currency; + const email = client.customerEmail; + const amount = Number(client.amount); + if (!publicKey || !txRef || !currency || !email || !Number.isFinite(amount)) { + callbacks.onError("Flutterwave did not return the checkout details"); + return; + } + + loadScript().then( + () => { + if (!w.FlutterwaveCheckout) { + callbacks.onError("Could not load Flutterwave. Check your connection and try again."); + return; + } + // `redirect_url` takes precedence over `callback` in Inline, so it + // is deliberately omitted: the callback moves the customer. + let settled = false; + const finish = () => { + if (settled) return; + settled = true; + callbacks.onFinished(); + }; + const close = () => { + if (settled) return; + settled = true; + callbacks.onClosed(); + }; + try { + w.FlutterwaveCheckout({ + public_key: publicKey, + tx_ref: txRef, + amount, + currency, + customer: { + email, + ...(client.customerName ? { name: client.customerName } : {}), + ...(client.customerPhone ? { phone_number: client.customerPhone } : {}), + }, + ...(client.orderDraftId ? { meta: { orderDraftId: client.orderDraftId } } : {}), + ...(client.paymentOptions ? { payment_options: client.paymentOptions } : {}), + callback: () => finish(), + onclose: () => close(), + }); + } catch (err) { + callbacks.onError( + err instanceof Error ? err.message : "Flutterwave could not start the payment", + ); + } + }, + () => callbacks.onError("Could not load Flutterwave. Check your connection and try again."), + ); + }, + }; +} + +/** Put the Flutterwave client next to any other providers' clients. */ +export function registerFlutterwaveCheckoutClient(win: Window, doc: Document): void { + const w = win as WindowWithFlutterwave; + w.DashCommerceCheckoutClients = { + ...(w.DashCommerceCheckoutClients ?? {}), + flutterwave: createFlutterwaveCheckoutClient(win, doc), + }; +} + +if (typeof window !== "undefined" && typeof document !== "undefined") { + registerFlutterwaveCheckoutClient(window, document); +} diff --git a/packages/flutterwave/src/provider.ts b/packages/flutterwave/src/provider.ts index 3a8737e..7d95c34 100644 --- a/packages/flutterwave/src/provider.ts +++ b/packages/flutterwave/src/provider.ts @@ -453,8 +453,9 @@ export const flutterwavePaymentProvider: PaymentProvider = { brandColour: "#f5a623", description: "Card, M-Pesa and mobile money across Africa, settled in your local currency.", - // Hosted page only; Flutterwave Inline needs a public key core does not store. - checkoutStyles: ["hosted"], + // Hosted page, or Flutterwave Inline over the store's checkout + // (./checkout-client), which needs the account's public key. + checkoutStyles: ["hosted", "on_page"], webhookHeaders: ["verif-hash"], @@ -469,6 +470,11 @@ export const flutterwavePaymentProvider: PaymentProvider = { prefixes: [], help: "The secret hash you set under Settings → Webhooks. Flutterwave sends it back in the verif-hash header on every delivery.", }, + publicKey: { + label: "Flutterwave public key", + prefixes: ["FLWPUBK_TEST-", "FLWPUBK-"], + help: "Settings → API Keys. Only needed for on-page checkout (Flutterwave Inline); it is safe to expose to the browser.", + }, }, supportsCurrency(currency: string): boolean { @@ -505,6 +511,33 @@ export const flutterwavePaymentProvider: PaymentProvider = { const phone = input.customer.phone ?? address?.phone; const paymentOptions = mapPaymentOptions(input.preferredChannels, currency); + if (input.checkoutStyle === "on_page") { + const publicKey = credentials.publicKey?.trim(); + if (!publicKey) { + throw new Error( + "Flutterwave on-page checkout needs the public key; add it in Settings → Payment provider", + ); + } + // Inline creates the transaction in the browser, so there is no + // server-side /payments call. The order still comes only from the + // signed webhook and the live verify. + return { + kind: "on_page", + checkoutReference: checkoutRef, + client: { + publicKey, + txRef: checkoutRef, + amount: String(toMajorUnits(input.amount)), + currency, + customerEmail: email, + ...(name ? { customerName: name } : {}), + ...(phone ? { customerPhone: phone } : {}), + ...(paymentOptions ? { paymentOptions: paymentOptions.join(",") } : {}), + orderDraftId: input.orderDraftId, + }, + }; + } + const data = await call<{ link?: string }>(ctx, { client, path: "/payments", diff --git a/packages/flutterwave/test/core-integration.test.ts b/packages/flutterwave/test/core-integration.test.ts index 2ea3ec5..83ab47f 100644 --- a/packages/flutterwave/test/core-integration.test.ts +++ b/packages/flutterwave/test/core-integration.test.ts @@ -21,6 +21,7 @@ import { flutterwavePaymentProvider } from "../src/provider"; const SECRET_KEY = "FLWSECK_TEST-1234567890abcdef-X"; const SECRET_HASH = "flw-test-secret-hash"; +const PUBLIC_KEY = "FLWPUBK_TEST-1234567890abcdef-X"; function json(body: unknown, status = 200): Response { return new Response(JSON.stringify(body), { @@ -638,7 +639,56 @@ describe("@dashcommerce/flutterwave through core", () => { expect(flutterwave.refunds).toHaveLength(2); }); - it("saves Flutterwave keys through the settings API and refuses a public key", async () => { + it("returns Inline data in embedded mode and still creates the order from the webhook", async () => { + const flutterwave = fakeFlutterwave(); + const { ctx, getCol } = makeContext( + { + ...flutterwaveSettings, + "settings:checkoutMode": "embedded", + "settings:flutterwavePublicKey": PUBLIC_KEY, + }, + flutterwave.fetch, + ); + + const initRes = await startCheckout(ctx, "sess_flw_onpage_1"); + expect(initRes.status).toBe(200); + const body = (await initRes.json()) as { + kind: string; + client: Record; + returnUrl: string; + orderDraftId: string; + }; + expect(body.kind).toBe("on_page"); + expect(body.client.publicKey).toBe(PUBLIC_KEY); + expect(body.client.txRef).toBe(`dc-${body.orderDraftId}`); + expect(body.client.amount).toBe("1500"); + expect(body.client.customerEmail).toBe("supporter@example.com"); + expect(body.returnUrl).toContain(`/thank-you/${body.orderDraftId}`); + + // Inline creates the transaction in the browser, so the fake only learns + // about it when the signed webhook arrives. + const tx = { id: 777001, amountMinor: 150000, currency: "KES", status: "successful" }; + flutterwave.transactions.set(body.client.txRef ?? "", tx); + + const res = await deliverWebhook( + ctx, + chargeCompleted(body.client.txRef ?? "", body.orderDraftId, tx.id), + SECRET_HASH, + ); + expect(res.status).toBe(200); + expect(getCol("orders").size).toBe(1); + }); + + it("refuses embedded checkout when the public key is missing", async () => { + const flutterwave = fakeFlutterwave(); + const { ctx } = makeContext( + { ...flutterwaveSettings, "settings:checkoutMode": "embedded" }, + flutterwave.fetch, + ); + await expect(startCheckout(ctx, "sess_flw_onpage_2")).rejects.toThrow(/needs the public key/); + }); + + it("saves Flutterwave keys through the settings API and refuses a public key as a secret", async () => { const { ctx } = makeContext({}, fakeFlutterwave().fetch); const routeCtx = { request: new Request("http://test/admin/settings", { method: "POST" }), @@ -646,16 +696,18 @@ describe("@dashcommerce/flutterwave through core", () => { paymentProvider: "flutterwave", flutterwaveSecretKey: SECRET_KEY, flutterwaveWebhookSecret: SECRET_HASH, + flutterwavePublicKey: PUBLIC_KEY, }, } as unknown as import("emdash").RouteContext; const res = (await sandbox.routes["admin/settings"].handler(routeCtx, ctx)) as Response; expect(res.status).toBe(200); expect(await ctx.kv.get("settings:flutterwaveSecretKey")).toBe(SECRET_KEY); + expect(await ctx.kv.get("settings:flutterwavePublicKey")).toBe(PUBLIC_KEY); const bad = (await sandbox.routes["admin/settings"].handler( { request: new Request("http://test/admin/settings", { method: "POST" }), - input: { flutterwaveSecretKey: "FLWPUBK_TEST-1234567890abcdef-X" }, + input: { flutterwaveSecretKey: PUBLIC_KEY }, } as unknown as import("emdash").RouteContext, ctx, )) as Response; diff --git a/packages/flutterwave/test/flutterwave-provider.test.ts b/packages/flutterwave/test/flutterwave-provider.test.ts index cf67282..6691140 100644 --- a/packages/flutterwave/test/flutterwave-provider.test.ts +++ b/packages/flutterwave/test/flutterwave-provider.test.ts @@ -64,9 +64,9 @@ describe("flutterwavePaymentProvider", () => { const credentials = { secretKey: "FLWSECK_TEST-1234567890abcdef-X" }; describe("declared to core", () => { - it("is a hosted provider that claims the verif-hash header", () => { + it("is a hosted and on-page provider that claims the verif-hash header", () => { expect(flutterwavePaymentProvider.id).toBe("flutterwave"); - expect(flutterwavePaymentProvider.checkoutStyles).toEqual(["hosted"]); + expect(flutterwavePaymentProvider.checkoutStyles).toEqual(["hosted", "on_page"]); expect(flutterwavePaymentProvider.webhookHeaders).toEqual(["verif-hash"]); expect(flutterwavePaymentProvider.collectsCustomerDetails).toBeUndefined(); expect(flutterwavePaymentProvider.capabilities).toEqual({ @@ -76,10 +76,11 @@ describe("flutterwavePaymentProvider", () => { }); }); - it("accepts only Flutterwave secret keys and any secret hash", () => { + it("accepts Flutterwave secret keys, a public key and any secret hash", () => { const fields = flutterwavePaymentProvider.credentialFields; expect(fields?.secretKey?.prefixes).toEqual(["FLWSECK_TEST-", "FLWSECK-"]); expect(fields?.webhookSecret?.prefixes).toEqual([]); + expect(fields?.publicKey?.prefixes).toEqual(["FLWPUBK_TEST-", "FLWPUBK-"]); }); }); @@ -294,6 +295,77 @@ describe("flutterwavePaymentProvider", () => { flutterwavePaymentProvider.initCheckout(ctx, checkoutInput(), credentials), ).rejects.toThrow("Flutterwave did not return a hosted checkout link"); }); + + describe("on-page (Flutterwave Inline)", () => { + const withPublicKey = { ...credentials, publicKey: "FLWPUBK_TEST-abc123-X" }; + + it("returns the browser client data without calling the API", async () => { + let calls = 0; + const ctx = makeMockRuntimeContext(async () => { + calls++; + return flutterwaveOk({}); + }); + + const result = await flutterwavePaymentProvider.initCheckout( + ctx, + checkoutInput({ checkoutStyle: "on_page" }), + withPublicKey, + ); + + expect(calls).toBe(0); + expect(result.kind).toBe("on_page"); + if (result.kind !== "on_page") throw new Error("expected on_page"); + expect(result.checkoutReference).toBe("dc-0123456789abcdef0123456789abcdef"); + expect(result.client).toEqual({ + publicKey: "FLWPUBK_TEST-abc123-X", + txRef: "dc-0123456789abcdef0123456789abcdef", + amount: "2500", + currency: "KES", + customerEmail: "fan@example.com", + orderDraftId: "0123456789abcdef0123456789abcdef", + }); + }); + + it("passes the customer's name, phone and channel hints", async () => { + const ctx = makeMockRuntimeContext(async () => flutterwaveOk({})); + const result = await flutterwavePaymentProvider.initCheckout( + ctx, + checkoutInput({ + checkoutStyle: "on_page", + preferredChannels: ["card", "mpesa"], + customer: { email: "fan@example.com", phone: "+254700000000" }, + shippingAddress: { firstName: "Aidi", lastName: "Onyango" }, + }), + withPublicKey, + ); + if (result.kind !== "on_page") throw new Error("expected on_page"); + expect(result.client.customerName).toBe("Aidi Onyango"); + expect(result.client.customerPhone).toBe("+254700000000"); + expect(result.client.paymentOptions).toBe("card,mpesa"); + }); + + it("refuses on-page checkout without the public key", async () => { + const ctx = makeMockRuntimeContext(async () => flutterwaveOk({})); + await expect( + flutterwavePaymentProvider.initCheckout( + ctx, + checkoutInput({ checkoutStyle: "on_page" }), + credentials, + ), + ).rejects.toThrow(/needs the public key/); + }); + + it("still validates the cart before asking for a public key", async () => { + const ctx = makeMockRuntimeContext(async () => flutterwaveOk({})); + await expect( + flutterwavePaymentProvider.initCheckout( + ctx, + checkoutInput({ checkoutStyle: "on_page", currency: "JPY" }), + withPublicKey, + ), + ).rejects.toThrow(/does not support currency JPY/); + }); + }); }); describe("verifyWebhook", () => { diff --git a/packages/flutterwave/test/on-page.test.ts b/packages/flutterwave/test/on-page.test.ts new file mode 100644 index 0000000..746e10a --- /dev/null +++ b/packages/flutterwave/test/on-page.test.ts @@ -0,0 +1,225 @@ +/** + * Flutterwave on-page checkout: Inline, opened over the store's checkout + * with the public key and `tx_ref` from create-session. + */ + +import { describe, expect, it } from "bun:test"; +import { + FLUTTERWAVE_INLINE_SCRIPT, + createFlutterwaveCheckoutClient, + registerFlutterwaveCheckoutClient, +} from "../src/checkout-client"; + +interface InlineOptions { + public_key: string; + tx_ref: string; + amount: number; + currency: string; + customer: { email: string; name?: string; phone_number?: string }; + meta?: Record; + payment_options?: string; + callback?: (payment: unknown) => void; + onclose?: (incomplete: boolean) => void; +} + +/** A minimal browser stand-in: script tags "load" when the test says so. */ +function fakeBrowser() { + const appended: Array<{ src: string; onload?: () => void; onerror?: () => void }> = []; + const opened: InlineOptions[] = []; + const win: Record = {}; + const doc = { + createElement: () => + ({}) as { src: string; async?: boolean; onload?: () => void; onerror?: () => void }, + head: { + appendChild: (el: { src: string; onload?: () => void; onerror?: () => void }) => { + appended.push(el); + }, + }, + }; + return { + win, + doc, + appended, + opened, + loadScript() { + win.FlutterwaveCheckout = (options: InlineOptions) => { + opened.push(options); + return { close() {} }; + }; + for (const el of appended) el.onload?.(); + }, + failScript() { + for (const el of appended) el.onerror?.(); + }, + }; +} + +function recorder() { + const events: string[] = []; + return { + events, + callbacks: { + onFinished: () => events.push("finished"), + onClosed: () => events.push("closed"), + onError: (m: string) => events.push(`error:${m}`), + }, + }; +} + +const clientData = { + publicKey: "FLWPUBK_TEST-abc123-X", + txRef: "dc-0123456789abcdef0123456789abcdef", + amount: "2500", + currency: "KES", + customerEmail: "fan@example.com", + customerName: "Aidi Onyango", + customerPhone: "+254700000000", + paymentOptions: "card,mpesa", + orderDraftId: "0123456789abcdef0123456789abcdef", +}; + +describe("Flutterwave checkout client", () => { + it("loads v3.js only when opened, then starts Inline with the client data", async () => { + const b = fakeBrowser(); + const client = createFlutterwaveCheckoutClient( + b.win as unknown as Window, + b.doc as unknown as Document, + ); + expect(b.appended).toHaveLength(0); + + const r = recorder(); + client.open(clientData, r.callbacks); + expect(b.appended.map((s) => s.src)).toEqual([FLUTTERWAVE_INLINE_SCRIPT]); + b.loadScript(); + await Promise.resolve(); + await Promise.resolve(); + + expect(b.opened).toHaveLength(1); + const options = b.opened[0]; + if (!options) throw new Error("Inline was not opened"); + expect(options.public_key).toBe("FLWPUBK_TEST-abc123-X"); + expect(options.tx_ref).toBe(clientData.txRef); + expect(options.amount).toBe(2500); + expect(options.currency).toBe("KES"); + expect(options.customer).toEqual({ + email: "fan@example.com", + name: "Aidi Onyango", + phone_number: "+254700000000", + }); + expect(options.meta).toEqual({ orderDraftId: clientData.orderDraftId }); + expect(options.payment_options).toBe("card,mpesa"); + // redirect_url would take precedence over the callback, so it is omitted. + expect("redirect_url" in options).toBe(false); + + options.callback?.({ status: "successful" }); + expect(r.events).toEqual(["finished"]); + }); + + it("moves the customer on only once, even when onclose follows the callback", async () => { + const b = fakeBrowser(); + const client = createFlutterwaveCheckoutClient( + b.win as unknown as Window, + b.doc as unknown as Document, + ); + const r = recorder(); + client.open(clientData, r.callbacks); + b.loadScript(); + await Promise.resolve(); + await Promise.resolve(); + + const options = b.opened[0]; + if (!options) throw new Error("Inline was not opened"); + options.callback?.({}); + options.onclose?.(false); + expect(r.events).toEqual(["finished"]); + }); + + it("reports a closed modal as not completed", async () => { + const b = fakeBrowser(); + const client = createFlutterwaveCheckoutClient( + b.win as unknown as Window, + b.doc as unknown as Document, + ); + const r = recorder(); + client.open(clientData, r.callbacks); + b.loadScript(); + await Promise.resolve(); + await Promise.resolve(); + + b.opened[0]?.onclose?.(true); + expect(r.events).toEqual(["closed"]); + }); + + it("reuses the loaded script for a second attempt", async () => { + const b = fakeBrowser(); + const client = createFlutterwaveCheckoutClient( + b.win as unknown as Window, + b.doc as unknown as Document, + ); + const r = recorder(); + client.open(clientData, r.callbacks); + b.loadScript(); + await Promise.resolve(); + await Promise.resolve(); + client.open({ ...clientData, txRef: "dc-second" }, r.callbacks); + await Promise.resolve(); + await Promise.resolve(); + expect(b.appended).toHaveLength(1); + expect(b.opened.map((o) => o.tx_ref)).toEqual([clientData.txRef, "dc-second"]); + }); + + it("says so when the script can't load, and lets the customer retry", async () => { + const b = fakeBrowser(); + const client = createFlutterwaveCheckoutClient( + b.win as unknown as Window, + b.doc as unknown as Document, + ); + const r = recorder(); + client.open(clientData, r.callbacks); + b.failScript(); + await Promise.resolve(); + await Promise.resolve(); + expect(r.events[0]).toMatch(/^error:Could not load Flutterwave/); + + client.open(clientData, r.callbacks); + expect(b.appended).toHaveLength(2); + }); + + it("reports a throw from Inline instead of leaving the form spinning", async () => { + const b = fakeBrowser(); + const client = createFlutterwaveCheckoutClient( + b.win as unknown as Window, + b.doc as unknown as Document, + ); + b.win.FlutterwaveCheckout = () => { + throw new Error("bad key"); + }; + const r = recorder(); + client.open(clientData, r.callbacks); + await Promise.resolve(); + await Promise.resolve(); + expect(r.events).toEqual(["error:bad key"]); + }); + + it("refuses to open without the data Inline needs", () => { + const b = fakeBrowser(); + const client = createFlutterwaveCheckoutClient( + b.win as unknown as Window, + b.doc as unknown as Document, + ); + const r = recorder(); + client.open({ ...clientData, publicKey: "" }, r.callbacks); + expect(r.events).toEqual(["error:Flutterwave did not return the checkout details"]); + expect(b.appended).toHaveLength(0); + }); + + it("registers itself next to other providers' clients", () => { + const b = fakeBrowser(); + const other = { open() {} }; + b.win.DashCommerceCheckoutClients = { acme: other }; + registerFlutterwaveCheckoutClient(b.win as unknown as Window, b.doc as unknown as Document); + const clients = b.win.DashCommerceCheckoutClients as Record; + expect(clients.acme).toBe(other); + expect(typeof (clients.flutterwave as { open: unknown }).open).toBe("function"); + }); +}); diff --git a/packages/flutterwave/tsdown.config.ts b/packages/flutterwave/tsdown.config.ts index 5353ebc..9fb112a 100644 --- a/packages/flutterwave/tsdown.config.ts +++ b/packages/flutterwave/tsdown.config.ts @@ -1,7 +1,8 @@ import { defineConfig } from "tsdown"; export default defineConfig({ - entry: ["src/index.ts"], + // checkout-client is the browser entry (Flutterwave Inline); index is the provider. + entry: ["src/index.ts", "src/checkout-client.ts"], format: ["esm"], dts: true, clean: true, From 422fc821ff59adf8de5f6eb5da534d489d47950a Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:04:50 +0100 Subject: [PATCH 05/50] feat(core): split payments across vendor payout accounts --- .changeset/provider-split-allocations.md | 11 + packages/core/README.md | 1 + packages/core/src/admin/pages/VendorsPage.tsx | 288 ++++++++++++++++-- .../core/src/payment-provider/capabilities.ts | 2 + packages/core/src/payment-provider/index.ts | 1 + packages/core/src/payment-provider/types.ts | 26 ++ packages/core/src/routes/admin-api.ts | 171 ++++++++++- packages/core/src/routes/checkout.ts | 30 +- packages/core/src/types.ts | 20 ++ packages/core/src/vendors/provider-split.ts | 151 +++++++++ .../core/test/checkout-provider-split.test.ts | 175 +++++++++++ .../provider-credentials-settings.test.ts | 1 + packages/core/test/provider-split.test.ts | 220 +++++++++++++ .../core/test/vendor-payment-accounts.test.ts | 262 ++++++++++++++++ 14 files changed, 1325 insertions(+), 34 deletions(-) create mode 100644 .changeset/provider-split-allocations.md create mode 100644 packages/core/src/vendors/provider-split.ts create mode 100644 packages/core/test/checkout-provider-split.test.ts create mode 100644 packages/core/test/provider-split.test.ts create mode 100644 packages/core/test/vendor-payment-accounts.test.ts diff --git a/.changeset/provider-split-allocations.md b/.changeset/provider-split-allocations.md new file mode 100644 index 0000000..2d0572c --- /dev/null +++ b/.changeset/provider-split-allocations.md @@ -0,0 +1,11 @@ +--- +"@dashcommerce/core": minor +--- + +Let a payment provider split one payment across vendor payout accounts. + +- `capabilities.splits` and `InitCheckoutInput.allocations` / `platformRemainderMinor`. Core computes exact per-vendor minor amounts from trusted cart prices and the vendor's platform fee; a provider only routes them to the account reference core supplies. +- `Vendor.paymentAccounts`, keyed by provider id, for providers other than Stripe: `accountReference`, `status`, and an optional settlement currency and label. Stripe Connect keeps its existing fields. +- `admin/vendors/item` accepts `POST` to create a vendor without Stripe, and `PATCH` with `paymentAccount` / `paymentAccounts` to add, replace or remove a provider account. Vendor routes open when Connect is on **or** a split-capable provider is registered. +- Settings exposes each provider's `capabilities`. The Vendors page adds a vendor and edits payout accounts when a split-capable provider is active, without requiring Stripe. +- A vendor cart is refused with a readable 409 when the active provider cannot split, or when a vendor has no active account for it, instead of silently charging the platform account. diff --git a/packages/core/README.md b/packages/core/README.md index 5e9a141..3c6f4da 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -70,6 +70,7 @@ For provider authors, `PaymentProvider` can declare: - `credentialFields`: the label, accepted prefixes and help text for the settings form. - `webhookHeaders`: the headers that identify its webhooks, besides `x--signature`. `verifyWebhook` receives every request header, and `credentials` (the provider's saved secret key and webhook secret) for headers signed with the API key rather than the webhook secret. - `checkConnection`: one read-only call with the saved keys, behind a "Test connection" button in Settings. Return `{ ok, message }`, with `ok: false` and a message the merchant can act on for a wrong or under-permitted key. +- `capabilities.splits`: core computes `allocations` (`vendorId`, `accountReference`, `amountMinor`) and `platformRemainderMinor` when the cart has vendor-owned items. Vendors store their payout account under `paymentAccounts[providerId]`; the provider only routes the amounts core supplies. `parseWebhookEvent` may return `refund.updated` to move a pending refund to `succeeded` or `failed`. A failed refund stops counting against its order: the refunded total, payment status and order status are worked out again, and stock the refund put back is taken back off. diff --git a/packages/core/src/admin/pages/VendorsPage.tsx b/packages/core/src/admin/pages/VendorsPage.tsx index 1135908..efa6b5c 100644 --- a/packages/core/src/admin/pages/VendorsPage.tsx +++ b/packages/core/src/admin/pages/VendorsPage.tsx @@ -2,8 +2,9 @@ * Vendors admin page. * * When multi-vendor marketplace is disabled, this page renders a first-run - * empty state directing the operator to Settings. When enabled, it shows - * onboarding + list + inline edit for platform fee and Stripe refresh. + * empty state directing the operator to Settings. When enabled (Stripe + * Connect, or a provider that can split payments), it shows onboarding, the + * vendor list, and inline edit for the platform fee and payout accounts. */ import { useCallback, useEffect, useMemo, useState } from "react"; @@ -17,6 +18,7 @@ import { Loading, Money, NumberInput, + Select, Table, confirm, countryOptions, @@ -25,7 +27,7 @@ import { } from "../kit"; import { EmptyState } from "../ui/EmptyState"; import { StatusBadge } from "../ui/StatusBadge"; -import type { Vendor, VendorPayout } from "../../types"; +import type { Vendor, VendorPaymentAccount, VendorPayout } from "../../types"; import { T } from "../theme"; const STATUS_OPTIONS = [ @@ -38,6 +40,8 @@ const STATUS_OPTIONS = [ interface SettingsGateState { connectEnabled: boolean; defaultFeePercent: number; + /** Registered providers that can split a payment across vendor accounts. */ + splitsProviders: Array<{ id: string; label: string }>; } type PageState = "loading" | "disabled" | "ready" | "error"; @@ -60,9 +64,7 @@ export function VendorsPage() { const [payouts, setPayouts] = useState>({}); const [pending, setPending] = useState>({}); const [editing, setEditing] = useState<{ - vendorId: string; - name: string; - fee: number; + vendor: Vendor; } | null>(null); const loadVendors = useCallback(async () => { @@ -80,14 +82,25 @@ export function VendorsPage() { try { const settings = await api.get>("admin/settings"); const enabled = settings.connectEnabled === true; + const providers = Array.isArray(settings._providers) + ? (settings._providers as Array<{ + id: string; + label: string; + capabilities?: { splits?: boolean }; + }>) + : []; + const splitsProviders = providers + .filter((provider) => provider.capabilities?.splits === true) + .map((provider) => ({ id: provider.id, label: provider.label })); setGate({ connectEnabled: enabled, defaultFeePercent: typeof settings.connectPlatformFeePercent === "number" ? (settings.connectPlatformFeePercent as number) : 0, + splitsProviders, }); - if (!enabled) { + if (!enabled && splitsProviders.length === 0) { setPageState("disabled"); return; } @@ -125,7 +138,7 @@ export function VendorsPage() { - { - setLinkUrl(url); - await loadVendors(); - }} - /> + {gate?.connectEnabled ? ( + { + setLinkUrl(url); + await loadVendors(); + }} + /> + ) : gate && gate.splitsProviders.length > 0 ? ( + + ) : null} {linkUrl && ( @@ -261,9 +278,7 @@ export function VendorsPage() { size="sm" onClick={() => setEditing({ - vendorId: v.id, - name: v.name, - fee: v.platformFeePercent, + vendor: v, }) } > @@ -376,12 +391,13 @@ export function VendorsPage() { {editing && ( setEditing(null)} onSave={async (patch) => { try { await api.patch<{ vendor: Vendor }>( - `admin/vendors/item?id=${encodeURIComponent(editing.vendorId)}`, + `admin/vendors/item?id=${encodeURIComponent(editing.vendor.id)}`, patch, ); toast.success("Vendor updated"); @@ -519,17 +535,162 @@ function VendorOnboardingCard({ ); } +function ProviderVendorCard({ + gate, + api, + onSuccess, +}: { + gate: SettingsGateState; + api: ReturnType; + onSuccess: () => Promise; +}) { + const [name, setName] = useState(""); + const [email, setEmail] = useState(""); + const [fee, setFee] = useState(gate.defaultFeePercent); + const [providerId, setProviderId] = useState(gate.splitsProviders[0]?.id ?? ""); + const [accountReference, setAccountReference] = useState(""); + const [submitting, setSubmitting] = useState(false); + + const valid = + name.trim().length > 0 && + /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) && + typeof fee === "number" && + fee >= 0 && + fee <= 100 && + providerId.length > 0 && + accountReference.trim().length >= 4; + + async function add(): Promise { + if (!valid) return; + setSubmitting(true); + try { + await api.post("admin/vendors/item", { + name: name.trim(), + email: email.trim(), + platformFeePercent: fee ?? 0, + paymentAccount: { + providerId, + accountReference: accountReference.trim(), + status: "active", + }, + }); + toast.success("Vendor added"); + setName(""); + setEmail(""); + setAccountReference(""); + await onSuccess(); + } catch (err) { + toast.error("Could not add vendor", err instanceof Error ? err.message : undefined); + } finally { + setSubmitting(false); + } + } + + return ( + +

+ Paste the payout account id the provider gave you. For Flutterwave, create a collection + subaccount in the dashboard and use its RS_… id. +

+ + setName(e.currentTarget.value)} + placeholder="Acme Widgets" + disabled={submitting} + /> + + + setEmail(e.currentTarget.value)} + placeholder="ops@acme.example" + disabled={submitting} + /> + + {gate.splitsProviders.length > 1 && ( + + setAccountReference(e.currentTarget.value)} + placeholder="RS_…" + disabled={submitting} + /> + + + setFee(v ?? 0)} + min={0} + max={100} + step={0.1} + suffix="%" + disabled={submitting} + /> + + +
+ ); +} + +interface PaymentAccountDraft { + accountReference: string; + status: VendorPaymentAccount["status"]; +} + function EditVendorModal({ initial, + providers, onClose, onSave, }: { - initial: { vendorId: string; name: string; fee: number }; + initial: Vendor; + providers: Array<{ id: string; label: string }>; onClose: () => void; - onSave: (patch: { name?: string; platformFeePercent?: number }) => Promise; + onSave: (patch: { + name?: string; + platformFeePercent?: number; + paymentAccounts?: Array<{ + providerId: string; + accountReference: string | null; + status: VendorPaymentAccount["status"]; + }>; + }) => Promise; }) { const [name, setName] = useState(initial.name); - const [fee, setFee] = useState(initial.fee); + const [fee, setFee] = useState(initial.platformFeePercent); + const [accounts, setAccounts] = useState>(() => { + const out: Record = {}; + for (const provider of providers) { + const account = initial.paymentAccounts?.[provider.id]; + out[provider.id] = { + accountReference: account?.accountReference ?? "", + status: account?.status ?? "active", + }; + } + return out; + }); const [saving, setSaving] = useState(false); const isValid = name.trim().length > 0 && @@ -537,6 +698,17 @@ function EditVendorModal({ fee >= 0 && fee <= 100; + function setAccount(providerId: string, patch: Partial): void { + setAccounts((current) => ({ + ...current, + [providerId]: { + accountReference: current[providerId]?.accountReference ?? "", + status: current[providerId]?.status ?? "active", + ...patch, + }, + })); + } + return (

Edit vendor

@@ -586,6 +760,46 @@ function EditVendorModal({ disabled={saving} /> + {providers.map((provider) => ( +
+ + + setAccount(provider.id, { accountReference: e.currentTarget.value }) + } + placeholder="RS_…" + disabled={saving} + /> + + + { + setCountry(e.currentTarget.value); + setBankCode(""); + setAccountName(null); + }} + options={countries.map((c) => ({ value: c.value, label: c.label }))} + disabled={creating} + /> + + + { + setAccountNumber(e.currentTarget.value); + setAccountName(null); + }} + disabled={creating} + /> + + + {accountName && ( + + {accountName} + + )} + + setBusinessName(e.currentTarget.value)} + disabled={creating} + /> + + + setBusinessEmail(e.currentTarget.value)} + disabled={creating} + /> + + + setBusinessMobile(e.currentTarget.value)} + placeholder="+234…" + disabled={creating} + /> + + + - setAccount(provider.id, { accountReference: e.currentTarget.value }) - } - placeholder="RS_…" - disabled={saving} - /> - - - + setAccount(provider.id, { accountReference: e.currentTarget.value }) + } + placeholder="RS_…" + disabled={saving} + /> + + + setAccountReference(e.currentTarget.value)} - placeholder="RS_…" + placeholder="Account id" disabled={submitting} /> @@ -670,15 +703,26 @@ function PayoutAccountForm({ provider, vendor, api, + defaultFeePercent, + defaultCurrency, onChanged, }: { - provider: { id: string; label: string; payoutOnboarding: boolean }; + provider: { + id: string; + label: string; + payoutOnboarding: boolean; + payoutVerification: boolean; + }; vendor: Vendor; api: ReturnType; + defaultFeePercent: number; + defaultCurrency: string | null; onChanged: () => Promise; }) { const stored = vendor.paymentAccounts?.[provider.id]; - const [country, setCountry] = useState("NG"); + const initialCountry = + COUNTRY_BY_CURRENCY[(defaultCurrency ?? "").toUpperCase()] ?? "NG"; + const [country, setCountry] = useState(initialCountry); const [banks, setBanks] = useState | null>(null); const [bankCode, setBankCode] = useState(""); const [accountNumber, setAccountNumber] = useState(""); @@ -687,7 +731,9 @@ function PayoutAccountForm({ const [businessEmail, setBusinessEmail] = useState(vendor.email); const [businessMobile, setBusinessMobile] = useState(""); const [splitType, setSplitType] = useState<"percentage" | "flat">("percentage"); - const [splitValue, setSplitValue] = useState(vendor.platformFeePercent || 10); + const [splitValue, setSplitValue] = useState( + vendor.platformFeePercent > 0 ? vendor.platformFeePercent : defaultFeePercent, + ); const [verifying, setVerifying] = useState(false); const [creating, setCreating] = useState(false); const [removing, setRemoving] = useState(false); @@ -724,7 +770,12 @@ function PayoutAccountForm({ {stored.bankName ?? stored.bankCode} {stored.maskedAccountNumber ? ` ${stored.maskedAccountNumber}` : ""} ·{" "} {stored.status} + {stored.verified === false ? " · unverified" : ""} +

+ Removing it here detaches the account from this vendor in DashCommerce. The + account at the provider is unchanged. +

); } + const requiresVerification = provider.payoutVerification; const valid = country.length === 2 && bankCode.length > 0 && @@ -759,7 +811,7 @@ function PayoutAccountForm({ businessName.trim().length > 0 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(businessEmail) && businessMobile.trim().length > 0 && - accountName !== null && + (!requiresVerification || accountName !== null) && typeof splitValue === "number" && splitValue >= 0 && (splitType === "flat" ? splitValue > 0 : splitValue <= 100); @@ -826,18 +878,27 @@ function PayoutAccountForm({ disabled={creating} /> - - { @@ -847,16 +908,25 @@ function PayoutAccountForm({ disabled={creating} /> - - {accountName && ( - - {accountName} + {requiresVerification ? ( + <> + + {accountName && ( + + {accountName} + + )} + + ) : ( + + This provider cannot verify account names here. The account will be saved as + unverified. )} @@ -925,13 +995,22 @@ function EditVendorModal({ initial, providers, api, + defaultFeePercent, + defaultCurrency, onClose, onSave, onChanged, }: { initial: Vendor; - providers: Array<{ id: string; label: string; payoutOnboarding: boolean }>; + providers: Array<{ + id: string; + label: string; + payoutOnboarding: boolean; + payoutVerification: boolean; + }>; api: ReturnType; + defaultFeePercent: number; + defaultCurrency: string | null; onClose: () => void; onSave: (patch: { name?: string; @@ -1033,6 +1112,8 @@ function EditVendorModal({ provider={provider} vendor={initial} api={api} + defaultFeePercent={defaultFeePercent} + defaultCurrency={defaultCurrency} onChanged={onChanged} /> ) : ( @@ -1046,14 +1127,14 @@ function EditVendorModal({ > setAccount(provider.id, { accountReference: e.currentTarget.value }) } - placeholder="RS_…" + placeholder="Account id" disabled={saving} /> diff --git a/packages/core/src/payment-provider/types.ts b/packages/core/src/payment-provider/types.ts index a26c838..f6b5fbc 100644 --- a/packages/core/src/payment-provider/types.ts +++ b/packages/core/src/payment-provider/types.ts @@ -377,7 +377,10 @@ export interface CreatePayoutAccountInput { /** What a provider returns after creating a vendor payout account. */ export interface CreatedPayoutAccount { accountReference: string; - accountName: string; + /** Absent when the provider cannot resolve account names. */ + accountName?: string; + /** False when the provider created the account but has not verified it. */ + verified?: boolean; bankName?: string; bankCode?: string; country?: string; diff --git a/packages/core/src/routes/admin-api.ts b/packages/core/src/routes/admin-api.ts index 73ffa77..79feb7c 100644 --- a/packages/core/src/routes/admin-api.ts +++ b/packages/core/src/routes/admin-api.ts @@ -207,6 +207,7 @@ async function providerSettingsRows(ctx: PluginContext) { checkoutStyles: providerCheckoutStyles(provider), canCheckConnection: typeof provider.checkConnection === "function", payoutOnboarding: typeof provider.createPayoutAccount === "function", + payoutVerification: typeof provider.resolvePayoutAccount === "function", secrets: { secretKey: await secretStatus(ctx, `${provider.id}SecretKey`), webhookSecret: await secretStatus(ctx, `${provider.id}WebhookSecret`), @@ -1643,6 +1644,7 @@ async function createProviderPayoutAccount( 400, ); } + const canVerify = typeof provider.resolvePayoutAccount === "function"; const credentials = await loadPaymentProviderCredentials(ctx.kv, providerId); if (!credentials) { return json({ error: `Payment provider "${providerId}" is not configured` }, 400); @@ -1686,14 +1688,15 @@ async function createProviderPayoutAccount( if (!created.accountReference?.trim()) { return json({ error: "Provider returned no account reference" }, 502); } - if (!created.accountName?.trim()) { + if (canVerify && !created.accountName?.trim()) { return json({ error: "Provider returned no account name" }, 502); } const now = new Date().toISOString(); const account: VendorPaymentAccount = { accountReference: created.accountReference.trim(), status: "active", - accountName: created.accountName.trim(), + ...(created.accountName ? { accountName: created.accountName.trim() } : {}), + verified: created.verified ?? canVerify, ...(created.bankName ? { bankName: created.bankName } : {}), bankCode: created.bankCode ?? bankCode, country: created.country ?? country, diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index 818664b..e213673 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -547,6 +547,8 @@ export interface VendorPaymentAccount { status: "active" | "pending" | "disabled"; /** Account holder name returned by the provider's account resolution. */ accountName?: string; + /** False when the provider created the account but has not verified it. */ + verified?: boolean; bankName?: string; bankCode?: string; /** ISO-2 country of the payout account. */ diff --git a/packages/core/test/provider-credentials-settings.test.ts b/packages/core/test/provider-credentials-settings.test.ts index 9f8ea5d..289d682 100644 --- a/packages/core/test/provider-credentials-settings.test.ts +++ b/packages/core/test/provider-credentials-settings.test.ts @@ -119,6 +119,7 @@ describe("provider credentials in the settings API", () => { capabilities: {}, canCheckConnection: false, payoutOnboarding: false, + payoutVerification: false, secrets: { secretKey: { isSet: true, hint: "••••1234" }, webhookSecret: { isSet: false, hint: null }, diff --git a/packages/core/test/provider-payout-onboarding.test.ts b/packages/core/test/provider-payout-onboarding.test.ts index 25aacb2..c2350a9 100644 --- a/packages/core/test/provider-payout-onboarding.test.ts +++ b/packages/core/test/provider-payout-onboarding.test.ts @@ -121,6 +121,7 @@ describe("provider payout onboarding", () => { expect(saved.paymentAccounts?.flw).toMatchObject({ accountReference: "RS_TEST", status: "active", + verified: true, accountName: "Name for 0690000031", bankName: "Access Bank", bankCode: "044", @@ -193,6 +194,63 @@ describe("provider payout onboarding", () => { expect(badFlat.status).toBe(400); }); + it("creates an unverified account when the provider cannot resolve names", async () => { + registerPaymentProvider({ + ...createMockPaymentProvider({ id: "flw" }), + label: "Flutterwave", + capabilities: { splits: true }, + async createPayoutAccount() { + return { + accountReference: "RS_UNVERIFIED", + bankName: "Access Bank", + bankCode: "044", + country: "NG", + maskedAccountNumber: "••••0031", + }; + }, + }); + const { ctx, getCol } = makeRouteContext({ "settings:flwSecretKey": "test-key" }); + getCol("vendors").set("v1", vendor()); + + const res = await call(ctx, "admin/vendors/payout-account", "POST", createInput); + expect(res.status).toBe(201); + const account = (res.body.vendor as Vendor).paymentAccounts?.flw; + expect(account?.accountReference).toBe("RS_UNVERIFIED"); + expect(account?.accountName).toBeUndefined(); + expect(account?.verified).toBe(false); + }); + + it("stores an active-but-unverified account the provider reports", async () => { + registerPaymentProvider({ + ...createMockPaymentProvider({ id: "flw" }), + label: "Flutterwave", + capabilities: { splits: true }, + async resolvePayoutAccount() { + return { accountName: "Bale Gary" }; + }, + async createPayoutAccount() { + return { + accountReference: "RS_ACTIVE_UNVERIFIED", + accountName: "Bale Gary", + verified: false, + bankName: "Access Bank", + bankCode: "044", + country: "NG", + maskedAccountNumber: "••••0031", + }; + }, + }); + const { ctx, getCol } = makeRouteContext({ "settings:flwSecretKey": "test-key" }); + getCol("vendors").set("v1", vendor()); + + const res = await call(ctx, "admin/vendors/payout-account", "POST", createInput); + expect(res.status).toBe(201); + const account = (res.body.vendor as Vendor).paymentAccounts?.flw; + expect(account?.status).toBe("active"); + expect(account?.verified).toBe(false); + expect(account?.accountName).toBe("Bale Gary"); + }); + it("is gated like the other vendor routes", async () => { const { ctx } = makeRouteContext({}); const res = await call(ctx, "admin/vendors/payout-banks", "GET"); @@ -206,5 +264,6 @@ describe("provider payout onboarding", () => { const providers = res.body._providers as Array>; const row = providers.find((provider) => provider.id === "flw"); expect(row?.payoutOnboarding).toBe(true); + expect(row?.payoutVerification).toBe(true); }); }); From 3b3e52189f3635bdf0b8eed794893ceaf382bfb3 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:29:39 +0100 Subject: [PATCH 19/50] fix(flutterwave): make payout onboarding idempotent --- .changeset/flutterwave-provider.md | 2 +- packages/flutterwave/README.md | 2 +- packages/flutterwave/src/provider.ts | 139 +++++++++++------- .../test/payout-onboarding.test.ts | 72 +++++++++ 4 files changed, 159 insertions(+), 56 deletions(-) diff --git a/.changeset/flutterwave-provider.md b/.changeset/flutterwave-provider.md index 2d9baf3..181b85a 100644 --- a/.changeset/flutterwave-provider.md +++ b/.changeset/flutterwave-provider.md @@ -9,7 +9,7 @@ New package: a Flutterwave payment provider for DashCommerce, built on core's Pa - Orders only from a signed `charge.completed`, confirmed with a live verify. `verif-hash` is checked in constant time against the secret hash; repeat and overlapping deliveries are deduplicated. - Refunds by transaction id or `tx_ref`, guarded against duplicates on retry, with Flutterwave's refund webhook moving each refund to succeeded or failed. - Split payments: core's exact per-vendor allocations map to `subaccounts` with `flat_subaccount`, for hosted and Inline. The subaccount default may be percentage or flat; the transaction override keeps the shares exact. -- In-admin vendor onboarding: list banks, verify the account name, create the collection subaccount, and store the masked result. +- In-admin vendor onboarding: list banks or mobile-money channels, verify the account name, create the collection subaccount, and store the masked result. Re-adding the same bank account returns the existing subaccount instead of failing. - Cart discounts: `capabilities.coupons` is true; the discount is applied to the amount Flutterwave charges. - Split reconciliation: parses `meta.split_settlement_info` and `app_fee` into core's `splitSettlement`, so the order records what each subaccount earned. - "Test Flutterwave connection" checks the saved key in test or live mode with a read-only balances call. diff --git a/packages/flutterwave/README.md b/packages/flutterwave/README.md index 9135a9e..b238832 100644 --- a/packages/flutterwave/README.md +++ b/packages/flutterwave/README.md @@ -23,7 +23,7 @@ A Flutterwave `PaymentProvider` for DashCommerce. Customers pay on Flutterwave's | Customer details | Flutterwave's hosted page collects neither a shipping address nor a name for the store, so the provider leaves `collectsCustomerDetails` unset and DashCommerce's checkout asks for email and address before payment. The email is also required by `POST /v3/payments` | | Not supported | Subscriptions. `capabilities` declares `subscriptions: false` | | Discounts | Cart discounts are applied to the amount Flutterwave charges, so `capabilities.coupons` is `true`. No provider-side coupon object is created; the customer sees the net total on Flutterwave's page | -| Vendor onboarding | In Vendors, choose the country and bank, enter the account number, **verify the account name**, then create the collection subaccount. The full account number is never stored; the `RS_…` id, resolved name, bank and last four are. A manually created `RS_…` id can still be pasted in | +| Vendor onboarding | In Vendors, choose the country and bank or mobile-money channel, enter the account or mobile number, **verify the account name**, then create the collection subaccount. The full account number is never stored; the `RS_…` id, resolved name, bank and last four are. Re-adding the same bank account returns Flutterwave's existing subaccount instead of failing with "already exists", so a retry is safe. A manually created `RS_…` id can still be pasted in | | On-page checkout | With checkout set to "On your page", Flutterwave Inline opens over the store's checkout using the public key and `tx_ref` from create-session. `checkout.flutterwave.com/v3.js` loads only when the customer presses Pay. The modal's `callback`/`onclose` only move the customer; the order still comes from the signed webhook and a live verify. `redirect_url` is deliberately not passed, because Inline gives it precedence over `callback` | | Split payments | When the cart has vendor-owned items, core sends exact per-vendor minor amounts (`allocations`); the package maps each to `subaccounts: [{ id, transaction_charge_type: "flat_subaccount", transaction_charge }]` for hosted and Inline. Each vendor receives exactly the amount core computed. The subaccount's default `split_type` can be percentage or flat, but DashCommerce overrides it per payment so the shares stay exact. A vendor without an active account blocks checkout with a 409 rather than settling everything to the platform | diff --git a/packages/flutterwave/src/provider.ts b/packages/flutterwave/src/provider.ts index 4e3093f..29c5431 100644 --- a/packages/flutterwave/src/provider.ts +++ b/packages/flutterwave/src/provider.ts @@ -216,6 +216,38 @@ function subaccountsFor(input: InitCheckoutInput): FlutterwaveSubaccount[] | und return subaccounts; } +interface FlutterwavePayoutSubaccount { + id?: number; + account_number?: string; + account_bank?: string; + full_name?: string; + subaccount_id?: string; + bank_name?: string; + country?: string; +} + +function createdPayoutAccount( + data: FlutterwavePayoutSubaccount, + accountNumber: string, + bankCode: string, + country: string, +): CreatedPayoutAccount { + const accountReference = data?.subaccount_id?.trim(); + if (!accountReference) throw new Error("Flutterwave returned no subaccount id"); + const accountName = data?.full_name?.trim(); + if (!accountName) throw new Error("Flutterwave returned no account name for the subaccount"); + return { + accountReference, + accountName, + verified: true, + ...(data.bank_name ? { bankName: data.bank_name } : {}), + bankCode: data.account_bank?.trim() || bankCode, + country: data.country?.trim().toUpperCase() || country, + maskedAccountNumber: accountNumber.length > 4 ? `••••${accountNumber.slice(-4)}` : "••••", + ...(typeof data.id === "number" ? { metadata: { providerAccountId: String(data.id) } } : {}), + }; +} + function channelLabel(type: string | undefined): string | undefined { if (!type) return undefined; const value = type.toLowerCase(); @@ -954,62 +986,61 @@ export const flutterwavePaymentProvider: PaymentProvider = { throw new Error("Flutterwave flat split value must be positive"); } - const data = await call<{ - id?: number; - account_number?: string; - account_bank?: string; - full_name?: string; - subaccount_id?: string; - bank_name?: string; - split_type?: string; - split_value?: number; - }>(ctx, { - client: toFlutterwaveClient(credentials), - path: "/subaccounts", - body: { - account_bank: bankCode, + let data: FlutterwavePayoutSubaccount; + try { + data = await call(ctx, { + client: toFlutterwaveClient(credentials), + path: "/subaccounts", + body: { + account_bank: bankCode, + account_number: accountNumber, + business_name: businessName, + business_email: businessEmail, + business_mobile: businessMobile, + country, + split_type: splitType, + split_value: splitValue, + ...(input.businessContact ? { business_contact: input.businessContact } : {}), + ...(input.businessContactMobile + ? { business_contact_mobile: input.businessContactMobile } + : {}), + ...(input.metadata + ? { + meta: Object.entries(input.metadata).map(([meta_name, meta_value]) => ({ + meta_name, + meta_value, + })), + } + : {}), + }, + }); + } catch (err) { + // Flutterwave rejects a second subaccount for the same bank account. + // Return the existing one so a retry or a re-add is idempotent. + if (!(err instanceof FlutterwaveApiError) || !/already exists/i.test(err.message)) { + throw err; + } + const query = new URLSearchParams({ account_number: accountNumber, - business_name: businessName, - business_email: businessEmail, - business_mobile: businessMobile, - country, - split_type: splitType, - split_value: splitValue, - ...(input.businessContact ? { business_contact: input.businessContact } : {}), - ...(input.businessContactMobile - ? { business_contact_mobile: input.businessContactMobile } - : {}), - ...(input.metadata - ? { - meta: Object.entries(input.metadata).map(([meta_name, meta_value]) => ({ - meta_name, - meta_value, - })), - } - : {}), - }, - }); - - const accountReference = data?.subaccount_id?.trim(); - if (!accountReference) { - throw new Error("Flutterwave returned no subaccount id"); - } - const accountName = data?.full_name?.trim(); - if (!accountName) { - throw new Error("Flutterwave returned no account name for the subaccount"); + account_bank: bankCode, + }); + const existing = await call(ctx, { + client: toFlutterwaveClient(credentials), + method: "GET", + path: `/subaccounts?${query}`, + }); + const match = Array.isArray(existing) + ? (existing.find( + (subaccount) => + subaccount.account_number === accountNumber && + subaccount.account_bank === bankCode, + ) ?? existing[0]) + : undefined; + if (!match) throw err; + return createdPayoutAccount(match, accountNumber, bankCode, country); } - return { - accountReference, - accountName, - ...(data.bank_name ? { bankName: data.bank_name } : {}), - bankCode: data.account_bank?.trim() || bankCode, - country, - maskedAccountNumber: - accountNumber.length > 4 ? `••••${accountNumber.slice(-4)}` : "••••", - ...(typeof data.id === "number" - ? { metadata: { providerAccountId: String(data.id) } } - : {}), - }; + + return createdPayoutAccount(data, accountNumber, bankCode, country); }, async getPaymentStatus( diff --git a/packages/flutterwave/test/payout-onboarding.test.ts b/packages/flutterwave/test/payout-onboarding.test.ts index 2fecc7d..a655012 100644 --- a/packages/flutterwave/test/payout-onboarding.test.ts +++ b/packages/flutterwave/test/payout-onboarding.test.ts @@ -20,6 +20,14 @@ function ok(data: unknown): Response { describe("Flutterwave payout onboarding", () => { const credentials = { secretKey: "FLWSECK_TEST-1234567890abcdef-X" }; + const baseInput = { + accountNumber: "0690000031", + bankCode: "044", + country: "NG", + businessName: "Vendor One", + businessEmail: "v1@example.com", + businessMobile: "09087930450", + }; it("lists the banks for a country, dropping malformed rows", async () => { let requested = ""; @@ -108,6 +116,7 @@ describe("Flutterwave payout onboarding", () => { expect(created).toEqual({ accountReference: "RS_TEST", accountName: "Forrest Green", + verified: true, bankName: "ACCESS BANK NIGERIA", bankCode: "044", country: "NG", @@ -116,6 +125,69 @@ describe("Flutterwave payout onboarding", () => { }); }); + it("returns the existing subaccount when Flutterwave says it already exists", async () => { + let listCalls = 0; + const ctx = makeCtx(async (url, init) => { + const { pathname, searchParams } = new URL(url); + if (pathname !== "/v3/subaccounts") { + return new Response("{}", { status: 404 }); + } + if (init?.method === "POST") { + return new Response( + JSON.stringify({ + status: "error", + message: "A subaccount with the account number and bank already exists", + data: null, + }), + { status: 400, headers: { "Content-Type": "application/json" } }, + ); + } + listCalls += 1; + expect(searchParams.get("account_number")).toBe("0690000031"); + expect(searchParams.get("account_bank")).toBe("044"); + return ok([ + { + id: 27708, + account_number: "0690000031", + account_bank: "044", + full_name: "Forrest Green", + subaccount_id: "RS_EXISTING", + bank_name: "ACCESS BANK NIGERIA", + country: "NG", + }, + ]); + }); + + const created = await flutterwavePaymentProvider.createPayoutAccount?.( + ctx, + baseInput, + credentials, + ); + expect(listCalls).toBe(1); + expect(created?.accountReference).toBe("RS_EXISTING"); + expect(created?.verified).toBe(true); + }); + + it("does not hide a non-duplicate Flutterwave error", async () => { + let listCalls = 0; + const ctx = makeCtx(async (url, init) => { + const { pathname } = new URL(url); + if (pathname === "/v3/subaccounts" && init?.method === "POST") { + return new Response( + JSON.stringify({ status: "error", message: "Application error", data: null }), + { status: 500, headers: { "Content-Type": "application/json" } }, + ); + } + listCalls += 1; + return ok([]); + }); + + await expect( + flutterwavePaymentProvider.createPayoutAccount?.(ctx, baseInput, credentials), + ).rejects.toThrow(/Application error/); + expect(listCalls).toBe(0); + }); + it("validates the split and the required business fields", async () => { const ctx = makeCtx(async () => ok({})); const base = { From 0ed388b5b589d3c61c19f9d1b35b9ccb164663af Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:30:29 +0100 Subject: [PATCH 20/50] fix(flutterwave): match existing subaccounts without relying on error text --- packages/flutterwave/src/provider.ts | 27 ++++++++++++------- .../test/payout-onboarding.test.ts | 17 ++++++++++++ 2 files changed, 35 insertions(+), 9 deletions(-) diff --git a/packages/flutterwave/src/provider.ts b/packages/flutterwave/src/provider.ts index 29c5431..5a24fc9 100644 --- a/packages/flutterwave/src/provider.ts +++ b/packages/flutterwave/src/provider.ts @@ -1016,25 +1016,34 @@ export const flutterwavePaymentProvider: PaymentProvider = { }); } catch (err) { // Flutterwave rejects a second subaccount for the same bank account. - // Return the existing one so a retry or a re-add is idempotent. - if (!(err instanceof FlutterwaveApiError) || !/already exists/i.test(err.message)) { + // Return the existing one so a retry or a re-add is idempotent. Match + // on the account, not the error text, which Flutterwave may reword. + if ( + !(err instanceof FlutterwaveApiError) || + (err.status !== 400 && err.status !== 409) + ) { throw err; } const query = new URLSearchParams({ account_number: accountNumber, account_bank: bankCode, }); - const existing = await call(ctx, { - client: toFlutterwaveClient(credentials), - method: "GET", - path: `/subaccounts?${query}`, - }); + let existing: FlutterwavePayoutSubaccount[]; + try { + existing = await call(ctx, { + client: toFlutterwaveClient(credentials), + method: "GET", + path: `/subaccounts?${query}`, + }); + } catch { + throw err; + } const match = Array.isArray(existing) - ? (existing.find( + ? existing.find( (subaccount) => subaccount.account_number === accountNumber && subaccount.account_bank === bankCode, - ) ?? existing[0]) + ) : undefined; if (!match) throw err; return createdPayoutAccount(match, accountNumber, bankCode, country); diff --git a/packages/flutterwave/test/payout-onboarding.test.ts b/packages/flutterwave/test/payout-onboarding.test.ts index a655012..c854cd6 100644 --- a/packages/flutterwave/test/payout-onboarding.test.ts +++ b/packages/flutterwave/test/payout-onboarding.test.ts @@ -168,6 +168,23 @@ describe("Flutterwave payout onboarding", () => { expect(created?.verified).toBe(true); }); + it("rethrows a 400 when no existing subaccount matches", async () => { + const ctx = makeCtx(async (url, init) => { + const { pathname } = new URL(url); + if (pathname === "/v3/subaccounts" && init?.method === "POST") { + return new Response( + JSON.stringify({ status: "error", message: "Invalid bank code", data: null }), + { status: 400, headers: { "Content-Type": "application/json" } }, + ); + } + return ok([]); + }); + + await expect( + flutterwavePaymentProvider.createPayoutAccount?.(ctx, baseInput, credentials), + ).rejects.toThrow(/Invalid bank code/); + }); + it("does not hide a non-duplicate Flutterwave error", async () => { let listCalls = 0; const ctx = makeCtx(async (url, init) => { From e6095c10bfd752b956a0663b39edcb34dea5f034 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:04:52 +0100 Subject: [PATCH 21/50] feat(core): make split refunds explicit --- .changeset/provider-split-refunds.md | 9 ++ .../core/src/admin/pages/OrderDetailPage.tsx | 5 + packages/core/src/orders/refund.ts | 5 + packages/core/src/payment-provider/types.ts | 8 + .../core/test/provider-split-refund.test.ts | 139 ++++++++++++++++++ 5 files changed, 166 insertions(+) create mode 100644 .changeset/provider-split-refunds.md create mode 100644 packages/core/test/provider-split-refund.test.ts diff --git a/.changeset/provider-split-refunds.md b/.changeset/provider-split-refunds.md new file mode 100644 index 0000000..e6d3bb4 --- /dev/null +++ b/.changeset/provider-split-refunds.md @@ -0,0 +1,9 @@ +--- +"@dashcommerce/core": minor +--- + +Make split refunds explicit. + +- `PaymentProviderCapabilities.splitRefunds` lets a provider declare that its API cannot refund a split charge. Missing means yes, preserving Stripe Connect behaviour. +- `refundOrder` refuses a split order before calling a provider that declares `splitRefunds: false`, with a message pointing to the provider's dashboard. +- The order detail's **Split settlement** card warns that a refund comes from the platform balance and that vendor shares are not recovered automatically. diff --git a/packages/core/src/admin/pages/OrderDetailPage.tsx b/packages/core/src/admin/pages/OrderDetailPage.tsx index df2e8e0..b89d0e2 100644 --- a/packages/core/src/admin/pages/OrderDetailPage.tsx +++ b/packages/core/src/admin/pages/OrderDetailPage.tsx @@ -328,6 +328,11 @@ function SplitSettlementCard({ order }: { order: Order }) { provider says each account earned; it does not change the shares DashCommerce computed.

+ + A refund comes out of the platform balance; vendor shares are not recovered + automatically. If the provider cannot refund a split payment from DashCommerce, use + its dashboard. + data={split.allocations} getRowKey={(a) => a.accountReference} diff --git a/packages/core/src/orders/refund.ts b/packages/core/src/orders/refund.ts index 8fbdc8a..fd186d9 100644 --- a/packages/core/src/orders/refund.ts +++ b/packages/core/src/orders/refund.ts @@ -177,6 +177,11 @@ async function providerRefundWithDedup( ): Promise { const providerId = order.providerId ?? "stripe"; const provider = requirePaymentProvider(providerId); + if (order.providerSplits && provider.capabilities?.splitRefunds === false) { + throw new Error( + `${provider.label} cannot refund split payments from DashCommerce. Refund this order in the ${provider.label} dashboard.`, + ); + } const creds = await loadPaymentProviderCredentials(ctx.kv, providerId); if (!creds) { throw new Error(`Payment provider "${providerId}" is not configured`); diff --git a/packages/core/src/payment-provider/types.ts b/packages/core/src/payment-provider/types.ts index 00e6a59..cfb1887 100644 --- a/packages/core/src/payment-provider/types.ts +++ b/packages/core/src/payment-provider/types.ts @@ -328,6 +328,14 @@ export interface PaymentProviderCapabilities { * `initCheckout`. */ splits?: boolean; + /** + * True when the provider can refund a split payment through core. + * Missing means yes (Stripe Connect refunds work, though vendor shares + * are not clawed back). Declare `false` when the provider's API cannot + * refund a split charge; core then refuses before calling it and tells + * the merchant to use the provider's dashboard. + */ + splitRefunds?: boolean; } /** How the admin settings form shows and validates one credential. */ diff --git a/packages/core/test/provider-split-refund.test.ts b/packages/core/test/provider-split-refund.test.ts new file mode 100644 index 0000000..3ae2cbe --- /dev/null +++ b/packages/core/test/provider-split-refund.test.ts @@ -0,0 +1,139 @@ +/** + * A provider that cannot refund a split charge should be refused before the + * call, with a message that points to its dashboard. Providers that do not + * declare `splitRefunds: false` keep the existing behaviour. + */ + +import { afterEach, describe, expect, it } from "bun:test"; +import type { PluginContext, RouteContext } from "emdash"; +import { refundOrder } from "../src/orders/refund"; +import { + type NormalizedPaymentEvent, + type PaymentProvider, + createMockPaymentProvider, + registerPaymentProvider, + resetPaymentProviders, +} from "../src/payment-provider"; +import sandbox from "../src/sandbox-entry"; +import type { Order, Vendor } from "../src/types"; +import { makeRouteContext, ticketCart } from "./helpers/route-harness"; + +afterEach(() => resetPaymentProviders()); + +const DRAFT_ID = "0123456789abcdef0123456789abcdef"; + +function vendor(id: string, reference: string): Vendor { + return { + id, + name: `Vendor ${id}`, + email: `${id}@example.com`, + onboardingStatus: "active", + platformFeePercent: 0, + detailsSubmitted: false, + chargesEnabled: false, + payoutsEnabled: false, + paymentAccounts: { + flw: { accountReference: reference, status: "active", updatedAt: "2026-01-01T00:00:00Z" }, + }, + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + }; +} + +function splitEvent(): NormalizedPaymentEvent { + return { + type: "charge.succeeded", + orderDraftId: DRAFT_ID, + providerId: "flw", + providerEventId: "evt_split_refund_1", + checkoutReference: "dc-split", + paymentReference: "pay_split_refund_1", + amount: 150_000, + currency: "KES", + customer: { email: "supporter@example.com" }, + splitSettlement: { + allocations: [ + { accountReference: "RS_V1", amountMinor: 90_000 }, + { accountReference: "RS_V2", amountMinor: 45_000 }, + ], + platformRemainderMinor: 7_650, + providerFeeMinor: 7_350, + currency: "KES", + raw: { source: "test" }, + }, + raw: {}, + }; +} + +function provider(splitRefunds?: boolean): PaymentProvider { + const base = createMockPaymentProvider({ id: "flw", capabilities: { splits: true } }); + return { + ...base, + ...(splitRefunds === undefined + ? {} + : { capabilities: { ...base.capabilities, splitRefunds } }), + webhookHeaders: ["verif-hash"], + parseWebhookEvent: () => splitEvent(), + async getPaymentStatus() { + return { + status: "succeeded", + paymentReference: "pay_split_refund_1", + amount: 150_000, + currency: "KES", + }; + }, + }; +} + +async function paidSplitOrder(providerImpl: PaymentProvider) { + registerPaymentProvider(providerImpl); + const { ctx, getCol } = makeRouteContext({ + "settings:paymentProvider": "flw", + "settings:flwSecretKey": "test-key", + "settings:flwWebhookSecret": "test-secret", + }); + await ctx.kv.set(`draft:${DRAFT_ID}`, { + cart: ticketCart("sess_split_refund"), + ttlMs: 900_000, + createdAt: new Date().toISOString(), + }); + getCol("vendors").set("v1", vendor("v1", "RS_V1")); + getCol("vendors").set("v2", vendor("v2", "RS_V2")); + + const request = new Request("http://test/checkout/webhook", { + method: "POST", + headers: { "verif-hash": "test-secret" }, + body: JSON.stringify({ split: true }), + }); + const routeCtx = { ...ctx, request } as unknown as RouteContext; + const res = (await sandbox.routes["checkout/webhook"].handler(routeCtx, ctx)) as Response; + expect(res.status).toBe(200); + const order = Array.from(getCol("orders").values())[0] as Order; + expect(order.providerSplits).toBeTruthy(); + return { ctx, getCol, order }; +} + +describe("split refunds", () => { + it("refuses before calling a provider that cannot refund splits", async () => { + const { ctx, getCol, order } = await paidSplitOrder(provider(false)); + await expect( + refundOrder(ctx as PluginContext, { + orderId: order.id, + amount: { amount: 10_000, currency: "KES" }, + idempotencyKey: "refund:split:1", + }), + ).rejects.toThrow(/cannot refund split payments/i); + expect(getCol("refunds").size).toBe(0); + }); + + it("keeps the existing behaviour when the provider does not declare a limit", async () => { + const { ctx, getCol, order } = await paidSplitOrder(provider()); + const refund = await refundOrder(ctx as PluginContext, { + orderId: order.id, + amount: { amount: 10_000, currency: "KES" }, + idempotencyKey: "refund:split:2", + }); + expect(refund.status).toBe("succeeded"); + expect(getCol("refunds").size).toBe(1); + }); +}); From e92f5f7120d1e52d92c9cb730e05c1046a773b63 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:30:00 +0100 Subject: [PATCH 22/50] feat(core): add a provider-neutral subscription seam --- .changeset/provider-subscriptions.md | 11 + packages/core/src/payment-provider/index.ts | 1 + packages/core/src/payment-provider/types.ts | 59 ++++ packages/core/src/routes/admin-api.ts | 3 +- .../core/src/routes/subscriptions-public.ts | 9 +- packages/core/src/routes/webhook.ts | 178 ++++++++-- packages/core/src/subscriptions/lifecycle.ts | 138 ++++++-- packages/core/src/subscriptions/provider.ts | 199 +++++++++++ packages/core/src/types.ts | 17 +- .../core/test/provider-subscriptions.test.ts | 308 ++++++++++++++++++ 10 files changed, 862 insertions(+), 61 deletions(-) create mode 100644 .changeset/provider-subscriptions.md create mode 100644 packages/core/src/subscriptions/provider.ts create mode 100644 packages/core/test/provider-subscriptions.test.ts diff --git a/.changeset/provider-subscriptions.md b/.changeset/provider-subscriptions.md new file mode 100644 index 0000000..c2ffd30 --- /dev/null +++ b/.changeset/provider-subscriptions.md @@ -0,0 +1,11 @@ +--- +"@dashcommerce/core": minor +--- + +Add a provider-neutral subscription seam. + +- `PaymentProvider` gains optional `getSubscription`, `cancelSubscription` and `resumeSubscription`. Stripe keeps its existing Billing path; providers that manage billing themselves can use these. +- `charge.succeeded` and `PaymentStatusResult` can carry `ProviderSubscriptionInfo`, so a provider can identify the subscription/plan behind a charge. +- New `subscriptions/provider.ts` stores a provider-managed subscription and its invoices in the existing collections. The first charge creates an order and a local subscription; later charges are recorded as invoices and extend the period, not as new orders. +- `subscriptions/lifecycle.ts` dispatches cancel/resume to a provider-managed subscription. Pause and in-place plan changes are refused for providers that do not support them. +- Stripe's `stripeSubscriptionId`/`stripeInvoiceId` fields keep their names for compatibility; they now hold the provider's subscription/plan and invoice id. diff --git a/packages/core/src/payment-provider/index.ts b/packages/core/src/payment-provider/index.ts index a1c3078..8385447 100644 --- a/packages/core/src/payment-provider/index.ts +++ b/packages/core/src/payment-provider/index.ts @@ -46,6 +46,7 @@ export type { PaymentProviderRuntimeContext, PaymentProviderShippingOption, PaymentStatusResult, + ProviderSubscriptionInfo, RefundResult, VerifyWebhookInput, VerifyWebhookResult, diff --git a/packages/core/src/payment-provider/types.ts b/packages/core/src/payment-provider/types.ts index 006dd4e..a1ef975 100644 --- a/packages/core/src/payment-provider/types.ts +++ b/packages/core/src/payment-provider/types.ts @@ -201,6 +201,12 @@ export type NormalizedPaymentEvent = shippingAddress?: PaymentProviderAddress; billingAddress?: PaymentProviderAddress; channel?: string; + /** + * Present when this charge belongs to a provider-managed + * subscription. Core records the first payment as an order and + * later charges as subscription invoices. + */ + subscription?: ProviderSubscriptionInfo; raw: unknown; } | { @@ -304,12 +310,42 @@ export interface ConnectionCheckResult { mode?: "test" | "live"; } +/** + * Provider-reported subscription state. `providerSubscriptionId` is the id + * the provider uses for cancel/resume; for Flutterwave it is the payment + * plan id, because DashCommerce creates one plan per subscription. + */ +export interface ProviderSubscriptionInfo { + providerSubscriptionId: string; + status: + | "active" + | "trialing" + | "past_due" + | "canceled" + | "paused" + | "unpaid" + | "incomplete" + | "incomplete_expired"; + currentPeriodStart?: string; + currentPeriodEnd?: string; + cancelAtPeriodEnd?: boolean; + canceledAt?: string; + trialEndsAt?: string; + /** Integer minor units, when the provider reports it. */ + amount?: number; + currency?: string; + interval?: "day" | "week" | "month" | "year"; + intervalCount?: number; +} + export interface PaymentStatusResult { status: "pending" | "succeeded" | "failed"; paymentReference?: string; amount?: number; currency?: string; reason?: string; + /** Present when the payment is a subscription charge. */ + subscription?: ProviderSubscriptionInfo; } export interface PaymentProvider { @@ -396,6 +432,29 @@ export interface PaymentProvider { credentials: PaymentProviderCredentials, ): Promise; + /** + * Provider-managed subscription lifecycle. Optional and independent; + * core falls back to its Stripe Billing path for Stripe subscriptions. + * The provider id is the one core stored on the local subscription. + */ + getSubscription?( + ctx: PaymentProviderRuntimeContext, + providerSubscriptionId: string, + credentials: PaymentProviderCredentials, + ): Promise; + + cancelSubscription?( + ctx: PaymentProviderRuntimeContext, + input: { providerSubscriptionId: string; atPeriodEnd?: boolean }, + credentials: PaymentProviderCredentials, + ): Promise; + + resumeSubscription?( + ctx: PaymentProviderRuntimeContext, + input: { providerSubscriptionId: string }, + credentials: PaymentProviderCredentials, + ): Promise; + /** * Optional check behind the "Test connection" button in Settings: one * read-only call with the saved credentials. It must not create or change diff --git a/packages/core/src/routes/admin-api.ts b/packages/core/src/routes/admin-api.ts index f45cce3..12a00d2 100644 --- a/packages/core/src/routes/admin-api.ts +++ b/packages/core/src/routes/admin-api.ts @@ -1128,8 +1128,7 @@ async function postSubscriptionAction( action: string, routeCtx: RouteContext, ): Promise { - const client = await loadStripeClient(ctx); - if (!client) return json({ error: "Stripe not configured" }, 500); + const client = (await loadStripeClient(ctx)) ?? undefined; const body = (routeCtx.input ?? {}) as { mode?: "immediate" | "at_period_end"; resumesAt?: number; diff --git a/packages/core/src/routes/subscriptions-public.ts b/packages/core/src/routes/subscriptions-public.ts index 8e4dce6..c3cf17c 100644 --- a/packages/core/src/routes/subscriptions-public.ts +++ b/packages/core/src/routes/subscriptions-public.ts @@ -127,8 +127,7 @@ async function handleCancel(routeCtx: RouteContext, _ctx?: PluginContext): Promi const loaded = await loadAuthorisedSub(ctx, extractToken(routeCtx.request, input)); if (!loaded.ok) return loaded.response; - const client = await loadStripeClient(ctx); - if (!client) return jsonResponse({ error: "Stripe not configured" }, 500); + const client = (await loadStripeClient(ctx)) ?? undefined; try { const updated = await cancel(ctx, { @@ -158,8 +157,7 @@ async function handlePause(routeCtx: RouteContext, _ctx?: PluginContext): Promis const loaded = await loadAuthorisedSub(ctx, extractToken(routeCtx.request, input)); if (!loaded.ok) return loaded.response; - const client = await loadStripeClient(ctx); - if (!client) return jsonResponse({ error: "Stripe not configured" }, 500); + const client = (await loadStripeClient(ctx)) ?? undefined; try { const updated = await pause(ctx, { @@ -186,8 +184,7 @@ async function handleResume(routeCtx: RouteContext, _ctx?: PluginContext): Promi const loaded = await loadAuthorisedSub(ctx, extractToken(routeCtx.request, input)); if (!loaded.ok) return loaded.response; - const client = await loadStripeClient(ctx); - if (!client) return jsonResponse({ error: "Stripe not configured" }, 500); + const client = (await loadStripeClient(ctx)) ?? undefined; try { const updated = await resume(ctx, { diff --git a/packages/core/src/routes/webhook.ts b/packages/core/src/routes/webhook.ts index 3d043e2..e012bec 100644 --- a/packages/core/src/routes/webhook.ts +++ b/packages/core/src/routes/webhook.ts @@ -29,7 +29,11 @@ import type { PluginContext, RouteContext, StorageCollection } from "emdash"; import { deleteLock, getLock } from "../cart/lock"; import { clear as clearCart } from "../cart/store"; import { sendSubscriptionRenewed, sendVendorActivated, sendVendorPayout } from "../emails"; -import { createOrderFromPaymentIntent, findOrderByPaymentIntent } from "../orders/create"; +import { + createOrderFromPaymentIntent, + findOrderByPaymentIntent, + loadOrderItems, +} from "../orders/create"; import { applyProviderRefundUpdate, recordRefundFromWebhook } from "../orders/refund"; import { type NormalizedPaymentEvent, @@ -53,8 +57,14 @@ import { upsertInvoiceFromStripe, } from "../subscriptions/create"; import { handleInvoicePaymentFailed } from "../subscriptions/dunning"; +import { + addSubscriptionInterval, + findProviderSubscription, + recordProviderSubscriptionInvoice, + upsertProviderSubscription, +} from "../subscriptions/provider"; import type { CartState, StripeEventRecord } from "../types"; -import type { Address, CountryCode, Customer, Order } from "../types"; +import type { Address, CountryCode, CurrencyCode, Customer, Order } from "../types"; import { randomId } from "../util/ids"; import { isUniqueViolation } from "../util/storage"; import { findVendorByStripeAccountId, upsertVendorFromStripeAccount } from "../vendors/onboarding"; @@ -258,6 +268,11 @@ async function loadStripeClient(ctx: PluginContext): Promise; +function ordersStore(ctx: PluginContext): OrdersStore { + return (ctx.storage as unknown as { orders: OrdersStore }).orders; +} + type CustomersStore = StorageCollection; function customersStore(ctx: PluginContext): CustomersStore { return (ctx.storage as unknown as { customers: CustomersStore }).customers; @@ -670,6 +685,79 @@ async function handleNormalizedChargeSucceeded( }); } + const provider = requirePaymentProvider(event.providerId); + let amount = event.amount; + let currency = event.currency; + let paymentReference = event.paymentReference; + let subscription = event.subscription; + + if (provider.getPaymentStatus) { + const creds = await loadPaymentProviderCredentials(ctx.kv, provider.id); + if (creds) { + let live: Awaited>>; + try { + live = await provider.getPaymentStatus(ctx, event.paymentReference, creds); + } catch (err) { + throw new ConfirmationFailure( + `Provider status check failed: ${err instanceof Error ? err.message : String(err)}`, + ); + } + if (live.status !== "succeeded") { + ctx.log.error("Provider retrieve did not confirm a succeeded payment", { + providerId: provider.id, + paymentReference: event.paymentReference, + status: live.status, + reason: live.reason, + }); + throw new ConfirmationFailure("Payment not succeeded at provider"); + } + if (typeof live.amount === "number") amount = live.amount; + if (live.currency) currency = live.currency; + if (live.paymentReference) paymentReference = live.paymentReference; + subscription = live.subscription ?? subscription; + } + } + + // A renewal has no checkout draft and must not create a second order. + // Record it as a subscription invoice and extend the local period. + if (subscription) { + const existingSub = await findProviderSubscription( + ctx, + provider.id, + subscription.providerSubscriptionId, + ); + if (existingSub) { + // The provider may still report the subscription's old period on a + // renewal charge. Extend from the local period, which is the last + // period we recorded. + const periodStart = existingSub.currentPeriodEnd; + const periodEnd = addSubscriptionInterval( + periodStart, + existingSub.interval, + existingSub.intervalCount, + ); + const invoice = await recordProviderSubscriptionInvoice(ctx, { + subscription: existingSub, + providerId: provider.id, + providerInvoiceId: paymentReference, + amount, + currency: currency.toUpperCase() as CurrencyCode, + status: "paid", + periodStart, + periodEnd, + }); + return new Response( + JSON.stringify({ + received: true, + subscriptionId: existingSub.id, + invoiceId: invoice.id, + renewal: true, + }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ); + } + } + const snapshot = await ctx.kv.get(draftKey(event.orderDraftId)); if (!snapshot) { ctx.log.error("No cart snapshot for orderDraftId", { @@ -707,36 +795,6 @@ async function handleNormalizedChargeSucceeded( } } - let amount = event.amount; - let currency = event.currency; - let paymentReference = event.paymentReference; - const provider = requirePaymentProvider(event.providerId); - if (provider.getPaymentStatus) { - const creds = await loadPaymentProviderCredentials(ctx.kv, provider.id); - if (creds) { - let live: Awaited>>; - try { - live = await provider.getPaymentStatus(ctx, event.paymentReference, creds); - } catch (err) { - throw new ConfirmationFailure( - `Provider status check failed: ${err instanceof Error ? err.message : String(err)}`, - ); - } - if (live.status !== "succeeded") { - ctx.log.error("Provider retrieve did not confirm a succeeded payment", { - providerId: provider.id, - paymentReference: event.paymentReference, - status: live.status, - reason: live.reason, - }); - throw new ConfirmationFailure("Payment not succeeded at provider"); - } - if (typeof live.amount === "number") amount = live.amount; - if (live.currency) currency = live.currency; - if (live.paymentReference) paymentReference = live.paymentReference; - } - } - const { order, duplicate } = await createOrderFromPaymentIntent(ctx, { paymentIntent: { id: paymentReference, @@ -767,6 +825,62 @@ async function handleNormalizedChargeSucceeded( } } + // The first subscription payment also creates the local subscription. + // A failure here must not fail the order: the payment is captured. + if (subscription) { + try { + const items = await loadOrderItems(ctx, order.id); + const item = items.find((row) => row.subscriptionConfig); + const config = item?.subscriptionConfig; + if (!item || !config) { + ctx.log.warn("Subscription charge created an order with no subscription item", { + orderId: order.id, + providerId: provider.id, + providerSubscriptionId: subscription.providerSubscriptionId, + }); + } else { + const periodStart = + subscription.currentPeriodStart ?? order.paidAt ?? new Date().toISOString(); + const periodEnd = + subscription.currentPeriodEnd ?? + addSubscriptionInterval(periodStart, config.interval, config.intervalCount); + const local = await upsertProviderSubscription(ctx, { + providerId: provider.id, + providerSubscriptionId: subscription.providerSubscriptionId, + customerId: order.customerId, + productId: item.productId, + ...(item.variantId ? { variantId: item.variantId } : {}), + status: subscription.status ?? "active", + currency: order.currency, + unitAmount: item.unitPrice.amount, + quantity: item.quantity, + interval: config.interval, + intervalCount: config.intervalCount, + currentPeriodStart: periodStart, + currentPeriodEnd: periodEnd, + ...(subscription.trialEndsAt ? { trialEndsAt: subscription.trialEndsAt } : {}), + cancelAtPeriodEnd: subscription.cancelAtPeriodEnd ?? false, + ...(subscription.canceledAt ? { canceledAt: subscription.canceledAt } : {}), + }); + const subscriptionIds = [ + ...new Set([...(order.subscriptionIds ?? []), local.id]), + ]; + await ordersStore(ctx).put(order.id, { + ...order, + subscriptionIds, + updatedAt: new Date().toISOString(), + }); + } + } catch (err) { + ctx.log.error("Could not record the provider subscription", { + orderId: order.id, + providerId: provider.id, + providerSubscriptionId: subscription.providerSubscriptionId, + error: err instanceof Error ? err.message : String(err), + }); + } + } + return new Response( JSON.stringify({ received: true, orderId: order.id, orderNumber: order.orderNumber }), { status: 200, headers: { "Content-Type": "application/json" } }, diff --git a/packages/core/src/subscriptions/lifecycle.ts b/packages/core/src/subscriptions/lifecycle.ts index f8c2271..4f18622 100644 --- a/packages/core/src/subscriptions/lifecycle.ts +++ b/packages/core/src/subscriptions/lifecycle.ts @@ -1,13 +1,19 @@ /** * Subscription lifecycle — merchant + customer self-service actions. * - * All paths call Stripe first (with Idempotency-Key) and then wait for the - * resulting `customer.subscription.updated` webhook to refresh our local - * row — we do NOT optimistically mutate local state, to keep Stripe the - * single source of truth. + * Stripe subscriptions call Stripe first (with Idempotency-Key) and wait for + * the resulting `customer.subscription.updated` webhook to refresh the local + * row. Provider-managed subscriptions (Flutterwave Payment Plans) call the + * provider and update the local row immediately, because their cancellation + * is not delivered as a subscription webhook. */ import type { PluginContext } from "emdash"; +import { + type ProviderSubscriptionInfo, + loadPaymentProviderCredentials, + requirePaymentProvider, +} from "../payment-provider"; import type { StripeClientOptions } from "../stripe/client"; import { cancelSubscription as stripeCancel, @@ -15,30 +21,41 @@ import { type StripeSubscription, } from "../stripe/subscriptions"; import type { Subscription } from "../types"; -import { findSubscription } from "./create"; +import { findSubscription, subsStore } from "./create"; export type CancelMode = "immediate" | "at_period_end"; export interface CancelInput { subscriptionId: string; // our local id mode: CancelMode; - client: StripeClientOptions; + /** Required for Stripe; ignored for a provider-managed subscription. */ + client?: StripeClientOptions; } export async function cancel( ctx: PluginContext, input: CancelInput, -): Promise { +): Promise { const local = await loadLocal(ctx, input.subscriptionId); + if (isProviderManaged(local)) { + const info = await providerCancel(ctx, local, input.mode); + await saveProviderState(ctx, local, info, { + cancelAtPeriodEnd: info.cancelAtPeriodEnd ?? input.mode === "at_period_end", + canceledAt: info.status === "canceled" ? (info.canceledAt ?? new Date().toISOString()) : undefined, + }); + return info; + } + + const client = requireStripeClient(input.client); const idemKey = `sub-cancel:${local.stripeSubscriptionId}:${input.mode}`; if (input.mode === "immediate") { - return stripeCancel(ctx, local.stripeSubscriptionId, input.client, idemKey); + return stripeCancel(ctx, local.stripeSubscriptionId, client, idemKey); } return stripeUpdate( ctx, local.stripeSubscriptionId, { cancelAtPeriodEnd: true }, - input.client, + client, idemKey, ); } @@ -47,7 +64,7 @@ export interface PauseInput { subscriptionId: string; behavior?: "keep_as_draft" | "mark_uncollectible" | "void"; resumesAt?: number; // unix seconds - client: StripeClientOptions; + client?: StripeClientOptions; } export async function pause( @@ -55,6 +72,10 @@ export async function pause( input: PauseInput, ): Promise { const local = await loadLocal(ctx, input.subscriptionId); + if (isProviderManaged(local)) { + throw new Error(`${local.providerId} does not support pausing subscriptions`); + } + const client = requireStripeClient(input.client); const idemKey = `sub-pause:${local.stripeSubscriptionId}:${input.resumesAt ?? "open"}`; return stripeUpdate( ctx, @@ -65,27 +86,37 @@ export async function pause( ...(input.resumesAt !== undefined ? { resumesAt: input.resumesAt } : {}), }, }, - input.client, + client, idemKey, ); } export interface ResumeInput { subscriptionId: string; - client: StripeClientOptions; + client?: StripeClientOptions; } export async function resume( ctx: PluginContext, input: ResumeInput, -): Promise { +): Promise { const local = await loadLocal(ctx, input.subscriptionId); + if (isProviderManaged(local)) { + const info = await providerResume(ctx, local); + await saveProviderState(ctx, local, info, { + cancelAtPeriodEnd: false, + canceledAt: undefined, + }); + return info; + } + + const client = requireStripeClient(input.client); const idemKey = `sub-resume:${local.stripeSubscriptionId}`; return stripeUpdate( ctx, local.stripeSubscriptionId, { pauseCollection: null }, - input.client, + client, idemKey, ); } @@ -97,7 +128,7 @@ export interface ChangePlanInput { newPriceId: string; quantity?: number; prorationBehavior?: "create_prorations" | "none" | "always_invoice"; - client: StripeClientOptions; + client?: StripeClientOptions; } export async function changePlan( @@ -105,6 +136,10 @@ export async function changePlan( input: ChangePlanInput, ): Promise { const local = await loadLocal(ctx, input.subscriptionId); + if (isProviderManaged(local)) { + throw new Error(`${local.providerId} does not support changing plans in place`); + } + const client = requireStripeClient(input.client); const idemKey = `sub-change:${local.stripeSubscriptionId}:${input.newPriceId}`; return stripeUpdate( ctx, @@ -119,18 +154,83 @@ export async function changePlan( ], prorationBehavior: input.prorationBehavior ?? "create_prorations", }, - input.client, + client, idemKey, ); } +function isProviderManaged(sub: Subscription): boolean { + return Boolean(sub.providerId && sub.providerId !== "stripe"); +} + +function requireStripeClient(client: StripeClientOptions | undefined): StripeClientOptions { + if (!client) throw new Error("Stripe not configured"); + return client; +} + +async function providerCancel( + ctx: PluginContext, + local: Subscription, + mode: CancelMode, +): Promise { + const provider = requirePaymentProvider(local.providerId ?? ""); + if (!provider.cancelSubscription) { + throw new Error(`${provider.label} does not support cancelling subscriptions`); + } + const creds = await loadPaymentProviderCredentials(ctx.kv, provider.id); + if (!creds) throw new Error(`Payment provider "${provider.id}" is not configured`); + return provider.cancelSubscription( + ctx, + { + providerSubscriptionId: local.stripeSubscriptionId, + atPeriodEnd: mode === "at_period_end", + }, + creds, + ); +} + +async function providerResume( + ctx: PluginContext, + local: Subscription, +): Promise { + const provider = requirePaymentProvider(local.providerId ?? ""); + if (!provider.resumeSubscription) { + throw new Error(`${provider.label} does not support resuming subscriptions`); + } + const creds = await loadPaymentProviderCredentials(ctx.kv, provider.id); + if (!creds) throw new Error(`Payment provider "${provider.id}" is not configured`); + return provider.resumeSubscription( + ctx, + { providerSubscriptionId: local.stripeSubscriptionId }, + creds, + ); +} + +async function saveProviderState( + ctx: PluginContext, + local: Subscription, + info: ProviderSubscriptionInfo, + extra: { cancelAtPeriodEnd?: boolean; canceledAt?: string | undefined }, +): Promise { + const now = new Date().toISOString(); + await subsStore(ctx).put(local.id, { + ...local, + status: info.status, + ...(info.currentPeriodStart ? { currentPeriodStart: info.currentPeriodStart } : {}), + ...(info.currentPeriodEnd ? { currentPeriodEnd: info.currentPeriodEnd } : {}), + cancelAtPeriodEnd: extra.cancelAtPeriodEnd ?? local.cancelAtPeriodEnd, + ...(extra.canceledAt ? { canceledAt: extra.canceledAt } : {}), + updatedAt: now, + }); +} + async function loadLocal(ctx: PluginContext, id: string): Promise { - // Accept either our uuid or the Stripe id for convenience. + // Accept either our uuid or the provider id for convenience. const directRes = await (ctx.storage as unknown as { subscriptions: { get(id: string): Promise }; }).subscriptions.get(id); if (directRes) return { ...(directRes as Subscription), id }; - const byStripe = await findSubscription(ctx, id); - if (byStripe) return byStripe; + const byProvider = await findSubscription(ctx, id); + if (byProvider) return byProvider; throw new Error(`Subscription ${id} not found`); } diff --git a/packages/core/src/subscriptions/provider.ts b/packages/core/src/subscriptions/provider.ts new file mode 100644 index 0000000..5c06c52 --- /dev/null +++ b/packages/core/src/subscriptions/provider.ts @@ -0,0 +1,199 @@ +/** + * Provider-neutral subscription storage. + * + * Stripe subscriptions still go through `create.ts` and `lifecycle.ts`; this + * module is the additive path for providers that manage billing themselves + * (Flutterwave Payment Plans). It reuses the existing `Subscription` and + * `SubscriptionInvoice` collections and their unique indexes, keyed on the + * provider's subscription/plan id. + */ + +import type { PluginContext, StorageCollection } from "emdash"; +import { money } from "../money"; +import type { + CurrencyCode, + IsoDateTime, + Subscription, + SubscriptionInvoice, + SubscriptionStatus, +} from "../types"; +import { randomId } from "../util/ids"; + +type SubsStore = StorageCollection; +type InvoiceStore = StorageCollection; + +export function providerSubsStore(ctx: PluginContext): SubsStore { + return (ctx.storage as unknown as { subscriptions: SubsStore }).subscriptions; +} + +function invoiceStore(ctx: PluginContext): InvoiceStore { + return (ctx.storage as unknown as { subscription_invoices: InvoiceStore }) + .subscription_invoices; +} + +/** Add a billing interval to an ISO date, clamping month-end. */ +export function addSubscriptionInterval( + start: IsoDateTime, + interval: Subscription["interval"], + count: number, +): IsoDateTime { + const date = new Date(start); + const n = Math.max(1, Math.trunc(count)); + if (interval === "day") { + date.setUTCDate(date.getUTCDate() + n); + return date.toISOString(); + } + if (interval === "week") { + date.setUTCDate(date.getUTCDate() + n * 7); + return date.toISOString(); + } + const months = interval === "year" ? n * 12 : n; + const day = date.getUTCDate(); + date.setUTCDate(1); + date.setUTCMonth(date.getUTCMonth() + months); + const lastDay = new Date( + Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0), + ).getUTCDate(); + date.setUTCDate(Math.min(day, lastDay)); + return date.toISOString(); +} + +export async function findProviderSubscription( + ctx: PluginContext, + providerId: string, + providerSubscriptionId: string, +): Promise { + const result = await providerSubsStore(ctx).query({ + where: { stripeSubscriptionId: providerSubscriptionId }, + limit: 1, + }); + const row = result.items[0]; + if (!row) return null; + const sub = { ...(row.data as Subscription), id: row.id }; + // Rows written before `providerId` existed are Stripe rows. + if ((sub.providerId ?? "stripe") !== providerId) return null; + return sub; +} + +export interface UpsertProviderSubscriptionInput { + providerId: string; + providerSubscriptionId: string; + customerId: string; + productId: string; + variantId?: string; + status: SubscriptionStatus; + currency: CurrencyCode; + /** Integer minor units. */ + unitAmount: number; + quantity: number; + interval: Subscription["interval"]; + intervalCount: number; + currentPeriodStart?: IsoDateTime; + currentPeriodEnd?: IsoDateTime; + trialEndsAt?: IsoDateTime; + cancelAtPeriodEnd?: boolean; + canceledAt?: IsoDateTime; +} + +export async function upsertProviderSubscription( + ctx: PluginContext, + input: UpsertProviderSubscriptionInput, +): Promise { + const existing = await findProviderSubscription( + ctx, + input.providerId, + input.providerSubscriptionId, + ); + const now = new Date().toISOString(); + const currentPeriodStart = input.currentPeriodStart ?? existing?.currentPeriodStart ?? now; + const currentPeriodEnd = + input.currentPeriodEnd ?? + existing?.currentPeriodEnd ?? + addSubscriptionInterval(currentPeriodStart, input.interval, input.intervalCount); + + const record: Subscription = { + id: existing?.id ?? randomId(), + stripeSubscriptionId: input.providerSubscriptionId, + providerId: input.providerId, + customerId: input.customerId, + productId: input.productId, + ...(input.variantId ? { variantId: input.variantId } : {}), + status: input.status, + currency: input.currency, + unitAmount: money(input.currency, input.unitAmount), + quantity: input.quantity, + interval: input.interval, + intervalCount: input.intervalCount, + ...(input.trialEndsAt ? { trialEndsAt: input.trialEndsAt } : {}), + currentPeriodStart, + currentPeriodEnd, + cancelAtPeriodEnd: input.cancelAtPeriodEnd ?? existing?.cancelAtPeriodEnd ?? false, + ...(input.canceledAt ? { canceledAt: input.canceledAt } : {}), + createdAt: existing?.createdAt ?? now, + updatedAt: now, + }; + await providerSubsStore(ctx).put(record.id, record); + return record; +} + +export interface RecordProviderInvoiceInput { + subscription: Subscription; + providerId: string; + providerInvoiceId: string; + /** Integer minor units. */ + amount: number; + currency: CurrencyCode; + status?: SubscriptionInvoice["status"]; + paidAt?: IsoDateTime; + attemptCount?: number; + /** When paid, the new billing period. */ + periodStart?: IsoDateTime; + periodEnd?: IsoDateTime; +} + +export async function recordProviderSubscriptionInvoice( + ctx: PluginContext, + input: RecordProviderInvoiceInput, +): Promise { + const existingResult = await invoiceStore(ctx).query({ + where: { stripeInvoiceId: input.providerInvoiceId }, + limit: 1, + }); + const existing = existingResult.items[0]; + const id = existing?.id ?? randomId(); + const status = input.status ?? "paid"; + const now = new Date().toISOString(); + + const invoice: SubscriptionInvoice = { + id, + stripeInvoiceId: input.providerInvoiceId, + providerId: input.providerId, + subscriptionId: input.subscription.id, + amount: money(input.currency, input.amount), + status, + ...(status === "paid" ? { paidAt: input.paidAt ?? now } : {}), + attemptCount: input.attemptCount ?? 0, + createdAt: (existing?.data as SubscriptionInvoice | undefined)?.createdAt ?? now, + }; + await invoiceStore(ctx).put(id, invoice); + + if (status === "paid") { + const periodStart = input.periodStart ?? input.subscription.currentPeriodStart; + const periodEnd = + input.periodEnd ?? + addSubscriptionInterval( + periodStart, + input.subscription.interval, + input.subscription.intervalCount, + ); + await providerSubsStore(ctx).put(input.subscription.id, { + ...input.subscription, + status: "active", + currentPeriodStart: periodStart, + currentPeriodEnd: periodEnd, + updatedAt: now, + }); + } + + return invoice; +} diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index fd5d2de..c5fe6fb 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -473,7 +473,14 @@ export type SubscriptionStatus = export interface Subscription { id: string; - stripeSubscriptionId: string; // unique + /** + * Provider subscription id. Unique. Stripe uses `sub_…`; Flutterwave + * uses the payment plan id, because DashCommerce creates one plan per + * subscription. The field name is legacy. + */ + stripeSubscriptionId: string; + /** Gateway that owns this subscription. Unset means Stripe. */ + providerId?: string; customerId: string; productId: string; variantId?: string; @@ -494,7 +501,13 @@ export interface Subscription { export interface SubscriptionInvoice { id: string; - stripeInvoiceId: string; // unique + /** + * Provider invoice/charge id. Unique. Stripe uses `in_…`; Flutterwave + * uses the recurring transaction id. The field name is legacy. + */ + stripeInvoiceId: string; + /** Gateway that owns this invoice. Unset means Stripe. */ + providerId?: string; subscriptionId: string; amount: Money; status: "draft" | "open" | "paid" | "uncollectible" | "void"; diff --git a/packages/core/test/provider-subscriptions.test.ts b/packages/core/test/provider-subscriptions.test.ts new file mode 100644 index 0000000..1ea7711 --- /dev/null +++ b/packages/core/test/provider-subscriptions.test.ts @@ -0,0 +1,308 @@ +/** + * Provider-managed subscriptions: the first charge creates an order and a + * local subscription; later charges are invoices, not orders. Flutterwave + * uses one payment plan per subscription, so the plan id is the local key. + */ + +import { afterEach, describe, expect, it } from "bun:test"; +import type { PluginContext, RouteContext } from "emdash"; +import { + type NormalizedPaymentEvent, + type PaymentProvider, + type ProviderSubscriptionInfo, + createMockPaymentProvider, + registerPaymentProvider, + resetPaymentProviders, +} from "../src/payment-provider"; +import sandbox from "../src/sandbox-entry"; +import { cancel, pause, resume } from "../src/subscriptions/lifecycle"; +import { + addSubscriptionInterval, + findProviderSubscription, + upsertProviderSubscription, +} from "../src/subscriptions/provider"; +import type { CartState, Order, Subscription, SubscriptionInvoice } from "../src/types"; +import { makeRouteContext, ticketCart } from "./helpers/route-harness"; + +afterEach(() => resetPaymentProviders()); + +const DRAFT_ID = "0123456789abcdef0123456789abcdef"; +const RENEWAL_DRAFT_ID = "fedcba9876543210fedcba9876543210"; + +function subscriptionCart(sessionId: string): CartState { + const cart = ticketCart(sessionId); + cart.items = cart.items.map((item) => ({ + ...item, + subscriptionConfig: { interval: "month", intervalCount: 1 }, + })); + return cart; +} + +function provider(current: { paymentReference: string; subscription: ProviderSubscriptionInfo }) { + const base = createMockPaymentProvider({ id: "acme" }); + const impl: PaymentProvider = { + ...base, + webhookHeaders: ["x-acme-signature"], + parseWebhookEvent(raw): NormalizedPaymentEvent { + const body = JSON.parse(raw) as { + id: string; + orderDraftId: string; + paymentReference: string; + }; + return { + type: "charge.succeeded", + orderDraftId: body.orderDraftId, + providerId: "acme", + providerEventId: body.id, + paymentReference: body.paymentReference, + amount: 150_000, + currency: "KES", + customer: { email: "supporter@example.com" }, + subscription: current.subscription, + raw: body, + }; + }, + async getPaymentStatus() { + return { + status: "succeeded", + paymentReference: current.paymentReference, + amount: 150_000, + currency: "KES", + subscription: current.subscription, + }; + }, + }; + return impl; +} + +async function deliver(ctx: PluginContext, payload: string): Promise { + const request = new Request("http://test/checkout/webhook", { + method: "POST", + headers: { "x-acme-signature": "signed" }, + body: payload, + }); + const routeCtx = { ...ctx, request } as unknown as RouteContext; + return (await sandbox.routes["checkout/webhook"].handler(routeCtx, ctx)) as Response; +} + +function setup(current: { paymentReference: string; subscription: ProviderSubscriptionInfo }) { + registerPaymentProvider(provider(current)); + const harness = makeRouteContext({ + "settings:paymentProvider": "acme", + "settings:acmeSecretKey": "acme-key", + "settings:acmeWebhookSecret": "test-secret", + }); + harness.ctx.kv.set(`draft:${DRAFT_ID}`, { + cart: subscriptionCart("sess_sub"), + ttlMs: 900_000, + createdAt: new Date().toISOString(), + }); + return harness; +} + +describe("addSubscriptionInterval", () => { + it("clamps a month-end start to the last day of the next month", () => { + expect(addSubscriptionInterval("2026-01-31T00:00:00.000Z", "month", 1)).toBe( + "2026-02-28T00:00:00.000Z", + ); + }); + + it("adds weeks and years", () => { + expect(addSubscriptionInterval("2026-01-01T00:00:00.000Z", "week", 2)).toBe( + "2026-01-15T00:00:00.000Z", + ); + expect(addSubscriptionInterval("2026-01-01T00:00:00.000Z", "year", 1)).toBe( + "2027-01-01T00:00:00.000Z", + ); + }); +}); + +describe("provider-managed subscriptions", () => { + it("creates an order and a local subscription from the first charge", async () => { + const current = { + paymentReference: "pay_sub_1", + subscription: { + providerSubscriptionId: "plan_1", + status: "active" as const, + currentPeriodStart: "2026-01-01T00:00:00.000Z", + currentPeriodEnd: "2026-02-01T00:00:00.000Z", + }, + }; + const { ctx, getCol } = setup(current); + + const res = await deliver( + ctx, + JSON.stringify({ + id: "evt_sub_1", + orderDraftId: DRAFT_ID, + paymentReference: "pay_sub_1", + }), + ); + expect(res.status).toBe(200); + + const order = Array.from(getCol("orders").values())[0] as Order; + expect(order.subscriptionIds?.length).toBe(1); + const sub = Array.from(getCol("subscriptions").values())[0] as Subscription; + expect(sub).toMatchObject({ + stripeSubscriptionId: "plan_1", + providerId: "acme", + customerId: order.customerId, + status: "active", + currency: "KES", + interval: "month", + intervalCount: 1, + currentPeriodStart: "2026-01-01T00:00:00.000Z", + currentPeriodEnd: "2026-02-01T00:00:00.000Z", + }); + expect(sub.unitAmount).toEqual({ amount: 150_000, currency: "KES" }); + expect(getCol("subscription_invoices").size).toBe(0); + }); + + it("records a later charge as an invoice and does not create a second order", async () => { + const current = { + paymentReference: "pay_sub_1", + subscription: { + providerSubscriptionId: "plan_1", + status: "active" as const, + currentPeriodStart: "2026-01-01T00:00:00.000Z", + currentPeriodEnd: "2026-02-01T00:00:00.000Z", + }, + }; + const { ctx, getCol } = setup(current); + + await deliver( + ctx, + JSON.stringify({ + id: "evt_sub_1", + orderDraftId: DRAFT_ID, + paymentReference: "pay_sub_1", + }), + ); + expect(getCol("orders").size).toBe(1); + + current.paymentReference = "pay_sub_2"; + const res = await deliver( + ctx, + JSON.stringify({ + id: "evt_sub_2", + orderDraftId: RENEWAL_DRAFT_ID, + paymentReference: "pay_sub_2", + }), + ); + expect(res.status).toBe(200); + expect(getCol("orders").size).toBe(1); + + const sub = Array.from(getCol("subscriptions").values())[0] as Subscription; + expect(sub.currentPeriodStart).toBe("2026-02-01T00:00:00.000Z"); + expect(sub.currentPeriodEnd).toBe("2026-03-01T00:00:00.000Z"); + const invoice = Array.from(getCol("subscription_invoices").values())[0] as SubscriptionInvoice; + expect(invoice).toMatchObject({ + stripeInvoiceId: "pay_sub_2", + providerId: "acme", + subscriptionId: sub.id, + status: "paid", + }); + expect(invoice.amount).toEqual({ amount: 150_000, currency: "KES" }); + }); + + it("does not hand a provider's plan id to another provider", async () => { + const current = { + paymentReference: "pay_sub_1", + subscription: { + providerSubscriptionId: "plan_1", + status: "active" as const, + }, + }; + const { ctx, getCol } = setup(current); + await deliver( + ctx, + JSON.stringify({ + id: "evt_sub_1", + orderDraftId: DRAFT_ID, + paymentReference: "pay_sub_1", + }), + ); + expect(await findProviderSubscription(ctx, "acme", "plan_1")).not.toBeNull(); + expect(await findProviderSubscription(ctx, "other", "plan_1")).toBeNull(); + expect(getCol("subscriptions").size).toBe(1); + }); +}); + + +describe("provider-managed lifecycle", () => { + it("cancels and resumes through the provider, not Stripe", async () => { + const calls: Array<{ action: string; id: string }> = []; + const base = createMockPaymentProvider({ id: "acme" }); + registerPaymentProvider({ + ...base, + async cancelSubscription(_ctx, input) { + calls.push({ action: "cancel", id: input.providerSubscriptionId }); + return { + providerSubscriptionId: input.providerSubscriptionId, + status: "canceled" as const, + canceledAt: "2026-02-01T00:00:00.000Z", + }; + }, + async resumeSubscription(_ctx, input) { + calls.push({ action: "resume", id: input.providerSubscriptionId }); + return { + providerSubscriptionId: input.providerSubscriptionId, + status: "active" as const, + }; + }, + }); + const { ctx, getCol } = makeRouteContext({ + "settings:paymentProvider": "acme", + "settings:acmeSecretKey": "acme-key", + }); + const sub = await upsertProviderSubscription(ctx, { + providerId: "acme", + providerSubscriptionId: "plan_1", + customerId: "cus_1", + productId: "prod_1", + status: "active", + currency: "KES", + unitAmount: 150_000, + quantity: 1, + interval: "month", + intervalCount: 1, + }); + + const canceled = await cancel(ctx, { subscriptionId: sub.id, mode: "immediate" }); + expect(canceled.status).toBe("canceled"); + expect(calls).toEqual([{ action: "cancel", id: "plan_1" }]); + expect((getCol("subscriptions").get(sub.id) as Subscription).status).toBe("canceled"); + + const resumed = await resume(ctx, { subscriptionId: sub.id }); + expect(resumed.status).toBe("active"); + expect(calls).toEqual([ + { action: "cancel", id: "plan_1" }, + { action: "resume", id: "plan_1" }, + ]); + expect((getCol("subscriptions").get(sub.id) as Subscription).status).toBe("active"); + }); + + it("refuses to pause a provider-managed subscription", async () => { + const base = createMockPaymentProvider({ id: "acme" }); + registerPaymentProvider(base); + const { ctx } = makeRouteContext({ + "settings:paymentProvider": "acme", + "settings:acmeSecretKey": "acme-key", + }); + const sub = await upsertProviderSubscription(ctx, { + providerId: "acme", + providerSubscriptionId: "plan_1", + customerId: "cus_1", + productId: "prod_1", + status: "active", + currency: "KES", + unitAmount: 150_000, + quantity: 1, + interval: "month", + intervalCount: 1, + }); + await expect(pause(ctx, { subscriptionId: sub.id })).rejects.toThrow( + /does not support pausing/i, + ); + }); +}); From 394815636f5b666137077fe49982cd8dd7628385 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:41:15 +0100 Subject: [PATCH 23/50] feat(core): apply subscription updates and provider-aware portal --- .changeset/provider-subscriptions.md | 3 +- .../src/admin/pages/SubscriptionsPage.tsx | 91 +++++++------------ .../islands/SubscriptionPortalIsland.tsx | 57 ++++++------ packages/core/src/payment-provider/types.ts | 17 ++++ .../core/src/routes/subscriptions-public.ts | 3 + packages/core/src/routes/webhook.ts | 43 ++++++++- .../core/test/provider-subscriptions.test.ts | 43 ++++++++- 7 files changed, 167 insertions(+), 90 deletions(-) diff --git a/.changeset/provider-subscriptions.md b/.changeset/provider-subscriptions.md index c2ffd30..6fef7d8 100644 --- a/.changeset/provider-subscriptions.md +++ b/.changeset/provider-subscriptions.md @@ -6,6 +6,7 @@ Add a provider-neutral subscription seam. - `PaymentProvider` gains optional `getSubscription`, `cancelSubscription` and `resumeSubscription`. Stripe keeps its existing Billing path; providers that manage billing themselves can use these. - `charge.succeeded` and `PaymentStatusResult` can carry `ProviderSubscriptionInfo`, so a provider can identify the subscription/plan behind a charge. +- A normalised `subscription.updated` event lets a provider report a cancellation or status change outside a charge; core updates the local row. - New `subscriptions/provider.ts` stores a provider-managed subscription and its invoices in the existing collections. The first charge creates an order and a local subscription; later charges are recorded as invoices and extend the period, not as new orders. -- `subscriptions/lifecycle.ts` dispatches cancel/resume to a provider-managed subscription. Pause and in-place plan changes are refused for providers that do not support them. +- `subscriptions/lifecycle.ts` dispatches cancel/resume to a provider-managed subscription. Pause and in-place plan changes are refused for providers that do not support them. The admin and customer portal hide pause and the Stripe billing portal for those subscriptions. - Stripe's `stripeSubscriptionId`/`stripeInvoiceId` fields keep their names for compatibility; they now hold the provider's subscription/plan and invoice id. diff --git a/packages/core/src/admin/pages/SubscriptionsPage.tsx b/packages/core/src/admin/pages/SubscriptionsPage.tsx index 1cdcd34..e45acdd 100644 --- a/packages/core/src/admin/pages/SubscriptionsPage.tsx +++ b/packages/core/src/admin/pages/SubscriptionsPage.tsx @@ -3,9 +3,9 @@ * `useListControls`, plus cancel/pause/resume with confirm dialogs, * per-row pending states, and toast feedback. * - * Stripe is the source of truth for subscription state, so we deliberately - * avoid optimistic updates: after every action we reload the list so the - * row reflects whatever webhook response came back. + * The payment provider is the source of truth for subscription state, so we + * deliberately avoid optimistic updates: after every action we reload the + * list so the row reflects whatever webhook response came back. */ import { useCallback, useMemo, useState } from "react"; @@ -64,19 +64,21 @@ function isCancellable(sub: Subscription): boolean { return !cancelled.includes(sub.status) && !sub.cancelAtPeriodEnd; } +function isProviderManaged(sub: Subscription): boolean { + return Boolean(sub.providerId && sub.providerId !== "stripe"); +} + function isPausable(sub: Subscription): boolean { - return sub.status === "active" || sub.status === "trialing"; + return (sub.status === "active" || sub.status === "trialing") && !isProviderManaged(sub); } function isResumable(sub: Subscription): boolean { - return sub.status === "paused"; + return sub.status === "paused" || (isProviderManaged(sub) && sub.status === "canceled"); } export function SubscriptionsPage() { const api = usePluginAPI(); - const [pending, setPending] = useState<{ id: string; action: Action } | null>( - null, - ); + const [pending, setPending] = useState<{ id: string; action: Action } | null>(null); const buildQuery = useMemo( () => (f: SubscriptionsFilters) => ({ @@ -89,23 +91,14 @@ export function SubscriptionsPage() { [], ); - const { - filters, - setFilter, - resetFilters, - items, - loading, - error, - hasMore, - loadMore, - reload, - } = useListControls({ - api, - endpoint: "admin/subscriptions", - initialFilters: INITIAL, - buildQuery, - limit: 50, - }); + const { filters, setFilter, resetFilters, items, loading, error, hasMore, loadMore, reload } = + useListControls({ + api, + endpoint: "admin/subscriptions", + initialFilters: INITIAL, + buildQuery, + limit: 50, + }); const act = useCallback( async (sub: Subscription, action: Action): Promise => { @@ -116,7 +109,7 @@ export function SubscriptionsPage() { title: immediate ? "Cancel subscription now?" : "Cancel at period end?", description: immediate ? "The customer loses access immediately. Any remaining time in the current period is not refunded automatically." - : `Access continues until ${new Date(sub.currentPeriodEnd).toLocaleDateString()}, then Stripe will cancel the subscription.`, + : `Access continues until ${new Date(sub.currentPeriodEnd).toLocaleDateString()}, then the payment provider will cancel the subscription.`, confirmLabel: immediate ? "Cancel now" : "Cancel at period end", destructive: true, }); @@ -126,7 +119,7 @@ export function SubscriptionsPage() { const ok = await confirm({ title: "Pause subscription?", description: - "Stripe stops generating invoices until the subscription is resumed. The customer keeps their record but won't be billed.", + "The payment provider stops generating invoices until the subscription is resumed. The customer keeps their record but won't be billed.", confirmLabel: "Pause", }); if (!ok) return; @@ -153,10 +146,7 @@ export function SubscriptionsPage() { } await reload(); } catch (err) { - toast.error( - "Action failed", - err instanceof Error ? err.message : String(err), - ); + toast.error("Action failed", err instanceof Error ? err.message : String(err)); } finally { setPending(null); } @@ -186,12 +176,7 @@ export function SubscriptionsPage() { label="Status" value={filters.status} options={STATUS_FILTERS} - onChange={(e) => - setFilter( - "status", - e.currentTarget.value as SubscriptionStatus | "", - ) - } + onChange={(e) => setFilter("status", e.currentTarget.value as SubscriptionStatus | "")} /> 0 ? "No subscriptions match" : "No subscriptions yet" - } + title={activeFilters > 0 ? "No subscriptions match" : "No subscriptions yet"} description={ activeFilters > 0 ? "Try widening your filters." @@ -272,9 +255,7 @@ export function SubscriptionsPage() { > {s.cancelAtPeriodEnd && ( - - Cancels at period end - + Cancels at period end )}
), @@ -306,11 +287,7 @@ export function SubscriptionsPage() { key: "act", header: "", render: (s) => ( - act(s, a)} - /> + act(s, a)} /> ), }, ]} @@ -379,14 +356,16 @@ function SubscriptionActions({ )} {isCancellable(sub) && ( <> - + {!isProviderManaged(sub) && ( + + )} )} - {sub.status !== "canceled" && sub.status !== "paused" && ( + {!providerManaged && sub.status !== "canceled" && sub.status !== "paused" && ( )} - {sub.status === "paused" && ( + {(sub.status === "paused" || (providerManaged && sub.status === "canceled")) && ( )} - + {!providerManaged && ( + + )} ); diff --git a/packages/core/src/payment-provider/types.ts b/packages/core/src/payment-provider/types.ts index a1ef975..7b384fa 100644 --- a/packages/core/src/payment-provider/types.ts +++ b/packages/core/src/payment-provider/types.ts @@ -219,6 +219,23 @@ export type NormalizedPaymentEvent = reason?: string; raw: unknown; } + | { + /** + * A provider-managed subscription changed state outside a charge + * (e.g. Flutterwave's `subscription.cancelled`). Core updates the + * local row; it does not create an order or an invoice. + */ + type: "subscription.updated"; + providerId: string; + providerEventId: string; + providerSubscriptionId: string; + status: ProviderSubscriptionInfo["status"]; + currentPeriodStart?: string; + currentPeriodEnd?: string; + cancelAtPeriodEnd?: boolean; + canceledAt?: string; + raw: unknown; + } | { /** * A refund this store created moved on at the provider (e.g. diff --git a/packages/core/src/routes/subscriptions-public.ts b/packages/core/src/routes/subscriptions-public.ts index c3cf17c..4148161 100644 --- a/packages/core/src/routes/subscriptions-public.ts +++ b/packages/core/src/routes/subscriptions-public.ts @@ -60,6 +60,8 @@ export interface PublicSubscription { intervalCount: number; currentPeriodEnd: Subscription["currentPeriodEnd"]; cancelAtPeriodEnd: boolean; + /** Gateway that owns the subscription. Unset means Stripe. */ + providerId?: string; } export function toPublicSubscription(sub: Subscription): PublicSubscription { @@ -72,6 +74,7 @@ export function toPublicSubscription(sub: Subscription): PublicSubscription { intervalCount: sub.intervalCount, currentPeriodEnd: sub.currentPeriodEnd, cancelAtPeriodEnd: sub.cancelAtPeriodEnd, + ...(sub.providerId ? { providerId: sub.providerId } : {}), }; } diff --git a/packages/core/src/routes/webhook.ts b/packages/core/src/routes/webhook.ts index e012bec..4bd6f40 100644 --- a/packages/core/src/routes/webhook.ts +++ b/packages/core/src/routes/webhook.ts @@ -60,6 +60,7 @@ import { handleInvoicePaymentFailed } from "../subscriptions/dunning"; import { addSubscriptionInterval, findProviderSubscription, + providerSubsStore, recordProviderSubscriptionInvoice, upsertProviderSubscription, } from "../subscriptions/provider"; @@ -862,9 +863,7 @@ async function handleNormalizedChargeSucceeded( cancelAtPeriodEnd: subscription.cancelAtPeriodEnd ?? false, ...(subscription.canceledAt ? { canceledAt: subscription.canceledAt } : {}), }); - const subscriptionIds = [ - ...new Set([...(order.subscriptionIds ?? []), local.id]), - ]; + const subscriptionIds = [...new Set([...(order.subscriptionIds ?? []), local.id])]; await ordersStore(ctx).put(order.id, { ...order, subscriptionIds, @@ -1010,6 +1009,44 @@ export const webhookRoutes = { if (normalized.type === "charge.failed") { return await handleNormalizedChargeFailed(ctx, normalized); } + if (normalized.type === "subscription.updated") { + if (normalized.providerId !== provider.id) { + return new Response( + JSON.stringify({ error: "Subscription event from another provider" }), + { status: 400, headers: { "Content-Type": "application/json" } }, + ); + } + const sub = await findProviderSubscription( + ctx, + provider.id, + normalized.providerSubscriptionId, + ); + if (!sub) { + return new Response(JSON.stringify({ received: true, orphan: true }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + } + await providerSubsStore(ctx).put(sub.id, { + ...sub, + status: normalized.status, + ...(normalized.currentPeriodStart + ? { currentPeriodStart: normalized.currentPeriodStart } + : {}), + ...(normalized.currentPeriodEnd + ? { currentPeriodEnd: normalized.currentPeriodEnd } + : {}), + ...(normalized.cancelAtPeriodEnd !== undefined + ? { cancelAtPeriodEnd: normalized.cancelAtPeriodEnd } + : {}), + ...(normalized.canceledAt ? { canceledAt: normalized.canceledAt } : {}), + updatedAt: new Date().toISOString(), + }); + return new Response(JSON.stringify({ received: true, subscriptionId: sub.id }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + } if (normalized.type === "refund.updated") { if (normalized.providerId !== provider.id) { return new Response(JSON.stringify({ error: "Refund event from another provider" }), { diff --git a/packages/core/test/provider-subscriptions.test.ts b/packages/core/test/provider-subscriptions.test.ts index 1ea7711..481f3d0 100644 --- a/packages/core/test/provider-subscriptions.test.ts +++ b/packages/core/test/provider-subscriptions.test.ts @@ -205,6 +205,48 @@ describe("provider-managed subscriptions", () => { expect(invoice.amount).toEqual({ amount: 150_000, currency: "KES" }); }); + it("applies a subscription.updated webhook to the local row", async () => { + const base = createMockPaymentProvider({ id: "acme" }); + registerPaymentProvider({ + ...base, + webhookHeaders: ["x-acme-signature"], + parseWebhookEvent(): NormalizedPaymentEvent { + return { + type: "subscription.updated", + providerId: "acme", + providerEventId: "sub-cancel-1", + providerSubscriptionId: "plan_1", + status: "canceled", + canceledAt: "2026-02-01T00:00:00.000Z", + raw: {}, + }; + }, + }); + const { ctx, getCol } = makeRouteContext({ + "settings:paymentProvider": "acme", + "settings:acmeSecretKey": "acme-key", + "settings:acmeWebhookSecret": "test-secret", + }); + const sub = await upsertProviderSubscription(ctx, { + providerId: "acme", + providerSubscriptionId: "plan_1", + customerId: "cus_1", + productId: "prod_1", + status: "active", + currency: "KES", + unitAmount: 150_000, + quantity: 1, + interval: "month", + intervalCount: 1, + }); + + const res = await deliver(ctx, JSON.stringify({ cancel: true })); + expect(res.status).toBe(200); + const stored = getCol("subscriptions").get(sub.id) as Subscription; + expect(stored.status).toBe("canceled"); + expect(stored.canceledAt).toBe("2026-02-01T00:00:00.000Z"); + }); + it("does not hand a provider's plan id to another provider", async () => { const current = { paymentReference: "pay_sub_1", @@ -228,7 +270,6 @@ describe("provider-managed subscriptions", () => { }); }); - describe("provider-managed lifecycle", () => { it("cancels and resumes through the provider, not Stripe", async () => { const calls: Array<{ action: string; id: string }> = []; From 224aade6732aac70948cbebf8d66138b38f7276f Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:43:43 +0100 Subject: [PATCH 24/50] docs(core): describe the subscription provider seam --- packages/core/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/core/README.md b/packages/core/README.md index 5e9a141..841da55 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -70,6 +70,8 @@ For provider authors, `PaymentProvider` can declare: - `credentialFields`: the label, accepted prefixes and help text for the settings form. - `webhookHeaders`: the headers that identify its webhooks, besides `x--signature`. `verifyWebhook` receives every request header, and `credentials` (the provider's saved secret key and webhook secret) for headers signed with the API key rather than the webhook secret. - `checkConnection`: one read-only call with the saved keys, behind a "Test connection" button in Settings. Return `{ ok, message }`, with `ok: false` and a message the merchant can act on for a wrong or under-permitted key. +- `capabilities.subscriptions` plus optional `getSubscription`, `cancelSubscription` and `resumeSubscription`: core stores the provider's subscription/plan id from the first `charge.succeeded` that carries `subscription`, records later charges as invoices, and dispatches cancel/resume. Return `ProviderSubscriptionInfo`. A provider that cannot pause or change plans in place can omit those methods; core refuses the action with a readable error. +- `parseWebhookEvent` may return `subscription.updated` for a cancellation or status change outside a charge. Core updates the local row and does not create an order. `parseWebhookEvent` may return `refund.updated` to move a pending refund to `succeeded` or `failed`. A failed refund stops counting against its order: the refunded total, payment status and order status are worked out again, and stock the refund put back is taken back off. From 6b9c49245de59bb7bdfeab52b6c6aa31a7c44612 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:44:45 +0100 Subject: [PATCH 25/50] fix(flutterwave): bill renewals at the recurring line total --- packages/flutterwave/README.md | 2 +- packages/flutterwave/src/provider.ts | 20 ++++++++++++++----- .../flutterwave/test/subscriptions.test.ts | 9 ++++++++- 3 files changed, 24 insertions(+), 7 deletions(-) diff --git a/packages/flutterwave/README.md b/packages/flutterwave/README.md index 9e89723..40347bf 100644 --- a/packages/flutterwave/README.md +++ b/packages/flutterwave/README.md @@ -122,7 +122,7 @@ Verified against Flutterwave's real test API with a Nigerian test account (KES w Flutterwave Payment Plans are card-only and tied to the customer's email. -1. On a subscription checkout, the package creates one plan (`POST /v3/payment-plans`) with the cart amount and interval, then sends `payment_plan` on `/v3/payments` or Inline. +1. On a subscription checkout, the package creates one plan (`POST /v3/payment-plans`) with the recurring line total and interval, then sends `payment_plan` on `/v3/payments` or Inline. The first charge can include tax or shipping; renewals charge the plan amount. 2. The plan id is stored as the provider subscription id. Because there is one plan per checkout, it is unique to that customer. 3. `verify` returns `plan`; the package reports it on `charge.succeeded` and `getPaymentStatus`. Core creates the order and the local subscription on the first charge, and records later charges as invoices. 4. **Cancel** calls `PUT /v3/payment-plans/{id}/cancel`. Flutterwave cancels immediately; `at_period_end` has no API equivalent. diff --git a/packages/flutterwave/src/provider.ts b/packages/flutterwave/src/provider.ts index bc90850..b02058b 100644 --- a/packages/flutterwave/src/provider.ts +++ b/packages/flutterwave/src/provider.ts @@ -324,23 +324,33 @@ async function createSubscriptionPlan( client: ReturnType, input: InitCheckoutInput, ): Promise { - const line = input.lineItems[0]; - const recurring = line?.recurring; - if (!line || !recurring) { + const recurringLines = input.lineItems.filter((item) => item.recurring); + if (recurringLines.length === 0) { throw new Error("Flutterwave subscription checkout needs a recurring line item"); } - if (input.lineItems.length !== 1) { + if (recurringLines.length > 1) { throw new Error("Flutterwave Payment Plans support one subscription line per checkout"); } + const line = recurringLines[0]; + const recurring = line?.recurring; + if (!line || !recurring) { + throw new Error("Flutterwave subscription checkout needs a recurring line item"); + } if ((input.subscriptionTrialPeriodDays ?? 0) > 0) { throw new Error("Flutterwave Payment Plans do not support trials"); } + // The plan is the renewal amount: the recurring line(s), without the + // one-time tax or shipping that the first checkout adds. + const recurringTotal = line.amount * line.quantity; + if (!Number.isSafeInteger(recurringTotal) || recurringTotal <= 0) { + throw new Error("Flutterwave subscription amount must be a positive integer"); + } const data = await call(ctx, { client, path: "/payment-plans", body: { name: `DC ${input.orderDraftId}`, - amount: toMajorUnits(input.amount), + amount: toMajorUnits(recurringTotal), currency: input.currency.toUpperCase(), interval: planInterval(recurring.interval, recurring.intervalCount), duration: 0, diff --git a/packages/flutterwave/test/subscriptions.test.ts b/packages/flutterwave/test/subscriptions.test.ts index 6e53a85..d007eed 100644 --- a/packages/flutterwave/test/subscriptions.test.ts +++ b/packages/flutterwave/test/subscriptions.test.ts @@ -88,7 +88,13 @@ describe("Flutterwave subscription checkout", () => { const result = await flutterwavePaymentProvider.initCheckout( runtime, - subscriptionInput(), + subscriptionInput({ + amount: 260_000, + lineItems: [ + ...subscriptionInput().lineItems, + { name: "Tax", amount: 10_000, currency: "KES", quantity: 1 }, + ], + }), credentials, ); @@ -101,6 +107,7 @@ describe("Flutterwave subscription checkout", () => { duration: 0, }); expect(calls[1]?.path).toBe("/v3/payments"); + expect(calls[1]?.body.amount).toBe(2600); expect(calls[1]?.body.payment_plan).toBe("254811"); expect(calls[1]?.body.meta).toMatchObject({ orderDraftId: "0123456789abcdef0123456789abcdef", From 0dd89eeddf6e6f4a4b6e73f57a63b1f4a23f9c13 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:45:20 +0100 Subject: [PATCH 26/50] fix(flutterwave): validate on-page checkout before creating a plan --- packages/flutterwave/src/provider.ts | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/packages/flutterwave/src/provider.ts b/packages/flutterwave/src/provider.ts index b02058b..6c9c971 100644 --- a/packages/flutterwave/src/provider.ts +++ b/packages/flutterwave/src/provider.ts @@ -785,7 +785,16 @@ export const flutterwavePaymentProvider: PaymentProvider = { if (!SUPPORTED_CURRENCIES.has(currency)) { throw new Error(`Flutterwave does not support currency ${input.currency}`); } + const onPage = input.checkoutStyle === "on_page"; + const publicKey = onPage ? credentials.publicKey?.trim() : undefined; + if (onPage && !publicKey) { + throw new Error( + "Flutterwave on-page checkout needs the public key; add it in Settings → Payment provider", + ); + } + const client = toFlutterwaveClient(credentials); + const subaccounts = subaccountsFor(input); const paymentPlan = input.mode === "subscription" ? await createSubscriptionPlan(ctx, client, input) : undefined; const checkoutRef = flutterwaveReferenceFor(input.orderDraftId); @@ -794,15 +803,8 @@ export const flutterwavePaymentProvider: PaymentProvider = { const name = input.customer.name ?? (addressName || undefined); const phone = input.customer.phone ?? address?.phone; const paymentOptions = mapPaymentOptions(input.preferredChannels, currency); - const subaccounts = subaccountsFor(input); - if (input.checkoutStyle === "on_page") { - const publicKey = credentials.publicKey?.trim(); - if (!publicKey) { - throw new Error( - "Flutterwave on-page checkout needs the public key; add it in Settings → Payment provider", - ); - } + if (onPage) { // Inline creates the transaction in the browser, so there is no // server-side /payments call. The order still comes only from the // signed webhook and the live verify. @@ -810,7 +812,7 @@ export const flutterwavePaymentProvider: PaymentProvider = { kind: "on_page", checkoutReference: checkoutRef, client: { - publicKey, + publicKey: publicKey ?? "", txRef: checkoutRef, amount: String(toMajorUnits(input.amount)), currency, From 601e62b461ad3972b97543372f19ad0be383a214 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:46:07 +0100 Subject: [PATCH 27/50] fix(core): keep the Stripe portal off provider-managed subscriptions --- .../core/src/routes/subscriptions-public.ts | 10 +++++++ .../core/test/subscriptions-public.test.ts | 28 +++++++++++++++++-- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/packages/core/src/routes/subscriptions-public.ts b/packages/core/src/routes/subscriptions-public.ts index 4148161..88fa965 100644 --- a/packages/core/src/routes/subscriptions-public.ts +++ b/packages/core/src/routes/subscriptions-public.ts @@ -223,6 +223,16 @@ async function handlePortal(routeCtx: RouteContext, _ctx?: PluginContext): Promi const loaded = await loadAuthorisedSub(ctx, extractToken(routeCtx.request, input)); if (!loaded.ok) return loaded.response; + if (loaded.subscription.providerId && loaded.subscription.providerId !== "stripe") { + return jsonResponse( + { + error: + "This subscription is managed by its payment provider. Use Cancel or Resume here instead.", + }, + 400, + ); + } + // Portal requires a Stripe customer id. Resolve via the local // customer row the subscription is linked to. const customerId = loaded.subscription.customerId; diff --git a/packages/core/test/subscriptions-public.test.ts b/packages/core/test/subscriptions-public.test.ts index 0f85aac..10d0af1 100644 --- a/packages/core/test/subscriptions-public.test.ts +++ b/packages/core/test/subscriptions-public.test.ts @@ -37,22 +37,26 @@ const storedSub: Subscription = { updatedAt: "2026-11-14T00:00:00.000Z", }; -function ctxWithSub(opts: { stripeConfigured?: boolean } = {}): PluginContext { +function ctxWithSub(opts: { stripeConfigured?: boolean; providerId?: string } = {}): PluginContext { const stripeConfigured = opts.stripeConfigured ?? true; + const sub = { + ...storedSub, + ...(opts.providerId ? { providerId: opts.providerId } : {}), + }; return { storage: { subscriptions: { query: async (q: { where?: { stripeSubscriptionId?: string } }) => { if (q.where?.stripeSubscriptionId === STRIPE_SUB) { return { - items: [{ id: storedSub.id, data: storedSub }], + items: [{ id: sub.id, data: sub }], cursor: null, hasMore: false, }; } return { items: [], cursor: null, hasMore: false }; }, - get: async (id: string) => (id === storedSub.id ? storedSub : null), + get: async (id: string) => (id === sub.id ? sub : null), }, }, kv: { @@ -163,6 +167,24 @@ describe("subscription mutation routes", () => { } }); + it("refuses the Stripe portal for a provider-managed subscription", async () => { + const ctx = ctxWithSub({ providerId: "flutterwave" }); + const token = await tokenFor(ctx); + const res = await subscriptionsPublicRoutes["subscriptions/portal"].handler( + { + request: new Request( + "http://localhost/_emdash/api/plugins/dashcommerce/subscriptions/portal", + { method: "POST" }, + ), + input: { token }, + } as RouteContext, + ctx, + ); + expect(res.status).toBe(400); + const body = (await res.json()) as { error?: string }; + expect(body.error).toMatch(/managed by its payment provider/i); + }); + it("cancel without a token is 400", async () => { const res = await subscriptionsPublicRoutes["subscriptions/cancel"].handler( { From fe9bc87b996fe1053d8947be13894b5bed174f58 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:46:22 +0100 Subject: [PATCH 28/50] fix(core): keep the Stripe portal off provider-managed subscriptions --- .../core/src/routes/subscriptions-public.ts | 10 +++++++ .../core/test/subscriptions-public.test.ts | 28 +++++++++++++++++-- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/packages/core/src/routes/subscriptions-public.ts b/packages/core/src/routes/subscriptions-public.ts index 4148161..88fa965 100644 --- a/packages/core/src/routes/subscriptions-public.ts +++ b/packages/core/src/routes/subscriptions-public.ts @@ -223,6 +223,16 @@ async function handlePortal(routeCtx: RouteContext, _ctx?: PluginContext): Promi const loaded = await loadAuthorisedSub(ctx, extractToken(routeCtx.request, input)); if (!loaded.ok) return loaded.response; + if (loaded.subscription.providerId && loaded.subscription.providerId !== "stripe") { + return jsonResponse( + { + error: + "This subscription is managed by its payment provider. Use Cancel or Resume here instead.", + }, + 400, + ); + } + // Portal requires a Stripe customer id. Resolve via the local // customer row the subscription is linked to. const customerId = loaded.subscription.customerId; diff --git a/packages/core/test/subscriptions-public.test.ts b/packages/core/test/subscriptions-public.test.ts index 0f85aac..10d0af1 100644 --- a/packages/core/test/subscriptions-public.test.ts +++ b/packages/core/test/subscriptions-public.test.ts @@ -37,22 +37,26 @@ const storedSub: Subscription = { updatedAt: "2026-11-14T00:00:00.000Z", }; -function ctxWithSub(opts: { stripeConfigured?: boolean } = {}): PluginContext { +function ctxWithSub(opts: { stripeConfigured?: boolean; providerId?: string } = {}): PluginContext { const stripeConfigured = opts.stripeConfigured ?? true; + const sub = { + ...storedSub, + ...(opts.providerId ? { providerId: opts.providerId } : {}), + }; return { storage: { subscriptions: { query: async (q: { where?: { stripeSubscriptionId?: string } }) => { if (q.where?.stripeSubscriptionId === STRIPE_SUB) { return { - items: [{ id: storedSub.id, data: storedSub }], + items: [{ id: sub.id, data: sub }], cursor: null, hasMore: false, }; } return { items: [], cursor: null, hasMore: false }; }, - get: async (id: string) => (id === storedSub.id ? storedSub : null), + get: async (id: string) => (id === sub.id ? sub : null), }, }, kv: { @@ -163,6 +167,24 @@ describe("subscription mutation routes", () => { } }); + it("refuses the Stripe portal for a provider-managed subscription", async () => { + const ctx = ctxWithSub({ providerId: "flutterwave" }); + const token = await tokenFor(ctx); + const res = await subscriptionsPublicRoutes["subscriptions/portal"].handler( + { + request: new Request( + "http://localhost/_emdash/api/plugins/dashcommerce/subscriptions/portal", + { method: "POST" }, + ), + input: { token }, + } as RouteContext, + ctx, + ); + expect(res.status).toBe(400); + const body = (await res.json()) as { error?: string }; + expect(body.error).toMatch(/managed by its payment provider/i); + }); + it("cancel without a token is 400", async () => { const res = await subscriptionsPublicRoutes["subscriptions/cancel"].handler( { From 9154287159295a73821aa6b18dce42490c36f204 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:47:22 +0100 Subject: [PATCH 29/50] fix(core): make subscription invoice recording idempotent --- packages/core/src/subscriptions/provider.ts | 15 ++++--- .../core/test/provider-subscriptions.test.ts | 41 +++++++++++++++++++ 2 files changed, 50 insertions(+), 6 deletions(-) diff --git a/packages/core/src/subscriptions/provider.ts b/packages/core/src/subscriptions/provider.ts index 5c06c52..87d6913 100644 --- a/packages/core/src/subscriptions/provider.ts +++ b/packages/core/src/subscriptions/provider.ts @@ -27,8 +27,7 @@ export function providerSubsStore(ctx: PluginContext): SubsStore { } function invoiceStore(ctx: PluginContext): InvoiceStore { - return (ctx.storage as unknown as { subscription_invoices: InvoiceStore }) - .subscription_invoices; + return (ctx.storage as unknown as { subscription_invoices: InvoiceStore }).subscription_invoices; } /** Add a billing interval to an ISO date, clamping month-end. */ @@ -51,9 +50,7 @@ export function addSubscriptionInterval( const day = date.getUTCDate(); date.setUTCDate(1); date.setUTCMonth(date.getUTCMonth() + months); - const lastDay = new Date( - Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0), - ).getUTCDate(); + const lastDay = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0)).getUTCDate(); date.setUTCDate(Math.min(day, lastDay)); return date.toISOString(); } @@ -160,8 +157,14 @@ export async function recordProviderSubscriptionInvoice( limit: 1, }); const existing = existingResult.items[0]; - const id = existing?.id ?? randomId(); + const existingInvoice = existing?.data as SubscriptionInvoice | undefined; const status = input.status ?? "paid"; + // A paid invoice is final. Returning it avoids extending the period a + // second time if the same charge is delivered with a different event id. + if (existingInvoice?.status === "paid" && status === "paid") { + return { ...existingInvoice, id: existing?.id ?? existingInvoice.id }; + } + const id = existing?.id ?? randomId(); const now = new Date().toISOString(); const invoice: SubscriptionInvoice = { diff --git a/packages/core/test/provider-subscriptions.test.ts b/packages/core/test/provider-subscriptions.test.ts index 481f3d0..b2cdb09 100644 --- a/packages/core/test/provider-subscriptions.test.ts +++ b/packages/core/test/provider-subscriptions.test.ts @@ -19,6 +19,7 @@ import { cancel, pause, resume } from "../src/subscriptions/lifecycle"; import { addSubscriptionInterval, findProviderSubscription, + recordProviderSubscriptionInvoice, upsertProviderSubscription, } from "../src/subscriptions/provider"; import type { CartState, Order, Subscription, SubscriptionInvoice } from "../src/types"; @@ -205,6 +206,46 @@ describe("provider-managed subscriptions", () => { expect(invoice.amount).toEqual({ amount: 150_000, currency: "KES" }); }); + it("does not extend the period twice for the same paid invoice", async () => { + const { ctx } = makeRouteContext({}); + const sub = await upsertProviderSubscription(ctx, { + providerId: "acme", + providerSubscriptionId: "plan_dup", + customerId: "cus_1", + productId: "prod_1", + status: "active", + currency: "KES", + unitAmount: 150_000, + quantity: 1, + interval: "month", + intervalCount: 1, + currentPeriodStart: "2026-01-01T00:00:00.000Z", + currentPeriodEnd: "2026-02-01T00:00:00.000Z", + }); + const first = await recordProviderSubscriptionInvoice(ctx, { + subscription: sub, + providerId: "acme", + providerInvoiceId: "pay_dup", + amount: 150_000, + currency: "KES", + status: "paid", + periodStart: "2026-02-01T00:00:00.000Z", + }); + const afterFirst = await findProviderSubscription(ctx, "acme", "plan_dup"); + expect(afterFirst?.currentPeriodEnd).toBe("2026-03-01T00:00:00.000Z"); + const second = await recordProviderSubscriptionInvoice(ctx, { + subscription: afterFirst ?? sub, + providerId: "acme", + providerInvoiceId: "pay_dup", + amount: 150_000, + currency: "KES", + status: "paid", + }); + expect(second.id).toBe(first.id); + const afterSecond = await findProviderSubscription(ctx, "acme", "plan_dup"); + expect(afterSecond?.currentPeriodEnd).toBe("2026-03-01T00:00:00.000Z"); + }); + it("applies a subscription.updated webhook to the local row", async () => { const base = createMockPaymentProvider({ id: "acme" }); registerPaymentProvider({ From 9bb56e3b5e73a64de3b0f02f465aa76904425270 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:47:36 +0100 Subject: [PATCH 30/50] fix(core): make subscription invoice recording idempotent --- packages/core/src/subscriptions/provider.ts | 8 +++- .../core/test/provider-subscriptions.test.ts | 41 +++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/packages/core/src/subscriptions/provider.ts b/packages/core/src/subscriptions/provider.ts index 307aafa..87d6913 100644 --- a/packages/core/src/subscriptions/provider.ts +++ b/packages/core/src/subscriptions/provider.ts @@ -157,8 +157,14 @@ export async function recordProviderSubscriptionInvoice( limit: 1, }); const existing = existingResult.items[0]; - const id = existing?.id ?? randomId(); + const existingInvoice = existing?.data as SubscriptionInvoice | undefined; const status = input.status ?? "paid"; + // A paid invoice is final. Returning it avoids extending the period a + // second time if the same charge is delivered with a different event id. + if (existingInvoice?.status === "paid" && status === "paid") { + return { ...existingInvoice, id: existing?.id ?? existingInvoice.id }; + } + const id = existing?.id ?? randomId(); const now = new Date().toISOString(); const invoice: SubscriptionInvoice = { diff --git a/packages/core/test/provider-subscriptions.test.ts b/packages/core/test/provider-subscriptions.test.ts index 481f3d0..b2cdb09 100644 --- a/packages/core/test/provider-subscriptions.test.ts +++ b/packages/core/test/provider-subscriptions.test.ts @@ -19,6 +19,7 @@ import { cancel, pause, resume } from "../src/subscriptions/lifecycle"; import { addSubscriptionInterval, findProviderSubscription, + recordProviderSubscriptionInvoice, upsertProviderSubscription, } from "../src/subscriptions/provider"; import type { CartState, Order, Subscription, SubscriptionInvoice } from "../src/types"; @@ -205,6 +206,46 @@ describe("provider-managed subscriptions", () => { expect(invoice.amount).toEqual({ amount: 150_000, currency: "KES" }); }); + it("does not extend the period twice for the same paid invoice", async () => { + const { ctx } = makeRouteContext({}); + const sub = await upsertProviderSubscription(ctx, { + providerId: "acme", + providerSubscriptionId: "plan_dup", + customerId: "cus_1", + productId: "prod_1", + status: "active", + currency: "KES", + unitAmount: 150_000, + quantity: 1, + interval: "month", + intervalCount: 1, + currentPeriodStart: "2026-01-01T00:00:00.000Z", + currentPeriodEnd: "2026-02-01T00:00:00.000Z", + }); + const first = await recordProviderSubscriptionInvoice(ctx, { + subscription: sub, + providerId: "acme", + providerInvoiceId: "pay_dup", + amount: 150_000, + currency: "KES", + status: "paid", + periodStart: "2026-02-01T00:00:00.000Z", + }); + const afterFirst = await findProviderSubscription(ctx, "acme", "plan_dup"); + expect(afterFirst?.currentPeriodEnd).toBe("2026-03-01T00:00:00.000Z"); + const second = await recordProviderSubscriptionInvoice(ctx, { + subscription: afterFirst ?? sub, + providerId: "acme", + providerInvoiceId: "pay_dup", + amount: 150_000, + currency: "KES", + status: "paid", + }); + expect(second.id).toBe(first.id); + const afterSecond = await findProviderSubscription(ctx, "acme", "plan_dup"); + expect(afterSecond?.currentPeriodEnd).toBe("2026-03-01T00:00:00.000Z"); + }); + it("applies a subscription.updated webhook to the local row", async () => { const base = createMockPaymentProvider({ id: "acme" }); registerPaymentProvider({ From d7a23a7dd02392643c14e3526dceba553bf3034d Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:48:51 +0100 Subject: [PATCH 31/50] fix(flutterwave): keep repeated subscription cancellations distinct --- packages/flutterwave/src/provider.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/flutterwave/src/provider.ts b/packages/flutterwave/src/provider.ts index 6c9c971..92def0f 100644 --- a/packages/flutterwave/src/provider.ts +++ b/packages/flutterwave/src/provider.ts @@ -925,7 +925,10 @@ export const flutterwavePaymentProvider: PaymentProvider = { return { type: "subscription.updated", providerId: "flutterwave", - providerEventId: `subscription.cancelled:${String(planId)}`, + // The payload has no event id. A timestamp keeps a later + // cancel-after-reactivate from being deduped against the first; + // a retry re-applies the same cancelled state harmlessly. + providerEventId: `subscription.cancelled:${String(planId)}:${Date.now()}`, providerSubscriptionId: String(planId), status: "canceled", canceledAt: new Date().toISOString(), From ae217a286dc1cba5195a5d90f0f709b5c672e216 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:49:31 +0100 Subject: [PATCH 32/50] fix(flutterwave): discard a subscription plan when hosted checkout fails --- packages/flutterwave/src/provider.ts | 68 +++++++++++++------ .../flutterwave/test/subscriptions.test.ts | 25 +++++++ 2 files changed, 71 insertions(+), 22 deletions(-) diff --git a/packages/flutterwave/src/provider.ts b/packages/flutterwave/src/provider.ts index 92def0f..019164b 100644 --- a/packages/flutterwave/src/provider.ts +++ b/packages/flutterwave/src/provider.ts @@ -362,6 +362,23 @@ async function createSubscriptionPlan( return String(data.id); } +async function discardPlan( + ctx: PaymentProviderRuntimeContext, + client: ReturnType, + planId: string | undefined, +): Promise { + if (!planId) return; + try { + await call(ctx, { + client, + method: "PUT", + path: `/payment-plans/${encodeURIComponent(planId)}/cancel`, + }); + } catch { + // Best effort: the checkout error is the one the merchant needs. + } +} + function channelLabel(type: string | undefined): string | undefined { if (!type) return undefined; const value = type.toLowerCase(); @@ -827,31 +844,38 @@ export const flutterwavePaymentProvider: PaymentProvider = { }; } - const data = await call<{ link?: string }>(ctx, { - client, - path: "/payments", - body: { - tx_ref: checkoutRef, - amount: toMajorUnits(input.amount), - currency, - redirect_url: flutterwaveCallbackUrl(input.successUrl), - customer: { - email, - ...(name ? { name } : {}), - ...(phone ? { phonenumber: phone } : {}), - }, - meta: { - ...input.metadata, - ...input.subscriptionMetadata, - orderDraftId: input.orderDraftId, + let data: { link?: string }; + try { + data = await call<{ link?: string }>(ctx, { + client, + path: "/payments", + body: { + tx_ref: checkoutRef, + amount: toMajorUnits(input.amount), + currency, + redirect_url: flutterwaveCallbackUrl(input.successUrl), + customer: { + email, + ...(name ? { name } : {}), + ...(phone ? { phonenumber: phone } : {}), + }, + meta: { + ...input.metadata, + ...input.subscriptionMetadata, + orderDraftId: input.orderDraftId, + }, + ...(paymentOptions ? { payment_options: paymentOptions.join(",") } : {}), + ...(subaccounts ? { subaccounts } : {}), + ...(paymentPlan ? { payment_plan: paymentPlan } : {}), }, - ...(paymentOptions ? { payment_options: paymentOptions.join(",") } : {}), - ...(subaccounts ? { subaccounts } : {}), - ...(paymentPlan ? { payment_plan: paymentPlan } : {}), - }, - }); + }); + } catch (err) { + await discardPlan(ctx, client, paymentPlan); + throw err; + } if (!data?.link) { + await discardPlan(ctx, client, paymentPlan); throw new Error("Flutterwave did not return a hosted checkout link"); } return { diff --git a/packages/flutterwave/test/subscriptions.test.ts b/packages/flutterwave/test/subscriptions.test.ts index d007eed..7466f6d 100644 --- a/packages/flutterwave/test/subscriptions.test.ts +++ b/packages/flutterwave/test/subscriptions.test.ts @@ -115,6 +115,31 @@ describe("Flutterwave subscription checkout", () => { }); }); + it("cancels the new plan when the hosted payment call fails", async () => { + const calls: Array<{ method: string; path: string }> = []; + const runtime = ctx(async (url, init) => { + const { pathname } = new URL(url); + calls.push({ method: init?.method ?? "GET", path: pathname }); + if (pathname === "/v3/payment-plans") return ok({ id: 254811, name: "DC plan" }); + if (pathname === "/v3/payments") { + return new Response(JSON.stringify({ status: "error", message: "boom", data: null }), { + status: 500, + headers: { "Content-Type": "application/json" }, + }); + } + if (pathname.endsWith("/cancel")) return ok({ id: 254811, status: "cancelled" }); + return new Response("{}", { status: 404 }); + }); + + await expect( + flutterwavePaymentProvider.initCheckout(runtime, subscriptionInput(), credentials), + ).rejects.toThrow(/boom/); + expect(calls).toContainEqual({ + method: "PUT", + path: "/v3/payment-plans/254811/cancel", + }); + }); + it("passes the plan to Inline on the on-page path", async () => { const calls: string[] = []; const runtime = ctx(async (url) => { From 8ca570be0b52f9aba4e74dcbd34ea68fa499df8e Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:50:18 +0100 Subject: [PATCH 33/50] docs(flutterwave): mention subscriptions in the package metadata --- packages/flutterwave/package.json | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/flutterwave/package.json b/packages/flutterwave/package.json index d88f128..9797e33 100644 --- a/packages/flutterwave/package.json +++ b/packages/flutterwave/package.json @@ -1,7 +1,7 @@ { "name": "@dashcommerce/flutterwave", "version": "0.0.0", - "description": "Flutterwave payment provider for @dashcommerce/core: card, M-Pesa and mobile money through Flutterwave's hosted checkout, verified webhooks, live status checks and refunds.", + "description": "Flutterwave payment provider for @dashcommerce/core: card, M-Pesa and mobile money through hosted checkout or Inline, verified webhooks, live status checks, refunds, vendor splits and Payment Plans subscriptions.", "type": "module", "main": "dist/index.mjs", "module": "dist/index.mjs", @@ -20,7 +20,16 @@ "engines": { "node": ">=20" }, - "keywords": ["dashcommerce", "flutterwave", "payments", "mpesa", "mobile-money", "africa"], + "keywords": [ + "dashcommerce", + "flutterwave", + "payments", + "mpesa", + "mobile-money", + "africa", + "subscriptions", + "payment-plans" + ], "author": "DashCommerce contributors", "license": "MIT", "repository": { From be3495b2ce147ae3a2d21208d06f6ff05d3e23f6 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:51:35 +0100 Subject: [PATCH 34/50] fix(core): scope provider subscription ids by provider --- packages/core/src/subscriptions/lifecycle.ts | 28 ++++++++----------- packages/core/src/subscriptions/provider.ts | 9 ++++-- packages/core/src/types.ts | 6 ++++ .../core/test/provider-subscriptions.test.ts | 3 +- 4 files changed, 26 insertions(+), 20 deletions(-) diff --git a/packages/core/src/subscriptions/lifecycle.ts b/packages/core/src/subscriptions/lifecycle.ts index 4f18622..7ae181a 100644 --- a/packages/core/src/subscriptions/lifecycle.ts +++ b/packages/core/src/subscriptions/lifecycle.ts @@ -41,7 +41,8 @@ export async function cancel( const info = await providerCancel(ctx, local, input.mode); await saveProviderState(ctx, local, info, { cancelAtPeriodEnd: info.cancelAtPeriodEnd ?? input.mode === "at_period_end", - canceledAt: info.status === "canceled" ? (info.canceledAt ?? new Date().toISOString()) : undefined, + canceledAt: + info.status === "canceled" ? (info.canceledAt ?? new Date().toISOString()) : undefined, }); return info; } @@ -67,10 +68,7 @@ export interface PauseInput { client?: StripeClientOptions; } -export async function pause( - ctx: PluginContext, - input: PauseInput, -): Promise { +export async function pause(ctx: PluginContext, input: PauseInput): Promise { const local = await loadLocal(ctx, input.subscriptionId); if (isProviderManaged(local)) { throw new Error(`${local.providerId} does not support pausing subscriptions`); @@ -112,13 +110,7 @@ export async function resume( const client = requireStripeClient(input.client); const idemKey = `sub-resume:${local.stripeSubscriptionId}`; - return stripeUpdate( - ctx, - local.stripeSubscriptionId, - { pauseCollection: null }, - client, - idemKey, - ); + return stripeUpdate(ctx, local.stripeSubscriptionId, { pauseCollection: null }, client, idemKey); } export interface ChangePlanInput { @@ -182,7 +174,7 @@ async function providerCancel( return provider.cancelSubscription( ctx, { - providerSubscriptionId: local.stripeSubscriptionId, + providerSubscriptionId: local.providerSubscriptionId ?? local.stripeSubscriptionId, atPeriodEnd: mode === "at_period_end", }, creds, @@ -201,7 +193,7 @@ async function providerResume( if (!creds) throw new Error(`Payment provider "${provider.id}" is not configured`); return provider.resumeSubscription( ctx, - { providerSubscriptionId: local.stripeSubscriptionId }, + { providerSubscriptionId: local.providerSubscriptionId ?? local.stripeSubscriptionId }, creds, ); } @@ -226,9 +218,11 @@ async function saveProviderState( async function loadLocal(ctx: PluginContext, id: string): Promise { // Accept either our uuid or the provider id for convenience. - const directRes = await (ctx.storage as unknown as { - subscriptions: { get(id: string): Promise }; - }).subscriptions.get(id); + const directRes = await ( + ctx.storage as unknown as { + subscriptions: { get(id: string): Promise }; + } + ).subscriptions.get(id); if (directRes) return { ...(directRes as Subscription), id }; const byProvider = await findSubscription(ctx, id); if (byProvider) return byProvider; diff --git a/packages/core/src/subscriptions/provider.ts b/packages/core/src/subscriptions/provider.ts index 87d6913..07ee1c4 100644 --- a/packages/core/src/subscriptions/provider.ts +++ b/packages/core/src/subscriptions/provider.ts @@ -55,13 +55,17 @@ export function addSubscriptionInterval( return date.toISOString(); } +function providerStorageKey(providerId: string, providerSubscriptionId: string): string { + return `${providerId}:${providerSubscriptionId}`; +} + export async function findProviderSubscription( ctx: PluginContext, providerId: string, providerSubscriptionId: string, ): Promise { const result = await providerSubsStore(ctx).query({ - where: { stripeSubscriptionId: providerSubscriptionId }, + where: { stripeSubscriptionId: providerStorageKey(providerId, providerSubscriptionId) }, limit: 1, }); const row = result.items[0]; @@ -110,8 +114,9 @@ export async function upsertProviderSubscription( const record: Subscription = { id: existing?.id ?? randomId(), - stripeSubscriptionId: input.providerSubscriptionId, + stripeSubscriptionId: providerStorageKey(input.providerId, input.providerSubscriptionId), providerId: input.providerId, + providerSubscriptionId: input.providerSubscriptionId, customerId: input.customerId, productId: input.productId, ...(input.variantId ? { variantId: input.variantId } : {}), diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index c5fe6fb..353b508 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -481,6 +481,12 @@ export interface Subscription { stripeSubscriptionId: string; /** Gateway that owns this subscription. Unset means Stripe. */ providerId?: string; + /** + * The provider's raw subscription/plan id, without the storage prefix. + * Provider-managed rows store `${providerId}:${id}` in + * `stripeSubscriptionId` so two providers cannot collide on a numeric id. + */ + providerSubscriptionId?: string; customerId: string; productId: string; variantId?: string; diff --git a/packages/core/test/provider-subscriptions.test.ts b/packages/core/test/provider-subscriptions.test.ts index b2cdb09..7ac77b9 100644 --- a/packages/core/test/provider-subscriptions.test.ts +++ b/packages/core/test/provider-subscriptions.test.ts @@ -145,8 +145,9 @@ describe("provider-managed subscriptions", () => { expect(order.subscriptionIds?.length).toBe(1); const sub = Array.from(getCol("subscriptions").values())[0] as Subscription; expect(sub).toMatchObject({ - stripeSubscriptionId: "plan_1", + stripeSubscriptionId: "acme:plan_1", providerId: "acme", + providerSubscriptionId: "plan_1", customerId: order.customerId, status: "active", currency: "KES", From 0a81937aae9a96dfdcf1f92a2e74c2a05e050e18 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:51:38 +0100 Subject: [PATCH 35/50] fix(core): scope provider subscription ids by provider --- packages/core/src/subscriptions/lifecycle.ts | 4 ++-- packages/core/src/subscriptions/provider.ts | 9 +++++++-- packages/core/src/types.ts | 6 ++++++ packages/core/test/provider-subscriptions.test.ts | 3 ++- 4 files changed, 17 insertions(+), 5 deletions(-) diff --git a/packages/core/src/subscriptions/lifecycle.ts b/packages/core/src/subscriptions/lifecycle.ts index 7af502b..7ae181a 100644 --- a/packages/core/src/subscriptions/lifecycle.ts +++ b/packages/core/src/subscriptions/lifecycle.ts @@ -174,7 +174,7 @@ async function providerCancel( return provider.cancelSubscription( ctx, { - providerSubscriptionId: local.stripeSubscriptionId, + providerSubscriptionId: local.providerSubscriptionId ?? local.stripeSubscriptionId, atPeriodEnd: mode === "at_period_end", }, creds, @@ -193,7 +193,7 @@ async function providerResume( if (!creds) throw new Error(`Payment provider "${provider.id}" is not configured`); return provider.resumeSubscription( ctx, - { providerSubscriptionId: local.stripeSubscriptionId }, + { providerSubscriptionId: local.providerSubscriptionId ?? local.stripeSubscriptionId }, creds, ); } diff --git a/packages/core/src/subscriptions/provider.ts b/packages/core/src/subscriptions/provider.ts index 87d6913..07ee1c4 100644 --- a/packages/core/src/subscriptions/provider.ts +++ b/packages/core/src/subscriptions/provider.ts @@ -55,13 +55,17 @@ export function addSubscriptionInterval( return date.toISOString(); } +function providerStorageKey(providerId: string, providerSubscriptionId: string): string { + return `${providerId}:${providerSubscriptionId}`; +} + export async function findProviderSubscription( ctx: PluginContext, providerId: string, providerSubscriptionId: string, ): Promise { const result = await providerSubsStore(ctx).query({ - where: { stripeSubscriptionId: providerSubscriptionId }, + where: { stripeSubscriptionId: providerStorageKey(providerId, providerSubscriptionId) }, limit: 1, }); const row = result.items[0]; @@ -110,8 +114,9 @@ export async function upsertProviderSubscription( const record: Subscription = { id: existing?.id ?? randomId(), - stripeSubscriptionId: input.providerSubscriptionId, + stripeSubscriptionId: providerStorageKey(input.providerId, input.providerSubscriptionId), providerId: input.providerId, + providerSubscriptionId: input.providerSubscriptionId, customerId: input.customerId, productId: input.productId, ...(input.variantId ? { variantId: input.variantId } : {}), diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index fafa90d..a9babff 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -504,6 +504,12 @@ export interface Subscription { stripeSubscriptionId: string; /** Gateway that owns this subscription. Unset means Stripe. */ providerId?: string; + /** + * The provider's raw subscription/plan id, without the storage prefix. + * Provider-managed rows store `${providerId}:${id}` in + * `stripeSubscriptionId` so two providers cannot collide on a numeric id. + */ + providerSubscriptionId?: string; customerId: string; productId: string; variantId?: string; diff --git a/packages/core/test/provider-subscriptions.test.ts b/packages/core/test/provider-subscriptions.test.ts index b2cdb09..7ac77b9 100644 --- a/packages/core/test/provider-subscriptions.test.ts +++ b/packages/core/test/provider-subscriptions.test.ts @@ -145,8 +145,9 @@ describe("provider-managed subscriptions", () => { expect(order.subscriptionIds?.length).toBe(1); const sub = Array.from(getCol("subscriptions").values())[0] as Subscription; expect(sub).toMatchObject({ - stripeSubscriptionId: "plan_1", + stripeSubscriptionId: "acme:plan_1", providerId: "acme", + providerSubscriptionId: "plan_1", customerId: order.customerId, status: "active", currency: "KES", From 60015dee689058f377ab22161f0eab6cb1a6beda Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:51:55 +0100 Subject: [PATCH 36/50] docs(core): note the provider-scoped subscription key --- .changeset/provider-subscriptions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/provider-subscriptions.md b/.changeset/provider-subscriptions.md index 6fef7d8..553c469 100644 --- a/.changeset/provider-subscriptions.md +++ b/.changeset/provider-subscriptions.md @@ -7,6 +7,6 @@ Add a provider-neutral subscription seam. - `PaymentProvider` gains optional `getSubscription`, `cancelSubscription` and `resumeSubscription`. Stripe keeps its existing Billing path; providers that manage billing themselves can use these. - `charge.succeeded` and `PaymentStatusResult` can carry `ProviderSubscriptionInfo`, so a provider can identify the subscription/plan behind a charge. - A normalised `subscription.updated` event lets a provider report a cancellation or status change outside a charge; core updates the local row. -- New `subscriptions/provider.ts` stores a provider-managed subscription and its invoices in the existing collections. The first charge creates an order and a local subscription; later charges are recorded as invoices and extend the period, not as new orders. +- New `subscriptions/provider.ts` stores a provider-managed subscription and its invoices in the existing collections. The provider id is part of the unique storage key (`${providerId}:${id}`), so two providers cannot collide on a numeric plan id. The first charge creates an order and a local subscription; later charges are recorded as invoices and extend the period, not as new orders. - `subscriptions/lifecycle.ts` dispatches cancel/resume to a provider-managed subscription. Pause and in-place plan changes are refused for providers that do not support them. The admin and customer portal hide pause and the Stripe billing portal for those subscriptions. - Stripe's `stripeSubscriptionId`/`stripeInvoiceId` fields keep their names for compatibility; they now hold the provider's subscription/plan and invoice id. From 0b224d25b18bccc7399e2c32b08958424d68e72c Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:53:19 +0100 Subject: [PATCH 37/50] fix(flutterwave): send the numeric plan id to hosted checkout --- packages/flutterwave/src/provider.ts | 4 +++- packages/flutterwave/test/subscriptions.test.ts | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/flutterwave/src/provider.ts b/packages/flutterwave/src/provider.ts index 019164b..e7299eb 100644 --- a/packages/flutterwave/src/provider.ts +++ b/packages/flutterwave/src/provider.ts @@ -814,6 +814,8 @@ export const flutterwavePaymentProvider: PaymentProvider = { const subaccounts = subaccountsFor(input); const paymentPlan = input.mode === "subscription" ? await createSubscriptionPlan(ctx, client, input) : undefined; + const paymentPlanValue = + paymentPlan && /^\d+$/.test(paymentPlan) ? Number(paymentPlan) : paymentPlan; const checkoutRef = flutterwaveReferenceFor(input.orderDraftId); const address = input.shippingAddress ?? input.billingAddress; const addressName = [address?.firstName, address?.lastName].filter(Boolean).join(" "); @@ -866,7 +868,7 @@ export const flutterwavePaymentProvider: PaymentProvider = { }, ...(paymentOptions ? { payment_options: paymentOptions.join(",") } : {}), ...(subaccounts ? { subaccounts } : {}), - ...(paymentPlan ? { payment_plan: paymentPlan } : {}), + ...(paymentPlanValue ? { payment_plan: paymentPlanValue } : {}), }, }); } catch (err) { diff --git a/packages/flutterwave/test/subscriptions.test.ts b/packages/flutterwave/test/subscriptions.test.ts index 7466f6d..64cbd7a 100644 --- a/packages/flutterwave/test/subscriptions.test.ts +++ b/packages/flutterwave/test/subscriptions.test.ts @@ -108,7 +108,7 @@ describe("Flutterwave subscription checkout", () => { }); expect(calls[1]?.path).toBe("/v3/payments"); expect(calls[1]?.body.amount).toBe(2600); - expect(calls[1]?.body.payment_plan).toBe("254811"); + expect(calls[1]?.body.payment_plan).toBe(254811); expect(calls[1]?.body.meta).toMatchObject({ orderDraftId: "0123456789abcdef0123456789abcdef", dashcommerceProductId: "prod_1", From 300b11f899e5d49ffbbd6b251ba795fd79f5720c Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:53:31 +0100 Subject: [PATCH 38/50] docs(flutterwave): note abandoned subscription plans --- packages/flutterwave/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/flutterwave/README.md b/packages/flutterwave/README.md index 40347bf..a0b096f 100644 --- a/packages/flutterwave/README.md +++ b/packages/flutterwave/README.md @@ -130,6 +130,8 @@ Flutterwave Payment Plans are card-only and tied to the customer's email. Not supported: trials, pausing, in-place plan changes, and more than one subscription line per checkout. All fail with a readable error rather than charging the wrong amount. +A plan is created when checkout starts. If the customer closes the page without paying, the unused plan remains in the Flutterwave dashboard; the hosted path cancels it when the payment call fails, but an abandoned Inline window cannot be cleaned up server-side. + Test-mode evidence: plan `254811` (KES 100/month) and a real card payment `10634465`. `GET /v3/subscriptions` answered `400 "Service error"` on the test account, which is why the plan id is the key instead of the subscription id. ### Reconciliation From 7e83604f16b5d0320ade5471904181cbcb290445 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:55:45 +0100 Subject: [PATCH 39/50] fix(core): scope provider invoice ids by provider --- packages/core/src/subscriptions/provider.ts | 6 ++++-- packages/core/src/types.ts | 2 ++ packages/core/test/provider-subscriptions.test.ts | 3 ++- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/packages/core/src/subscriptions/provider.ts b/packages/core/src/subscriptions/provider.ts index 07ee1c4..0c4ab48 100644 --- a/packages/core/src/subscriptions/provider.ts +++ b/packages/core/src/subscriptions/provider.ts @@ -157,8 +157,9 @@ export async function recordProviderSubscriptionInvoice( ctx: PluginContext, input: RecordProviderInvoiceInput, ): Promise { + const storageKey = `${input.providerId}:${input.providerInvoiceId}`; const existingResult = await invoiceStore(ctx).query({ - where: { stripeInvoiceId: input.providerInvoiceId }, + where: { stripeInvoiceId: storageKey }, limit: 1, }); const existing = existingResult.items[0]; @@ -174,8 +175,9 @@ export async function recordProviderSubscriptionInvoice( const invoice: SubscriptionInvoice = { id, - stripeInvoiceId: input.providerInvoiceId, + stripeInvoiceId: storageKey, providerId: input.providerId, + providerInvoiceId: input.providerInvoiceId, subscriptionId: input.subscription.id, amount: money(input.currency, input.amount), status, diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index 353b508..bce4c68 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -514,6 +514,8 @@ export interface SubscriptionInvoice { stripeInvoiceId: string; /** Gateway that owns this invoice. Unset means Stripe. */ providerId?: string; + /** The provider's raw invoice/charge id, without the storage prefix. */ + providerInvoiceId?: string; subscriptionId: string; amount: Money; status: "draft" | "open" | "paid" | "uncollectible" | "void"; diff --git a/packages/core/test/provider-subscriptions.test.ts b/packages/core/test/provider-subscriptions.test.ts index 7ac77b9..c6c1c2b 100644 --- a/packages/core/test/provider-subscriptions.test.ts +++ b/packages/core/test/provider-subscriptions.test.ts @@ -199,8 +199,9 @@ describe("provider-managed subscriptions", () => { expect(sub.currentPeriodEnd).toBe("2026-03-01T00:00:00.000Z"); const invoice = Array.from(getCol("subscription_invoices").values())[0] as SubscriptionInvoice; expect(invoice).toMatchObject({ - stripeInvoiceId: "pay_sub_2", + stripeInvoiceId: "acme:pay_sub_2", providerId: "acme", + providerInvoiceId: "pay_sub_2", subscriptionId: sub.id, status: "paid", }); From dcce582b8d2b4bba8ebcfe7a395ff85ecb2928ab Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:55:47 +0100 Subject: [PATCH 40/50] fix(core): scope provider invoice ids by provider --- packages/core/src/subscriptions/provider.ts | 6 ++++-- packages/core/src/types.ts | 2 ++ packages/core/test/provider-subscriptions.test.ts | 3 ++- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/packages/core/src/subscriptions/provider.ts b/packages/core/src/subscriptions/provider.ts index 07ee1c4..0c4ab48 100644 --- a/packages/core/src/subscriptions/provider.ts +++ b/packages/core/src/subscriptions/provider.ts @@ -157,8 +157,9 @@ export async function recordProviderSubscriptionInvoice( ctx: PluginContext, input: RecordProviderInvoiceInput, ): Promise { + const storageKey = `${input.providerId}:${input.providerInvoiceId}`; const existingResult = await invoiceStore(ctx).query({ - where: { stripeInvoiceId: input.providerInvoiceId }, + where: { stripeInvoiceId: storageKey }, limit: 1, }); const existing = existingResult.items[0]; @@ -174,8 +175,9 @@ export async function recordProviderSubscriptionInvoice( const invoice: SubscriptionInvoice = { id, - stripeInvoiceId: input.providerInvoiceId, + stripeInvoiceId: storageKey, providerId: input.providerId, + providerInvoiceId: input.providerInvoiceId, subscriptionId: input.subscription.id, amount: money(input.currency, input.amount), status, diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index a9babff..26f6717 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -537,6 +537,8 @@ export interface SubscriptionInvoice { stripeInvoiceId: string; /** Gateway that owns this invoice. Unset means Stripe. */ providerId?: string; + /** The provider's raw invoice/charge id, without the storage prefix. */ + providerInvoiceId?: string; subscriptionId: string; amount: Money; status: "draft" | "open" | "paid" | "uncollectible" | "void"; diff --git a/packages/core/test/provider-subscriptions.test.ts b/packages/core/test/provider-subscriptions.test.ts index 7ac77b9..c6c1c2b 100644 --- a/packages/core/test/provider-subscriptions.test.ts +++ b/packages/core/test/provider-subscriptions.test.ts @@ -199,8 +199,9 @@ describe("provider-managed subscriptions", () => { expect(sub.currentPeriodEnd).toBe("2026-03-01T00:00:00.000Z"); const invoice = Array.from(getCol("subscription_invoices").values())[0] as SubscriptionInvoice; expect(invoice).toMatchObject({ - stripeInvoiceId: "pay_sub_2", + stripeInvoiceId: "acme:pay_sub_2", providerId: "acme", + providerInvoiceId: "pay_sub_2", subscriptionId: sub.id, status: "paid", }); From 1c3346d0c77485abe1d510bd1d48014f995de884 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:56:09 +0100 Subject: [PATCH 41/50] docs(core): note the provider-scoped invoice key --- .changeset/provider-subscriptions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/provider-subscriptions.md b/.changeset/provider-subscriptions.md index 553c469..d9f123e 100644 --- a/.changeset/provider-subscriptions.md +++ b/.changeset/provider-subscriptions.md @@ -7,6 +7,6 @@ Add a provider-neutral subscription seam. - `PaymentProvider` gains optional `getSubscription`, `cancelSubscription` and `resumeSubscription`. Stripe keeps its existing Billing path; providers that manage billing themselves can use these. - `charge.succeeded` and `PaymentStatusResult` can carry `ProviderSubscriptionInfo`, so a provider can identify the subscription/plan behind a charge. - A normalised `subscription.updated` event lets a provider report a cancellation or status change outside a charge; core updates the local row. -- New `subscriptions/provider.ts` stores a provider-managed subscription and its invoices in the existing collections. The provider id is part of the unique storage key (`${providerId}:${id}`), so two providers cannot collide on a numeric plan id. The first charge creates an order and a local subscription; later charges are recorded as invoices and extend the period, not as new orders. +- New `subscriptions/provider.ts` stores a provider-managed subscription and its invoices in the existing collections. The provider id is part of the unique storage key for both subscriptions and invoices (`${providerId}:${id}`), so two providers cannot collide on a numeric plan or transaction id. The first charge creates an order and a local subscription; later charges are recorded as invoices and extend the period, not as new orders. - `subscriptions/lifecycle.ts` dispatches cancel/resume to a provider-managed subscription. Pause and in-place plan changes are refused for providers that do not support them. The admin and customer portal hide pause and the Stripe billing portal for those subscriptions. - Stripe's `stripeSubscriptionId`/`stripeInvoiceId` fields keep their names for compatibility; they now hold the provider's subscription/plan and invoice id. From d8912b9a16987eba1acc83a3f319cd8fbf6a995a Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:57:00 +0100 Subject: [PATCH 42/50] fix(flutterwave): keep subscription checkout card-only --- packages/flutterwave/src/provider.ts | 5 ++++- packages/flutterwave/test/subscriptions.test.ts | 2 ++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/flutterwave/src/provider.ts b/packages/flutterwave/src/provider.ts index e7299eb..2a49150 100644 --- a/packages/flutterwave/src/provider.ts +++ b/packages/flutterwave/src/provider.ts @@ -821,7 +821,10 @@ export const flutterwavePaymentProvider: PaymentProvider = { const addressName = [address?.firstName, address?.lastName].filter(Boolean).join(" "); const name = input.customer.name ?? (addressName || undefined); const phone = input.customer.phone ?? address?.phone; - const paymentOptions = mapPaymentOptions(input.preferredChannels, currency); + // Payment Plans are card-only; a channel hint would conflict. + const paymentOptions = paymentPlan + ? undefined + : mapPaymentOptions(input.preferredChannels, currency); if (onPage) { // Inline creates the transaction in the browser, so there is no diff --git a/packages/flutterwave/test/subscriptions.test.ts b/packages/flutterwave/test/subscriptions.test.ts index 64cbd7a..cef1f80 100644 --- a/packages/flutterwave/test/subscriptions.test.ts +++ b/packages/flutterwave/test/subscriptions.test.ts @@ -90,6 +90,7 @@ describe("Flutterwave subscription checkout", () => { runtime, subscriptionInput({ amount: 260_000, + preferredChannels: ["mobile_money"], lineItems: [ ...subscriptionInput().lineItems, { name: "Tax", amount: 10_000, currency: "KES", quantity: 1 }, @@ -109,6 +110,7 @@ describe("Flutterwave subscription checkout", () => { expect(calls[1]?.path).toBe("/v3/payments"); expect(calls[1]?.body.amount).toBe(2600); expect(calls[1]?.body.payment_plan).toBe(254811); + expect(calls[1]?.body.payment_options).toBeUndefined(); expect(calls[1]?.body.meta).toMatchObject({ orderDraftId: "0123456789abcdef0123456789abcdef", dashcommerceProductId: "prod_1", From e672facd681088a50581d9707aed0853a7935d6d Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:57:13 +0100 Subject: [PATCH 43/50] fix(flutterwave): name the plan after the subscription line --- packages/flutterwave/src/provider.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/flutterwave/src/provider.ts b/packages/flutterwave/src/provider.ts index 2a49150..72ddf40 100644 --- a/packages/flutterwave/src/provider.ts +++ b/packages/flutterwave/src/provider.ts @@ -349,7 +349,7 @@ async function createSubscriptionPlan( client, path: "/payment-plans", body: { - name: `DC ${input.orderDraftId}`, + name: `DC ${line.name}`, amount: toMajorUnits(recurringTotal), currency: input.currency.toUpperCase(), interval: planInterval(recurring.interval, recurring.intervalCount), From 54b67d59b44b262c8d61f6ff83e2620553fe61f1 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:57:47 +0100 Subject: [PATCH 44/50] docs(flutterwave): record the package-level plan probe --- packages/flutterwave/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/flutterwave/README.md b/packages/flutterwave/README.md index a0b096f..9adc436 100644 --- a/packages/flutterwave/README.md +++ b/packages/flutterwave/README.md @@ -132,7 +132,7 @@ Not supported: trials, pausing, in-place plan changes, and more than one subscri A plan is created when checkout starts. If the customer closes the page without paying, the unused plan remains in the Flutterwave dashboard; the hosted path cancels it when the payment call fails, but an abandoned Inline window cannot be cleaned up server-side. -Test-mode evidence: plan `254811` (KES 100/month) and a real card payment `10634465`. `GET /v3/subscriptions` answered `400 "Service error"` on the test account, which is why the plan id is the key instead of the subscription id. +Test-mode evidence: plan `254811` (KES 100/month) and a real card payment `10634465`; the package's `initCheckout` also created plan `254812` and opened Inline with `payment_plan`. Both plans were cancelled after the probe. `GET /v3/subscriptions` answered `400 "Service error"` on the test account, which is why the plan id is the key instead of the subscription id. ### Reconciliation From 7f5d332964f1db960baf3479421c716fcbd012b5 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:58:17 +0100 Subject: [PATCH 45/50] feat(core): show the subscription provider in the admin list --- packages/core/src/admin/pages/SubscriptionsPage.tsx | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/packages/core/src/admin/pages/SubscriptionsPage.tsx b/packages/core/src/admin/pages/SubscriptionsPage.tsx index e45acdd..7cfe49b 100644 --- a/packages/core/src/admin/pages/SubscriptionsPage.tsx +++ b/packages/core/src/admin/pages/SubscriptionsPage.tsx @@ -242,6 +242,16 @@ export function SubscriptionsPage() { data={items} getRowKey={(s) => s.id} columns={[ + { + key: "provider", + header: "Provider", + render: (s) => { + const provider = s.providerId ?? "stripe"; + if (provider === "stripe") return "Stripe"; + if (provider === "flutterwave") return "Flutterwave"; + return provider; + }, + }, { key: "status", header: "Status", From 9bd5aaed1904b4216edb10b5aef48d88a2d8919f Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:58:29 +0100 Subject: [PATCH 46/50] feat(core): show the subscription provider in the admin list --- packages/core/src/admin/pages/SubscriptionsPage.tsx | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/packages/core/src/admin/pages/SubscriptionsPage.tsx b/packages/core/src/admin/pages/SubscriptionsPage.tsx index e45acdd..7cfe49b 100644 --- a/packages/core/src/admin/pages/SubscriptionsPage.tsx +++ b/packages/core/src/admin/pages/SubscriptionsPage.tsx @@ -242,6 +242,16 @@ export function SubscriptionsPage() { data={items} getRowKey={(s) => s.id} columns={[ + { + key: "provider", + header: "Provider", + render: (s) => { + const provider = s.providerId ?? "stripe"; + if (provider === "stripe") return "Stripe"; + if (provider === "flutterwave") return "Flutterwave"; + return provider; + }, + }, { key: "status", header: "Status", From 8134eb0e085038a8d2605066866375a5cc74fd04 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:20:39 +0100 Subject: [PATCH 47/50] fix: resolve subscription renewals without a draft --- packages/core/src/routes/webhook.ts | 14 +++ .../core/test/provider-subscriptions.test.ts | 107 ++++++++++++++++++ packages/flutterwave/src/provider.ts | 7 +- .../flutterwave/test/subscriptions.test.ts | 20 ++++ 4 files changed, 145 insertions(+), 3 deletions(-) diff --git a/packages/core/src/routes/webhook.ts b/packages/core/src/routes/webhook.ts index 3923c91..9e783ff 100644 --- a/packages/core/src/routes/webhook.ts +++ b/packages/core/src/routes/webhook.ts @@ -819,6 +819,20 @@ async function handleNormalizedChargeSucceeded( } } + // A charge with no draft and no local subscription is not ours (for + // example another payment on the same Flutterwave account). Acknowledge + // it instead of returning 500 and making the provider retry. + if (!event.orderDraftId) { + ctx.log.info("Ignoring a charge with no checkout draft and no subscription", { + providerId: provider.id, + paymentReference: event.paymentReference, + }); + return new Response(JSON.stringify({ received: true, ignored: "no_draft" }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + } + const snapshot = await ctx.kv.get(draftKey(event.orderDraftId)); if (!snapshot) { ctx.log.error("No cart snapshot for orderDraftId", { diff --git a/packages/core/test/provider-subscriptions.test.ts b/packages/core/test/provider-subscriptions.test.ts index c6c1c2b..8da8914 100644 --- a/packages/core/test/provider-subscriptions.test.ts +++ b/packages/core/test/provider-subscriptions.test.ts @@ -290,6 +290,113 @@ describe("provider-managed subscriptions", () => { expect(stored.canceledAt).toBe("2026-02-01T00:00:00.000Z"); }); + it("records a renewal when the webhook has no draft or plan field", async () => { + const base = createMockPaymentProvider({ id: "acme" }); + registerPaymentProvider({ + ...base, + webhookHeaders: ["x-acme-signature"], + parseWebhookEvent(raw): NormalizedPaymentEvent { + const body = JSON.parse(raw) as { id: string; paymentReference: string }; + return { + type: "charge.succeeded", + orderDraftId: "", + providerId: "acme", + providerEventId: body.id, + paymentReference: body.paymentReference, + amount: 150_000, + currency: "KES", + customer: { email: "supporter@example.com" }, + raw: body, + }; + }, + async getPaymentStatus() { + return { + status: "succeeded", + paymentReference: "pay_renewal_no_draft", + amount: 150_000, + currency: "KES", + subscription: { + providerSubscriptionId: "plan_1", + status: "active" as const, + }, + }; + }, + }); + const { ctx, getCol } = makeRouteContext({ + "settings:paymentProvider": "acme", + "settings:acmeSecretKey": "acme-key", + "settings:acmeWebhookSecret": "test-secret", + }); + await upsertProviderSubscription(ctx, { + providerId: "acme", + providerSubscriptionId: "plan_1", + customerId: "cus_1", + productId: "prod_1", + status: "active", + currency: "KES", + unitAmount: 150_000, + quantity: 1, + interval: "month", + intervalCount: 1, + currentPeriodStart: "2026-01-01T00:00:00.000Z", + currentPeriodEnd: "2026-02-01T00:00:00.000Z", + }); + + const res = await deliver( + ctx, + JSON.stringify({ id: "evt_no_draft", paymentReference: "pay_renewal_no_draft" }), + ); + expect(res.status).toBe(200); + expect(getCol("orders").size).toBe(0); + expect(getCol("subscription_invoices").size).toBe(1); + const sub = Array.from(getCol("subscriptions").values())[0] as Subscription; + expect(sub.currentPeriodEnd).toBe("2026-03-01T00:00:00.000Z"); + }); + + it("ignores a charge with no draft and no subscription", async () => { + const base = createMockPaymentProvider({ id: "acme" }); + registerPaymentProvider({ + ...base, + webhookHeaders: ["x-acme-signature"], + parseWebhookEvent(raw): NormalizedPaymentEvent { + const body = JSON.parse(raw) as { id: string; paymentReference: string }; + return { + type: "charge.succeeded", + orderDraftId: "", + providerId: "acme", + providerEventId: body.id, + paymentReference: body.paymentReference, + amount: 150_000, + currency: "KES", + customer: { email: "someone@example.com" }, + raw: body, + }; + }, + async getPaymentStatus() { + return { + status: "succeeded", + paymentReference: "pay_other", + amount: 150_000, + currency: "KES", + }; + }, + }); + const { ctx, getCol } = makeRouteContext({ + "settings:paymentProvider": "acme", + "settings:acmeSecretKey": "acme-key", + "settings:acmeWebhookSecret": "test-secret", + }); + + const res = await deliver( + ctx, + JSON.stringify({ id: "evt_other", paymentReference: "pay_other" }), + ); + expect(res.status).toBe(200); + expect(await res.json()).toMatchObject({ received: true, ignored: "no_draft" }); + expect(getCol("orders").size).toBe(0); + expect(getCol("subscriptions").size).toBe(0); + }); + it("does not hand a provider's plan id to another provider", async () => { const current = { paymentReference: "pay_sub_1", diff --git a/packages/flutterwave/src/provider.ts b/packages/flutterwave/src/provider.ts index 72ddf40..417c66d 100644 --- a/packages/flutterwave/src/provider.ts +++ b/packages/flutterwave/src/provider.ts @@ -985,9 +985,10 @@ export const flutterwavePaymentProvider: PaymentProvider = { : draftIdFromReference(d?.tx_ref ?? ""); const planId = d?.plan === undefined || d?.plan === null ? undefined : String(d.plan).trim(); - // A renewal may not carry the original order draft. It still has the - // plan id, which is enough for core to find the local subscription. - if (!transactionId || !d.tx_ref || (!orderDraftId && !planId)) { + // A renewal may carry neither the original order draft nor a plan + // field. Core asks the provider for the live status, which includes + // `plan`, and ignores a charge that is not ours. + if (!transactionId || !d.tx_ref) { return { type: "unhandled", providerEventType: event.event, diff --git a/packages/flutterwave/test/subscriptions.test.ts b/packages/flutterwave/test/subscriptions.test.ts index cef1f80..3b54672 100644 --- a/packages/flutterwave/test/subscriptions.test.ts +++ b/packages/flutterwave/test/subscriptions.test.ts @@ -252,6 +252,26 @@ describe("Flutterwave subscription state", () => { expect(event.status).toBe("canceled"); }); + it("accepts a charge with no draft and no plan so core can verify it", () => { + const event = flutterwavePaymentProvider.parseWebhookEvent( + JSON.stringify({ + event: "charge.completed", + data: { + id: 10634467, + tx_ref: "renewal-10634467", + status: "successful", + amount: 2500, + currency: "KES", + customer: { email: "fan@example.com" }, + }, + }), + ); + expect(event.type).toBe("charge.succeeded"); + if (event.type !== "charge.succeeded") throw new Error("expected charge.succeeded"); + expect(event.orderDraftId).toBe(""); + expect(event.subscription).toBeUndefined(); + }); + it("reports the plan id from a live verify", async () => { const runtime = ctx(async () => ok({ From a1e02280c665694a52ae20fb70f06e969249b3c3 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:20:58 +0100 Subject: [PATCH 48/50] fix(core): ignore charges with no draft and no subscription --- packages/core/src/routes/webhook.ts | 14 +++ .../core/test/provider-subscriptions.test.ts | 107 ++++++++++++++++++ 2 files changed, 121 insertions(+) diff --git a/packages/core/src/routes/webhook.ts b/packages/core/src/routes/webhook.ts index 4bd6f40..0de8d8c 100644 --- a/packages/core/src/routes/webhook.ts +++ b/packages/core/src/routes/webhook.ts @@ -759,6 +759,20 @@ async function handleNormalizedChargeSucceeded( } } + // A charge with no draft and no local subscription is not ours (for + // example another payment on the same Flutterwave account). Acknowledge + // it instead of returning 500 and making the provider retry. + if (!event.orderDraftId) { + ctx.log.info("Ignoring a charge with no checkout draft and no subscription", { + providerId: provider.id, + paymentReference: event.paymentReference, + }); + return new Response(JSON.stringify({ received: true, ignored: "no_draft" }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + } + const snapshot = await ctx.kv.get(draftKey(event.orderDraftId)); if (!snapshot) { ctx.log.error("No cart snapshot for orderDraftId", { diff --git a/packages/core/test/provider-subscriptions.test.ts b/packages/core/test/provider-subscriptions.test.ts index c6c1c2b..8da8914 100644 --- a/packages/core/test/provider-subscriptions.test.ts +++ b/packages/core/test/provider-subscriptions.test.ts @@ -290,6 +290,113 @@ describe("provider-managed subscriptions", () => { expect(stored.canceledAt).toBe("2026-02-01T00:00:00.000Z"); }); + it("records a renewal when the webhook has no draft or plan field", async () => { + const base = createMockPaymentProvider({ id: "acme" }); + registerPaymentProvider({ + ...base, + webhookHeaders: ["x-acme-signature"], + parseWebhookEvent(raw): NormalizedPaymentEvent { + const body = JSON.parse(raw) as { id: string; paymentReference: string }; + return { + type: "charge.succeeded", + orderDraftId: "", + providerId: "acme", + providerEventId: body.id, + paymentReference: body.paymentReference, + amount: 150_000, + currency: "KES", + customer: { email: "supporter@example.com" }, + raw: body, + }; + }, + async getPaymentStatus() { + return { + status: "succeeded", + paymentReference: "pay_renewal_no_draft", + amount: 150_000, + currency: "KES", + subscription: { + providerSubscriptionId: "plan_1", + status: "active" as const, + }, + }; + }, + }); + const { ctx, getCol } = makeRouteContext({ + "settings:paymentProvider": "acme", + "settings:acmeSecretKey": "acme-key", + "settings:acmeWebhookSecret": "test-secret", + }); + await upsertProviderSubscription(ctx, { + providerId: "acme", + providerSubscriptionId: "plan_1", + customerId: "cus_1", + productId: "prod_1", + status: "active", + currency: "KES", + unitAmount: 150_000, + quantity: 1, + interval: "month", + intervalCount: 1, + currentPeriodStart: "2026-01-01T00:00:00.000Z", + currentPeriodEnd: "2026-02-01T00:00:00.000Z", + }); + + const res = await deliver( + ctx, + JSON.stringify({ id: "evt_no_draft", paymentReference: "pay_renewal_no_draft" }), + ); + expect(res.status).toBe(200); + expect(getCol("orders").size).toBe(0); + expect(getCol("subscription_invoices").size).toBe(1); + const sub = Array.from(getCol("subscriptions").values())[0] as Subscription; + expect(sub.currentPeriodEnd).toBe("2026-03-01T00:00:00.000Z"); + }); + + it("ignores a charge with no draft and no subscription", async () => { + const base = createMockPaymentProvider({ id: "acme" }); + registerPaymentProvider({ + ...base, + webhookHeaders: ["x-acme-signature"], + parseWebhookEvent(raw): NormalizedPaymentEvent { + const body = JSON.parse(raw) as { id: string; paymentReference: string }; + return { + type: "charge.succeeded", + orderDraftId: "", + providerId: "acme", + providerEventId: body.id, + paymentReference: body.paymentReference, + amount: 150_000, + currency: "KES", + customer: { email: "someone@example.com" }, + raw: body, + }; + }, + async getPaymentStatus() { + return { + status: "succeeded", + paymentReference: "pay_other", + amount: 150_000, + currency: "KES", + }; + }, + }); + const { ctx, getCol } = makeRouteContext({ + "settings:paymentProvider": "acme", + "settings:acmeSecretKey": "acme-key", + "settings:acmeWebhookSecret": "test-secret", + }); + + const res = await deliver( + ctx, + JSON.stringify({ id: "evt_other", paymentReference: "pay_other" }), + ); + expect(res.status).toBe(200); + expect(await res.json()).toMatchObject({ received: true, ignored: "no_draft" }); + expect(getCol("orders").size).toBe(0); + expect(getCol("subscriptions").size).toBe(0); + }); + it("does not hand a provider's plan id to another provider", async () => { const current = { paymentReference: "pay_sub_1", From 90b246fdd9393937deaa5d0431511d5a73483ac8 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:26:04 +0100 Subject: [PATCH 49/50] fix(core): refuse subscription carts with vendor items --- packages/core/src/routes/checkout.ts | 14 ++++++++ .../core/test/provider-subscriptions.test.ts | 34 +++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/packages/core/src/routes/checkout.ts b/packages/core/src/routes/checkout.ts index a80bce0..c57ccc7 100644 --- a/packages/core/src/routes/checkout.ts +++ b/packages/core/src/routes/checkout.ts @@ -589,6 +589,20 @@ export const checkoutRoutes = { { status: 409, headers: { "Content-Type": "application/json" } }, ); } + // Recurring vendor splits are not implemented for any provider: + // Stripe's subscription path does not send transfer_data, and + // Flutterwave's Payment Plans do not guarantee subaccount payouts on + // renewal. Refuse rather than underpay the vendor. + if (isSubscriptionCart && recalculated.items.some((item) => item.vendorId)) { + return new Response( + JSON.stringify({ + error: + "Subscription carts with vendor-owned items are not supported yet. Split the subscription from the vendor items.", + code: "subscription_vendor_items", + }), + { status: 409, headers: { "Content-Type": "application/json" } }, + ); + } let transferDataPreview: { destination: string; amount?: number } | undefined; let applicationFeePreview: number | undefined; diff --git a/packages/core/test/provider-subscriptions.test.ts b/packages/core/test/provider-subscriptions.test.ts index 8da8914..8e0bc40 100644 --- a/packages/core/test/provider-subscriptions.test.ts +++ b/packages/core/test/provider-subscriptions.test.ts @@ -420,6 +420,40 @@ describe("provider-managed subscriptions", () => { }); }); +describe("subscription checkout guards", () => { + it("refuses a subscription cart with vendor-owned items", async () => { + const current = { + paymentReference: "pay_guard", + subscription: { providerSubscriptionId: "plan_guard", status: "active" as const }, + }; + registerPaymentProvider(provider(current)); + const { ctx } = makeRouteContext({ + "settings:paymentProvider": "acme", + "settings:checkoutMode": "hosted", + "settings:acmeSecretKey": "acme-key", + "settings:acmeWebhookSecret": "test-secret", + }); + const sessionId = `sess_guard_${Math.random()}`; + const cart = subscriptionCart(sessionId); + cart.items = cart.items.map((item) => ({ ...item, vendorId: "v1" })); + await ctx.kv.set(`cart:${sessionId}`, cart); + const routeCtx = { + ...ctx, + request: new Request("http://test/checkout/create-session", { + method: "POST", + headers: { Cookie: `dashcommerce_sid=${sessionId}` }, + }), + input: {}, + } as unknown as RouteContext; + const res = (await sandbox.routes["checkout/create-session"].handler( + routeCtx, + ctx, + )) as Response; + expect(res.status).toBe(409); + expect(await res.json()).toMatchObject({ code: "subscription_vendor_items" }); + }); +}); + describe("provider-managed lifecycle", () => { it("cancels and resumes through the provider, not Stripe", async () => { const calls: Array<{ action: string; id: string }> = []; From b4bf286e921c5b92ba819eb328a43c5c35635924 Mon Sep 17 00:00:00 2001 From: Alexander Asomba <3323537+alexasomba@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:26:07 +0100 Subject: [PATCH 50/50] fix(core): refuse subscription carts with vendor items --- packages/core/src/routes/checkout.ts | 14 ++++++++ .../core/test/provider-subscriptions.test.ts | 34 +++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/packages/core/src/routes/checkout.ts b/packages/core/src/routes/checkout.ts index abbae5c..b888148 100644 --- a/packages/core/src/routes/checkout.ts +++ b/packages/core/src/routes/checkout.ts @@ -595,6 +595,20 @@ export const checkoutRoutes = { let transferDataPreview: { destination: string; amount?: number } | undefined; let applicationFeePreview: number | undefined; const hasVendorItems = recalculated.items.some((item) => item.vendorId); + // Recurring vendor splits are not implemented for any provider: + // Stripe's subscription path does not send transfer_data, and + // Flutterwave's Payment Plans do not guarantee subaccount payouts on + // renewal. Refuse rather than underpay the vendor. + if (isSubscriptionCart && hasVendorItems) { + return new Response( + JSON.stringify({ + error: + "Subscription carts with vendor-owned items are not supported yet. Split the subscription from the vendor items.", + code: "subscription_vendor_items", + }), + { status: 409, headers: { "Content-Type": "application/json" } }, + ); + } if (provider.id === "stripe" && (await connectEnabled(ctx))) { try { const plan = await computeSplit(ctx, recalculated); diff --git a/packages/core/test/provider-subscriptions.test.ts b/packages/core/test/provider-subscriptions.test.ts index 8da8914..8e0bc40 100644 --- a/packages/core/test/provider-subscriptions.test.ts +++ b/packages/core/test/provider-subscriptions.test.ts @@ -420,6 +420,40 @@ describe("provider-managed subscriptions", () => { }); }); +describe("subscription checkout guards", () => { + it("refuses a subscription cart with vendor-owned items", async () => { + const current = { + paymentReference: "pay_guard", + subscription: { providerSubscriptionId: "plan_guard", status: "active" as const }, + }; + registerPaymentProvider(provider(current)); + const { ctx } = makeRouteContext({ + "settings:paymentProvider": "acme", + "settings:checkoutMode": "hosted", + "settings:acmeSecretKey": "acme-key", + "settings:acmeWebhookSecret": "test-secret", + }); + const sessionId = `sess_guard_${Math.random()}`; + const cart = subscriptionCart(sessionId); + cart.items = cart.items.map((item) => ({ ...item, vendorId: "v1" })); + await ctx.kv.set(`cart:${sessionId}`, cart); + const routeCtx = { + ...ctx, + request: new Request("http://test/checkout/create-session", { + method: "POST", + headers: { Cookie: `dashcommerce_sid=${sessionId}` }, + }), + input: {}, + } as unknown as RouteContext; + const res = (await sandbox.routes["checkout/create-session"].handler( + routeCtx, + ctx, + )) as Response; + expect(res.status).toBe(409); + expect(await res.json()).toMatchObject({ code: "subscription_vendor_items" }); + }); +}); + describe("provider-managed lifecycle", () => { it("cancels and resumes through the provider, not Stripe", async () => { const calls: Array<{ action: string; id: string }> = [];