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

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.
52 changes: 52 additions & 0 deletions packages/paystack/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
{
"name": "@dashcommerce/paystack",
"version": "0.0.0",
"description": "Paystack payment provider for @dashcommerce/core: card and M-Pesa through Paystack's hosted page or its Popup on your checkout, signed 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"
},
"./checkout-client": {
"import": "./dist/checkout-client.mjs",
"types": "./dist/checkout-client.d.mts"
}
},
"files": ["dist", "README.md"],
"engines": {
"node": ">=20"
},
"keywords": ["dashcommerce", "paystack", "payments", "mpesa", "kenya", "africa"],
"author": "DashCommerce contributors",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/emdashCommerce/dashcommerce.git",
"directory": "packages/paystack"
},
"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"
}
}
97 changes: 97 additions & 0 deletions packages/paystack/src/checkout-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/**
* Browser side of Paystack on-page checkout (the Popup).
*
* A storefront imports this once, in its checkout page's client script:
*
* import "@dashcommerce/paystack/checkout-client";
*
* which registers the client on `window.DashCommerceCheckoutClients.paystack`.
* DashCommerce's checkout form calls it with the `accessCode` from
* create-session. Paystack's `inline.js` is loaded only then, never on page
* load. The callbacks only move the customer along: the order is created by
* the signed webhook and a live verify, never by the browser.
*
* Runs in the browser only; nothing here may be imported by the provider.
*/

import type { OnPageCheckoutClient } from "@dashcommerce/core/payment-provider";

export const PAYSTACK_INLINE_SCRIPT = "https://js.paystack.co/v2/inline.js";

interface PaystackPopInstance {
resumeTransaction(
accessCode: string,
callbacks: {
onSuccess?: (transaction: unknown) => void;
onCancel?: () => void;
onError?: (error: { message?: string } | undefined) => void;
},
): void;
}

type WindowWithPaystack = Window & {
PaystackPop?: new () => PaystackPopInstance;
DashCommerceCheckoutClients?: Record<string, OnPageCheckoutClient>;
};

/** Build the client for a given window and document (tests pass stand-ins). */
export function createPaystackCheckoutClient(win: Window, doc: Document): OnPageCheckoutClient {
const w = win as WindowWithPaystack;
let loading: Promise<void> | null = null;

function loadScript(): Promise<void> {
if (w.PaystackPop) return Promise.resolve();
if (!loading) {
loading = new Promise<void>((resolve, reject) => {
const script = doc.createElement("script");
script.src = PAYSTACK_INLINE_SCRIPT;
script.async = true;
script.onload = () => resolve();
script.onerror = () => reject(new Error("script failed"));
doc.head.appendChild(script);
}).catch((err) => {
loading = null; // let a retry load it again
throw err;
});
}
return loading;
}

return {
open(client, callbacks) {
const accessCode = client.accessCode;
if (!accessCode) {
callbacks.onError("Paystack did not return an access code");
return;
}
loadScript().then(
() => {
if (!w.PaystackPop) {
callbacks.onError("Could not load Paystack. Check your connection and try again.");
return;
}
new w.PaystackPop().resumeTransaction(accessCode, {
onSuccess: () => callbacks.onFinished(),
onCancel: () => callbacks.onClosed(),
onError: (error) =>
callbacks.onError(error?.message ?? "Paystack could not start the payment"),
});
},
() => callbacks.onError("Could not load Paystack. Check your connection and try again."),
);
},
};
}

/** Put the Paystack client next to any other providers' clients. */
export function registerPaystackCheckoutClient(win: Window, doc: Document): void {
const w = win as WindowWithPaystack;
w.DashCommerceCheckoutClients = {
...(w.DashCommerceCheckoutClients ?? {}),
paystack: createPaystackCheckoutClient(win, doc),
};
}

if (typeof window !== "undefined" && typeof document !== "undefined") {
registerPaystackCheckoutClient(window, document);
}
97 changes: 97 additions & 0 deletions packages/paystack/src/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/**
* Paystack 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 (Paystack REST API).
* - Auto-injects `Authorization: Bearer {secretKey}`.
* - Throws `PaystackApiError` on a non-2xx or a body with `status: false`.
*/

import type { PaymentProviderRuntimeContext } from "@dashcommerce/core/payment-provider";

export const PAYSTACK_API_BASE = "https://api.paystack.co";

export class PaystackApiError extends Error {
readonly status: number;
readonly body: Record<string, unknown>;
constructor(status: number, body: Record<string, unknown>, message: string) {
super(message);
this.name = "PaystackApiError";
this.status = status;
this.body = body;
}
}

export interface PaystackClientOptions {
secretKey: string;
/** Override for tests. */
apiBase?: string;
}

export interface PaystackCallOptions {
method?: "GET" | "POST";
path: string; // leading slash, e.g. /transaction/initialize
body?: Record<string, unknown>;
client: PaystackClientOptions;
}

export interface PaystackResponse<T> {
status: boolean;
message: string;
data: T;
}

export async function call<T = Record<string, unknown>>(
ctx: PaymentProviderRuntimeContext,
opts: PaystackCallOptions,
): Promise<T> {
return (await callEnvelope<T>(ctx, opts)).data;
}

/** As `call`, but returns the whole response, including list `meta`. */
export async function callEnvelope<T = Record<string, unknown>>(
ctx: PaymentProviderRuntimeContext,
opts: PaystackCallOptions,
): Promise<PaystackResponse<T> & { meta?: Record<string, unknown> }> {
const method = opts.method ?? "POST";
const base = opts.client.apiBase ?? PAYSTACK_API_BASE;
const headers: Record<string, string> = {
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("Paystack 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: PaystackResponse<T> & { meta?: Record<string, unknown> };
try {
parsed = JSON.parse(rawText) as PaystackResponse<T> & { meta?: Record<string, unknown> };
} catch {
throw new PaystackApiError(
res.status,
{ raw: rawText },
`Paystack returned unparseable response (${res.status})`,
);
}

if (!res.ok || !parsed.status) {
const msg =
parsed.message ||
(typeof parsed.data === "string" ? parsed.data : undefined) ||
`Paystack API error (${res.status})`;
throw new PaystackApiError(res.status, parsed as unknown as Record<string, unknown>, msg);
}

return parsed;
}
Loading
Loading