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 1/2] 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 2/2] 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) => {