From 222a14b59e831bad01f4b1b0ba38740bc9be46b8 Mon Sep 17 00:00:00 2001 From: Nyaenya Obadiah Moseti Date: Fri, 20 Nov 2026 07:51:53 +0300 Subject: [PATCH 1/3] feat(paystack): Paystack payment provider package A PaymentProvider for Paystack on core's provider interface: card and M-Pesa through Paystack's hosted page or its Popup over the store's own checkout. - Orders come only from a signed charge.success, confirmed with /transaction/verify. Both signature schemes are checked with the key each is signed with: Paystack-Signature with a whsec_ secret (final when present, so its 300-second replay window holds) and x-paystack-signature with the sk_ key. In a real test-mode run Paystack sent only x-paystack-signature on an account with a whsec_ secret, so both matter. - Refunds by transaction reference, tagged with core's refundRequestId so a retry returns the existing refund instead of creating a second one; refund.* webhooks (which carry the refund id as a string) map to refund.updated. - A payment refunded in full at Paystack before its order exists is not confirmed, so a late webhook retry creates no order. Paystack reports reversed after partial refunds too, so the refunded total decides. - "Test Paystack connection" checks the saved key, test or live. - The Popup client (./checkout-client) loads js.paystack.co only when the customer presses Pay. Tested end to end in Paystack test mode: hosted and Popup, card and M-Pesa, declined cards, duplicate and stale webhooks, refunds that succeed and fail. --- .changeset/paystack-provider.md | 12 + bun.lock | 14 + packages/paystack/README.md | 104 +++ packages/paystack/package.json | 52 ++ packages/paystack/src/checkout-client.ts | 97 +++ packages/paystack/src/client.ts | 97 +++ packages/paystack/src/index.ts | 44 ++ packages/paystack/src/logo.ts | 6 + packages/paystack/src/provider.ts | 691 ++++++++++++++++ packages/paystack/src/webhook-verify.ts | 164 ++++ .../paystack/test/connection-check.test.ts | 100 +++ .../paystack/test/core-enablement.test.ts | 162 ++++ .../paystack/test/core-integration.test.ts | 736 ++++++++++++++++++ .../fixtures/refund-list-by-transaction.json | 94 +++ .../fixtures/verify-reversal-pending.json | 65 ++ packages/paystack/test/on-page.test.ts | 211 +++++ .../paystack/test/paystack-provider.test.ts | 501 ++++++++++++ .../paystack/test/provider-hardening.test.ts | 651 ++++++++++++++++ packages/paystack/tsconfig.json | 11 + packages/paystack/tsdown.config.ts | 9 + 20 files changed, 3821 insertions(+) create mode 100644 .changeset/paystack-provider.md create mode 100644 packages/paystack/README.md create mode 100644 packages/paystack/package.json create mode 100644 packages/paystack/src/checkout-client.ts create mode 100644 packages/paystack/src/client.ts create mode 100644 packages/paystack/src/index.ts create mode 100644 packages/paystack/src/logo.ts create mode 100644 packages/paystack/src/provider.ts create mode 100644 packages/paystack/src/webhook-verify.ts create mode 100644 packages/paystack/test/connection-check.test.ts create mode 100644 packages/paystack/test/core-enablement.test.ts create mode 100644 packages/paystack/test/core-integration.test.ts create mode 100644 packages/paystack/test/fixtures/refund-list-by-transaction.json create mode 100644 packages/paystack/test/fixtures/verify-reversal-pending.json create mode 100644 packages/paystack/test/on-page.test.ts create mode 100644 packages/paystack/test/paystack-provider.test.ts create mode 100644 packages/paystack/test/provider-hardening.test.ts create mode 100644 packages/paystack/tsconfig.json create mode 100644 packages/paystack/tsdown.config.ts diff --git a/.changeset/paystack-provider.md b/.changeset/paystack-provider.md new file mode 100644 index 0000000..eae9efe --- /dev/null +++ b/.changeset/paystack-provider.md @@ -0,0 +1,12 @@ +--- +"@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. +- 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. + +Register it with `import "@dashcommerce/paystack"` in a server module and add `api.paystack.co` to `allowedHosts`; see the package README. diff --git a/bun.lock b/bun.lock index ab110bf..2c16585 100644 --- a/bun.lock +++ b/bun.lock @@ -73,6 +73,18 @@ "emdash": ">=1.3.0 <2.0.0", }, }, + "packages/paystack": { + "name": "@dashcommerce/paystack", + "version": "0.0.0", + "devDependencies": { + "@dashcommerce/core": "workspace:*", + "tsdown": "^0.20.0", + "typescript": "^5.9.3", + }, + "peerDependencies": { + "@dashcommerce/core": "workspace:*", + }, + }, "packages/registry-setup": { "name": "@dashcommerce/registry-setup", "version": "0.1.1", @@ -341,6 +353,8 @@ "@dashcommerce/lite": ["@dashcommerce/lite@workspace:packages/lite"], + "@dashcommerce/paystack": ["@dashcommerce/paystack@workspace:packages/paystack"], + "@dashcommerce/registry-setup": ["@dashcommerce/registry-setup@workspace:packages/registry-setup"], "@dashcommerce/starter": ["@dashcommerce/starter@workspace:packages/starter"], diff --git a/packages/paystack/README.md b/packages/paystack/README.md new file mode 100644 index 0000000..68b2843 --- /dev/null +++ b/packages/paystack/README.md @@ -0,0 +1,104 @@ +# @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. + +> **Status: needs core with the provider-enablement changes** (the companion core PR). Released core 0.3.5 cannot call `api.paystack.co`, save Paystack keys, pass `Paystack-Signature`, or take refund updates. See [Core requirements](#core-requirements). The package is `private` and is not published. + +## What it does + +| Area | Behaviour | +|---|---| +| Checkout | `POST /transaction/initialize`, then a redirect to Paystack's hosted page. The reference is `dc-`, 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 `providerEventId` is left empty and core relies on its unique index on the payment reference: a repeat delivery never creates a second order, and Paystack's retry after a failed first delivery still creates it | +| Draft lookup | From `metadata.orderDraftId`, or from the `dc-` 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=)` 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=,v1=:`; 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. **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. + +2. **Allow Paystack's API host:** + + ```ts + emdash({ plugins: [dashcommerce({ allowedHosts: ["api.paystack.co"] })] }); + ``` + +3. **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. + +4. **For on-page checkout, load the browser client** in your checkout page's client script, so Vite bundles it: + + ```astro + + ``` + + If your site sends a Content-Security-Policy, allow `https://js.paystack.co` for scripts and Paystack's checkout frames. + +5. **Set the webhook URL** in the Paystack dashboard: + + ``` + https:///_emdash/api/plugins/dashcommerce/checkout/webhook?provider=paystack + ``` + +## Core requirements + +From core (the companion core PR, proposed together with this package): + +1. **`dashcommerce({ allowedHosts })`.** Without it, `ctx.http.fetch` refuses `api.paystack.co`, and EmDash 1.5 throws. +2. **Per-provider credentials** in the settings API and admin, accepting the `rk_` and `whsec_` prefixes this package declares in `credentialFields`. +3. **All request headers in `verifyWebhook`** plus `webhookHeaders` routing, so `Paystack-Signature` reaches the provider. +4. **`refund.updated`**, so `refund.*` webhooks move a refund out of `pending`. Live refunds can take days. +5. **`checkConnection`**, for the Test connection button in Settings. Optional: without it the button doesn't show. + +## 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. diff --git a/packages/paystack/package.json b/packages/paystack/package.json new file mode 100644 index 0000000..dafac4b --- /dev/null +++ b/packages/paystack/package.json @@ -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": "workspace:*" + }, + "devDependencies": { + "@dashcommerce/core": "workspace:*", + "tsdown": "^0.20.0", + "typescript": "^5.9.3" + } +} diff --git a/packages/paystack/src/checkout-client.ts b/packages/paystack/src/checkout-client.ts new file mode 100644 index 0000000..628db66 --- /dev/null +++ b/packages/paystack/src/checkout-client.ts @@ -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; +}; + +/** 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 | null = null; + + function loadScript(): Promise { + if (w.PaystackPop) return Promise.resolve(); + if (!loading) { + loading = new Promise((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); +} diff --git a/packages/paystack/src/client.ts b/packages/paystack/src/client.ts new file mode 100644 index 0000000..17fb6a3 --- /dev/null +++ b/packages/paystack/src/client.ts @@ -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; + constructor(status: number, body: Record, 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; + client: PaystackClientOptions; +} + +export interface PaystackResponse { + status: boolean; + message: string; + data: T; +} + +export async function call>( + ctx: PaymentProviderRuntimeContext, + opts: PaystackCallOptions, +): Promise { + return (await callEnvelope(ctx, opts)).data; +} + +/** As `call`, but returns the whole response, including list `meta`. */ +export async function callEnvelope>( + ctx: PaymentProviderRuntimeContext, + opts: PaystackCallOptions, +): Promise & { meta?: Record }> { + const method = opts.method ?? "POST"; + const base = opts.client.apiBase ?? PAYSTACK_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("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 & { meta?: Record }; + try { + parsed = JSON.parse(rawText) as PaystackResponse & { meta?: Record }; + } 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, msg); + } + + return parsed; +} diff --git a/packages/paystack/src/index.ts b/packages/paystack/src/index.ts new file mode 100644 index 0000000..a6a6908 --- /dev/null +++ b/packages/paystack/src/index.ts @@ -0,0 +1,44 @@ +/** + * @dashcommerce/paystack + * + * Paystack PaymentProvider for DashCommerce: hosted checkout (card and + * M-Pesa via Paystack's `mobile_money` channel), Web Crypto HMAC-SHA512 + * 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 { paystackPaymentProvider } from "./provider"; + +export { paystackPaymentProvider, paystackReferenceFor } from "./provider"; +export { + verifyPaystackSignature, + type VerifyInput, + type VerifyResult, +} from "./webhook-verify"; +export { + call as callPaystack, + PaystackApiError, + PAYSTACK_API_BASE, + type PaystackClientOptions, + type PaystackCallOptions, + type PaystackResponse, +} from "./client"; + +/** + * Register the Paystack provider. Safe to call more than once. If a + * different provider already holds the `paystack` id this throws, unless + * `{ override: true }` is passed, so a clash is never silent. + */ +export function registerPaystackProvider(opts: { override?: boolean } = {}): void { + if ( + !opts.override && + getPaymentProvider(paystackPaymentProvider.id) === paystackPaymentProvider + ) { + return; + } + registerPaymentProvider(paystackPaymentProvider, opts); +} + +registerPaystackProvider(); diff --git a/packages/paystack/src/logo.ts b/packages/paystack/src/logo.ts new file mode 100644 index 0000000..590db3c --- /dev/null +++ b/packages/paystack/src/logo.ts @@ -0,0 +1,6 @@ +/** + * Paystack's mark for the provider card in Settings (181×148 WebP, 860 bytes). + * Inlined as a data URI so the admin loads nothing from a third-party host. + */ +export const PAYSTACK_LOGO = + "data:image/webp;base64,UklGRlQDAABXRUJQVlA4IEgDAACwGgCdASq1AJQAPoE+m0ilI6KhLFPYGKAQCU3cLaIYGI7X1/Db4auA84/krxu/6T2AbZnzAfsl+uXvVf3b9SfbF30D9gPYA6XBG+bgJVJ3dNaOoRkHDLxH1MsFEorDBOrKrgQnHxP8fTQ6WNf/ey2kGgz/vgum+8ntvEFvoZUyHO21lV0AlkTVVLG8R4cpVmpk8HtpWgIbc8fVnYJRhnewYft9piFw4T2w5e7e/Q4YOcV4rk5e/FMnx5oFiuYwoZZIiWWycIv3I860UxGPz+QqKroAr4dFl7sDhl4j6AAA/v4sF73M9+y6iiptSC+dAC0OogcYWyX9JTwsJlBP1JofeeoKyrpif/3EpbMIkXUvG6ihf12kz0YP4O7Np2CNyvvNZlpwL/lRw3sToaXTp4iWYTGQI8Bhl9R/j7tfxW7veENsjlMcY8y4JEM8nwPpPvkPKxco0Iar+5h+o6uBQMUmSrK3WqNPwu++E5nLbZhD0QcxXLMdSTKZwjewlciwLLoLG4Gsmen3i2BPLD2YuUEAlBqmvZnl1ZsofTCpHU/OQ4/Oeoo3O/tHTMwIpnxLY/IBiodp/sv6tc3hBOV06iyfWSncP2evy0KCeR8ba9i+F5fFUXZgNCq/13svd3O6PBzeFSa2vOzlZ7gFOtfb+WCxtMlVO6ZfiF2gyZpomyn4M0g1ghTqySTKQpl7BZDq9th/vJXsmjLQjBYjJfJTb9Hr7FmskA5MnFWnzUPNE0IHB5ggNVbCS5Ad5zgraOy93mfYuEbHoHb4l5HT9icMywD6C3lkpttSIGuMmuA0Cxfg+Vb3sH5mz2mqcgaqDGQ+2fO2SdqoQoK8NPaQYt/qFrgv+4kAJ7NCFghqfKL+b2WuFnY77dr32K3oGjgDt4wDSG0KNmvCWfZKSeCkUMIladgw/9WBpIsqrnzOrfiGFa1n2zCk0SgdtWUrtqToClht5c3mdWbsWbttTR4vpiKnx7YFDeglnARnz9cG62Ptieb9Zjwd4+DT1mROnHkvCoTcVtVBBmPz2gwoTRaBrFuI93ia4ho+ExPXjdgRS1cvBSd+Ue9UOebFCmck/R5DcQajOunoEYUNH+lt8+9FxU8/3LqVnzFqAAAAAAA="; diff --git a/packages/paystack/src/provider.ts b/packages/paystack/src/provider.ts new file mode 100644 index 0000000..1f5dacb --- /dev/null +++ b/packages/paystack/src/provider.ts @@ -0,0 +1,691 @@ +/** + * PaystackPaymentProvider — Paystack implementing @dashcommerce/core's + * PaymentProvider interface. + * + * Channel note: Paystack's hosted checkout page offers whichever + * channels are enabled on the merchant's Paystack Kenya account + * ("card", "mobile_money" — M-Pesa STK is triggered from inside the + * `mobile_money` channel on the hosted page). + */ + +import type { + ConnectionCheckResult, + CreateRefundInput, + InitCheckoutInput, + InitCheckoutResult, + NormalizedPaymentEvent, + PaymentProvider, + PaymentProviderCredentials, + PaymentProviderRuntimeContext, + RefundResult, + VerifyWebhookInput, + VerifyWebhookResult, +} from "@dashcommerce/core/payment-provider"; +import { call, callEnvelope, PaystackApiError, type PaystackClientOptions } from "./client"; +import { PAYSTACK_LOGO } from "./logo"; +import { verifyPaystackSignature } from "./webhook-verify"; + +const SUPPORTED_CURRENCIES = new Set(["KES", "NGN", "GHS", "ZAR", "USD"]); + +const PAYSTACK_CHANNEL_MAP: Record = { + card: "card", + mpesa: "mobile_money", + "m-pesa": "mobile_money", + mobile_money: "mobile_money", +}; + +/** + * Paystack accepts only `-`, `.`, `=` and alphanumerics in a transaction + * reference. Core's draft ids are hex, so this is normally `dc-`; + * anything else is replaced rather than sent and rejected. + */ +export function paystackReferenceFor(orderDraftId: string): string { + return `${REFERENCE_PREFIX}${orderDraftId.replace(/[^A-Za-z0-9.=-]/g, "-")}`; +} + +const REFERENCE_PREFIX = "dc-"; + +/** 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. Paystack does not, so drop it and let + * Paystack append its own `trxref` and `reference` parameters. + */ +function paystackCallbackUrl(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(); +} + +/** Paystack documents metadata as a JSON object, but tolerate 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; +} + +function toPaystackClient(credentials: PaymentProviderCredentials): PaystackClientOptions { + return { secretKey: credentials.secretKey }; +} + +function mapChannels(preferred: string[] | undefined): string[] | undefined { + if (!preferred || preferred.length === 0) return undefined; + const mapped = new Set(); + for (const p of preferred) { + const m = PAYSTACK_CHANNEL_MAP[p.toLowerCase()]; + if (m) mapped.add(m); + } + return mapped.size > 0 ? Array.from(mapped) : undefined; +} + +interface PaystackInitializeData { + authorization_url: string; + access_code: string; + reference: string; +} + +interface PaystackWebhookEvent { + event: string; + data: { + id: number; + reference: string; + amount?: number; + currency?: string; + status?: string; + customer?: { + id?: number; + email?: string; + first_name?: string; + last_name?: string; + phone?: string; + }; + authorization?: { channel?: string }; + channel?: string; + metadata?: { + orderDraftId?: string; + checkoutReference?: string; + billingAddress?: unknown; + shippingAddress?: unknown; + [key: string]: unknown; + }; + gateway_response?: string; + }; +} + +interface PaystackVerifyData { + id: number; + reference: string; + amount: number; + currency: string; + status: string; + gateway_response?: string; + channel?: string; +} + +interface PaystackRefundData { + id: number; + status: string; + amount: number; + currency: string; + merchant_note?: string | null; + createdAt?: string; +} + +interface PaystackRefundPage { + data: PaystackRefundData[]; + pageCount: number; +} + +/** + * Transaction statuses from https://paystack.com/docs/payments/verify-payments/, + * plus `reversal-pending`, which the docs omit but /transaction/verify returns + * once a refund has started (seen on the test account, 19 Nov 2026). + * A reversed transaction was paid: Paystack reports `reversed` and + * `reversal-pending` after partial refunds too, and those refunds are tracked + * on their own. `getPaymentStatus` refuses only one that has been refunded in + * full, so a late webhook retry cannot create an order for money already + * returned. + * `abandoned` is not final: the customer may still complete the payment. + */ +const TRANSACTION_STATUS: Record = { + success: "succeeded", + reversed: "succeeded", + "reversal-pending": "succeeded", + failed: "failed", + abandoned: "pending", + ongoing: "pending", + pending: "pending", + processing: "pending", + queued: "pending", +}; + +/** Refund statuses from https://paystack.com/docs/payments/refunds/. */ +const REFUND_STATUS: Record = { + pending: "pending", + processing: "pending", + "needs-attention": "pending", + processed: "succeeded", + failed: "failed", +}; + +/** + * Paystack keeps no idempotency key for refunds, and assigns its own refund + * reference. `merchant_note` 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 `reason` cannot pose as the tag. +const NOTE_REQUEST_ID = /\(refundRequestId=([^\s()]+)\)\s*$/; + +function merchantNoteFor(refundRequestId: string, reason?: string): string { + const tag = `(refundRequestId=${refundRequestId})`; + const text = reason?.replace(/[()]/g, "").trim(); + return text ? `${text} ${tag}` : tag; +} + +const REVERSED = new Set(["reversed", "reversal-pending"]); + +const REFUND_PAGE_SIZE = 100; +const MAX_REFUND_PAGES = 20; + +/** + * Find a refund on this transaction already made for `refundRequestId`. + * Refunds are listed by the numeric transaction id: filtering by reference + * silently returns nothing. A failed refund does not count, so it can be + * retried. The earliest match wins. + */ +async function findRefundForRequest( + ctx: PaymentProviderRuntimeContext, + client: PaystackClientOptions, + transactionRef: string, + refundRequestId: string, +): Promise { + const transaction = await call(ctx, { + client, + method: "GET", + path: `/transaction/verify/${encodeURIComponent(transactionRef)}`, + }); + if (!Number.isSafeInteger(transaction.id)) { + throw new Error("Paystack verify returned no numeric transaction id; refusing to refund blind"); + } + + const matches: PaystackRefundData[] = []; + for (let page = 1, pageCount = 1; page <= pageCount; page += 1) { + if (page > MAX_REFUND_PAGES) { + throw new Error( + `Paystack lists more than ${MAX_REFUND_PAGES} pages of refunds for one transaction`, + ); + } + const result = await listRefundPage(ctx, client, transaction.id, page); + for (const refund of result.data) { + const tagged = NOTE_REQUEST_ID.exec(refund.merchant_note ?? "")?.[1]; + if (tagged === refundRequestId && refund.status !== "failed") matches.push(refund); + } + pageCount = result.pageCount; + } + + matches.sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? "") || a.id - b.id); + return matches[0]; +} + +/** Sum of a transaction's refunds that have not failed, in minor units. */ +async function refundedTotal( + ctx: PaymentProviderRuntimeContext, + client: PaystackClientOptions, + transactionId: number, +): Promise { + let total = 0; + for (let page = 1, pageCount = 1; page <= pageCount; page += 1) { + if (page > MAX_REFUND_PAGES) { + throw new Error( + `Paystack lists more than ${MAX_REFUND_PAGES} pages of refunds for one transaction`, + ); + } + const result = await listRefundPage(ctx, client, transactionId, page); + for (const refund of result.data) { + if (refund.status !== "failed" && typeof refund.amount === "number") total += refund.amount; + } + pageCount = result.pageCount; + } + return total; +} + +async function listRefundPage( + ctx: PaymentProviderRuntimeContext, + client: PaystackClientOptions, + transactionId: number, + page: number, +): Promise { + const query = new URLSearchParams({ + transaction: String(transactionId), + perPage: String(REFUND_PAGE_SIZE), + page: String(page), + }); + const result = await callEnvelope(ctx, { + client, + method: "GET", + path: `/refund?${query}`, + }); + if (!Array.isArray(result.data)) { + throw new Error("Paystack refund list returned no data array"); + } + const pageCount = result.meta?.pageCount; + return { + data: result.data, + pageCount: typeof pageCount === "number" ? pageCount : 1, + }; +} + +const SECRET_KEY = /^sk_(test|live)_/; + +/** + * Pick the header and the secret to verify it with. `Paystack-Signature` is + * keyed with the `whsec_` signing secret; `x-paystack-signature` with the + * `sk_` secret key, which may be saved as the webhook secret or as the API + * key. Paystack can send either or both: a real test-mode run delivered only + * `x-paystack-signature` on an account that had a `whsec_` secret. + * + * When `Paystack-Signature` is present and a `whsec_` secret is saved, it + * decides alone, so a replay outside its 300-second window cannot pass on + * the window-less legacy header sent alongside it. + */ +function signatureToVerify(input: VerifyWebhookInput): { header: string; secret: string } { + const current = input.headers?.get("paystack-signature") ?? null; + const legacy = input.headers?.get("x-paystack-signature") ?? null; + const saved = [input.secret, input.credentials?.webhookSecret, input.credentials?.secretKey]; + const whsec = saved.find((s) => s?.startsWith("whsec_")); + const skKey = saved.find((s) => s !== undefined && SECRET_KEY.test(s)); + + if (current && whsec) return { header: current, secret: whsec }; + if (legacy && skKey) return { header: legacy, secret: skKey }; + // Nothing pairs up: verify what core routed on with the webhook secret, + // which gives the merchant the precise reason it fails. + return { header: input.signatureHeader, secret: input.secret }; +} + +interface PaystackRefundWebhookData { + id?: number | string; + status?: string; + transaction_reference?: string; + refund_reference?: string; +} + +/** Refund webhooks, from https://paystack.com/docs/payments/refunds/. */ +const REFUND_EVENT_STATUS: Record = { + "refund.pending": "pending", + "refund.processing": "pending", + "refund.needs-attention": "pending", + "refund.processed": "succeeded", + "refund.failed": "failed", +}; + +/** + * Report a refund's new status by the numeric refund id that `refund()` + * returned. Paystack's documented sample shows only `refund_reference`, but + * real deliveries carry `id` (a string such as "19244346") with a null + * `refund_reference`. Without an id the event is left unhandled rather than + * matched by guesswork. + */ +function refundEvent( + eventName: string, + data: PaystackRefundWebhookData | undefined, + raw: unknown, +): NormalizedPaymentEvent { + const status = REFUND_EVENT_STATUS[eventName]; + const id = data?.id; + if (!status || (typeof id !== "number" && typeof id !== "string") || String(id) === "") { + return { type: "unhandled", providerEventType: eventName, raw }; + } + return { + type: "refund.updated", + providerId: "paystack", + providerEventId: "", + providerRefundId: String(id), + status, + ...(data?.transaction_reference ? { paymentReference: data.transaction_reference } : {}), + raw, + }; +} + +export const paystackPaymentProvider: PaymentProvider = { + id: "paystack", + label: "Paystack", + capabilities: { + coupons: false, + connect: false, + subscriptions: false, + }, + + logo: PAYSTACK_LOGO, + description: "Card and M-Pesa payments for African shoppers, settled in your local currency.", + // Hosted page, or the Popup over the store's checkout (./checkout-client). + checkoutStyles: ["hosted", "on_page"], + + // Current scheme first; see ./webhook-verify for both. + webhookHeaders: ["paystack-signature", "x-paystack-signature"], + + credentialFields: { + secretKey: { + label: "Paystack secret or restricted key", + prefixes: ["sk_test_", "sk_live_", "rk_test_", "rk_live_"], + help: "Best: a restricted key with transactions:write and disputes_refunds:write only.", + }, + webhookSecret: { + label: "Paystack webhook signing secret", + prefixes: ["whsec_", "sk_test_", "sk_live_"], + help: "The whsec_ signing secret from Developers → API configuration, or your sk_ secret key. Webhooks Paystack signs with the secret key are checked with the sk_ key from either field.", + }, + }, + + 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("Paystack requires customer email to initialize checkout"); + } + if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { + throw new Error("Paystack requires a valid customer email to initialize checkout"); + } + + if (!SUPPORTED_CURRENCIES.has(input.currency.trim().toUpperCase())) { + throw new Error(`Paystack does not support currency ${input.currency}`); + } + if (input.mode === "subscription") { + throw new Error("Paystack provider does not support subscription checkout"); + } + + const client = toPaystackClient(credentials); + const channels = mapChannels(input.preferredChannels); + const checkoutRef = paystackReferenceFor(input.orderDraftId); + + const data = await call(ctx, { + client, + path: "/transaction/initialize", + body: { + email, + amount: input.amount, + currency: input.currency.toUpperCase(), + reference: checkoutRef, + callback_url: paystackCallbackUrl(input.successUrl), + metadata: { + ...input.metadata, + orderDraftId: input.orderDraftId, + }, + ...(channels ? { channels } : {}), + }, + }); + + if (input.checkoutStyle === "on_page") { + return { + kind: "on_page", + checkoutReference: data.reference, + client: { accessCode: data.access_code }, + }; + } + return { + kind: "redirect", + redirectUrl: data.authorization_url, + checkoutReference: data.reference, + }; + }, + + async verifyWebhook(input: VerifyWebhookInput): Promise { + const { header, secret } = signatureToVerify(input); + const result = await verifyPaystackSignature({ + payload: input.rawBody, + signatureHeader: header, + secret, + }); + return { ok: result.ok, reason: result.reason }; + }, + + parseWebhookEvent(rawBody: string): NormalizedPaymentEvent { + let event: PaystackWebhookEvent; + try { + event = JSON.parse(rawBody); + } catch { + return { + type: "unhandled", + providerEventType: "unparseable", + raw: rawBody, + }; + } + + if (!event || typeof event !== "object" || !event.event) { + return { + type: "unhandled", + providerEventType: "malformed", + raw: event, + }; + } + + if (event.event.startsWith("refund.")) { + return refundEvent(event.event, event.data as unknown as PaystackRefundWebhookData, event); + } + + // Paystack documents `charge.success` for completed payments. It has no + // `charge.failed` webhook, so failures are left to the draft expiring. + if (event.event === "charge.success") { + const d = event.data; + const metaDraftId = metadataOf(d?.metadata)?.orderDraftId; + const orderDraftId = + typeof metaDraftId === "string" && metaDraftId + ? metaDraftId + : draftIdFromReference(d?.reference ?? ""); + if (!orderDraftId || !d.reference || !d.currency || typeof d.amount !== "number") { + return { + type: "unhandled", + providerEventType: event.event, + raw: event, + }; + } + + const customerName = [d.customer?.first_name, d.customer?.last_name] + .filter(Boolean) + .join(" "); + + const rawChannel = d.channel ?? d.authorization?.channel; + const displayChannel = + rawChannel === "mobile_money" ? "M-Pesa" : rawChannel === "card" ? "Card" : rawChannel; + + return { + type: "charge.succeeded", + orderDraftId, + providerId: "paystack", + // The reference, not the numeric id: core passes paymentReference + // to getPaymentStatus, and /transaction/verify accepts only the + // reference. /refund accepts either. + checkoutReference: d.reference, + paymentReference: d.reference, + // Paystack webhooks carry no event id (`data.id` is the transaction). + // Leaving this empty makes core skip event-level dedup, which it + // records before the handler runs and never releases: a delivery + // that failed (say Paystack's verify was briefly down) would turn + // every retry into a "duplicate" and the paid order would never be + // created. Core still refuses a second order for the same payment + // through its unique index on the payment reference. + providerEventId: "", + amount: d.amount, + currency: d.currency.toUpperCase(), + customer: { + email: d.customer?.email ?? "", + ...(customerName ? { name: customerName } : {}), + ...(d.customer?.phone ? { phone: d.customer.phone } : {}), + }, + ...(displayChannel ? { channel: displayChannel } : {}), + raw: event, + }; + } + + return { + type: "unhandled", + providerEventType: event.event, + raw: event, + }; + }, + + /** + * Verifies a reference that can't exist. Paystack answers + * `transaction_not_found` only for a key it accepts that can read + * transactions, which checkout needs; nothing is created. + */ + async checkConnection( + ctx: PaymentProviderRuntimeContext, + credentials: PaymentProviderCredentials, + ): Promise { + const mode: ConnectionCheckResult["mode"] = /^(sk|rk)_live_/.test(credentials.secretKey) + ? "live" + : /^(sk|rk)_test_/.test(credentials.secretKey) + ? "test" + : undefined; + const modeResult = mode ? { mode } : {}; + try { + await call(ctx, { + client: toPaystackClient(credentials), + method: "GET", + path: "/transaction/verify/dashcommerce-connection-check", + }); + } catch (err) { + if (!(err instanceof PaystackApiError)) throw err; + if (err.body.code === "transaction_not_found") { + return { + ok: true, + ...modeResult, + message: `Connected${mode ? ` in ${mode} mode` : ""}. The key can read transactions.`, + }; + } + if (err.status === 401 || err.status === 403) { + return { ok: false, ...modeResult, message: `Paystack refused the key: ${err.message}` }; + } + return { + ok: false, + ...modeResult, + message: `Paystack answered ${err.status}: ${err.message}`, + }; + } + return { ok: true, ...modeResult, message: `Connected${mode ? ` in ${mode} mode` : ""}.` }; + }, + + async getPaymentStatus( + ctx: PaymentProviderRuntimeContext, + paymentOrCheckoutReference: string, + credentials: PaymentProviderCredentials, + ): Promise<{ + status: "pending" | "succeeded" | "failed"; + paymentReference?: string; + amount?: number; + currency?: string; + reason?: string; + }> { + const client = toPaystackClient(credentials); + if (!paymentOrCheckoutReference) { + return { + status: "failed", + reason: "No reference provided for payment status lookup", + }; + } + + const data = await call(ctx, { + client, + method: "GET", + path: `/transaction/verify/${encodeURIComponent(paymentOrCheckoutReference)}`, + }); + + const status = TRANSACTION_STATUS[data.status]; + if (REVERSED.has(data.status) && Number.isSafeInteger(data.id)) { + const refunded = await refundedTotal(ctx, client, data.id); + if (refunded >= data.amount) { + return { + status: "failed", + paymentReference: data.reference, + amount: data.amount, + currency: data.currency?.toUpperCase(), + reason: `Payment was refunded in full at Paystack (${refunded} of ${data.amount})`, + }; + } + } + return { + status: status ?? "pending", + paymentReference: data.reference, + amount: data.amount, + currency: data.currency?.toUpperCase(), + reason: status ? data.gateway_response : `Unrecognised Paystack status: ${data.status}`, + }; + }, + + async refund( + ctx: PaymentProviderRuntimeContext, + input: CreateRefundInput, + credentials: PaymentProviderCredentials, + ): Promise { + if (!input.refundRequestId || !input.refundRequestId.trim()) { + throw new Error( + "Paystack refund requires a non-empty refundRequestId for operation idempotency", + ); + } + + if (!REFUND_REQUEST_ID.test(input.refundRequestId)) { + throw new Error( + "Paystack refund needs a refundRequestId without spaces or brackets, so the merchant note can carry it", + ); + } + + const client = toPaystackClient(credentials); + const transactionRef = input.paymentReference; + if (!transactionRef) { + throw new Error("Paystack refund requires paymentReference"); + } + + // Paystack accepts an identical second refund as a new one (tested on + // 19 Nov 2026), so a retry with the same refundRequestId must find the + // first refund rather than create another. + const existing = await findRefundForRequest(ctx, client, transactionRef, input.refundRequestId); + const data = + existing ?? + (await call(ctx, { + client, + path: "/refund", + body: { + transaction: transactionRef, + ...(input.amount !== undefined ? { amount: input.amount } : {}), + currency: input.currency.toUpperCase(), + merchant_note: merchantNoteFor(input.refundRequestId, input.reason), + }, + })); + + return { + providerRefundId: String(data.id), + refundRequestId: input.refundRequestId, + status: REFUND_STATUS[data.status] ?? "pending", + amount: data.amount, + currency: (data.currency ?? input.currency).toUpperCase(), + }; + }, + + formatAmount(amount: number, currency: string): string { + const major = (amount / 100).toFixed(2); + return `${currency.toUpperCase()} ${major}`; + }, +}; diff --git a/packages/paystack/src/webhook-verify.ts b/packages/paystack/src/webhook-verify.ts new file mode 100644 index 0000000..d3dd7a3 --- /dev/null +++ b/packages/paystack/src/webhook-verify.ts @@ -0,0 +1,164 @@ +/** + * Paystack webhook signature verification. Web Crypto only, so it is + * sandbox-safe. + * + * Paystack sends two signature schemes + * (https://paystack.com/docs/v2/developer-tools/integration/webhooks): + * + * - `Paystack-Signature: t=,v1=:[,v1=…]`, the current + * scheme. Each `v1` is a lowercase-hex HMAC-SHA512 of `"." + raw body`, + * keyed with the whole `whsec_` signing secret. There are two `v1` values + * while a secret is being rotated; any match is enough. `t` must be within + * 300 seconds of the server clock, so a captured delivery cannot be + * replayed later. + * - `x-paystack-signature: `, deprecated: an HMAC-SHA512 of the raw body + * keyed with the `sk_` secret key. No timestamp, so no replay window. + * Paystack stops sending it once the secret key is deleted. + * + * The scheme is chosen from the header value, so either header works with + * whichever secret the merchant configured for it. + */ + +/** Paystack's tolerance, in seconds, either side of the server clock. */ +export const SIGNATURE_TOLERANCE_SECONDS = 300; + +const HEX_SHA512 = /^[0-9a-f]{128}$/; + +function hexToBytes(hex: string): Uint8Array { + const bytes = new Uint8Array(hex.length / 2); + for (let i = 0; i < bytes.length; i += 1) { + bytes[i] = Number.parseInt(hex.substring(i * 2, i * 2 + 2), 16); + } + return bytes; +} + +function constantTimeEqualBytes(a: Uint8Array, b: Uint8Array): boolean { + if (a.length !== b.length) return false; + let diff = 0; + for (let i = 0; i < a.length; i += 1) { + diff |= (a[i] ?? 0) ^ (b[i] ?? 0); + } + return diff === 0; +} + +async function hmacSha512(secret: string, data: string): Promise { + const encoder = new TextEncoder(); + const key = await crypto.subtle.importKey( + "raw", + encoder.encode(secret), + { name: "HMAC", hash: "SHA-512" }, + false, + ["sign"], + ); + return new Uint8Array(await crypto.subtle.sign("HMAC", key, encoder.encode(data))); +} + +export interface VerifyInput { + payload: string; + signatureHeader: string; + secret: string; + /** Override the clock in tests; Unix seconds. */ + nowSeconds?: number; +} + +export interface VerifyResult { + ok: boolean; + reason?: string; +} + +interface ParsedHeader { + /** Exactly as sent: Paystack signs this string, not a re-serialised number. */ + rawTimestamp: string; + timestamp: number; + signatures: string[]; +} + +/** Parse `t=…,v1=…[,v1=…]`, ignoring fields Paystack may add later. */ +function parseSignatureHeader(header: string): ParsedHeader | string { + const timestamps: string[] = []; + const signatures: string[] = []; + for (const part of header.split(",")) { + const eq = part.indexOf("="); + if (eq < 0) continue; + const name = part.slice(0, eq).trim(); + const value = part.slice(eq + 1).trim(); + if (name === "t") timestamps.push(value); + // `:`; the key id names the secret, the hex is the signature. + if (name === "v1") signatures.push(value.slice(value.lastIndexOf(":") + 1).toLowerCase()); + } + if (timestamps.length !== 1) return "Paystack-Signature must carry exactly one t"; + const raw = timestamps[0] ?? ""; + if (!/^\d+$/.test(raw)) return "Paystack-Signature has a malformed t"; + if (signatures.length === 0) return "Paystack-Signature carries no v1 signature"; + return { rawTimestamp: raw, timestamp: Number(raw), signatures }; +} + +async function verifyCurrentScheme(input: VerifyInput, header: string): Promise { + const parsed = parseSignatureHeader(header); + if (typeof parsed === "string") return { ok: false, reason: parsed }; + + const now = input.nowSeconds ?? Math.floor(Date.now() / 1000); + if (Math.abs(now - parsed.timestamp) > SIGNATURE_TOLERANCE_SECONDS) { + return { ok: false, reason: "Paystack-Signature timestamp is outside the 300-second window" }; + } + + let computed: Uint8Array; + try { + computed = await hmacSha512(input.secret, `${parsed.rawTimestamp}.${input.payload}`); + } catch (err) { + return { ok: false, reason: `Web Crypto HMAC error: ${(err as Error).message}` }; + } + + // Check every candidate, without stopping at the first match. + let matched = false; + for (const candidate of parsed.signatures) { + if (!HEX_SHA512.test(candidate)) continue; + if (constantTimeEqualBytes(hexToBytes(candidate), computed)) matched = true; + } + if (matched) return { ok: true }; + + if (!input.secret.startsWith("whsec_")) { + return { + ok: false, + reason: "Signature mismatch: Paystack-Signature is keyed with the whsec_ signing secret", + }; + } + return { ok: false, reason: "Signature mismatch" }; +} + +async function verifyLegacyScheme(input: VerifyInput, header: string): Promise { + const expectedHex = header.toLowerCase(); + if (!HEX_SHA512.test(expectedHex)) { + return { ok: false, reason: "Malformed Paystack signature (expected 128-char SHA-512 hex)" }; + } + + let computed: Uint8Array; + try { + computed = await hmacSha512(input.secret, input.payload); + } catch (err) { + return { ok: false, reason: `Web Crypto HMAC error: ${(err as Error).message}` }; + } + + if (constantTimeEqualBytes(hexToBytes(expectedHex), computed)) return { ok: true }; + if (input.secret.startsWith("whsec_")) { + return { + ok: false, + reason: + "Signature mismatch: Paystack sent only x-paystack-signature, which is signed with your sk_ secret key; save that key as the Paystack key or the webhook secret", + }; + } + return { ok: false, reason: "Signature mismatch" }; +} + +export async function verifyPaystackSignature(input: VerifyInput): Promise { + const header = input.signatureHeader?.trim() ?? ""; + if (!header) { + return { ok: false, reason: "Missing Paystack-Signature or x-paystack-signature header" }; + } + if (!input.secret || !input.secret.trim()) { + return { ok: false, reason: "Missing Paystack webhook secret for verification" }; + } + return /(^|,)\s*t=/.test(header) + ? verifyCurrentScheme(input, header) + : verifyLegacyScheme(input, header); +} diff --git a/packages/paystack/test/connection-check.test.ts b/packages/paystack/test/connection-check.test.ts new file mode 100644 index 0000000..f19ff95 --- /dev/null +++ b/packages/paystack/test/connection-check.test.ts @@ -0,0 +1,100 @@ +/** + * "Test Paystack connection" in Settings: one read-only verify of a + * reference that can't exist, read as accepted, refused or unexpected. + */ + +import { describe, expect, it } from "bun:test"; +import type { PaymentProviderRuntimeContext } from "@dashcommerce/core/payment-provider"; +import { paystackPaymentProvider } from "../src/provider"; + +function answering(status: number, body: Record) { + const calls: Array<{ url: string; init?: RequestInit }> = []; + const ctx: PaymentProviderRuntimeContext = { + http: { + fetch: async (url, init) => { + calls.push({ url, init }); + return new Response(JSON.stringify(body), { status }); + }, + }, + log: { info() {}, warn() {}, error() {} }, + }; + return { ctx, calls }; +} + +const NOT_FOUND = { + status: false, + message: "Transaction reference not found.", + type: "validation_error", + code: "transaction_not_found", +}; + +function check(ctx: PaymentProviderRuntimeContext, secretKey: string) { + const fn = paystackPaymentProvider.checkConnection; + if (!fn) throw new Error("checkConnection missing"); + return fn(ctx, { secretKey }); +} + +describe("Paystack connection check", () => { + it("makes one GET verify with the key and nothing else", async () => { + const { ctx, calls } = answering(400, NOT_FOUND); + await check(ctx, "rk_test_1234567890abcdef"); + expect(calls).toHaveLength(1); + expect(calls[0]?.url).toBe( + "https://api.paystack.co/transaction/verify/dashcommerce-connection-check", + ); + expect(calls[0]?.init?.method).toBe("GET"); + expect((calls[0]?.init?.headers as Record).Authorization).toBe( + "Bearer rk_test_1234567890abcdef", + ); + }); + + it("reads 'reference not found' as connected, with the key's mode", async () => { + expect(await check(answering(400, NOT_FOUND).ctx, "sk_test_1234567890abcdef")).toEqual({ + ok: true, + mode: "test", + message: "Connected in test mode. The key can read transactions.", + }); + expect(await check(answering(400, NOT_FOUND).ctx, "rk_live_1234567890abcdef")).toEqual({ + ok: true, + mode: "live", + message: "Connected in live mode. The key can read transactions.", + }); + }); + + it("passes on Paystack's reason when it refuses the key", async () => { + const refused = answering(401, { status: false, message: "Invalid key" }); + expect(await check(refused.ctx, "sk_test_1234567890abcdef")).toEqual({ + ok: false, + mode: "test", + message: "Paystack refused the key: Invalid key", + }); + const forbidden = answering(403, { + status: false, + message: "This key does not have permission to perform this action", + }); + expect((await check(forbidden.ctx, "rk_test_1234567890abcdef")).message).toBe( + "Paystack refused the key: This key does not have permission to perform this action", + ); + }); + + it("reports any other answer as not connected", async () => { + const down = answering(503, { status: false, message: "Service unavailable" }); + expect(await check(down.ctx, "sk_test_1234567890abcdef")).toEqual({ + ok: false, + mode: "test", + message: "Paystack answered 503: Service unavailable", + }); + }); + + it("lets a network failure through for core to report", async () => { + const ctx: PaymentProviderRuntimeContext = { + http: { + fetch: async () => { + throw new TypeError("fetch failed"); + }, + }, + log: { info() {}, warn() {}, error() {} }, + }; + await expect(check(ctx, "sk_test_1234567890abcdef")).rejects.toThrow("fetch failed"); + }); +}); diff --git a/packages/paystack/test/core-enablement.test.ts b/packages/paystack/test/core-enablement.test.ts new file mode 100644 index 0000000..96255f9 --- /dev/null +++ b/packages/paystack/test/core-enablement.test.ts @@ -0,0 +1,162 @@ +/** + * What the package declares to core: its webhook headers, its + * credential fields, and refund.* events as refund.updated. + */ + +import { createHmac } from "node:crypto"; +import { describe, expect, it } from "bun:test"; +import { paystackPaymentProvider } from "../src/provider"; + +const sk = "sk_test_1234567890abcdef"; +const whsec = "whsec_1234567890abcdef"; +const body = '{"event":"charge.success","data":{"id":1}}'; + +function bothHeaders(t = Math.floor(Date.now() / 1000)): Headers { + const v1 = createHmac("sha512", whsec).update(`${t}.${body}`).digest("hex"); + const legacy = createHmac("sha512", sk).update(body).digest("hex"); + return new Headers({ + "Paystack-Signature": `t=${t},v1=whk_test:${v1}`, + "x-paystack-signature": legacy, + }); +} + +describe("declared to core", () => { + it("claims both Paystack signature headers, the current one first", () => { + expect(paystackPaymentProvider.webhookHeaders).toEqual([ + "paystack-signature", + "x-paystack-signature", + ]); + }); + + it("accepts secret or restricted keys, and whsec_ or (legacy) sk_ webhook secrets", () => { + const fields = paystackPaymentProvider.credentialFields; + expect(fields?.secretKey?.prefixes).toEqual(["sk_test_", "sk_live_", "rk_test_", "rk_live_"]); + expect(fields?.webhookSecret?.prefixes).toEqual(["whsec_", "sk_test_", "sk_live_"]); + }); +}); + +describe("verifyWebhook picks the header that matches the configured secret", () => { + it("uses Paystack-Signature for a whsec_ secret", async () => { + const headers = bothHeaders(); + const result = await paystackPaymentProvider.verifyWebhook({ + rawBody: body, + signatureHeader: headers.get("x-paystack-signature") ?? "", + secret: whsec, + headers, + }); + expect(result.ok).toBe(true); + }); + + it("uses x-paystack-signature for an sk_ secret", async () => { + const headers = bothHeaders(); + const result = await paystackPaymentProvider.verifyWebhook({ + rawBody: body, + signatureHeader: headers.get("paystack-signature") ?? "", + secret: sk, + headers, + }); + expect(result.ok).toBe(true); + }); + + // What Paystack did in a real test-mode run: the account had a whsec_ + // secret, but each delivery carried only x-paystack-signature. + const legacyOnly = (rawBody = body) => + new Headers({ "x-paystack-signature": createHmac("sha512", sk).update(rawBody).digest("hex") }); + + it("verifies a legacy-only delivery with the saved sk_ secret key when the webhook secret is whsec_", async () => { + const headers = legacyOnly(); + const result = await paystackPaymentProvider.verifyWebhook({ + rawBody: body, + signatureHeader: headers.get("x-paystack-signature") ?? "", + secret: whsec, + headers, + credentials: { secretKey: sk, webhookSecret: whsec }, + }); + expect(result.ok).toBe(true); + }); + + it("still refuses a tampered legacy-only delivery", async () => { + const headers = legacyOnly(); + const result = await paystackPaymentProvider.verifyWebhook({ + rawBody: body.replace('"id":1', '"id":2'), + signatureHeader: headers.get("x-paystack-signature") ?? "", + secret: whsec, + headers, + credentials: { secretKey: sk, webhookSecret: whsec }, + }); + expect(result.ok).toBe(false); + }); + + it("explains the fix when a legacy-only delivery comes and no sk_ key is saved", async () => { + const headers = legacyOnly(); + const result = await paystackPaymentProvider.verifyWebhook({ + rawBody: body, + signatureHeader: headers.get("x-paystack-signature") ?? "", + secret: whsec, + headers, + credentials: { secretKey: "rk_test_restricted", webhookSecret: whsec }, + }); + expect(result.ok).toBe(false); + expect(result.reason).toContain("only x-paystack-signature"); + expect(result.reason).toContain("sk_ secret key"); + }); + + it("does not fall back to the legacy header when Paystack-Signature fails", async () => { + // A replay outside the 300-second window must not pass on the + // window-less legacy header sent alongside it. + const headers = bothHeaders(Math.floor(Date.now() / 1000) - 1000); + const result = await paystackPaymentProvider.verifyWebhook({ + rawBody: body, + signatureHeader: headers.get("paystack-signature") ?? "", + secret: whsec, + headers, + credentials: { secretKey: sk, webhookSecret: whsec }, + }); + expect(result.ok).toBe(false); + expect(result.reason).toContain("300-second window"); + }); +}); + +describe("refund.* events", () => { + const refundEvent = (event: string, data: Record) => + JSON.stringify({ event, data: { transaction_reference: "dc-x", currency: "KES", ...data } }); + + it("maps each documented refund event to refund.updated", () => { + for (const [event, status] of [ + ["refund.pending", "pending"], + ["refund.processing", "pending"], + ["refund.needs-attention", "pending"], + ["refund.processed", "succeeded"], + ["refund.failed", "failed"], + ] as const) { + const parsed = paystackPaymentProvider.parseWebhookEvent( + refundEvent(event, { id: 19224707 }), + ); + expect(parsed).toMatchObject({ + type: "refund.updated", + providerId: "paystack", + providerRefundId: "19224707", + paymentReference: "dc-x", + status, + }); + } + }); + + it("handles the shape real deliveries have: a string id and a null refund_reference", () => { + const parsed = paystackPaymentProvider.parseWebhookEvent( + refundEvent("refund.processed", { id: "19244346", status: "processed", refund_reference: null }), + ); + expect(parsed).toMatchObject({ + type: "refund.updated", + providerRefundId: "19244346", + status: "succeeded", + }); + }); + + it("leaves a refund event without a refund id unhandled rather than guess", () => { + const parsed = paystackPaymentProvider.parseWebhookEvent( + refundEvent("refund.processed", { refund_reference: "01a1f190-36de-773b-a7b3-04eafa8597cd" }), + ); + expect(parsed).toMatchObject({ type: "unhandled", providerEventType: "refund.processed" }); + }); +}); diff --git a/packages/paystack/test/core-integration.test.ts b/packages/paystack/test/core-integration.test.ts new file mode 100644 index 0000000..bdc8cfc --- /dev/null +++ b/packages/paystack/test/core-integration.test.ts @@ -0,0 +1,736 @@ +/** + * Runs @dashcommerce/paystack through released @dashcommerce/core's own + * route handlers (create-session → webhook → order), with no core changes. + * + * The HTTP stub behaves like Paystack where it matters: initialize echoes + * the reference it was given, and verify answers only for a reference that + * initialize issued (404 otherwise), so a provider that verifies by the + * wrong identifier fails here instead of in production. + */ + +import { describe, expect, it } from "bun:test"; +import { type CartState, dashcommerce, type Order } from "@dashcommerce/core"; +import { + getPaymentProvider, + registerPaymentProvider, + resolveProvider, +} from "@dashcommerce/core/payment-provider"; +import sandbox from "@dashcommerce/core/sandbox"; +import { registerPaystackProvider } from "../src/index"; +import { paystackPaymentProvider } from "../src/provider"; + +const SECRET_KEY = "sk_test_1234567890abcdef"; + +async function sign(secret: string, payload: string): Promise { + const enc = new TextEncoder(); + const key = await crypto.subtle.importKey( + "raw", + enc.encode(secret), + { name: "HMAC", hash: "SHA-512" }, + false, + ["sign"], + ); + const sig = await crypto.subtle.sign("HMAC", key, enc.encode(payload)); + return Array.from(new Uint8Array(sig)) + .map((b) => b.toString(16).padStart(2, "0")) + .join(""); +} + +function json(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { "Content-Type": "application/json" }, + }); +} + +interface FakePaystackOptions { + /** Amount Paystack records as charged. Defaults to what initialize was asked for. */ + chargedAmount?: number; + /** Status verify reports. Defaults to "success". */ + verifyStatus?: string; + /** Number of verify calls that fail with a 503 before Paystack recovers. */ + verifyOutages?: number; +} + +/** + * A Paystack stand-in that only knows the transactions it initialised, + * requires the secret key on every call, and records what it charged. + */ +function fakePaystack(options: FakePaystackOptions = {}) { + const transactions = new Map(); + const refunds: Array> = []; + let nextId = 55443322; + let lastInit: Record | null = null; + let outagesLeft = options.verifyOutages ?? 0; + + async function fetch(url: string, init?: RequestInit): Promise { + const headers = new Headers(init?.headers); + if (headers.get("Authorization") !== `Bearer ${SECRET_KEY}`) { + return json({ status: false, message: "Invalid key" }, 401); + } + const { pathname } = new URL(url); + if (pathname === "/transaction/initialize") { + const body = JSON.parse(String(init?.body)) as Record; + lastInit = body; + const reference = String(body.reference); + if (!/^[A-Za-z0-9.=-]+$/.test(reference)) { + return json({ status: false, message: "Invalid transaction reference" }, 400); + } + if (!Number.isInteger(body.amount)) { + return json({ status: false, message: "Amount must be an integer in subunits" }, 400); + } + transactions.set(reference, { + id: nextId++, + amount: options.chargedAmount ?? (body.amount as number), + currency: String(body.currency), + }); + return json({ + status: true, + message: "Authorization URL created", + data: { + authorization_url: "https://checkout.paystack.com/test-access-code", + access_code: "test-access-code", + reference, + }, + }); + } + if (pathname.startsWith("/transaction/verify/")) { + if (outagesLeft > 0) { + outagesLeft--; + return json({ status: false, message: "Service unavailable" }, 503); + } + const reference = decodeURIComponent(pathname.slice("/transaction/verify/".length)); + const tx = transactions.get(reference); + if (!tx) return json({ status: false, message: "Transaction reference not found" }, 404); + return json({ + status: true, + message: "Verification successful", + data: { + ...tx, + status: options.verifyStatus ?? "success", + reference, + channel: "mobile_money", + }, + }); + } + if (pathname === "/refund" && (init?.method ?? "GET") === "GET") { + // As the live API: filtering by a reference instead of the numeric + // transaction id silently returns nothing. + const filter = new URL(url).searchParams.get("transaction"); + const created = refunds + .filter((r) => String(r.transactionId) === filter) + .map((r) => ({ + id: r.id, + status: "pending", + amount: r.amount, + currency: r.currency, + merchant_note: r.merchant_note, + createdAt: r.createdAt, + })); + return json({ + status: true, + message: "Refunds retrieved", + data: created, + meta: { total: created.length, page: 1, pageCount: created.length ? 1 : 0 }, + }); + } + if (pathname === "/refund") { + const body = JSON.parse(String(init?.body)) as Record; + const tx = transactions.get(String(body.transaction)); + if (!tx) return json({ status: false, message: "Transaction not found" }, 404); + const id = 887766 + refunds.length; + refunds.push({ + ...body, + id, + transactionId: tx.id, + amount: body.amount ?? tx.amount, + currency: tx.currency, + createdAt: new Date(Date.UTC(2026, 10, 19, 2, refunds.length)).toISOString(), + }); + return json({ + status: true, + message: "Refund has been queued for processing", + data: { + id, + status: "pending", + amount: body.amount ?? tx.amount, + currency: tx.currency, + }, + }); + } + return json({ status: false, message: "Not found" }, 404); + } + + return { fetch, transactions, refunds, getLastInit: () => lastInit }; +} + +// 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 paystackSettings = { + "settings:paymentProvider": "paystack", + "settings:paystackSecretKey": SECRET_KEY, + // Paystack signs webhooks with the secret key; core reads the signing + // secret from this key, so a merchant stores the secret key here too. + "settings:paystackWebhookSecret": SECRET_KEY, +}; + +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, + signature: string | Record, + url = "http://test/checkout/webhook", +) { + const request = new Request(url, { + method: "POST", + headers: typeof signature === "string" ? { "x-paystack-signature": signature } : signature, + 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 chargeSuccess(reference: string, orderDraftId: string, id: number, amount = 150000) { + return JSON.stringify({ + event: "charge.success", + data: { + id, + reference, + amount, + currency: "KES", + status: "success", + customer: { email: "supporter@example.com", first_name: "Aidi", last_name: "Onyango" }, + channel: "mobile_money", + metadata: { orderDraftId }, + }, + }); +} + +describe("@dashcommerce/paystack through core", () => { + it("registers on import and resolves as the configured provider", async () => { + expect(getPaymentProvider("paystack")).toBe(paystackPaymentProvider); + const { ctx } = makeContext({ "settings:paymentProvider": "paystack" }, fakePaystack().fetch); + expect((await resolveProvider(ctx.kv)).id).toBe("paystack"); + }); + + it("registering again is a no-op, but a different provider under the same id fails loudly", () => { + expect(() => registerPaystackProvider()).not.toThrow(); + expect(() => + registerPaymentProvider({ ...paystackPaymentProvider, label: "Impostor" }), + ).toThrow(/already registered/); + expect(getPaymentProvider("paystack")).toBe(paystackPaymentProvider); + }); + + it("runs checkout → signed webhook → verified order, and ignores a replay", async () => { + const paystack = fakePaystack(); + const { ctx, getCol } = makeContext(paystackSettings, paystack.fetch); + + const initRes = await startCheckout(ctx, "sess_paystack_1"); + expect(initRes.status).toBe(200); + const { url, orderDraftId } = (await initRes.json()) as { url: string; orderDraftId: string }; + expect(url).toBe("https://checkout.paystack.com/test-access-code"); + + const reference = String(paystack.getLastInit()?.reference); + expect(reference).toBe(`dc-${orderDraftId}`); + const tx = paystack.transactions.get(reference); + if (!tx) throw new Error("initialize did not register a transaction"); + + const payload = chargeSuccess(reference, orderDraftId, tx.id); + const signature = await sign(SECRET_KEY, payload); + const webhookRes = await deliverWebhook(ctx, payload, signature); + 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("paystack"); + expect(order.paymentReference).toBe(reference); + expect(order.checkoutReference).toBe(reference); + expect(order.total.amount).toBe(150000); + expect(order.total.currency).toBe("KES"); + expect(order.paymentStatus).toBe("paid"); + + const replay = await deliverWebhook(ctx, payload, signature); + 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 reference Paystack does not know", async () => { + const paystack = fakePaystack(); + const { ctx, getCol } = makeContext(paystackSettings, paystack.fetch); + const initRes = await startCheckout(ctx, "sess_paystack_2"); + const { orderDraftId } = (await initRes.json()) as { orderDraftId: string }; + + const payload = chargeSuccess("dc-not-a-real-transaction", orderDraftId, 1); + const res = await deliverWebhook(ctx, payload, await sign(SECRET_KEY, payload)); + expect(res.status).not.toBe(200); + expect(getCol("orders").size).toBe(0); + }); + + it("rejects a webhook signed with the wrong key before any side effect", async () => { + const paystack = fakePaystack(); + const { ctx, getCol } = makeContext(paystackSettings, paystack.fetch); + const initRes = await startCheckout(ctx, "sess_paystack_3"); + const { orderDraftId } = (await initRes.json()) as { orderDraftId: string }; + const reference = String(paystack.getLastInit()?.reference); + + const payload = chargeSuccess(reference, orderDraftId, 1); + const res = await deliverWebhook(ctx, payload, await sign("sk_test_wrong_key", payload)); + expect(res.status).toBe(400); + expect(getCol("orders").size).toBe(0); + }); + + it("holds the order when Paystack confirms a different amount than the cart", async () => { + // The payload claims the full amount; Paystack's own record says less. + const paystack = fakePaystack({ chargedAmount: 100 }); + const { ctx, getCol } = makeContext(paystackSettings, paystack.fetch); + const initRes = await startCheckout(ctx, "sess_paystack_4"); + const { orderDraftId } = (await initRes.json()) as { orderDraftId: string }; + const reference = String(paystack.getLastInit()?.reference); + const tx = paystack.transactions.get(reference); + if (!tx) throw new Error("initialize did not register a transaction"); + + const payload = chargeSuccess(reference, orderDraftId, tx.id, 150000); + const res = await deliverWebhook(ctx, payload, await sign(SECRET_KEY, payload)); + expect(res.status).toBe(200); + + // Core trusts Paystack's verified record over the webhook body and + // puts the order on hold for an operator to review. + 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 Paystack's retry follows a failed first delivery", async () => { + // Paystack is briefly down when core confirms the first delivery, so + // core answers 500. Paystack's retry must still produce the order. + const paystack = fakePaystack({ verifyOutages: 1 }); + const { ctx, getCol } = makeContext(paystackSettings, paystack.fetch); + const initRes = await startCheckout(ctx, "sess_paystack_5"); + const { orderDraftId } = (await initRes.json()) as { orderDraftId: string }; + const reference = String(paystack.getLastInit()?.reference); + const tx = paystack.transactions.get(reference); + if (!tx) throw new Error("initialize did not register a transaction"); + + const payload = chargeSuccess(reference, orderDraftId, tx.id); + const signature = await sign(SECRET_KEY, payload); + + const first = await deliverWebhook(ctx, payload, signature); + expect(first.status).toBe(500); + expect(getCol("orders").size).toBe(0); + + const retry = await deliverWebhook(ctx, payload, signature); + expect(retry.status).toBe(200); + expect(getCol("orders").size).toBe(1); + }); + + it("creates no order when Paystack reports the transaction as not successful", async () => { + const paystack = fakePaystack({ verifyStatus: "abandoned" }); + const { ctx, getCol } = makeContext(paystackSettings, paystack.fetch); + const initRes = await startCheckout(ctx, "sess_paystack_6"); + const { orderDraftId } = (await initRes.json()) as { orderDraftId: string }; + const reference = String(paystack.getLastInit()?.reference); + const tx = paystack.transactions.get(reference); + if (!tx) throw new Error("initialize did not register a transaction"); + + const payload = chargeSuccess(reference, orderDraftId, tx.id); + const res = await deliverWebhook(ctx, payload, await sign(SECRET_KEY, payload)); + expect(res.status).not.toBe(200); + expect(getCol("orders").size).toBe(0); + }); + + it("finds the draft from the reference when Paystack returns no metadata", async () => { + const paystack = fakePaystack(); + const { ctx, getCol } = makeContext(paystackSettings, paystack.fetch); + const initRes = await startCheckout(ctx, "sess_paystack_7"); + const { orderDraftId } = (await initRes.json()) as { orderDraftId: string }; + const reference = String(paystack.getLastInit()?.reference); + const tx = paystack.transactions.get(reference); + if (!tx) throw new Error("initialize did not register a transaction"); + + const event = JSON.parse(chargeSuccess(reference, orderDraftId, tx.id)); + const { metadata: _omitted, ...data } = event.data; + const payload = JSON.stringify({ ...event, data }); + const res = await deliverWebhook(ctx, payload, await sign(SECRET_KEY, payload)); + expect(res.status).toBe(200); + expect(getCol("orders").size).toBe(1); + }); + + it("sends Paystack a callback URL without Stripe's session placeholder", async () => { + const paystack = fakePaystack(); + const { ctx } = makeContext(paystackSettings, paystack.fetch); + const initRes = await startCheckout(ctx, "sess_paystack_8"); + const { orderDraftId } = (await initRes.json()) as { orderDraftId: string }; + + const callback = new URL(String(paystack.getLastInit()?.callback_url)); + expect(callback.pathname).toBe(`/thank-you/${orderDraftId}`); + expect(callback.search).toBe(""); + expect(String(paystack.getLastInit()?.callback_url)).not.toContain("CHECKOUT_SESSION_ID"); + }); + + it("charges the cart total in subunits and refunds the order's payment", async () => { + const paystack = fakePaystack(); + const { ctx, getCol } = makeContext(paystackSettings, paystack.fetch); + const initRes = await startCheckout(ctx, "sess_paystack_9"); + const { orderDraftId } = (await initRes.json()) as { orderDraftId: string }; + expect(paystack.getLastInit()?.amount).toBe(150000); + expect(paystack.getLastInit()?.currency).toBe("KES"); + + const reference = String(paystack.getLastInit()?.reference); + const tx = paystack.transactions.get(reference); + if (!tx) throw new Error("initialize did not register a transaction"); + const payload = chargeSuccess(reference, orderDraftId, tx.id); + await deliverWebhook(ctx, payload, await sign(SECRET_KEY, payload)); + const order = Array.from(getCol("orders").values())[0] as Order; + + const refund = await paystackPaymentProvider.refund( + { http: ctx.http, log: ctx.log }, + { + refundRequestId: "refund-req-1", + paymentReference: order.paymentReference ?? "", + amount: 50000, + currency: "KES", + }, + { secretKey: SECRET_KEY }, + ); + expect(paystack.refunds).toHaveLength(1); + expect(paystack.refunds[0]?.transaction).toBe(reference); + expect(paystack.refunds[0]?.amount).toBe(50000); + expect(refund.status).toBe("pending"); + + // A retry with the same request id (say the first response timed out) + // returns the first refund; Paystack itself would accept a second one. + const retry = await paystackPaymentProvider.refund( + { http: ctx.http, log: ctx.log }, + { + refundRequestId: "refund-req-1", + paymentReference: order.paymentReference ?? "", + amount: 50000, + currency: "KES", + }, + { secretKey: SECRET_KEY }, + ); + expect(paystack.refunds).toHaveLength(1); + expect(retry.providerRefundId).toBe(refund.providerRefundId); + + // A different request for the same amount is a new, legitimate refund. + await paystackPaymentProvider.refund( + { http: ctx.http, log: ctx.log }, + { + refundRequestId: "refund-req-2", + paymentReference: order.paymentReference ?? "", + amount: 50000, + currency: "KES", + }, + { secretKey: SECRET_KEY }, + ); + expect(paystack.refunds).toHaveLength(2); + }); +}); + +// ── With core enablement ──────────────────────────────────────────────────── + +const WHSEC = "whsec_1234567890abcdef"; + +async function paystackSignatureHeader(payload: string, t = Math.floor(Date.now() / 1000)) { + const enc = new TextEncoder(); + const key = await crypto.subtle.importKey( + "raw", + enc.encode(WHSEC), + { name: "HMAC", hash: "SHA-512" }, + false, + ["sign"], + ); + const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(`${t}.${payload}`))); + return `t=${t},v1=whk_test:${Array.from(mac, (b) => b.toString(16).padStart(2, "0")).join("")}`; +} + +describe("@dashcommerce/paystack with core enablement", () => { + it("saves a restricted key and a whsec_ secret through the settings API", async () => { + const { ctx } = makeContext({}, fakePaystack().fetch); + const routeCtx = { + request: new Request("http://test/admin/settings", { method: "POST" }), + input: { + paymentProvider: "paystack", + paystackSecretKey: "rk_test_1234567890abcdef", + paystackWebhookSecret: WHSEC, + }, + } 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:paystackSecretKey")).toBe("rk_test_1234567890abcdef"); + + const bad = (await sandbox.routes["admin/settings"].handler( + { + request: new Request("http://test/admin/settings", { method: "POST" }), + input: { paystackSecretKey: "pk_test_public_key" }, + } as unknown as import("emdash").RouteContext, + ctx, + )) as Response; + expect(bad.status).toBe(400); + }); + + it("creates the order from a Paystack-Signature webhook verified with the whsec_ secret", async () => { + const paystack = fakePaystack(); + const { ctx, getCol } = makeContext( + { ...paystackSettings, "settings:paystackWebhookSecret": WHSEC }, + paystack.fetch, + ); + const initRes = await startCheckout(ctx, "sess_paystack_v2"); + const { orderDraftId } = (await initRes.json()) as { orderDraftId: string }; + const reference = String(paystack.getLastInit()?.reference); + const tx = paystack.transactions.get(reference); + if (!tx) throw new Error("initialize did not register a transaction"); + const payload = chargeSuccess(reference, orderDraftId, tx.id); + + const res = await deliverWebhook(ctx, payload, { + "Paystack-Signature": await paystackSignatureHeader(payload), + }); + expect(res.status).toBe(200); + expect(getCol("orders").size).toBe(1); + }); + + it("verifies whichever header matches the configured secret when Paystack sends both", async () => { + const paystack = fakePaystack(); + const { ctx, getCol } = makeContext(paystackSettings, paystack.fetch); + const initRes = await startCheckout(ctx, "sess_paystack_both"); + const { orderDraftId } = (await initRes.json()) as { orderDraftId: string }; + const reference = String(paystack.getLastInit()?.reference); + const tx = paystack.transactions.get(reference); + if (!tx) throw new Error("initialize did not register a transaction"); + const payload = chargeSuccess(reference, orderDraftId, tx.id); + + // The merchant still has the sk_ key as webhook secret (legacy header). + const res = await deliverWebhook(ctx, payload, { + "Paystack-Signature": await paystackSignatureHeader(payload), + "x-paystack-signature": await sign(SECRET_KEY, payload), + }); + expect(res.status).toBe(200); + expect(getCol("orders").size).toBe(1); + }); + + it("rejects a replayed Paystack-Signature older than five minutes", async () => { + const paystack = fakePaystack(); + const { ctx, getCol } = makeContext( + { ...paystackSettings, "settings:paystackWebhookSecret": WHSEC }, + paystack.fetch, + ); + const initRes = await startCheckout(ctx, "sess_paystack_old"); + const { orderDraftId } = (await initRes.json()) as { orderDraftId: string }; + const reference = String(paystack.getLastInit()?.reference); + const tx = paystack.transactions.get(reference); + if (!tx) throw new Error("initialize did not register a transaction"); + const payload = chargeSuccess(reference, orderDraftId, tx.id); + + const res = await deliverWebhook(ctx, payload, { + "Paystack-Signature": await paystackSignatureHeader( + payload, + Math.floor(Date.now() / 1000) - 301, + ), + }); + expect(res.status).toBe(400); + expect(getCol("orders").size).toBe(0); + }); + + it("moves a refund to succeeded when Paystack reports refund.processed", async () => { + const paystack = fakePaystack(); + const { ctx, getCol } = makeContext(paystackSettings, paystack.fetch); + const initRes = await startCheckout(ctx, "sess_paystack_refund_evt"); + const { orderDraftId } = (await initRes.json()) as { orderDraftId: string }; + const reference = String(paystack.getLastInit()?.reference); + const tx = paystack.transactions.get(reference); + if (!tx) throw new Error("initialize did not register a transaction"); + const charge = chargeSuccess(reference, orderDraftId, tx.id); + await deliverWebhook(ctx, charge, await sign(SECRET_KEY, charge)); + const order = Array.from(getCol("orders").values())[0] as Order; + + // Create the refund through the admin route, as a merchant would. + 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); + const refundRow = Array.from(getCol("refunds").values())[0] as { status: string }; + expect(refundRow.status).toBe("pending"); + const refundId = Number(paystack.refunds[0]?.id); + + const event = JSON.stringify({ + event: "refund.processed", + data: { + id: refundId, + status: "processed", + transaction_reference: reference, + amount: 50000, + currency: "KES", + }, + }); + const res = await deliverWebhook(ctx, event, await sign(SECRET_KEY, event)); + expect(res.status).toBe(200); + expect((Array.from(getCol("refunds").values())[0] as { status: string }).status).toBe( + "succeeded", + ); + }); +}); diff --git a/packages/paystack/test/fixtures/refund-list-by-transaction.json b/packages/paystack/test/fixtures/refund-list-by-transaction.json new file mode 100644 index 0000000..682fd64 --- /dev/null +++ b/packages/paystack/test/fixtures/refund-list-by-transaction.json @@ -0,0 +1,94 @@ +{ + "_source": "GET /refund?transaction=6480092473 on the Paystack test account, 19 Nov 2026. Customer, integration and staff fields replaced with placeholders.", + "status": true, + "message": "Refunds retrieved", + "data": [ + { + "integration": 100000, + "transaction": 6480092473, + "dispute": null, + "settlement": null, + "id": 19224741, + "domain": "test", + "currency": "KES", + "amount": 10000, + "status": "processing", + "refunded_at": null, + "refunded_by": "merchant", + "customer_note": "Test refund", + "merchant_note": "Refund test 1 (refundRequestId=fik57-test-1)", + "deducted_amount": 10000, + "fully_deducted": 1, + "createdAt": "2026-11-19T02:21:08.000Z", + "bank_reference": null, + "transaction_reference": "T877626421263494", + "reason": "PROCESSING", + "customer": { + "id": 1, + "first_name": "", + "last_name": "", + "email": "customer@example.com", + "customer_code": "CUS_xxxxxxxxxxxxxxx", + "phone": "", + "metadata": null, + "risk_action": "default", + "international_format_phone": null + }, + "initiated_by": "merchant", + "reference": "01a1f19b-96e1-72ce-bfd4-279f77e4a72f", + "refund_type": "Partial", + "transaction_amount": 100000, + "refund_channel": "Original Payment", + "session_id": null, + "retriable": false + }, + { + "integration": 100000, + "transaction": 6480092473, + "dispute": null, + "settlement": null, + "id": 19224707, + "domain": "test", + "currency": "KES", + "amount": 10000, + "status": "processed", + "refunded_at": "2026-11-19T02:15:05.000Z", + "refunded_by": "merchant", + "customer_note": "Test refund", + "merchant_note": "Refund test 1 (refundRequestId=fik57-test-1)", + "deducted_amount": 10000, + "fully_deducted": 1, + "createdAt": "2026-11-19T02:08:42.000Z", + "bank_reference": null, + "transaction_reference": "T877626421263494", + "reason": "PROCESSED", + "customer": { + "id": 1, + "first_name": "", + "last_name": "", + "email": "customer@example.com", + "customer_code": "CUS_xxxxxxxxxxxxxxx", + "phone": "", + "metadata": null, + "risk_action": "default", + "international_format_phone": null + }, + "initiated_by": "merchant", + "reference": "01a1f190-36de-773b-a7b3-04eafa8597cd", + "refund_type": "Partial", + "transaction_amount": 100000, + "refund_channel": "Original Payment", + "session_id": null, + "retriable": false + } + ], + "meta": { + "total": 2, + "skipped": 0, + "perPage": 50, + "page": 1, + "pageCount": 1, + "totalRetriable": 0, + "partialAmountLeft": 80000 + } +} diff --git a/packages/paystack/test/fixtures/verify-reversal-pending.json b/packages/paystack/test/fixtures/verify-reversal-pending.json new file mode 100644 index 0000000..56f361c --- /dev/null +++ b/packages/paystack/test/fixtures/verify-reversal-pending.json @@ -0,0 +1,65 @@ +{ + "_source": "GET /transaction/verify/T877626421263494 on the Paystack test account after two partial refunds, 19 Nov 2026. Customer, IP, phone, authorisation and metadata replaced with placeholders.", + "status": true, + "message": "Verification successful", + "data": { + "id": 6480092473, + "domain": "test", + "status": "reversal-pending", + "reference": "T877626421263494", + "receipt_number": "10101", + "amount": 100000, + "message": null, + "gateway_response": "Approved", + "paid_at": "2026-08-21T21:51:38.000Z", + "created_at": "2026-08-21T21:51:03.000Z", + "channel": "mobile_money", + "currency": "KES", + "ip_address": "192.0.2.1", + "metadata": {}, + "fees": 1500, + "fees_split": null, + "authorization": { + "authorization_code": "AUTH_xxxxxxxxxx", + "bin": "071XXX", + "last4": "X000", + "exp_month": "12", + "exp_year": "9999", + "channel": "mobile_money", + "card_type": "", + "bank": "M-PESA", + "country_code": "KE", + "brand": "M-pesa", + "reusable": false, + "signature": null, + "account_name": null, + "mobile_money_number": "0700000000", + "receiver_bank_account_number": null, + "receiver_bank": null + }, + "customer": { + "id": 1, + "first_name": "", + "last_name": "", + "email": "customer@example.com", + "customer_code": "CUS_xxxxxxxxxxxxxxx", + "phone": "", + "metadata": null, + "risk_action": "default", + "international_format_phone": null + }, + "plan": null, + "split": {}, + "order_id": null, + "paidAt": "2026-08-21T21:51:38.000Z", + "createdAt": "2026-08-21T21:51:03.000Z", + "requested_amount": 100000, + "pos_transaction_data": null, + "source": null, + "fees_breakdown": null, + "connect": null, + "transaction_date": "2026-08-21T21:51:03.000Z", + "plan_object": {}, + "subaccount": {} + } +} diff --git a/packages/paystack/test/on-page.test.ts b/packages/paystack/test/on-page.test.ts new file mode 100644 index 0000000..2c5b3cc --- /dev/null +++ b/packages/paystack/test/on-page.test.ts @@ -0,0 +1,211 @@ +/** + * Paystack on-page checkout: the Popup, opened over the store's + * checkout with the access code from /transaction/initialize. + */ + +import { describe, expect, it } from "bun:test"; +import type { PaymentProviderRuntimeContext } from "@dashcommerce/core/payment-provider"; +import { + createPaystackCheckoutClient, + PAYSTACK_INLINE_SCRIPT, + registerPaystackCheckoutClient, +} from "../src/checkout-client"; +import { paystackPaymentProvider } from "../src/provider"; + +describe("provider declarations", () => { + it("offers hosted and on-page checkout, and needs the store to collect customer details", () => { + expect(paystackPaymentProvider.checkoutStyles).toEqual(["hosted", "on_page"]); + expect(paystackPaymentProvider.collectsCustomerDetails).toBeFalsy(); + expect(paystackPaymentProvider.description).toMatch(/M-Pesa/); + }); + + it("ships its logo inline as a WebP data URI the Settings card accepts", () => { + const logo = paystackPaymentProvider.logo ?? ""; + expect(logo).toMatch(/^data:image\/webp;base64,[A-Za-z0-9+/]+=*$/); + const bytes = Buffer.from(logo.split(",")[1] ?? "", "base64"); + expect(bytes.subarray(0, 4).toString("ascii")).toBe("RIFF"); + expect(bytes.subarray(8, 12).toString("ascii")).toBe("WEBP"); + expect(bytes.length).toBeLessThan(4096); + }); + + it("returns the access code for on-page checkout", async () => { + const ctx: PaymentProviderRuntimeContext = { + http: { + fetch: async () => + new Response( + JSON.stringify({ + status: true, + message: "Authorization URL created", + data: { + authorization_url: "https://checkout.paystack.com/abc", + access_code: "abc123access", + reference: "dc-0123456789abcdef0123456789abcdef", + }, + }), + ), + }, + log: { info() {}, warn() {}, error() {} }, + }; + const result = await paystackPaymentProvider.initCheckout( + ctx, + { + orderDraftId: "0123456789abcdef0123456789abcdef", + amount: 150000, + currency: "KES", + customer: { email: "fan@example.com" }, + lineItems: [], + successUrl: "https://shop.example/thank-you/x", + cancelUrl: "https://shop.example/checkout", + checkoutStyle: "on_page", + }, + { secretKey: "sk_test_1234567890abcdef" }, + ); + expect(result).toEqual({ + kind: "on_page", + checkoutReference: "dc-0123456789abcdef0123456789abcdef", + client: { accessCode: "abc123access" }, + }); + }); +}); + +/** A minimal browser stand-in: script tags "load" when the test says so. */ +function fakeBrowser() { + const appended: Array<{ src: string; onload?: () => void; onerror?: () => void }> = []; + const resumed: Array<{ code: string; callbacks: Record void> }> = []; + const win: Record = {}; + class PaystackPop { + resumeTransaction(code: string, callbacks: Record void>) { + resumed.push({ code, callbacks }); + } + } + const doc = { + createElement: () => + ({}) as { src: string; async?: boolean; onload?: () => void; onerror?: () => void }, + head: { + appendChild: (el: { src: string; onload?: () => void; onerror?: () => void }) => { + appended.push(el); + }, + }, + }; + return { + win, + doc, + appended, + resumed, + loadScript() { + win.PaystackPop = PaystackPop; + for (const el of appended) el.onload?.(); + }, + failScript() { + for (const el of appended) el.onerror?.(); + }, + }; +} + +function recorder() { + const events: string[] = []; + return { + events, + callbacks: { + onFinished: () => events.push("finished"), + onClosed: () => events.push("closed"), + onError: (m: string) => events.push(`error:${m}`), + }, + }; +} + +describe("Paystack checkout client", () => { + it("loads inline.js only when opened, then resumes the transaction", async () => { + const b = fakeBrowser(); + const client = createPaystackCheckoutClient( + b.win as unknown as Window, + b.doc as unknown as Document, + ); + expect(b.appended).toHaveLength(0); + + const r = recorder(); + client.open({ accessCode: "abc123access" }, r.callbacks); + expect(b.appended.map((s) => s.src)).toEqual([PAYSTACK_INLINE_SCRIPT]); + b.loadScript(); + await Promise.resolve(); + await Promise.resolve(); + expect(b.resumed.map((x) => x.code)).toEqual(["abc123access"]); + + b.resumed[0]?.callbacks.onSuccess?.({ reference: "dc-x" }); + expect(r.events).toEqual(["finished"]); + }); + + it("reuses the loaded script for a second attempt", async () => { + const b = fakeBrowser(); + const client = createPaystackCheckoutClient( + b.win as unknown as Window, + b.doc as unknown as Document, + ); + const r = recorder(); + client.open({ accessCode: "first" }, r.callbacks); + b.loadScript(); + await Promise.resolve(); + await Promise.resolve(); + b.resumed[0]?.callbacks.onCancel?.(); + client.open({ accessCode: "second" }, r.callbacks); + await Promise.resolve(); + await Promise.resolve(); + expect(b.appended).toHaveLength(1); + expect(b.resumed.map((x) => x.code)).toEqual(["first", "second"]); + expect(r.events).toEqual(["closed"]); + }); + + it("reports Paystack's load error", async () => { + const b = fakeBrowser(); + const client = createPaystackCheckoutClient( + b.win as unknown as Window, + b.doc as unknown as Document, + ); + const r = recorder(); + client.open({ accessCode: "abc" }, r.callbacks); + b.loadScript(); + await Promise.resolve(); + await Promise.resolve(); + b.resumed[0]?.callbacks.onError?.({ message: "Transaction not found" }); + expect(r.events).toEqual(["error:Transaction not found"]); + }); + + it("says so when the script can't load, and lets the customer retry", async () => { + const b = fakeBrowser(); + const client = createPaystackCheckoutClient( + b.win as unknown as Window, + b.doc as unknown as Document, + ); + const r = recorder(); + client.open({ accessCode: "abc" }, r.callbacks); + b.failScript(); + await Promise.resolve(); + await Promise.resolve(); + expect(r.events[0]).toMatch(/^error:Could not load Paystack/); + + client.open({ accessCode: "abc" }, r.callbacks); + expect(b.appended).toHaveLength(2); + }); + + it("refuses to open without an access code", () => { + const b = fakeBrowser(); + const client = createPaystackCheckoutClient( + b.win as unknown as Window, + b.doc as unknown as Document, + ); + const r = recorder(); + client.open({}, r.callbacks); + expect(r.events).toEqual(["error:Paystack did not return an access code"]); + expect(b.appended).toHaveLength(0); + }); + + it("registers itself next to other providers' clients", () => { + const b = fakeBrowser(); + const other = { open() {} }; + b.win.DashCommerceCheckoutClients = { acme: other }; + registerPaystackCheckoutClient(b.win as unknown as Window, b.doc as unknown as Document); + const clients = b.win.DashCommerceCheckoutClients as Record; + expect(clients.acme).toBe(other); + expect(typeof (clients.paystack as { open: unknown }).open).toBe("function"); + }); +}); diff --git a/packages/paystack/test/paystack-provider.test.ts b/packages/paystack/test/paystack-provider.test.ts new file mode 100644 index 0000000..faa9b7b --- /dev/null +++ b/packages/paystack/test/paystack-provider.test.ts @@ -0,0 +1,501 @@ +import { describe, expect, it } from "bun:test"; +import type { + InitCheckoutInput, + PaymentProviderRuntimeContext, +} from "@dashcommerce/core/payment-provider"; +import { paystackPaymentProvider, paystackReferenceFor } 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 paystackOk(data: unknown): Response { + return new Response(JSON.stringify({ status: true, message: "ok", data }), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); +} + +// Paystack allows only `-`, `.`, `=` and alphanumerics in a transaction reference. +const PAYSTACK_REFERENCE = /^[A-Za-z0-9.=-]+$/; + +describe("paystackPaymentProvider", () => { + const credentials = { secretKey: "sk_test_1234567890abcdef" }; + + describe("supportsCurrency", () => { + it("supports the currencies Paystack settles", () => { + expect(paystackPaymentProvider.supportsCurrency("KES")).toBe(true); + expect(paystackPaymentProvider.supportsCurrency("ngn")).toBe(true); + expect(paystackPaymentProvider.supportsCurrency(" GHS ")).toBe(true); + expect(paystackPaymentProvider.supportsCurrency("ZAR")).toBe(true); + expect(paystackPaymentProvider.supportsCurrency("USD")).toBe(true); + }); + + it("rejects other currencies", () => { + expect(paystackPaymentProvider.supportsCurrency("EUR")).toBe(false); + expect(paystackPaymentProvider.supportsCurrency("GBP")).toBe(false); + expect(paystackPaymentProvider.supportsCurrency("")).toBe(false); + }); + }); + + describe("paystackReferenceFor", () => { + it("produces a reference Paystack accepts from a core draft id", () => { + const ref = paystackReferenceFor("0123456789abcdef0123456789abcdef"); + expect(ref).toBe("dc-0123456789abcdef0123456789abcdef"); + expect(ref).toMatch(PAYSTACK_REFERENCE); + }); + + it("replaces characters Paystack rejects", () => { + expect(paystackReferenceFor("draft_pstk_1")).toMatch(PAYSTACK_REFERENCE); + }); + }); + + describe("initCheckout", () => { + it("initialises a transaction with a valid reference and returns the redirect", async () => { + let capturedUrl = ""; + let capturedBody: Record = {}; + const ctx = makeMockRuntimeContext(async (url, init) => { + capturedUrl = url; + capturedBody = JSON.parse(String(init?.body)); + return paystackOk({ + authorization_url: "https://checkout.paystack.com/abc", + access_code: "abc", + reference: capturedBody.reference, + }); + }); + + const result = await paystackPaymentProvider.initCheckout( + ctx, + checkoutInput({ preferredChannels: ["card", "mpesa"] }), + credentials, + ); + + expect(capturedUrl).toBe("https://api.paystack.co/transaction/initialize"); + expect(capturedBody.email).toBe("fan@example.com"); + expect(capturedBody.amount).toBe(250000); + expect(capturedBody.currency).toBe("KES"); + expect(capturedBody.reference).toBe("dc-0123456789abcdef0123456789abcdef"); + expect(String(capturedBody.reference)).toMatch(PAYSTACK_REFERENCE); + expect(capturedBody.callback_url).toBe("https://shop.example/thank-you"); + expect(capturedBody.channels).toEqual(["card", "mobile_money"]); + expect((capturedBody.metadata 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.paystack.com/abc"); + expect(result.checkoutReference).toBe("dc-0123456789abcdef0123456789abcdef"); + }); + + it("throws before calling Paystack when the email is missing", async () => { + let calls = 0; + const ctx = makeMockRuntimeContext(async () => { + calls++; + return new Response("{}"); + }); + await expect( + paystackPaymentProvider.initCheckout( + ctx, + checkoutInput({ customer: { email: "" } }), + credentials, + ), + ).rejects.toThrow("Paystack requires customer email to initialize checkout"); + expect(calls).toBe(0); + }); + + it("throws before calling Paystack when the email is malformed", async () => { + let calls = 0; + const ctx = makeMockRuntimeContext(async () => { + calls++; + return new Response("{}"); + }); + await expect( + paystackPaymentProvider.initCheckout( + ctx, + checkoutInput({ customer: { email: "invalid-email" } }), + credentials, + ), + ).rejects.toThrow("Paystack requires a valid customer email to initialize checkout"); + expect(calls).toBe(0); + }); + + it("throws before calling Paystack for an unsupported currency", async () => { + let calls = 0; + const ctx = makeMockRuntimeContext(async () => { + calls++; + return new Response("{}"); + }); + await expect( + paystackPaymentProvider.initCheckout(ctx, checkoutInput({ currency: "EUR" }), credentials), + ).rejects.toThrow(/does not support currency EUR/); + expect(calls).toBe(0); + }); + + it("throws before calling Paystack for subscription mode", async () => { + let calls = 0; + const ctx = makeMockRuntimeContext(async () => { + calls++; + return new Response("{}"); + }); + await expect( + paystackPaymentProvider.initCheckout( + ctx, + checkoutInput({ mode: "subscription" }), + credentials, + ), + ).rejects.toThrow(/subscription/); + expect(calls).toBe(0); + }); + + it("drops Stripe's session placeholder from the callback URL", async () => { + let body: Record = {}; + const ctx = makeMockRuntimeContext(async (_url, init) => { + body = JSON.parse(String(init?.body)); + return paystackOk({ + authorization_url: "https://checkout.paystack.com/x", + reference: body.reference, + }); + }); + await paystackPaymentProvider.initCheckout( + ctx, + checkoutInput({ + successUrl: "https://shop.example/thank-you/abc?session_id={CHECKOUT_SESSION_ID}&keep=1", + }), + credentials, + ); + expect(body.callback_url).toBe("https://shop.example/thank-you/abc?keep=1"); + }); + + it("refuses to call Paystack without the runtime's fetch", async () => { + const ctx: PaymentProviderRuntimeContext = { log: { info() {}, warn() {}, error() {} } }; + await expect( + paystackPaymentProvider.initCheckout(ctx, checkoutInput(), credentials), + ).rejects.toThrow(/ctx\.http\.fetch/); + }); + + it("surfaces a Paystack API error", async () => { + const ctx = makeMockRuntimeContext( + async () => + new Response(JSON.stringify({ status: false, message: "Invalid key" }), { + status: 401, + headers: { "Content-Type": "application/json" }, + }), + ); + await expect( + paystackPaymentProvider.initCheckout(ctx, checkoutInput(), credentials), + ).rejects.toThrow("Invalid key"); + }); + }); + + describe("verifyWebhook", () => { + async function sign(secret: string, payload: string): Promise { + const enc = new TextEncoder(); + const key = await crypto.subtle.importKey( + "raw", + enc.encode(secret), + { name: "HMAC", hash: "SHA-512" }, + false, + ["sign"], + ); + const sig = await crypto.subtle.sign("HMAC", key, enc.encode(payload)); + return Array.from(new Uint8Array(sig)) + .map((b) => b.toString(16).padStart(2, "0")) + .join(""); + } + + it("accepts a valid HMAC-SHA512 signature over the raw body", async () => { + const body = JSON.stringify({ event: "charge.success", data: { id: 123 } }); + const result = await paystackPaymentProvider.verifyWebhook({ + rawBody: body, + signatureHeader: await sign(credentials.secretKey, body), + secret: credentials.secretKey, + }); + expect(result.ok).toBe(true); + }); + + it("rejects a signature made with another key", async () => { + const body = JSON.stringify({ event: "charge.success", data: { id: 123 } }); + const result = await paystackPaymentProvider.verifyWebhook({ + rawBody: body, + signatureHeader: await sign("sk_test_wrong_key", body), + secret: credentials.secretKey, + }); + expect(result.ok).toBe(false); + expect(result.reason).toContain("Signature mismatch"); + }); + + it("rejects a body changed after signing", async () => { + const body = JSON.stringify({ event: "charge.success", data: { amount: 100 } }); + const signature = await sign(credentials.secretKey, body); + const result = await paystackPaymentProvider.verifyWebhook({ + rawBody: body.replace("100", "1"), + signatureHeader: signature, + secret: credentials.secretKey, + }); + expect(result.ok).toBe(false); + }); + + it("rejects a missing signature or secret", async () => { + expect( + ( + await paystackPaymentProvider.verifyWebhook({ + rawBody: "{}", + signatureHeader: "", + secret: credentials.secretKey, + }) + ).ok, + ).toBe(false); + expect( + ( + await paystackPaymentProvider.verifyWebhook({ + rawBody: "{}", + signatureHeader: "abc", + secret: "", + }) + ).ok, + ).toBe(false); + }); + }); + + describe("parseWebhookEvent", () => { + const successPayload = { + event: "charge.success", + data: { + id: 99887766, + reference: "dc-0123456789abcdef0123456789abcdef", + amount: 350000, + currency: "KES", + status: "success", + customer: { + email: "captain@example.com", + first_name: "Biko", + last_name: "Adema", + phone: "+254711223344", + }, + channel: "mobile_money", + metadata: { orderDraftId: "0123456789abcdef0123456789abcdef" }, + }, + }; + + it("maps charge.success using the transaction reference, not the numeric id", () => { + const parsed = paystackPaymentProvider.parseWebhookEvent(JSON.stringify(successPayload)); + expect(parsed.type).toBe("charge.succeeded"); + if (parsed.type !== "charge.succeeded") throw new Error("expected charge.succeeded"); + expect(parsed.orderDraftId).toBe("0123456789abcdef0123456789abcdef"); + // `/transaction/verify/:reference` only accepts the reference, and core + // passes paymentReference to getPaymentStatus before creating the order. + expect(parsed.paymentReference).toBe("dc-0123456789abcdef0123456789abcdef"); + expect(parsed.checkoutReference).toBe("dc-0123456789abcdef0123456789abcdef"); + // Paystack sends no event id; an empty one makes core rely on its + // per-payment unique index, so a failed delivery can be retried. + expect(parsed.providerEventId).toBe(""); + expect(parsed.providerId).toBe("paystack"); + expect(parsed.amount).toBe(350000); + expect(parsed.currency).toBe("KES"); + expect(parsed.customer.email).toBe("captain@example.com"); + expect(parsed.customer.name).toBe("Biko Adema"); + expect(parsed.customer.phone).toBe("+254711223344"); + expect(parsed.channel).toBe("M-Pesa"); + }); + + it("recovers the draft id from the reference when metadata is missing", () => { + const { metadata: _omitted, ...data } = successPayload.data; + const parsed = paystackPaymentProvider.parseWebhookEvent( + JSON.stringify({ ...successPayload, data }), + ); + expect(parsed.type).toBe("charge.succeeded"); + if (parsed.type !== "charge.succeeded") throw new Error("expected charge.succeeded"); + expect(parsed.orderDraftId).toBe("0123456789abcdef0123456789abcdef"); + }); + + it("reads metadata sent back as a JSON string", () => { + const parsed = paystackPaymentProvider.parseWebhookEvent( + JSON.stringify({ + ...successPayload, + data: { + ...successPayload.data, + reference: "not-ours", + metadata: JSON.stringify({ orderDraftId: "draft-from-string" }), + }, + }), + ); + expect(parsed.type).toBe("charge.succeeded"); + if (parsed.type !== "charge.succeeded") throw new Error("expected charge.succeeded"); + expect(parsed.orderDraftId).toBe("draft-from-string"); + }); + + it("does not guess a draft id from a reference it did not issue", () => { + const { metadata: _omitted, ...data } = successPayload.data; + const parsed = paystackPaymentProvider.parseWebhookEvent( + JSON.stringify({ ...successPayload, data: { ...data, reference: "T685312322670591" } }), + ); + expect(parsed.type).toBe("unhandled"); + }); + + it("does not invent a currency when Paystack omits it", () => { + const { currency: _omitted, ...data } = successPayload.data; + const parsed = paystackPaymentProvider.parseWebhookEvent( + JSON.stringify({ ...successPayload, data }), + ); + expect(parsed.type).toBe("unhandled"); + }); + + it("leaves events Paystack does not document for this flow unhandled", () => { + const parsed = paystackPaymentProvider.parseWebhookEvent( + JSON.stringify({ + event: "charge.failed", + data: { ...successPayload.data, status: "failed" }, + }), + ); + expect(parsed.type).toBe("unhandled"); + }); + + it("returns unhandled on unparseable JSON without throwing", () => { + const parsed = paystackPaymentProvider.parseWebhookEvent("invalid-json-body"); + expect(parsed.type).toBe("unhandled"); + if (parsed.type !== "unhandled") throw new Error("expected unhandled"); + expect(parsed.providerEventType).toBe("unparseable"); + }); + + it("returns unhandled when the charge has no orderDraftId", () => { + const parsed = paystackPaymentProvider.parseWebhookEvent( + JSON.stringify({ + event: "charge.success", + data: { id: 554433, reference: "no-draft", amount: 1000, currency: "KES" }, + }), + ); + expect(parsed.type).toBe("unhandled"); + }); + }); + + describe("getPaymentStatus", () => { + it("verifies by reference and returns the reference", async () => { + let calledUrl = ""; + const ctx = makeMockRuntimeContext(async (url) => { + calledUrl = url; + return paystackOk({ + id: 776655, + status: "success", + reference: "dc-abc", + amount: 450000, + currency: "KES", + }); + }); + + const status = await paystackPaymentProvider.getPaymentStatus?.(ctx, "dc-abc", credentials); + + expect(calledUrl).toBe("https://api.paystack.co/transaction/verify/dc-abc"); + expect(status?.status).toBe("succeeded"); + expect(status?.paymentReference).toBe("dc-abc"); + expect(status?.amount).toBe(450000); + expect(status?.currency).toBe("KES"); + }); + + it("maps failed and abandoned transactions", async () => { + for (const [paystackStatus, expected] of [ + ["failed", "failed"], + ["abandoned", "pending"], + ["ongoing", "pending"], + ] as const) { + const ctx = makeMockRuntimeContext(async () => + paystackOk({ + id: 1, + status: paystackStatus, + reference: "dc-x", + amount: 1, + currency: "KES", + }), + ); + const status = await paystackPaymentProvider.getPaymentStatus?.(ctx, "dc-x", credentials); + expect(status?.status).toBe(expected); + } + }); + }); + + describe("refund", () => { + it("refunds by transaction reference with the request id in the merchant note", async () => { + let capturedBody: Record = {}; + const ctx = makeMockRuntimeContext(async (url, init) => { + // The double-refund guard looks first: verify for the numeric id, then list. + if (url.startsWith("https://api.paystack.co/transaction/verify/")) { + return paystackOk({ id: 6480092473, status: "success", reference: "dc-x" }); + } + if (url.startsWith("https://api.paystack.co/refund?")) return paystackOk([]); + expect(url).toBe("https://api.paystack.co/refund"); + capturedBody = JSON.parse(String(init?.body)); + return paystackOk({ id: 990011, status: "processed", amount: 250000, currency: "KES" }); + }); + + const result = await paystackPaymentProvider.refund( + ctx, + { + refundRequestId: "refund-req-1", + paymentReference: "dc-0123456789abcdef0123456789abcdef", + amount: 250000, + currency: "KES", + reason: "Event cancelled", + }, + credentials, + ); + + expect(capturedBody.transaction).toBe("dc-0123456789abcdef0123456789abcdef"); + expect(capturedBody.amount).toBe(250000); + expect(capturedBody.currency).toBe("KES"); + expect(capturedBody.merchant_note).toBe("Event cancelled (refundRequestId=refund-req-1)"); + expect(result.status).toBe("succeeded"); + expect(result.providerRefundId).toBe("990011"); + expect(result.refundRequestId).toBe("refund-req-1"); + }); + + it("reports a queued refund as pending", async () => { + const ctx = makeMockRuntimeContext(async (url) => { + if (url.includes("/transaction/verify/")) return paystackOk({ id: 1, status: "success" }); + if (url.includes("/refund?")) return paystackOk([]); + return paystackOk({ id: 1, status: "pending", amount: 100, currency: "KES" }); + }); + const result = await paystackPaymentProvider.refund( + ctx, + { refundRequestId: "r", paymentReference: "dc-x", amount: 100, currency: "KES" }, + credentials, + ); + expect(result.status).toBe("pending"); + }); + + it("throws when refundRequestId is missing", async () => { + const ctx = makeMockRuntimeContext(async () => new Response()); + await expect( + paystackPaymentProvider.refund( + ctx, + { refundRequestId: "", paymentReference: "dc-x", amount: 1000, currency: "KES" }, + credentials, + ), + ).rejects.toThrow(/refundRequestId/); + }); + }); + + describe("formatAmount", () => { + it("formats minor units as major units with the currency code", () => { + expect(paystackPaymentProvider.formatAmount(250000, "KES")).toBe("KES 2500.00"); + expect(paystackPaymentProvider.formatAmount(999, "usd")).toBe("USD 9.99"); + }); + }); +}); diff --git a/packages/paystack/test/provider-hardening.test.ts b/packages/paystack/test/provider-hardening.test.ts new file mode 100644 index 0000000..3ab75be --- /dev/null +++ b/packages/paystack/test/provider-hardening.test.ts @@ -0,0 +1,651 @@ +/** + * Double-refund guard, transaction-status mapping and `Paystack-Signature` + * verification. + * + * The refund and verify fixtures are real Paystack test-mode responses + * (sanitised) from 19 Nov 2026: transaction T877626421263494 (id 6480092473) + * with two identical partial refunds, 19224707 (processed) and 19224741 + * (processing). Paystack accepted the second as a fresh refund, which is why + * the guard exists. + */ + +import { createHmac } from "node:crypto"; +import { describe, expect, it } from "bun:test"; +import type { PaymentProviderRuntimeContext } from "@dashcommerce/core/payment-provider"; +import { paystackPaymentProvider } from "../src/provider"; +import { verifyPaystackSignature } from "../src/webhook-verify"; +import refundList from "./fixtures/refund-list-by-transaction.json"; +import verifyReversalPending from "./fixtures/verify-reversal-pending.json"; + +const credentials = { secretKey: "sk_test_1234567890abcdef" }; + +interface Recorded { + method: string; + url: string; + body?: Record; +} + +function json(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { "Content-Type": "application/json" }, + }); +} + +/** A fake Paystack that answers by method and path, and records each call. */ +function fakePaystack(routes: Record Response>): { + ctx: PaymentProviderRuntimeContext; + calls: Recorded[]; +} { + const calls: Recorded[] = []; + const ctx: PaymentProviderRuntimeContext = { + http: { + fetch: async (url, init) => { + const method = init?.method ?? "GET"; + const parsed = new URL(url); + calls.push({ + method, + url, + ...(init?.body ? { body: JSON.parse(String(init.body)) } : {}), + }); + const handler = routes[`${method} ${parsed.pathname}`]; + if (!handler) throw new Error(`Unexpected Paystack call: ${method} ${url}`); + return handler(parsed); + }, + }, + log: { info() {}, warn() {}, error() {} }, + }; + return { ctx, calls }; +} + +const emptyRefundList = { + status: true, + message: "Refunds retrieved", + data: [], + meta: { total: 0, skipped: 0, perPage: 100, page: 1, pageCount: 0 }, +}; + +const createdRefund = { + status: true, + message: "Refund has been queued for processing", + data: { + id: 19300001, + status: "pending", + amount: 10000, + currency: "KES", + merchant_note: "(refundRequestId=refund:order1:abc)", + }, +}; + +describe("refund: double-refund guard", () => { + it("returns the refund already carrying this refundRequestId instead of creating another", async () => { + const { ctx, calls } = fakePaystack({ + "GET /transaction/verify/T877626421263494": () => json(verifyReversalPending), + "GET /refund": () => json(refundList), + }); + + const result = await paystackPaymentProvider.refund( + ctx, + { + refundRequestId: "fik57-test-1", + paymentReference: "T877626421263494", + amount: 10000, + currency: "KES", + }, + credentials, + ); + + expect(calls.some((c) => c.method === "POST")).toBe(false); + // The first refund made for this request, not the accidental duplicate. + expect(result.providerRefundId).toBe("19224707"); + expect(result.status).toBe("succeeded"); + expect(result.amount).toBe(10000); + expect(result.currency).toBe("KES"); + expect(result.refundRequestId).toBe("fik57-test-1"); + }); + + it("lists refunds by the numeric transaction id, never the reference", async () => { + const { ctx, calls } = fakePaystack({ + "GET /transaction/verify/T877626421263494": () => json(verifyReversalPending), + "GET /refund": () => json(refundList), + }); + + await paystackPaymentProvider.refund( + ctx, + { + refundRequestId: "fik57-test-1", + paymentReference: "T877626421263494", + amount: 10000, + currency: "KES", + }, + credentials, + ); + + const list = calls.find((c) => c.method === "GET" && new URL(c.url).pathname === "/refund"); + expect(list).toBeDefined(); + expect(new URL(list?.url ?? "").searchParams.get("transaction")).toBe("6480092473"); + }); + + it("creates a refund when none carries this refundRequestId", async () => { + const { ctx, calls } = fakePaystack({ + "GET /transaction/verify/T877626421263494": () => json(verifyReversalPending), + "GET /refund": () => json(refundList), + "POST /refund": () => json(createdRefund), + }); + + const result = await paystackPaymentProvider.refund( + ctx, + { + refundRequestId: "refund:order1:abc", + paymentReference: "T877626421263494", + amount: 10000, + currency: "KES", + }, + credentials, + ); + + const post = calls.find((c) => c.method === "POST"); + expect(post?.body?.transaction).toBe("T877626421263494"); + expect(post?.body?.amount).toBe(10000); + expect(result.providerRefundId).toBe("19300001"); + expect(result.status).toBe("pending"); + }); + + it("does not match a request id that merely starts with this one", async () => { + const { ctx, calls } = fakePaystack({ + "GET /transaction/verify/T877626421263494": () => json(verifyReversalPending), + "GET /refund": () => json(refundList), + "POST /refund": () => json(createdRefund), + }); + + await paystackPaymentProvider.refund( + ctx, + { + refundRequestId: "fik57-test", + paymentReference: "T877626421263494", + amount: 10000, + currency: "KES", + }, + credentials, + ); + + expect(calls.some((c) => c.method === "POST")).toBe(true); + }); + + it("ignores a failed refund with the same request id and tries again", async () => { + const failedOnly = { + ...refundList, + data: [{ ...refundList.data[1], status: "failed", reason: "FAILED" }], + }; + const { ctx, calls } = fakePaystack({ + "GET /transaction/verify/T877626421263494": () => json(verifyReversalPending), + "GET /refund": () => json(failedOnly), + "POST /refund": () => json(createdRefund), + }); + + await paystackPaymentProvider.refund( + ctx, + { + refundRequestId: "fik57-test-1", + paymentReference: "T877626421263494", + amount: 10000, + currency: "KES", + }, + credentials, + ); + + expect(calls.some((c) => c.method === "POST")).toBe(true); + }); + + it("reads every page of refunds before deciding", async () => { + const page1 = { + ...emptyRefundList, + data: [{ ...refundList.data[0], merchant_note: "refundRequestId=someone-else" }], + meta: { ...emptyRefundList.meta, total: 2, pageCount: 2 }, + }; + const page2 = { + ...emptyRefundList, + data: [refundList.data[1]], + meta: { ...emptyRefundList.meta, total: 2, page: 2, pageCount: 2 }, + }; + const { ctx, calls } = fakePaystack({ + "GET /transaction/verify/T877626421263494": () => json(verifyReversalPending), + "GET /refund": (url) => json(url.searchParams.get("page") === "2" ? page2 : page1), + }); + + const result = await paystackPaymentProvider.refund( + ctx, + { + refundRequestId: "fik57-test-1", + paymentReference: "T877626421263494", + amount: 10000, + currency: "KES", + }, + credentials, + ); + + expect(calls.some((c) => c.method === "POST")).toBe(false); + expect(result.providerRefundId).toBe("19224707"); + }); + + it("writes the request id into merchant_note in the form the guard reads back", async () => { + const { ctx, calls } = fakePaystack({ + "GET /transaction/verify/dc-x": () => + json({ ...verifyReversalPending, data: { ...verifyReversalPending.data, id: 42 } }), + "GET /refund": () => json(emptyRefundList), + "POST /refund": () => json(createdRefund), + }); + + await paystackPaymentProvider.refund( + ctx, + { + refundRequestId: "refund:order1:abc", + paymentReference: "dc-x", + amount: 10000, + currency: "KES", + reason: "Event cancelled", + }, + credentials, + ); + + const post = calls.find((c) => c.method === "POST"); + expect(post?.body?.merchant_note).toBe("Event cancelled (refundRequestId=refund:order1:abc)"); + }); + + it("cannot be fooled by a tag inside the reason", async () => { + const { ctx, calls } = fakePaystack({ + "GET /transaction/verify/dc-x": () => json(verifyReversalPending), + "GET /refund": () => + json({ + ...refundList, + data: [ + { + ...refundList.data[1], + merchant_note: "Event cancelled (refundRequestId=real-1)", + }, + ], + }), + "POST /refund": () => json(createdRefund), + }); + + await paystackPaymentProvider.refund( + ctx, + { + refundRequestId: "other-2", + paymentReference: "dc-x", + amount: 10000, + currency: "KES", + reason: "dup (refundRequestId=real-1)", + }, + credentials, + ); + + const post = calls.find((c) => c.method === "POST"); + // The brackets are stripped, so the note ends with our tag and no other. + expect(post?.body?.merchant_note).toBe("dup refundRequestId=real-1 (refundRequestId=other-2)"); + }); + + it("matches only the tag at the end of the note", async () => { + const spoofed = { + ...refundList, + data: [ + { + ...refundList.data[1], + merchant_note: "(refundRequestId=target) (refundRequestId=someone-else)", + }, + ], + }; + const { ctx, calls } = fakePaystack({ + "GET /transaction/verify/dc-x": () => json(verifyReversalPending), + "GET /refund": () => json(spoofed), + "POST /refund": () => json(createdRefund), + }); + + await paystackPaymentProvider.refund( + ctx, + { refundRequestId: "target", paymentReference: "dc-x", amount: 10000, currency: "KES" }, + credentials, + ); + + expect(calls.some((c) => c.method === "POST")).toBe(true); + }); + + it("refuses a request id the merchant note cannot hold unambiguously", async () => { + const { ctx } = fakePaystack({}); + await expect( + paystackPaymentProvider.refund( + ctx, + { + refundRequestId: "has space", + paymentReference: "dc-x", + amount: 100, + currency: "KES", + }, + credentials, + ), + ).rejects.toThrow(/refundRequestId/); + }); + + it("does not create a refund when the lookup fails", async () => { + const { ctx, calls } = fakePaystack({ + "GET /transaction/verify/dc-x": () => + json({ status: false, message: "Transaction reference not found" }, 400), + }); + + await expect( + paystackPaymentProvider.refund( + ctx, + { refundRequestId: "r1", paymentReference: "dc-x", amount: 100, currency: "KES" }, + credentials, + ), + ).rejects.toThrow(/not found/); + expect(calls.some((c) => c.method === "POST")).toBe(false); + }); + + it("maps each documented refund status", async () => { + for (const [paystackStatus, expected] of [ + ["pending", "pending"], + ["processing", "pending"], + ["needs-attention", "pending"], + ["processed", "succeeded"], + ["failed", "failed"], + ] as const) { + const { ctx } = fakePaystack({ + "GET /transaction/verify/dc-x": () => json(verifyReversalPending), + "GET /refund": () => json(emptyRefundList), + "POST /refund": () => + json({ ...createdRefund, data: { ...createdRefund.data, status: paystackStatus } }), + }); + const result = await paystackPaymentProvider.refund( + ctx, + { refundRequestId: "r1", paymentReference: "dc-x", amount: 10000, currency: "KES" }, + credentials, + ); + expect(result.status).toBe(expected); + } + }); +}); + +describe("getPaymentStatus: full transaction-status mapping", () => { + it("treats a partly refunded transaction (live reversal-pending response) as paid", async () => { + const { ctx } = fakePaystack({ + "GET /transaction/verify/T877626421263494": () => json(verifyReversalPending), + // The live refund list for it: KES 200 of KES 1,000 refunded. + "GET /refund": () => json(refundList), + }); + const status = await paystackPaymentProvider.getPaymentStatus?.( + ctx, + "T877626421263494", + credentials, + ); + expect(status?.status).toBe("succeeded"); + expect(status?.amount).toBe(100000); + expect(status?.currency).toBe("KES"); + expect(status?.paymentReference).toBe("T877626421263494"); + }); + + it("maps every status in Paystack's docs, plus the reversal-pending the API returns", async () => { + for (const [paystackStatus, expected] of [ + ["success", "succeeded"], + ["reversed", "succeeded"], + ["reversal-pending", "succeeded"], + ["failed", "failed"], + ["abandoned", "pending"], + ["ongoing", "pending"], + ["pending", "pending"], + ["processing", "pending"], + ["queued", "pending"], + ] as const) { + const { ctx } = fakePaystack({ + "GET /transaction/verify/dc-x": () => + json({ + ...verifyReversalPending, + data: { ...verifyReversalPending.data, status: paystackStatus }, + }), + "GET /refund": () => json(emptyRefundList), + }); + const status = await paystackPaymentProvider.getPaymentStatus?.(ctx, "dc-x", credentials); + expect({ paystackStatus, status: status?.status }).toEqual({ + paystackStatus, + status: expected, + }); + } + }); + + it("never reports an unknown status as paid or failed", async () => { + const { ctx } = fakePaystack({ + "GET /transaction/verify/dc-x": () => + json({ + ...verifyReversalPending, + data: { ...verifyReversalPending.data, status: "something-new" }, + }), + }); + const status = await paystackPaymentProvider.getPaymentStatus?.(ctx, "dc-x", credentials); + expect(status?.status).toBe("pending"); + expect(status?.reason).toContain("something-new"); + }); +}); + +describe("Paystack-Signature verification", () => { + // Obviously fake; the real secret lives only in the merchant's settings. + const whsec = "whsec_1234567890abcdef"; + const body = '{"event":"charge.success","data":{"id":1,"amount":1.50}}'; + + function v1(secret: string, t: number, raw: string): string { + return createHmac("sha512", secret).update(`${t}.${raw}`).digest("hex"); + } + const now = () => Math.floor(Date.now() / 1000); + + it("accepts a valid signature through the provider", async () => { + const t = now(); + const result = await paystackPaymentProvider.verifyWebhook({ + rawBody: body, + signatureHeader: `t=${t},v1=whk_3f9a1c2e:${v1(whsec, t, body)}`, + secret: whsec, + }); + expect(result).toEqual({ ok: true }); + }); + + it("accepts when any v1 matches, as during secret rotation", async () => { + const t = now(); + const header = `t=${t},v1=whk_old:${v1("whsec_old_secret_000", t, body)},v1=whk_new:${v1(whsec, t, body)}`; + const result = await verifyPaystackSignature({ + payload: body, + signatureHeader: header, + secret: whsec, + }); + expect(result.ok).toBe(true); + }); + + it("ignores fields it does not recognise", async () => { + const t = now(); + const result = await verifyPaystackSignature({ + payload: body, + signatureHeader: `t=${t},v0=legacy,v1=whk_a:${v1(whsec, t, body)},x=1`, + secret: whsec, + }); + expect(result.ok).toBe(true); + }); + + it("rejects a signature made with another secret", async () => { + const t = now(); + const result = await verifyPaystackSignature({ + payload: body, + signatureHeader: `t=${t},v1=whk_a:${v1("whsec_other_secret_00", t, body)}`, + secret: whsec, + }); + expect(result.ok).toBe(false); + expect(result.reason).toContain("Signature mismatch"); + }); + + it("rejects a body changed after signing", async () => { + const t = now(); + const result = await verifyPaystackSignature({ + payload: body.replace("1.50", "1.5"), + signatureHeader: `t=${t},v1=whk_a:${v1(whsec, t, body)}`, + secret: whsec, + }); + expect(result.ok).toBe(false); + }); + + it("rejects a signature whose timestamp was altered", async () => { + const t = now(); + const result = await verifyPaystackSignature({ + payload: body, + signatureHeader: `t=${t + 1},v1=whk_a:${v1(whsec, t, body)}`, + secret: whsec, + }); + expect(result.ok).toBe(false); + }); + + it("accepts exactly 300 seconds of skew and rejects 301, either way", async () => { + const nowSeconds = 1_760_270_400; + const at = async (t: number) => + ( + await verifyPaystackSignature({ + payload: body, + signatureHeader: `t=${t},v1=whk_a:${v1(whsec, t, body)}`, + secret: whsec, + nowSeconds, + }) + ).ok; + expect(await at(nowSeconds - 300)).toBe(true); + expect(await at(nowSeconds + 300)).toBe(true); + expect(await at(nowSeconds - 301)).toBe(false); + expect(await at(nowSeconds + 301)).toBe(false); + }); + + it("signs the timestamp exactly as sent", async () => { + const nowSeconds = 1_760_270_400; + const raw = `0${nowSeconds}`; + const sig = createHmac("sha512", whsec).update(`${raw}.${body}`).digest("hex"); + const result = await verifyPaystackSignature({ + payload: body, + signatureHeader: `t=${raw},v1=whk_a:${sig}`, + secret: whsec, + nowSeconds, + }); + expect(result.ok).toBe(true); + }); + + it("rejects a header with no timestamp, two timestamps, or no v1", async () => { + const t = now(); + const sig = v1(whsec, t, body); + for (const header of [ + `v1=whk_a:${sig}`, + `t=${t},t=${t},v1=whk_a:${sig}`, + `t=abc,v1=whk_a:${sig}`, + `t=${t}`, + `t=${t},v1=whk_a:not-hex`, + ]) { + const result = await verifyPaystackSignature({ + payload: body, + signatureHeader: header, + secret: whsec, + }); + expect({ header, ok: result.ok }).toEqual({ header, ok: false }); + } + }); + + it("says which secret is needed when an sk_ key is configured for the new header", async () => { + const t = now(); + const result = await verifyPaystackSignature({ + payload: body, + signatureHeader: `t=${t},v1=whk_a:${v1(whsec, t, body)}`, + secret: credentials.secretKey, + }); + expect(result.ok).toBe(false); + expect(result.reason).toContain("whsec_"); + }); + + it("still accepts the legacy x-paystack-signature, keyed with the secret key", async () => { + const legacy = createHmac("sha512", credentials.secretKey).update(body).digest("hex"); + const result = await paystackPaymentProvider.verifyWebhook({ + rawBody: body, + signatureHeader: legacy, + secret: credentials.secretKey, + }); + expect(result.ok).toBe(true); + }); +}); + +describe("refund guard: fails loudly", () => { + it("refuses to refund when verify gives no numeric transaction id", async () => { + const { ctx, calls } = fakePaystack({ + "GET /transaction/verify/dc-x": () => + json({ status: true, message: "ok", data: { reference: "dc-x", status: "success" } }), + }); + await expect( + paystackPaymentProvider.refund( + ctx, + { refundRequestId: "r1", paymentReference: "dc-x", amount: 100, currency: "KES" }, + credentials, + ), + ).rejects.toThrow(/numeric transaction id/); + expect(calls.some((c) => c.method === "POST")).toBe(false); + }); + + it("stops paging rather than loop on an absurd page count", async () => { + const { ctx, calls } = fakePaystack({ + "GET /transaction/verify/dc-x": () => json(verifyReversalPending), + "GET /refund": () => + json({ ...emptyRefundList, meta: { ...emptyRefundList.meta, pageCount: 1_000_000 } }), + }); + await expect( + paystackPaymentProvider.refund( + ctx, + { refundRequestId: "r1", paymentReference: "dc-x", amount: 100, currency: "KES" }, + credentials, + ), + ).rejects.toThrow(/pages of refunds/); + expect(calls.some((c) => c.method === "POST")).toBe(false); + }); +}); + +describe("getPaymentStatus: a payment refunded in full before its order exists", () => { + // Paystack reports `reversed` / `reversal-pending` after partial refunds + // too, so only the refunded total can tell a fully returned payment apart. + const refunds = (...rows: Array<[number, string, number]>) => ({ + ...emptyRefundList, + data: rows.map(([id, status, amount]) => ({ + id, + status, + amount, + currency: "KES", + transaction_reference: "dc-x", + })), + meta: { ...emptyRefundList.meta, total: rows.length, pageCount: 1 }, + }); + const verifyAs = (status: string) => () => + json({ ...verifyReversalPending, data: { ...verifyReversalPending.data, status } }); + + it("does not confirm a payment whose refunds add up to the whole amount", async () => { + for (const status of ["reversed", "reversal-pending"]) { + const { ctx } = fakePaystack({ + "GET /transaction/verify/dc-x": verifyAs(status), + "GET /refund": () => json(refunds([1, "processed", 60000], [2, "pending", 40000])), + }); + const result = await paystackPaymentProvider.getPaymentStatus?.(ctx, "dc-x", credentials); + expect(result?.status).toBe("failed"); + expect(result?.reason).toContain("refunded in full"); + } + }); + + it("leaves failed refunds out of the total", async () => { + const { ctx } = fakePaystack({ + "GET /transaction/verify/dc-x": verifyAs("reversed"), + "GET /refund": () => json(refunds([1, "failed", 100000], [2, "processed", 10000])), + }); + const result = await paystackPaymentProvider.getPaymentStatus?.(ctx, "dc-x", credentials); + expect(result?.status).toBe("succeeded"); + }); + + it("does not list refunds for a transaction that was never reversed", async () => { + const { ctx, calls } = fakePaystack({ + "GET /transaction/verify/dc-x": verifyAs("success"), + }); + const result = await paystackPaymentProvider.getPaymentStatus?.(ctx, "dc-x", credentials); + expect(result?.status).toBe("succeeded"); + expect(calls.map((c) => c.url)).toEqual(["https://api.paystack.co/transaction/verify/dc-x"]); + }); +}); diff --git a/packages/paystack/tsconfig.json b/packages/paystack/tsconfig.json new file mode 100644 index 0000000..82829f9 --- /dev/null +++ b/packages/paystack/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/paystack/tsdown.config.ts b/packages/paystack/tsdown.config.ts new file mode 100644 index 0000000..92bddfd --- /dev/null +++ b/packages/paystack/tsdown.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from "tsdown"; + +export default defineConfig({ + // checkout-client is the browser entry (Paystack Popup); index is the provider. + entry: ["src/index.ts", "src/checkout-client.ts"], + format: ["esm"], + dts: true, + clean: true, +}); From fadc0ef7a4fc92451a96a5d80c1fd7c001ef0740 Mon Sep 17 00:00:00 2001 From: Nyaenya Obadiah Moseti Date: Tue, 24 Nov 2026 01:41:05 +0300 Subject: [PATCH 2/3] fix(paystack): event ids for webhook dedup; release 0.1.0 with core 0.4.0 - Set providerEventId on refund.* events (`:`), so two refund.failed deliveries reverse a refund once, and on charge.success (`charge.success:`), so overlapping deliveries run once. Core still releases the record when confirming with Paystack fails. - Peer @dashcommerce/core ^0.4.0 instead of workspace:*, which made changesets version this package 1.0.0. It now releases as 0.1.0. - README: needs core 0.4.0, install step, why ?provider=paystack, removed the pre-merge core requirements section. Co-Authored-By: Claude Opus 5.5 --- .changeset/paystack-provider.md | 3 +- bun.lock | 2 +- packages/paystack/README.md | 30 ++-- packages/paystack/package.json | 2 +- packages/paystack/src/provider.ts | 24 +-- .../paystack/test/core-enablement.test.ts | 10 +- .../paystack/test/core-integration.test.ts | 156 +++++++++++++++--- packages/paystack/test/on-page.test.ts | 2 +- .../paystack/test/paystack-provider.test.ts | 6 +- .../paystack/test/provider-hardening.test.ts | 2 +- 10 files changed, 174 insertions(+), 63 deletions(-) diff --git a/.changeset/paystack-provider.md b/.changeset/paystack-provider.md index eae9efe..f5bd035 100644 --- a/.changeset/paystack-provider.md +++ b/.changeset/paystack-provider.md @@ -6,7 +6,8 @@ New package: a Paystack payment provider for DashCommerce, built on core's Payme - 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. -Register it with `import "@dashcommerce/paystack"` in a server module and add `api.paystack.co` to `allowedHosts`; see the package README. +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. diff --git a/bun.lock b/bun.lock index 2c16585..3a2dff9 100644 --- a/bun.lock +++ b/bun.lock @@ -82,7 +82,7 @@ "typescript": "^5.9.3", }, "peerDependencies": { - "@dashcommerce/core": "workspace:*", + "@dashcommerce/core": "^0.4.0", }, }, "packages/registry-setup": { diff --git a/packages/paystack/README.md b/packages/paystack/README.md index 68b2843..7ab1293 100644 --- a/packages/paystack/README.md +++ b/packages/paystack/README.md @@ -2,7 +2,7 @@ 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. -> **Status: needs core with the provider-enablement changes** (the companion core PR). Released core 0.3.5 cannot call `api.paystack.co`, save Paystack keys, pass `Paystack-Signature`, or take refund updates. See [Core requirements](#core-requirements). The package is `private` and is not published. +> **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 @@ -11,7 +11,7 @@ A Paystack `PaymentProvider` for DashCommerce. Customers pay on Paystack's hoste | Checkout | `POST /transaction/initialize`, then a redirect to Paystack's hosted page. The reference is `dc-`, 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 `providerEventId` is left empty and core relies on its unique index on the payment reference: a repeat delivery never creates a second order, and Paystack's retry after a failed first delivery still creates it | +| Duplicates | Paystack webhooks carry no event id, so the provider builds one: `charge.success:` and `:` (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-` 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=)` 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 | @@ -42,7 +42,13 @@ Paystack sends no `charge.failed` webhook. A payment that fails or is abandoned ## Use -1. **Register the provider at runtime.** Import the package in a module the server loads before any request, such as `src/middleware.ts`: +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 @@ -50,13 +56,13 @@ Paystack sends no `charge.failed` webhook. A payment that fails or is abandoned 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. -2. **Allow Paystack's API host:** +3. **Allow Paystack's API host:** ```ts emdash({ plugins: [dashcommerce({ allowedHosts: ["api.paystack.co"] })] }); ``` -3. **Choose Paystack and enter its keys** in Settings → Payment provider: +4. **Choose Paystack and enter its keys** in Settings → Payment provider: | Field | Value | |---|---| @@ -67,7 +73,7 @@ Paystack sends no `charge.failed` webhook. A payment that fails or is abandoned 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. -4. **For on-page checkout, load the browser client** in your checkout page's client script, so Vite bundles it: +5. **For on-page checkout, load the browser client** in your checkout page's client script, so Vite bundles it: ```astro