diff --git a/.changeset/flutterwave-on-page.md b/.changeset/flutterwave-on-page.md new file mode 100644 index 0000000..fe4e4c5 --- /dev/null +++ b/.changeset/flutterwave-on-page.md @@ -0,0 +1,10 @@ +--- +"@dashcommerce/flutterwave": minor +--- + +On-page checkout with Flutterwave Inline. + +- Declares `checkoutStyles: ["hosted", "on_page"]` and a `publicKey` credential (`FLWPUBK_…`), saved by core as `settings:flutterwavePublicKey`. +- With checkout set to "On your page", `initCheckout` returns `on_page` with the public key, `tx_ref`, amount in major units and customer details. No server-side payment is created; Inline creates the transaction in the browser. +- New `./checkout-client` entry registers Flutterwave Inline on `window.DashCommerceCheckoutClients.flutterwave`, loads `checkout.flutterwave.com/v3.js` only when the customer presses Pay, and maps `callback`/`onclose` to finished/closed. Orders still come only from the signed webhook and the live verify. +- On-page checkout refuses to start, with a message naming the setting, when the public key is missing. diff --git a/.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/.changeset/flutterwave-splits.md b/.changeset/flutterwave-splits.md new file mode 100644 index 0000000..57c8cc2 --- /dev/null +++ b/.changeset/flutterwave-splits.md @@ -0,0 +1,10 @@ +--- +"@dashcommerce/flutterwave": minor +--- + +Split payments across vendor subaccounts. + +- Declares `capabilities.splits`. When core sends `allocations`, each becomes a Flutterwave `subaccounts` item with `transaction_charge_type: "flat_subaccount"` and the exact major-unit amount, for hosted checkout and Inline. +- On-page checkout carries the split as JSON in the client payload; the browser client parses it and refuses a malformed split rather than opening an unsplit payment. +- Validates every share before calling Flutterwave: no empty account, no non-positive amount, no total above the checkout amount, no negative platform remainder. +- Needs a core release with the split allocation seam (`capabilities.splits`, `allocations`, `platformRemainderMinor`). diff --git a/.changeset/provider-public-key.md b/.changeset/provider-public-key.md new file mode 100644 index 0000000..a2bedb8 --- /dev/null +++ b/.changeset/provider-public-key.md @@ -0,0 +1,9 @@ +--- +"@dashcommerce/core": minor +--- + +Let a payment provider save a browser public key. + +- `PaymentProviderCredentials.publicKey` and `credentialFields.publicKey`, saved as `settings:PublicKey` and validated against the prefixes the provider declares. Providers that need it for on-page checkout (Flutterwave Inline) can hand it to their browser client; nothing else changes for providers that do not. +- Settings shows the field only for a provider that declares it, beside the secret key and webhook secret. A provider that does not declare one cannot have a public key saved, and its settings row is unchanged. +- `loadPaymentProviderCredentials` returns `publicKey` when one is set. diff --git a/.changeset/provider-split-allocations.md b/.changeset/provider-split-allocations.md new file mode 100644 index 0000000..2d0572c --- /dev/null +++ b/.changeset/provider-split-allocations.md @@ -0,0 +1,11 @@ +--- +"@dashcommerce/core": minor +--- + +Let a payment provider split one payment across vendor payout accounts. + +- `capabilities.splits` and `InitCheckoutInput.allocations` / `platformRemainderMinor`. Core computes exact per-vendor minor amounts from trusted cart prices and the vendor's platform fee; a provider only routes them to the account reference core supplies. +- `Vendor.paymentAccounts`, keyed by provider id, for providers other than Stripe: `accountReference`, `status`, and an optional settlement currency and label. Stripe Connect keeps its existing fields. +- `admin/vendors/item` accepts `POST` to create a vendor without Stripe, and `PATCH` with `paymentAccount` / `paymentAccounts` to add, replace or remove a provider account. Vendor routes open when Connect is on **or** a split-capable provider is registered. +- Settings exposes each provider's `capabilities`. The Vendors page adds a vendor and edits payout accounts when a split-capable provider is active, without requiring Stripe. +- A vendor cart is refused with a readable 409 when the active provider cannot split, or when a vendor has no active account for it, instead of silently charging the platform account. diff --git a/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/core/README.md b/packages/core/README.md index 5e9a141..b99560c 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -62,14 +62,15 @@ Stripe is built in. A gateway package (for example `@dashcommerce/paystack`) reg emdash({ plugins: [dashcommerce({ allowedHosts: ["api.paystack.co"] })] }); ``` -3. **Choose the provider and enter its keys** in Settings → Payment provider. They are saved as `settings:SecretKey` and `settings:WebhookSecret`, masked like Stripe's. +3. **Choose the provider and enter its keys** in Settings → Payment provider. They are saved as `settings:SecretKey` and `settings:WebhookSecret` (plus `settings:PublicKey` when the provider declares one), masked like Stripe's. 4. **Point the provider's webhooks** at `/_emdash/api/plugins/dashcommerce/checkout/webhook?provider=`. For provider authors, `PaymentProvider` can declare: -- `credentialFields`: the label, accepted prefixes and help text for the settings form. +- `credentialFields`: the label, accepted prefixes and help text for the settings form. A `publicKey` field is shown only when declared, for on-page checkout that needs the browser key (Flutterwave Inline); `credentials.publicKey` carries the saved value. - `webhookHeaders`: the headers that identify its webhooks, besides `x--signature`. `verifyWebhook` receives every request header, and `credentials` (the provider's saved secret key and webhook secret) for headers signed with the API key rather than the webhook secret. - `checkConnection`: one read-only call with the saved keys, behind a "Test connection" button in Settings. Return `{ ok, message }`, with `ok: false` and a message the merchant can act on for a wrong or under-permitted key. +- `capabilities.splits`: core computes `allocations` (`vendorId`, `accountReference`, `amountMinor`) and `platformRemainderMinor` when the cart has vendor-owned items. Vendors store their payout account under `paymentAccounts[providerId]`; the provider only routes the amounts core supplies. `parseWebhookEvent` may return `refund.updated` to move a pending refund to `succeeded` or `failed`. A failed refund stops counting against its order: the refunded total, payment status and order status are worked out again, and stock the refund put back is taken back off. diff --git a/packages/core/src/admin/fields/VendorSelect.tsx b/packages/core/src/admin/fields/VendorSelect.tsx index b5a0b59..ab27225 100644 --- a/packages/core/src/admin/fields/VendorSelect.tsx +++ b/packages/core/src/admin/fields/VendorSelect.tsx @@ -8,22 +8,18 @@ * context (field definition, entry metadata) without needing changes here. * * Behaviour: - * - Reads `settings:connectEnabled` via the admin settings API on mount. - * - When multi-vendor is off, renders an info banner instead of the picker. - * - When on, fetches `admin/vendors` and renders a searchable Combobox of - * active/pending vendors, dimming entries with `chargesEnabled=false`. + * - Reads `settings:connectEnabled` and the registered providers' `splits` + * capability via the admin settings API on mount. + * - Marketplace mode is Stripe Connect **or** a provider that can split + * payments (Flutterwave subaccounts). + * - When neither is on, renders an info banner instead of the picker. + * - When on, fetches `admin/vendors` and renders a searchable Combobox, + * dimming vendors with no active payout account. */ import { useEffect, useMemo, useState } from "react"; -import { - Alert, - Combobox, - FormField, - Loading, - usePluginAPI, - type ComboboxOption, -} from "../kit"; import type { Vendor } from "../../types"; +import { Alert, Combobox, type ComboboxOption, FormField, Loading, usePluginAPI } from "../kit"; export interface VendorSelectProps { value?: string | null; @@ -35,7 +31,9 @@ export interface VendorSelectProps { export function VendorSelect(props: VendorSelectProps) { const api = usePluginAPI(); const [vendors, setVendors] = useState(null); - const [connectEnabled, setConnectEnabled] = useState(null); + const [marketplaceEnabled, setMarketplaceEnabled] = useState(null); + const [connectEnabled, setConnectEnabled] = useState(false); + const [splitsProviders, setSplitsProviders] = useState>([]); const [error, setError] = useState(null); useEffect(() => { @@ -44,22 +42,31 @@ export function VendorSelect(props: VendorSelectProps) { try { const settings = await api.get>("admin/settings"); if (!alive) return; - const on = settings.connectEnabled === true; - setConnectEnabled(on); - if (on) { + const connect = settings.connectEnabled === true; + const providers = Array.isArray(settings._providers) + ? (settings._providers as Array<{ + id: string; + label: string; + capabilities?: { splits?: boolean }; + }>) + : []; + const splits = providers + .filter((provider) => provider.capabilities?.splits === true) + .map((provider) => ({ id: provider.id, label: provider.label })); + const enabled = connect || splits.length > 0; + setConnectEnabled(connect); + setSplitsProviders(splits); + setMarketplaceEnabled(enabled); + if (enabled) { try { const res = await api.get<{ items: Vendor[] }>("admin/vendors"); if (alive) setVendors(res.items ?? []); } catch (err) { - if (alive) - setError( - err instanceof Error ? err.message : "Could not load vendors", - ); + if (alive) setError(err instanceof Error ? err.message : "Could not load vendors"); } } } catch (err) { - if (alive) - setError(err instanceof Error ? err.message : "Could not load settings"); + if (alive) setError(err instanceof Error ? err.message : "Could not load settings"); } } load(); @@ -71,29 +78,33 @@ export function VendorSelect(props: VendorSelectProps) { const options = useMemo(() => { if (!vendors) return []; return vendors.map((v) => { - const statusHint = - v.onboardingStatus === "active" && v.chargesEnabled - ? "Active" - : v.onboardingStatus === "restricted" - ? "Restricted" - : "Pending"; + const stripeReady = connectEnabled && v.chargesEnabled; + const providerReady = splitsProviders.some( + (provider) => v.paymentAccounts?.[provider.id]?.status === "active", + ); + const ready = stripeReady || providerReady; + const statusHint = ready + ? "Active" + : v.onboardingStatus === "restricted" + ? "Restricted" + : "Pending"; return { value: v.id, label: `${v.name} · ${v.email}`, hint: statusHint, - disabled: !v.chargesEnabled, + disabled: !ready, }; }); - }, [vendors]); + }, [vendors, connectEnabled, splitsProviders]); const { value, onChange, field, readOnly } = props; const label = field?.label ?? "Vendor"; - if (connectEnabled === null) { + if (marketplaceEnabled === null) { return ; } - if (!connectEnabled) { + if (!marketplaceEnabled) { return ( - Enable it in Settings → Stripe Connect to assign products to vendors. - Leave this field blank for now. + Enable it in Settings, or install a payment provider that supports split payments, to + assign products to vendors. Leave this field blank for now. ); diff --git a/packages/core/src/admin/pages/SettingsPage.tsx b/packages/core/src/admin/pages/SettingsPage.tsx index cf623d0..031fa27 100644 --- a/packages/core/src/admin/pages/SettingsPage.tsx +++ b/packages/core/src/admin/pages/SettingsPage.tsx @@ -132,16 +132,25 @@ interface ProviderRow { description?: string | null; logo?: string | null; brandColour?: string | null; - credentialFields?: { secretKey?: CredentialField; webhookSecret?: CredentialField }; + credentialFields?: { + secretKey?: CredentialField; + webhookSecret?: CredentialField; + publicKey?: CredentialField; + }; canCheckConnection?: boolean; - secrets?: { secretKey: SecretMeta; webhookSecret: SecretMeta }; + secrets?: { + secretKey: SecretMeta; + webhookSecret: SecretMeta; + /** Present only when the provider declares a public key. */ + publicKey?: SecretMeta; + }; /** Absent from servers before on-page checkout: treat as hosted only. */ checkoutStyles?: Array<"hosted" | "on_page">; } /** - * Fixed settings, plus `SecretKey` / `WebhookSecret` - * for registered non-Stripe providers. + * Fixed settings, plus `SecretKey` / `WebhookSecret` / + * `PublicKey` for registered non-Stripe providers. */ type Draft = Partial> & { [providerCredential: string]: unknown; @@ -580,6 +589,21 @@ function GroupBody({ setField={setField} disabled={disabled} /> + {selected.credentialFields?.publicKey && ( + + )} {selected.canCheckConnection && ( )} @@ -831,7 +855,7 @@ function SecretField({ setField, disabled, }: { - /** `stripeSecretKey`, `stripeWebhookSecret`, or a provider's `SecretKey` / `WebhookSecret`. */ + /** `stripeSecretKey`, `stripeWebhookSecret`, or a provider's `SecretKey` / `WebhookSecret` / `PublicKey`. */ keyName: string; label: string; description?: string; diff --git a/packages/core/src/admin/pages/VendorsPage.tsx b/packages/core/src/admin/pages/VendorsPage.tsx index 1135908..efa6b5c 100644 --- a/packages/core/src/admin/pages/VendorsPage.tsx +++ b/packages/core/src/admin/pages/VendorsPage.tsx @@ -2,8 +2,9 @@ * Vendors admin page. * * When multi-vendor marketplace is disabled, this page renders a first-run - * empty state directing the operator to Settings. When enabled, it shows - * onboarding + list + inline edit for platform fee and Stripe refresh. + * empty state directing the operator to Settings. When enabled (Stripe + * Connect, or a provider that can split payments), it shows onboarding, the + * vendor list, and inline edit for the platform fee and payout accounts. */ import { useCallback, useEffect, useMemo, useState } from "react"; @@ -17,6 +18,7 @@ import { Loading, Money, NumberInput, + Select, Table, confirm, countryOptions, @@ -25,7 +27,7 @@ import { } from "../kit"; import { EmptyState } from "../ui/EmptyState"; import { StatusBadge } from "../ui/StatusBadge"; -import type { Vendor, VendorPayout } from "../../types"; +import type { Vendor, VendorPaymentAccount, VendorPayout } from "../../types"; import { T } from "../theme"; const STATUS_OPTIONS = [ @@ -38,6 +40,8 @@ const STATUS_OPTIONS = [ interface SettingsGateState { connectEnabled: boolean; defaultFeePercent: number; + /** Registered providers that can split a payment across vendor accounts. */ + splitsProviders: Array<{ id: string; label: string }>; } type PageState = "loading" | "disabled" | "ready" | "error"; @@ -60,9 +64,7 @@ export function VendorsPage() { const [payouts, setPayouts] = useState>({}); const [pending, setPending] = useState>({}); const [editing, setEditing] = useState<{ - vendorId: string; - name: string; - fee: number; + vendor: Vendor; } | null>(null); const loadVendors = useCallback(async () => { @@ -80,14 +82,25 @@ export function VendorsPage() { try { const settings = await api.get>("admin/settings"); const enabled = settings.connectEnabled === true; + const providers = Array.isArray(settings._providers) + ? (settings._providers as Array<{ + id: string; + label: string; + capabilities?: { splits?: boolean }; + }>) + : []; + const splitsProviders = providers + .filter((provider) => provider.capabilities?.splits === true) + .map((provider) => ({ id: provider.id, label: provider.label })); setGate({ connectEnabled: enabled, defaultFeePercent: typeof settings.connectPlatformFeePercent === "number" ? (settings.connectPlatformFeePercent as number) : 0, + splitsProviders, }); - if (!enabled) { + if (!enabled && splitsProviders.length === 0) { setPageState("disabled"); return; } @@ -125,7 +138,7 @@ export function VendorsPage() { - { - setLinkUrl(url); - await loadVendors(); - }} - /> + {gate?.connectEnabled ? ( + { + setLinkUrl(url); + await loadVendors(); + }} + /> + ) : gate && gate.splitsProviders.length > 0 ? ( + + ) : null} {linkUrl && ( @@ -261,9 +278,7 @@ export function VendorsPage() { size="sm" onClick={() => setEditing({ - vendorId: v.id, - name: v.name, - fee: v.platformFeePercent, + vendor: v, }) } > @@ -376,12 +391,13 @@ export function VendorsPage() { {editing && ( setEditing(null)} onSave={async (patch) => { try { await api.patch<{ vendor: Vendor }>( - `admin/vendors/item?id=${encodeURIComponent(editing.vendorId)}`, + `admin/vendors/item?id=${encodeURIComponent(editing.vendor.id)}`, patch, ); toast.success("Vendor updated"); @@ -519,17 +535,162 @@ function VendorOnboardingCard({ ); } +function ProviderVendorCard({ + gate, + api, + onSuccess, +}: { + gate: SettingsGateState; + api: ReturnType; + onSuccess: () => Promise; +}) { + const [name, setName] = useState(""); + const [email, setEmail] = useState(""); + const [fee, setFee] = useState(gate.defaultFeePercent); + const [providerId, setProviderId] = useState(gate.splitsProviders[0]?.id ?? ""); + const [accountReference, setAccountReference] = useState(""); + const [submitting, setSubmitting] = useState(false); + + const valid = + name.trim().length > 0 && + /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) && + typeof fee === "number" && + fee >= 0 && + fee <= 100 && + providerId.length > 0 && + accountReference.trim().length >= 4; + + async function add(): Promise { + if (!valid) return; + setSubmitting(true); + try { + await api.post("admin/vendors/item", { + name: name.trim(), + email: email.trim(), + platformFeePercent: fee ?? 0, + paymentAccount: { + providerId, + accountReference: accountReference.trim(), + status: "active", + }, + }); + toast.success("Vendor added"); + setName(""); + setEmail(""); + setAccountReference(""); + await onSuccess(); + } catch (err) { + toast.error("Could not add vendor", err instanceof Error ? err.message : undefined); + } finally { + setSubmitting(false); + } + } + + return ( + +

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

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

Edit vendor

@@ -586,6 +760,46 @@ function EditVendorModal({ disabled={saving} /> + {providers.map((provider) => ( +
+ + + setAccount(provider.id, { accountReference: e.currentTarget.value }) + } + placeholder="RS_…" + disabled={saving} + /> + + +