Skip to content
Open
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
8 changes: 8 additions & 0 deletions .changeset/clear-currency-refusal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@dashcommerce/core": patch
"@dashcommerce/paystack": patch
---

When the payment provider refuses the cart's currency, checkout now tells the customer: "This shop can't take payments in USD right now. Choose another currency, or contact the shop." Before, `create-session` answered 500 and the customer saw "Payment couldn't start. Please try again in a moment", which retrying never fixed.

Providers signal it by throwing `CurrencyNotSupportedError` (exported from `@dashcommerce/core/payment-provider`) from `initCheckout`. Paystack does this for a currency it doesn't support and for its `unsupported_currency` refusal (an account not enabled for that currency).
13 changes: 13 additions & 0 deletions .changeset/paystack-provider.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
"@dashcommerce/paystack": minor
---

New package: a Paystack payment provider for DashCommerce, built on core's PaymentProvider interface.

- Card and M-Pesa payments through Paystack's hosted page, or its Popup over your checkout. Currencies: KES, NGN, GHS, ZAR and USD.
- Orders are created only from a signed `charge.success`, confirmed against Paystack before the order is written. `Paystack-Signature` (with a `whsec_` secret, 300-second replay window) and `x-paystack-signature` (with the `sk_` key) are both verified.
- Repeat and overlapping webhook deliveries run once: each `charge.success` and `refund.*` event carries an event id core can deduplicate on.
- Refunds by transaction reference, guarded against duplicates on retry, with `refund.*` webhooks moving each refund to succeeded or failed.
- "Test Paystack connection" in Settings checks the saved key in test or live mode.

Needs `@dashcommerce/core` 0.4.0 or later. Register it with `import "@dashcommerce/paystack"` in a server module, add `api.paystack.co` to `allowedHosts`, and point Paystack's webhook at `…/checkout/webhook?provider=paystack`; see the package README.
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.

2 changes: 2 additions & 0 deletions packages/core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ For provider authors, `PaymentProvider` can declare:

Event-level dedup skips a repeated delivery even if the first one failed, so a duplicate side effect never runs. The exception is a failure to confirm the payment with the provider (`getPaymentStatus` throwing or not reporting paid). That failure happens before any side effect, so the provider's retry is processed.

If the provider refuses the cart's currency (an account not enabled for it, say), throw `CurrencyNotSupportedError` from `initCheckout`. Core answers `create-session` with a 400 that tells the customer to choose another currency, instead of a 500.

## Seed merge CLI

`@dashcommerce/core` ships a `dashcommerce-merge-seed` binary (on your `PATH` via `node_modules/.bin`). It writes the `products` collection and `product_category` / `product_tag` taxonomies into your EmDash `seed.json`, replacing any prior DashCommerce entries by slug / name. Unrelated keys in the seed file (settings, content, menus, other collections) are left intact.
Expand Down
27 changes: 27 additions & 0 deletions packages/core/src/payment-provider/errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* Thrown by a provider's `initCheckout` when the provider refuses the cart's
* currency, for example a Paystack account that isn't enabled for USD.
* Core answers `create-session` with a 400 the customer can act on, instead
* of a 500 that suggests trying again.
*
* Core recognises it by `code`, not `instanceof`, so a provider package
* bundled with its own copy of core still works.
*/
export class CurrencyNotSupportedError extends Error {
readonly code = "currency_not_supported";

constructor(readonly currency: string) {
super(`The payment provider does not accept ${currency} for this shop`);
this.name = "CurrencyNotSupportedError";
}
}

/** True for a {@link CurrencyNotSupportedError}, from any copy of core. */
export function isCurrencyNotSupportedError(err: unknown): err is CurrencyNotSupportedError {
return (
typeof err === "object" &&
err !== null &&
(err as { code?: unknown }).code === "currency_not_supported" &&
typeof (err as { currency?: unknown }).currency === "string"
);
}
1 change: 1 addition & 0 deletions packages/core/src/payment-provider/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export type {
ProviderCredentialName,
ProviderCredentialSetting,
} from "./credentials";
export { CurrencyNotSupportedError, isCurrencyNotSupportedError } from "./errors";
export { createMockPaymentProvider } from "./mock-provider";
export type { MockPaymentProviderOptions } from "./mock-provider";
export {
Expand Down
28 changes: 23 additions & 5 deletions packages/core/src/routes/checkout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { money, zero } from "../money";
import {
DEFAULT_PAYMENT_PROVIDER_ID,
type InitCheckoutInput,
isCurrencyNotSupportedError,
loadPaymentProviderCredentials,
providerCheckoutStyles,
resolveProvider,
Expand Down Expand Up @@ -843,11 +844,28 @@ export const checkoutRoutes = {
: {}),
};

const checkoutResult = await provider.initCheckout(
ctx,
{ ...initCheckout, checkoutStyle: onPage ? "on_page" : "hosted" },
creds,
);
let checkoutResult: Awaited<ReturnType<typeof provider.initCheckout>>;
try {
checkoutResult = await provider.initCheckout(
ctx,
{ ...initCheckout, checkoutStyle: onPage ? "on_page" : "hosted" },
creds,
);
} catch (err) {
if (!isCurrencyNotSupportedError(err)) throw err;
ctx.log.warn("Payment provider refused the cart's currency", {
providerId: provider.id,
currency: err.currency,
});
return new Response(
JSON.stringify({
error: `This shop can't take payments in ${err.currency} right now. Choose another currency, or contact the shop.`,
code: "currency_not_supported",
currency: err.currency,
}),
{ status: 400, headers: { "Content-Type": "application/json" } },
);
}
if (onPage) {
if (checkoutResult.kind !== "on_page") {
return new Response(
Expand Down
88 changes: 88 additions & 0 deletions packages/core/test/checkout-currency-refused.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/**
* When a provider refuses the cart's currency (a Paystack account not
* enabled for USD, say), create-session answers with a 400 the customer can
* act on, not a 500 that suggests trying again.
*/

import { afterEach, describe, expect, it } from "bun:test";
import type { RouteContext } from "emdash";
import {
CurrencyNotSupportedError,
createMockPaymentProvider,
registerPaymentProvider,
resetPaymentProviders,
} from "../src/payment-provider";
import sandbox from "../src/sandbox-entry";
import { makeRouteContext, ticketCart } from "./helpers/route-harness";

afterEach(() => resetPaymentProviders());

const mockSettings = {
"settings:paymentProvider": "mock",
"settings:checkoutMode": "hosted",
"settings:mockSecretKey": "mock-secret-key",
"settings:mockWebhookSecret": "test-secret",
};

function providerThrowing(err: Error) {
return {
...createMockPaymentProvider({ id: "mock" }),
async initCheckout(): Promise<never> {
throw err;
},
};
}

async function createSession(ctx: import("emdash").PluginContext, sessionId: string) {
await ctx.kv.set(`cart:${sessionId}`, ticketCart(sessionId));
const routeCtx = {
...ctx,
request: new Request("http://test/checkout/create-session", {
method: "POST",
headers: { "Content-Type": "application/json", Cookie: `dashcommerce_sid=${sessionId}` },
}),
input: { customerEmail: "supporter@example.com" },
} as unknown as RouteContext;
return (await sandbox.routes["checkout/create-session"].handler(routeCtx, ctx)) as Response;
}

describe("create-session when the provider refuses the currency", () => {
it("answers 400 with a message naming the currency", async () => {
registerPaymentProvider(providerThrowing(new CurrencyNotSupportedError("KES")), {
override: true,
});
const { ctx, logs } = makeRouteContext(mockSettings);
const res = await createSession(ctx, "sess_currency_refused");
expect(res.status).toBe(400);
expect(await res.json()).toEqual({
error:
"This shop can't take payments in KES right now. Choose another currency, or contact the shop.",
code: "currency_not_supported",
currency: "KES",
});
expect(logs).toContainEqual(
expect.objectContaining({
level: "warn",
meta: { providerId: "mock", currency: "KES" },
}),
);
});

it("recognises the error by its code, so a provider bundling its own copy of core works", async () => {
const foreign = Object.assign(new Error("refused"), {
code: "currency_not_supported",
currency: "USD",
});
registerPaymentProvider(providerThrowing(foreign), { override: true });
const { ctx } = makeRouteContext(mockSettings);
const res = await createSession(ctx, "sess_currency_foreign");
expect(res.status).toBe(400);
expect(((await res.json()) as { currency?: string }).currency).toBe("USD");
});

it("still fails loudly for any other provider error", async () => {
registerPaymentProvider(providerThrowing(new Error("Paystack is down")), { override: true });
const { ctx } = makeRouteContext(mockSettings);
await expect(createSession(ctx, "sess_other_error")).rejects.toThrow("Paystack is down");
});
});
102 changes: 102 additions & 0 deletions packages/paystack/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# @dashcommerce/paystack

A Paystack `PaymentProvider` for DashCommerce. Customers pay on Paystack's hosted page by card or M-Pesa (Paystack's `mobile_money` channel). DashCommerce creates the order when Paystack's signed `charge.success` webhook arrives and the transaction is confirmed with Paystack.

> **Needs `@dashcommerce/core` 0.4.0 or later.** 0.4.0 is the first core release that can call `api.paystack.co`, save Paystack keys, pass `Paystack-Signature` 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 /transaction/initialize`, then a redirect to Paystack's hosted page. The reference is `dc-<orderDraftId>`, since Paystack allows only `-`, `.`, `=` and alphanumerics |
| Webhook | Verifies both of Paystack's signature schemes in constant time with Web Crypto, choosing by the header value. See [Webhook signatures](#webhook-signatures) |
| Confirmation | Core calls `getPaymentStatus`, which uses `GET /transaction/verify/:reference`, before creating the order. The amount and currency come from Paystack's record, not the webhook body. `success`, `reversed` and `reversal-pending` count as paid (Paystack reports the last two after partial refunds too); `failed` as failed; `abandoned`, `ongoing`, `pending`, `processing` and `queued` as pending. An unknown status is reported as pending, never as paid. A `reversed` or `reversal-pending` payment whose refunds (other than failed ones) add up to the whole amount is reported as failed, so a webhook retry that arrives after a full refund creates no order |
| Duplicates | Paystack webhooks carry no event id, so the provider builds one: `charge.success:<reference>` and `<event>:<refund id>` (for example `refund.failed:19244346`). 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 Paystack fails (Paystack down, or the payment not yet successful), core releases the record, so Paystack's retry still creates the order. Any other failure keeps the record, as it does for Stripe: Paystack's retry is then answered as a duplicate, and the order has to be recovered by hand. Core's unique index on the payment reference also refuses a second order for the same payment |
| Draft lookup | From `metadata.orderDraftId`, or from the `dc-<draftId>` reference if Paystack returns no metadata |
| Return URL | Core's success URL minus Stripe's `{CHECKOUT_SESSION_ID}` placeholder; Paystack appends its own `trxref` and `reference` |
| Refunds | `POST /refund` by transaction reference, with `(refundRequestId=<id>)` in `merchant_note`. Paystack takes no idempotency key for refunds and accepts an identical second refund as a new one, so the provider first looks up the transaction's numeric id, lists its 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 note, 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. M-Pesa refunds go back to the customer's phone. Refund statuses map as `processed` → succeeded, `failed` → failed, and `pending`, `processing`, `needs-attention` → pending. `refund.*` webhooks become core's `refund.updated`, matched by the refund id. Paystack's documented sample shows only `refund_reference`, but real test-mode deliveries carry `id` (as a string, e.g. `"19244346"`) and a null `refund_reference`; an event without an id is left unhandled rather than matched by guesswork |
| Currencies | KES, NGN, GHS, ZAR and USD. Your Paystack account must be enabled for the currency you sell in |
| On-page checkout | With checkout set to "On your page", Paystack's Popup opens over the store's checkout using the `access_code` from initialise. `inline.js` loads only when the customer presses Pay. The Popup's success callback only sends the customer to the thank-you page; the order still comes from the signed webhook and a live verify |
| Customer details | Paystack's page collects neither email nor address, so the provider leaves `collectsCustomerDetails` unset and DashCommerce's checkout asks for them before payment |
| Not supported | Coupons on Paystack's page, Connect splits and subscriptions. `capabilities` declares all three as `false` |

## Webhook signatures

Paystack documents two headers ([docs](https://paystack.com/docs/v2/developer-tools/integration/webhooks)):

| Header | Format | Keyed with | Replay window |
|---|---|---|---|
| `Paystack-Signature` (current) | `t=<unix>,v1=<whk_ key id>:<hex HMAC-SHA512 of "t." + raw body>`; two `v1` values while a secret is rotated, any match accepted | the whole `whsec_` signing secret | `t` must be within 300 seconds of the server clock |
| `x-paystack-signature` (deprecated) | hex HMAC-SHA512 of the raw body | the `sk_` secret key | none |

The provider checks each header with the key it is signed with:

- `Paystack-Signature` with a saved `whsec_` secret. When it is present and a `whsec_` is saved, its result is final, so a replay outside the 300-second window cannot pass on the legacy header sent with it.
- Otherwise `x-paystack-signature`, with an `sk_` secret key saved in either field: the Paystack key or the webhook secret.

Paystack does not always send both. In a test-mode run (November 2026) its deliveries carried only `x-paystack-signature`, on an account that had a `whsec_` secret. Those verify as long as an `sk_` key is saved. If your Paystack key is a restricted `rk_` key, save the `sk_` key as the webhook secret, or webhooks are refused with a 400 that says so. Paystack retries refused deliveries, so fixing the setting recovers them.

Prefer `whsec_` where Paystack sends `Paystack-Signature`: it adds the replay window. With only `x-paystack-signature`, a captured webhook can be replayed, but it cannot create a second order or an order Paystack's own records do not confirm.

Paystack sends no `charge.failed` webhook. A payment that fails or is abandoned leaves the checkout draft unpaid, and no order is created.

## Use

1. **Install** both packages:

```sh
npm install @dashcommerce/core@^0.4.0 @dashcommerce/paystack
```

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/paystack"; // registers the "paystack" 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 `paystack` id, the import throws instead of silently replacing it.

3. **Allow Paystack's API host:**

```ts
emdash({ plugins: [dashcommerce({ allowedHosts: ["api.paystack.co"] })] });
```

4. **Choose Paystack and enter its keys** in Settings → Payment provider:

| Field | Value |
|---|---|
| Secret or restricted key | best: a restricted key (`rk_test_…`) with only `transactions:write` and `disputes_refunds:write`; or the secret key (`sk_test_…`) |
| Webhook signing secret | the `whsec_…` secret from Developers → API configuration, or the `sk_` secret key. With a restricted `rk_` key above, use the `sk_` key here unless your deliveries carry `Paystack-Signature` (see [Webhook signatures](#webhook-signatures)) |

Save, then press **Test Paystack connection**. It makes one read-only call (verifying a reference that can't exist) and says whether Paystack accepts the key, in test or live mode, and whether it can read transactions.

Under **How customers pay**, choose hosted (Paystack's page) or on your page (the Popup). Do not delete the `sk_` key from Paystack before your webhooks verify with `whsec_`: Paystack stops sending `x-paystack-signature` once it is gone.

5. **For on-page checkout, load the browser client** in your checkout page's client script, so Vite bundles it:

```astro
<script>
import "@dashcommerce/paystack/checkout-client";
</script>
```

If your site sends a Content-Security-Policy, allow `https://js.paystack.co` for scripts and Paystack's checkout frames.

6. **Set the webhook URL** in the Paystack dashboard, including `?provider=paystack`:

```
https://<your-site>/_emdash/api/plugins/dashcommerce/checkout/webhook?provider=paystack
```

Without the query, core picks the provider from the signature header. That works today, but the query keeps Paystack's webhooks going to Paystack even if another provider later uses a header with the same name.

## Develop

```sh
bun test # unit tests, plus checkout → webhook → order through core's real routes
bun run typecheck
bun run build
```

The integration tests use a Paystack stand-in that only answers `verify` for references it issued. A provider that verifies by the wrong identifier fails there.
Loading
Loading