Skip to content

feat(paystack): Paystack payment provider package - #85

Merged
cavewebs merged 2 commits into
emdashCommerce:mainfrom
FIKANOVA:feat/paystack-payment-provider
Nov 27, 2026
Merged

cavewebs merged 2 commits into
emdashCommerce:mainfrom
FIKANOVA:feat/paystack-payment-provider

Conversation

@moset15

@moset15 moset15 commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Part of the Paystack set described in #76. Builds on #84.

What

packages/paystack: a PaymentProvider for Paystack on core's provider interface. It covers card and M-Pesa, through Paystack's hosted page or its Popup over the store's checkout, in KES, NGN, GHS, ZAR and USD. It registers itself on import "@dashcommerce/paystack". The README covers setup: allowedHosts: ["api.paystack.co"], keys, webhook URL and the Popup client.

How it behaves

  • Orders: created only from a signed charge.success, confirmed with /transaction/verify before core writes the order. Paystack sends no charge.failed, so a failed or abandoned payment leaves no order.
  • Signatures: each header is checked with the key it is signed with.
    • Paystack-Signature with a whsec_ secret. When it's present, it alone decides, so its 300-second replay window can't be sidestepped by the older header sent with it.
    • Otherwise x-paystack-signature, with an sk_ key saved in either field.
    • In our test run Paystack sent only x-paystack-signature, on an account with a whsec_ secret, so both paths matter.
  • Refunds: by transaction reference, tagged with core's refundRequestId, so a retry returns the existing refund instead of creating a second one. Paystack itself accepts identical duplicates.
    • refund.* webhooks map to refund.updated. Real ones carry the refund id as a string; Paystack's docs don't show it.
  • Refunded before the order exists: Paystack reports reversed after partial refunds too, so for a reversed or reversal-pending payment the package adds up its refunds. One refunded in full is not confirmed, so a late charge.success retry creates no order; a partly refunded one is.
  • Connection check: "Test Paystack connection" makes one read-only call. It reports test or live mode, and whether the key can read transactions.
  • Popup client: ./checkout-client loads js.paystack.co only when the customer presses Pay.

Package

  • Publishable like core: publishConfig.access: public, author "DashCommerce contributors". Minor changeset takes it to 0.1.0.
  • bun.lock gains only the new workspace entry.

Tests

  • 102 tests, including checkout → webhook → order through core's real routes.
  • Full, partial and failed refunds in the refunded-total check.
  • Both signature schemes, including the legacy-only delivery Paystack actually sends, a tampered body, and a stale Paystack-Signature that must not fall back.
  • Every Paystack status mapped, plus the refund duplicate guard.
  • CI steps pass.

End to end in Paystack test mode (20 Nov 2026)

Check Result
Hosted, M-Pesa Paid order
Popup, M-Pesa and card Paid orders; M-Pesa offered in the Popup
Popup closed No order; "Payment not completed. You can try again."
Declined card No order; retry offered
Real delivery, whsec_ saved, only x-paystack-signature sent 200, order created; Paystack's retry of an earlier refused delivery also created its order
Same event again / 400 s old 200 duplicate, one order / 400 outside the window
Refunds Real refund.pending → refund.processed (succeeded) and refund.failed (failed)
Double-clicked refund One refund
Live status of a fully / partly refunded payment Not confirmed ("refunded in full, 160999 of 160999") / confirmed

Screenshots

Paystack's Popup over the store's checkout

Declined test card in the Popup; the customer stays on checkout

Thank-you page after a real Paystack delivery

@cavewebs cavewebs left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HMAC is done the way we asked: SHA-512 of the raw body, Web Crypto, constant-time compare, both Paystack-Signature (whsec_, 300 second window) and x-paystack-signature (sk_). When the current header and a whsec_ secret are present, a stale replay cannot sneak through on the legacy header. Amounts come from the cart, then /transaction/verify, then core's reconcile. ctx.http.fetch only, host api.paystack.co. No extra npm deps. Keeping this as its own package, not inside core, is right.

Please set providerEventId on refund events. You already have data.id. Empty string skips core's event dedup, and two refund.failed deliveries can both reverse the order (#82's pending check is not a lock). Something like refund.failed:19244346 is enough. For charge.success, core's unique index on the payment reference still stops a second order. Now that #81 drops the dedup row on ConfirmationFailure, you could also set charge.success:${reference} so a retry after a down verify still works, and two overlapping deliveries do not both run the handler.

README says the package is private and not published. package.json is public 0.0.0 with a minor changeset. If we merge as-is, the next release will publish @dashcommerce/paystack. Either add "private": true until you mean to ship it, or say in the README that 0.1.0 goes out with this core.

Webhook URL: tell merchants to append ?provider=paystack so a future header clash cannot depend on registry order. stripe-signature already wins for Stripe.

moset15 and others added 2 commits November 24, 2026 01:10
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.
….4.0

- Set providerEventId on refund.* events (`<event>:<refund id>`), so two
  refund.failed deliveries reverse a refund once, and on charge.success
  (`charge.success:<reference>`), 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 <noreply@anthropic.com>
@moset15
moset15 force-pushed the feat/paystack-payment-provider branch from dc2f9e0 to fadc0ef Compare November 24, 2026 02:01
@moset15

moset15 commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. All three points are in fadc0ef, on top of the branch rebased onto main (after #90).

Event ids. Refund events now carry <event>:<refund id>, for example refund.failed:19244346. Each status has its own id, so refund.pending never blocks the later refund.failed. charge.success carries charge.success:<reference>. New tests through core's routes:

  • two refund.failed deliveries at the same time: one runs, one is answered as a duplicate, and the refund is reversed once
  • refund.pending then refund.failed for the same refund: both run
  • two overlapping charge.success deliveries (with a slow verify): Paystack is verified once and one order is created

The existing test where verify is down on the first delivery still passes: ConfirmationFailure releases the record and the retry creates the order. One thing I've written into the README: any other failure keeps the record, as it does for Stripe, so a transient storage error during the order write means the retry is answered as a duplicate. I kept the id for parity with Stripe and because you suggested it. If you'd rather leave charge.success without an id, it's a one-line change.

Tested by hand against Paystack test mode (24 Nov, this branch, EmDash 1.6, webhooks through a tunnel with ?provider=paystack and a whsec_ secret saved):

  • M-Pesa and card checkouts each created one order from the signed charge.success. Paystack sent both Paystack-Signature and x-paystack-signature, and the whsec_ path verified them.
  • Replaying charge.success inside the window returned {"duplicate":true}. Replaying it after five minutes returned 400 ("outside the 300-second window").
  • A partial refund went refund.pending (answered unchanged) → refund.processed 18 minutes later (answered updated, refund succeeded). Replaying that refund.processed returned {"duplicate":true}.
  • A full card refund also went refund.pending → refund.processed (answered updated).
  • I couldn't get Paystack test mode to fail a refund this time, so the double refund.failed case is covered by the route tests above, not by hand.

Publishing. It ships. The README says 0.1.0 goes out with core 0.4.0. I also changed the peer from workspace:* to ^0.4.0. With workspace:*, changeset version bumped this package to 1.0.0, because core's minor bump counts as a peer change. With ^0.4.0, it versions to 0.1.0 next to core 0.4.0. One note for the release: npm publish doesn't rewrite workspace:*, and the devDependency still uses it. That doesn't affect installs, but bun publish writes a cleaner manifest.

Webhook URL. The setup step now says to include ?provider=paystack and why: Paystack webhooks keep reaching Paystack even if another provider later uses the same header name.

Also on the earlier PRs: noted on #84 that client is public. I'll send that docs line, plus the paymentProvider registry check from #81, as small separate PRs.

@moset15

moset15 commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

The follow-ups from this review round are up, so they're ready when you finish here. Each is small, tested and has a changeset.

Any order, independent of #85:

After #85:

At the 0.4.0 / 0.1.0 release:

For discussion only, no action needed now:

@alexasomba

Copy link
Copy Markdown
Contributor

Heads-up for the Paystack package, since subscriptions are the next item in #108:

Core now has a provider-neutral subscription seam in #114 (open, independent). It adds optional getSubscription, cancelSubscription and resumeSubscription to PaymentProvider, a ProviderSubscriptionInfo shape, and a normalised subscription.updated event. The first charge.succeeded that carries subscription creates the order and the local subscription; later charges are recorded as invoices and extend the period, not as new orders. Cancel/resume dispatch to the provider; pause and in-place upgrades are refused unless the provider implements them.

#85 currently declares subscriptions: false and throws on mode: "subscription", which is fine if subscriptions are out of scope for this PR. If you do want them, Paystack's Plans/Subscriptions APIs fit the seam more directly than Flutterwave's plan-id workaround: Paystack returns a real subscription id, so cancel/enable map cleanly. The Flutterwave adapter in #107 is the reference implementation.

No action needed if it is out of scope — just flagging it so the seam is there when you get to the "Subscriptions with Paystack" item. Happy to share the Flutterwave adapter details if useful.

@moset15

moset15 commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

@cavewebs the three points from your review are in fadc0ef (details in my comment above), so I'm re-requesting your review. CI is green and the branch merges cleanly with main.

@alexasomba thanks for the pointer to #114. I'll keep subscriptions out of this PR so it stays small. Paystack Plans fit #114 well, as you say, so Paystack subscriptions will build on it once it lands. They're listed in #108.

@moset15
moset15 requested a review from cavewebs November 25, 2026 16:50
moset15 added a commit to FIKANOVA/dashcommerce that referenced this pull request Nov 26, 2026
[FIK-57] feat(paystack): Paystack payment provider package (fork integration of upstream emdashCommerce#85)
cavewebs added a commit that referenced this pull request Nov 27, 2026
Follow-up from your #84 review. Independent of #85 and of the other
follow-ups; merge in any order.

## Change

`client` in an on-page checkout result is sent to the browser as JSON by
`create-session`. The README's provider-author list now says so, and
that a provider must never put a secret key or webhook secret in it
(Paystack sends only `{ accessCode }`). The same warning is on the
`client` field in `types.ts`.

Docs and a comment only, plus a patch changeset. No behaviour change.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
cavewebs added a commit that referenced this pull request Nov 27, 2026
Found while testing #85. Independent of #85 and of the other follow-ups;
merge in any order.

## Problem

A skipped duplicate webhook logs `Stripe webhook deduped`, whichever
provider sent it. A Paystack shop's log shows `Stripe webhook deduped {
stripeEventId: 'charge.success:dc-…' }`.

## Change

The log reads `Webhook deduped { providerId, eventId, type }`. If anyone
filters logs on the old `stripeEventId` field, it is now `eventId`. The
storage collection and its `stripeEventId` field are unchanged, since
renaming them would need a migration.

## Tested

The existing "skips an exact repeat" test now also checks the log line
and provider. It fails without the change.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
cavewebs added a commit that referenced this pull request Nov 27, 2026
Follow-up from your #81 review. Independent of #85 and of the other
follow-ups; merge in any order.

## Problem

The settings API checks only that `paymentProvider` looks like an id. A
typo (`paystak`) or a provider whose package isn't imported on the
server saves fine, then checkout fails.

## Change

`admin/settings` and `admin/settings/validate` check the value against
the provider registry. An unregistered id gets a 400 under
`errors.paymentProvider`:

> paymentProvider "paystak" is not a registered payment provider.
Registered: stripe, paystack. Import the provider's package in a server
module first.

The schema module still only checks the shape, so the admin bundle
doesn't import the registry. Saves that don't include `paymentProvider`
are unaffected.

## Tested

Two route tests in `provider-credentials-settings.test.ts`: the save
refuses an unregistered id and stores nothing, a registered one still
saves, and the single-field validator flags it too. Both fail without
the change. Core: 317 pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

@cavewebs cavewebs left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the follow-up. The refund providerEventId is in place, and the publish metadata looks right: 0.1.0, public, with a ^0.4.0 peer on core. I'll merge this now.

@cavewebs
cavewebs merged commit 8a55d64 into emdashCommerce:main Nov 27, 2026
11 checks passed
cavewebs added a commit that referenced this pull request Nov 27, 2026
Part of the Flutterwave set described in #97. **Item 2** — a generic
core seam, independent of #85 (Paystack) and #98 (the Flutterwave
package). No Flutterwave code in core.

## Why

Flutterwave Inline, its on-page checkout, is a browser SDK initialised
with the account's **public** key (`FLWPUBK-…`). Core's provider
settings stored only `secretKey` and `webhookSecret`, and a provider has
no KV access, so the server could not hand the browser client the key it
needs.

The shortcut — deriving the public key from the secret key — is not
available. I checked a real test pair: `FLWPUBK_TEST-991d…` and
`FLWSECK_TEST-03d5…` have different hash segments.

## What

- `PaymentProviderCredentials.publicKey` and
`credentialFields.publicKey` (label, prefixes, help).
- `settings:<id>PublicKey` in the settings schema,
`providerCredentialSetting` and `GET admin/settings` `_providers`,
validated against the prefixes the provider declares and masked like the
other credentials.
- A third field in Settings → Payment provider, rendered **only** for a
provider that declares one.
- `loadPaymentProviderCredentials` returns `publicKey` when set.

## What does not change

- Stripe's fields, keys and behaviour.
- Providers that do not declare a public key: their settings row is
byte-for-byte the same, and a `publicKey` value is refused for them (so
a typo cannot save a key nothing reads).
- The secret key and webhook secret are still offered for every
provider, as before.

## Tests

- `provider-credentials-settings.test.ts`: saves and loads the public
key, validates its prefix, refuses one for a provider that does not
declare it, never returns the value (only set/hint), and omits the row
entirely for such a provider.
- 12 tests in that file, 58 across the
provider/credentials/webhook-header files, `tsc --noEmit` clean.
- Changeset: minor for `@dashcommerce/core`.

## Next

Item 3 is
[#100](#100): the
provider declares the field, returns `on_page` with `{ publicKey, txRef,
amount, currency, customer… }`, and ships a `./checkout-client` that
loads `checkout.flutterwave.com/v3.js` only when the customer presses
Pay. The split seams are
[#101](#101) (core)
and [#102](#102)
(Flutterwave). All are open.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants