Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/flutterwave-on-page.md
Original file line number Diff line number Diff line change
@@ -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.
14 changes: 14 additions & 0 deletions .changeset/flutterwave-provider.md
Original file line number Diff line number Diff line change
@@ -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.
9 changes: 9 additions & 0 deletions .changeset/provider-public-key.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"@dashcommerce/core": minor
---

Let a payment provider save a browser public key.

- `PaymentProviderCredentials.publicKey` and `credentialFields.publicKey`, saved as `settings:<id>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.
14 changes: 14 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions packages/core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,12 @@ Stripe is built in. A gateway package (for example `@dashcommerce/paystack`) reg
emdash({ plugins: [dashcommerce({ allowedHosts: ["api.paystack.co"] })] });
```

3. **Choose the provider and enter its keys** in Settings → Payment provider. They are saved as `settings:<id>SecretKey` and `settings:<id>WebhookSecret`, masked like Stripe's.
3. **Choose the provider and enter its keys** in Settings → Payment provider. They are saved as `settings:<id>SecretKey` and `settings:<id>WebhookSecret` (plus `settings:<id>PublicKey` when the provider declares one), masked like Stripe's.
4. **Point the provider's webhooks** at `/_emdash/api/plugins/dashcommerce/checkout/webhook?provider=<id>`.

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

Expand Down
34 changes: 29 additions & 5 deletions packages/core/src/admin/pages/SettingsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<providerId>SecretKey` / `<providerId>WebhookSecret`
* for registered non-Stripe providers.
* Fixed settings, plus `<providerId>SecretKey` / `<providerId>WebhookSecret` /
* `<providerId>PublicKey` for registered non-Stripe providers.
*/
type Draft = Partial<Omit<SettingsShape, "_secrets" | "_providers">> & {
[providerCredential: string]: unknown;
Expand Down Expand Up @@ -580,6 +589,21 @@ function GroupBody({
setField={setField}
disabled={disabled}
/>
{selected.credentialFields?.publicKey && (
<SecretField
keyName={`${selected.id}PublicKey`}
label={
selected.credentialFields.publicKey.label ?? `${selected.label} public key`
}
description={credentialDescription(selected.credentialFields.publicKey)}
meta={selected.secrets?.publicKey}
saved={saved}
draft={draft}
errors={errors}
setField={setField}
disabled={disabled}
/>
)}
{selected.canCheckConnection && (
<ProviderConnectionCheck providerId={selected.id} label={selected.label} />
)}
Expand Down Expand Up @@ -831,7 +855,7 @@ function SecretField({
setField,
disabled,
}: {
/** `stripeSecretKey`, `stripeWebhookSecret`, or a provider's `<id>SecretKey` / `<id>WebhookSecret`. */
/** `stripeSecretKey`, `stripeWebhookSecret`, or a provider's `<id>SecretKey` / `<id>WebhookSecret` / `<id>PublicKey`. */
keyName: string;
label: string;
description?: string;
Expand Down
30 changes: 24 additions & 6 deletions packages/core/src/payment-provider/credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
*
* Stripe keeps the existing key names (`settings:stripeSecretKey` /
* `settings:stripeWebhookSecret`). Other providers use
* `settings:<id>SecretKey` and `settings:<id>WebhookSecret`.
* `settings:<id>SecretKey`, `settings:<id>WebhookSecret` and, when they
* declare one, `settings:<id>PublicKey`.
*/

import { getPaymentProvider } from "./registry";
Expand All @@ -26,7 +27,12 @@ export async function loadPaymentProviderCredentials(
const secretKey = await kv.get<string>(`settings:${providerId}SecretKey`);
if (!secretKey) return null;
const webhookSecret = (await kv.get<string>(`settings:${providerId}WebhookSecret`)) ?? undefined;
return { secretKey, webhookSecret };
const publicKey = (await kv.get<string>(`settings:${providerId}PublicKey`)) ?? undefined;
return {
secretKey,
...(webhookSecret ? { webhookSecret } : {}),
...(publicKey ? { publicKey } : {}),
};
}

export function webhookSignatureHeader(headers: Headers, providerId: string): string | null {
Expand All @@ -40,15 +46,21 @@ export function webhookSignatureHeader(headers: Headers, providerId: string): st
);
}

export type ProviderCredentialName = "secretKey" | "webhookSecret";
export type ProviderCredentialName = "secretKey" | "webhookSecret" | "publicKey";

export interface ProviderCredentialSetting {
providerId: string;
field: ProviderCredentialName;
spec: PaymentProviderCredentialField;
}

const PROVIDER_CREDENTIAL_KEY = /^([a-z][a-z0-9_-]{0,63})(SecretKey|WebhookSecret)$/;
const PROVIDER_CREDENTIAL_KEY = /^([a-z][a-z0-9_-]{0,63})(SecretKey|WebhookSecret|PublicKey)$/;

const CREDENTIAL_FIELD: Record<string, ProviderCredentialName> = {
SecretKey: "secretKey",
WebhookSecret: "webhookSecret",
PublicKey: "publicKey",
};

/**
* If `key` (without the `settings:` prefix) is a credential setting of a
Expand All @@ -58,9 +70,15 @@ const PROVIDER_CREDENTIAL_KEY = /^([a-z][a-z0-9_-]{0,63})(SecretKey|WebhookSecre
export function providerCredentialSetting(key: string): ProviderCredentialSetting | undefined {
const match = PROVIDER_CREDENTIAL_KEY.exec(key);
const providerId = match?.[1];
if (!match || !providerId || providerId === "stripe") return undefined;
const suffix = match?.[2];
if (!match || !providerId || !suffix || providerId === "stripe") return undefined;
const provider = getPaymentProvider(providerId);
if (!provider) return undefined;
const field: ProviderCredentialName = match[2] === "SecretKey" ? "secretKey" : "webhookSecret";
const field = CREDENTIAL_FIELD[suffix];
if (!field) return undefined;
// Secret key and webhook secret are offered for every provider (Settings
// falls back to a generic label). A public key is only meaningful when the
// provider declares one, so don't accept one for a provider that doesn't.
if (field === "publicKey" && !provider.credentialFields?.publicKey) return undefined;
return { providerId, field, spec: provider.credentialFields?.[field] ?? {} };
}
14 changes: 13 additions & 1 deletion packages/core/src/payment-provider/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,12 @@ export interface RefundResult {
export interface PaymentProviderCredentials {
secretKey: string;
webhookSecret?: string;
/**
* The provider's browser-side public key, when it has one. Used by
* providers whose on-page checkout needs it in the browser (Flutterwave
* Inline). Never a secret, but saved with the same settings plumbing.
*/
publicKey?: string;
}

/** Subset of PluginContext a provider may use. */
Expand Down Expand Up @@ -353,11 +359,17 @@ export interface PaymentProvider {

/**
* Credentials the merchant enters in admin settings, saved as
* `settings:<id>SecretKey` and `settings:<id>WebhookSecret`.
* `settings:<id>SecretKey`, `settings:<id>WebhookSecret` and
* `settings:<id>PublicKey`.
*/
readonly credentialFields?: {
secretKey?: PaymentProviderCredentialField;
webhookSecret?: PaymentProviderCredentialField;
/**
* The browser-side public key, for on-page checkout that needs one
* (Flutterwave Inline). Settings shows the field only when declared.
*/
publicKey?: PaymentProviderCredentialField;
};

/** True if this provider can charge `currency` (ISO-4217). */
Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/routes/admin-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,9 @@ async function providerSettingsRows(ctx: PluginContext) {
secrets: {
secretKey: await secretStatus(ctx, `${provider.id}SecretKey`),
webhookSecret: await secretStatus(ctx, `${provider.id}WebhookSecret`),
...(provider.credentialFields?.publicKey
? { publicKey: await secretStatus(ctx, `${provider.id}PublicKey`) }
: {}),
},
});
}
Expand Down
50 changes: 49 additions & 1 deletion packages/core/test/provider-credentials-settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
import { afterEach, describe, expect, it } from "bun:test";
import type { PluginContext, RouteContext } from "emdash";
import {
type PaymentProvider,
createMockPaymentProvider,
loadPaymentProviderCredentials,
type PaymentProvider,
registerPaymentProvider,
resetPaymentProviders,
} from "../src/payment-provider";
Expand All @@ -30,6 +30,11 @@ function acme(): PaymentProvider {
prefixes: ["awh_"],
help: "From the dashboard",
},
publicKey: {
label: "Browser public key",
prefixes: ["apk_test_", "apk_"],
help: "Used by on-page checkout",
},
},
};
}
Expand All @@ -51,14 +56,33 @@ describe("provider credentials in the settings API", () => {
paymentProvider: "acme",
acmeSecretKey: "ark_test_1234567890",
acmeWebhookSecret: "awh_1234567890",
acmePublicKey: "apk_test_1234567890",
});
expect(res).toEqual({ status: 200, body: { ok: true } });
expect(await loadPaymentProviderCredentials(ctx.kv, "acme")).toEqual({
secretKey: "ark_test_1234567890",
webhookSecret: "awh_1234567890",
publicKey: "apk_test_1234567890",
});
});

it("validates the public key against its declared prefixes", async () => {
registerPaymentProvider(acme());
const { ctx, kvStore } = makeRouteContext({});
const res = await call(ctx, "POST", { acmePublicKey: "sk_live_wrong" });
expect(res.status).toBe(400);
expect(String((res.body.errors as Record<string, string>).acmePublicKey)).toContain("apk_");
expect(kvStore.has("settings:acmePublicKey")).toBe(false);
});

it("refuses a public key for a provider that does not declare one", async () => {
registerPaymentProvider(createMockPaymentProvider({ id: "plain" }));
const { ctx } = makeRouteContext({});
const res = await call(ctx, "POST", { plainPublicKey: "pk_123" });
expect(res.status).toBe(400);
expect(Object.keys(res.body.errors as object)).toEqual(["plainPublicKey"]);
});

it("refuses a value without a declared prefix", async () => {
registerPaymentProvider(acme());
const { ctx, kvStore } = makeRouteContext({});
Expand Down Expand Up @@ -95,9 +119,11 @@ describe("provider credentials in the settings API", () => {
const { ctx } = makeRouteContext({
"settings:paymentProvider": "acme",
"settings:acmeSecretKey": "ak_test_abcd1234",
"settings:acmePublicKey": "apk_test_public5678",
});
const { body } = await call(ctx, "GET");
expect(JSON.stringify(body)).not.toContain("ak_test_abcd1234");
expect(JSON.stringify(body)).not.toContain("apk_test_public5678");
const providers = body._providers as Array<Record<string, unknown>>;
expect(providers.map((p) => p.id)).toEqual(["stripe", "acme"]);
const acmeRow = providers.find((p) => p.id === "acme");
Expand All @@ -114,14 +140,36 @@ describe("provider credentials in the settings API", () => {
prefixes: ["awh_"],
help: "From the dashboard",
},
publicKey: {
label: "Browser public key",
prefixes: ["apk_test_", "apk_"],
help: "Used by on-page checkout",
},
},
checkoutStyles: ["hosted"],
canCheckConnection: false,
secrets: {
secretKey: { isSet: true, hint: "••••1234" },
webhookSecret: { isSet: false, hint: null },
publicKey: { isSet: true, hint: "••••5678" },
},
});
});

it("omits the public key row for providers that do not declare one", async () => {
registerPaymentProvider(createMockPaymentProvider({ id: "plain" }));
const { ctx } = makeRouteContext({});
const providers = (await call(ctx, "GET")).body._providers as Array<Record<string, unknown>>;
expect(providers.find((p) => p.id === "plain")).toMatchObject({
secrets: {
secretKey: { isSet: false, hint: null },
webhookSecret: { isSet: false, hint: null },
},
});
const plain = providers.find((p) => p.id === "plain") as {
secrets: Record<string, unknown>;
};
expect(plain.secrets.publicKey).toBeUndefined();
});

it("leaves Stripe's keys exactly as before", async () => {
Expand Down
Loading