Skip to content

Paystack for Shopware 6 — 0.9.0-beta.1 - #1

Merged
KommandHub merged 43 commits into
mainfrom
develop
Jul 15, 2026
Merged

KommandHub merged 43 commits into
mainfrom
develop

Conversation

@KommandHub

Copy link
Copy Markdown
Collaborator

Summary

Full plugin buildout, brought to a 0.9.0-beta.1 pre-release for internal QA and sandbox/staging validation ahead of a 1.0.0 Shopware Store submission.

Architecture

  • Restructured into a feature-first module layout (Checkout/, Client/, Webhook/, BankVerification/, DataAbstractionLayer/, Setting/, Logging/, Exception/, Util/, Installer/) mirroring Shopware's own plugins.
  • Removed the intermediate hexagonal Application/Domain/Infrastructure layering in favor of one obvious home per class.

Security & correctness (money path)

  • Payment verification now checks status and amount and currency before marking an order paid — the callback reference is attacker-controllable.
  • Fixed a critical bug: webhook refunds silently defaulted to NGN when the order currency wasn't loaded, and could accept a refund exceeding the transaction total. Introduced OrderCurrencyResolver, which fails closed instead of guessing, and added a server-side over-refund cap on both the admin and webhook refund paths.
  • Fixed ApiResource discarding Paystack's JSON error body on 4xx responses (toArray() throws by default) — every status === false branch was unreachable and merchant-facing error messages never surfaced.
  • Timing-safe webhook signature verification (hash_equals, HMAC-SHA512 over the raw body).
  • Added a dedicated paystack.refund admin permission (depends on the order-editor permission) instead of gating refunds on generic order access.

Admin UI

  • Hardened the refund flow: fixed a double-load race, a wrong capture-id bug, a config-load timing race, and per-currency rounding.
  • Migrated the refund modal and empty state to the Meteor component library (mt-number-field, mt-text-field, mt-empty-state); data grids/modals remain on sw-* pending a larger migration.
  • Extracted refund math into a pure, unit-tested refund-calculator.js.

Testing & CI

  • 364 tests, 100% line coverage on the CI-run subset (kernel-dependent tests excluded and run locally via make test).
  • PHPStan level 9 clean; PHP-CS-Fixer clean.
  • Fixed a CI-only PHPStan failure (scanDirectories pointed at a host-only path) and a coverage gate that could never pass (CI only ran unit tests against a 100% threshold measured on the full suite).

Docs & packaging

  • README rewritten as full contributor documentation (architecture, directory map, Docker/Make workflow, security, deployment, roadmap).
  • Corrected changelog/README claims about African currency and language seeding (removed with the migrations that provided it) in all three languages (en-GB, de-DE, fr-FR).
  • composer.json: declared shopware/storefront, moved shopware/fixture-bundle to require-dev, tightened minimum-stability, optimized Packagist keywords, added homepage/support.
  • Versioned 1.0.0 → 0.9.0-beta.1 to accurately reflect pre-release status (namespaces have churned twice; no live/browser validation yet).

Test plan

  • make cs && make analyse && make test green (verified locally throughout)
  • CI green on this PR
  • Manual sandbox checkout → verify → paid
  • Manual admin refund (full + partial) with paystack.refund permission on a restricted role
  • Webhook delivery via tunnel: charge.success recovery, refund.pending/refund.processed
  • shopware-cli extension validate . --full --store-compliance clean (previously confirmed by maintainer)

🤖 Generated with Claude Code

KommandHub added 30 commits June 7, 2026 12:25
- Remove dependency on `kommandhub/foundation-sw` and migrate essential core logic into the Paystack plugin.
- Relocate and reorganize foundation classes:
    - `AbstractEntityReader`, `AbstractEntityWriter`, `OrderTransactionReader`, and `OrderTransactionWriter` moved to `Infrastructure/Shopware/EntityHandler`.
    - `PaymentFinalizedEvent` moved to `Domain/Event`.
- Improve `PaymentMethodInstaller` to skip installation if a method with the same handler or technical name already exists, preventing duplicate errors.
- Integrate foundation migrations for African currencies and languages directly into the plugin.
- Implement comprehensive unit tests for the internalized entity handlers (`AbstractEntityReader`, `AbstractEntityWriter`, etc.) with full logical coverage.
- Fix PHPStan "Dead catch" error in `WebhookController` by adding appropriate `@throws` annotations in the application layer.
- Update `TestBootstrap` and PHPUnit configuration to support the new standalone structure and improve coverage reporting.
- Optimize `docker-compose.yml` for macOS performance using `:delegated` flags and improve volume management for IDE code completion.
- Remove dependency on `kommandhub/foundation-sw` and migrate essential core logic into the Paystack plugin.
- Relocate and reorganize foundation classes:
    - `AbstractEntityReader`, `AbstractEntityWriter`, `OrderTransactionReader`, and `OrderTransactionWriter` moved to `Infrastructure/Shopware/EntityHandler`.
    - `PaymentFinalizedEvent` moved to `Domain/Event`.
- Improve `PaymentMethodInstaller` to skip installation if a method with the same handler or technical name already exists, preventing duplicate errors.
- Integrate foundation migrations for African currencies and languages directly into the plugin.
- Implement comprehensive unit tests for the internalized entity handlers (`AbstractEntityReader`, `AbstractEntityWriter`, etc.) with full logical coverage.
- Fix PHPStan "Dead catch" error in `WebhookController` by adding appropriate `@throws` annotations in the application layer.
- Update `TestBootstrap` and PHPUnit configuration to support the new standalone structure and improve coverage reporting.
- Optimize `docker-compose.yml` for macOS performance using `:delegated` flags and improve volume management for IDE code completion.
Reorganized the codebase to follow a flattened, feature-first module structure as defined in the project guidelines. This improves maintainability and aligns with Shopware plugin best practices.

Key changes:
- Consolidated payment and cart logic under the `Checkout` module.
- Moved Paystack API clients and resources to a dedicated `Client` module.
- Refactored Webhook handling into a flat `Webhook` module, renaming listeners to subscribers.
- Grouped Bank Verification logic into its own module.
- Moved data access logic to `DataAbstractionLayer/OrderTransaction`.
- Centralized cross-cutting concerns (Util, Exception, Installer, Logging, Setting) at the root level.
- Updated all namespaces and imports across production and test code.
- Renamed various services and subscribers for better clarity (e.g., EventListeners to Subscribers).

This refactoring maintains existing functionality while providing a cleaner, more scalable directory structure.
KommandHub and others added 13 commits July 13, 2026 16:30
Server (RefundController):
- require the `order:update` ACL privilege on the refund endpoint
- add a server-side over-refund cap (refundable balance from non-failed
  captures / transaction total minus completed+in-progress refunds) so the
  client-side bound can no longer be bypassed

Admin (Vue):
- gate the refund action on acl.can('order.editor'), the feature flag and a
  positive refundable balance (canRefund)
- fix a double, concurrent capture/refund load (re-entrancy guard + single
  watcher-driven trigger)
- stop sending the transaction id as orderTransactionCaptureId
- load plugin config reactively off the order's sales channel instead of a
  created()-timing race
- round the max refundable amount to the currency's decimals
- remove dead code (debugRefundCalculation) and the unused orderId prop

Refactor:
- extract pure refund math into service/refund-calculator.js (+ spec) and a
  shared util/paystack.js (handler identifier, isAbortError), removing the
  duplicated constants and helpers across the two components

Meteor migration (first slice):
- migrate the refund-modal form controls and the empty state to Meteor
  (mt-number-field, mt-text-field, mt-empty-state); data grids, modals,
  labels and the tab item stay on sw-* (no drop-in Meteor equivalent yet)

Also: add CLAUDE.md, cover over-refund rejection with a test, rebuild the
administration bundle.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Introduced a specific administrative permission `paystack.refund` to allow granular control over who can process refunds through Paystack, independent of general order editing rights.

Key changes:
- Registered `paystack.refund` privilege in the administration under the "Additional permissions" category.
- Updated `RefundController` to enforce the new `paystack.refund` ACL check on the backend.
- Modified the administration frontend to gate the refund action using the new permission.
- Added translation snippets for the new permission label in English, German, and French.
- Integrated the ACL configuration into the main administration entry point.
…dation suite

- Added `validate-plugin` command to Makefile using `shopware-cli`.
- Fixed PHPStan "class.notFound" errors by adding `scanDirectories` to `phpstan.dist.neon` and using `--no-copy` flag.
- Resolved ESLint warnings by removing unused imports in Administration and replacing `HttpClient` with `fetch` in Storefront.
- Updated `WebhookController` and its tests to return and assert `204 No Content` for successful requests.
- Increased test coverage for `TransactionVerificationProcessor` to 100%.
- Added French translation for the plugin changelog (`CHANGELOG_fr-FR.md`).
- Refactored `BankVerificationController` to use explicit constants from `StorefrontController`.
- Rewrite README.md as full contributor documentation: architecture,
  feature-first directory map, Docker/Make workflow, configuration
  options, build/test/CI, security, deployment and contributing. Fixes
  the stale hexagonal structure and the incorrect compatibility table.
- Optimize composer.json keywords for Packagist and search discoverability
  (drop generic/vendor terms, add high-intent Shopware/payment/channel terms).
- Add homepage and support (issues/source/docs) metadata, plus an author
  homepage.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
phpstan.dist.neon pointed scanDirectories at ../../../vendor/shopware/storefront
(the host Shopware install). That path does not exist in CI or in
shopware-cli, where the extension is analysed in an isolated directory, so
PHPStan failed with "Scanned directory .../vendor/shopware/storefront does
not exist".

shopware/storefront is already a declared dependency, so PHPStan resolves
Shopware\Storefront\* through the Composer autoloader once dependencies are
installed. Removed the scanDirectories path. Verified `make analyse` (the CI
command) passes at level 9 with no errors using the locally installed vendor.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
The CI coverage gate is set to 100%, but CI ran only tests/Unit (no Shopware
kernel), which measured 91.85% — the gap being code exercised by the
integration tests. So the gate could never pass.

- CI now runs `phpunit --exclude-group kernel`, which adds the mockable
  integration tests (controllers, payment handler) on top of the unit tests.
- The two integration tests that need a booted kernel + database
  (KommandhubPaystackSWTest, CustomFieldsInstallerTest) are tagged
  `#[Group('kernel')]` and excluded from CI; they still run in the full local
  suite via `make test`.
- The plugin bootstrap class (KommandhubPaystackSW.php) is lifecycle glue that
  can only be reached with a kernel, so it is excluded from the coverage
  metric in phpunit.dist.xml (still covered by the kernel integration test in
  the full suite).

Verified: `phpunit --exclude-group kernel` → 100.00% (1251/1251), gate passes;
full `make test` still green (303 tests).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Remove the plugin's two schema-less data migrations
(Migration1780388405AddAfricanCurrencies, Migration1780389223AddAfricanLanguages)
and the now-empty src/Migration/ directory. Nothing in the codebase or tests
referenced them.

The plugin no longer ships any migrations; payment method and custom fields are
still set up through the install/update lifecycle installers. Note that African
currencies and languages are no longer seeded on install — existing installs are
unaffected, but new installs must add those currencies/languages manually if
required. PaystackCurrencyHelper continues to handle per-currency decimals
independently of the Shopware currency entities.

Update README: replace the "Database Migrations" section with "Data Handling".
- Testing: Achieved 100% unit test coverage for `TransactionVerificationProcessor`, `WebhookProcessor`, and `ConfigurableLogger` by adding edge-case tests.
- Webhook Security: Added amount verification and de-duplication to `WebhookSubscriber` and `RefundInitializeService` to prevent over-refunding and handle redeliveries safely.
- Refund Logic: Improved `RefundInitializeService` to validate refundable amounts against the transaction total and handle synthetic captures.
- Tooling: Updated `.gitignore` to exclude IDE-specific coverage reports and temporary files.
- Refactor: Cleaned up deprecated `setAccessible()` calls in the test suite for PHP 8.1+ compatibility.
The African currency and language migrations were removed in 2693b09, but the
README and both changelogs still advertised that the plugin adds African
currencies and languages to the shop. That is no longer true and would mislead
merchants evaluating the extension.

State what the plugin actually does: it converts amounts correctly for every
currency Paystack supports, including zero-decimal (XOF, RWF) and three-decimal
(KWD) currencies, and it does not create currencies or languages — that stays a
normal shop configuration step. Also document the plugin UI translations
(en-GB, de-DE, fr-FR), which are real and were previously unstated.
…ariants

Both recent critical defects shared one root cause: money code silently
defaulted the currency to NGN when the order association was not loaded,
converting amounts by the wrong power of ten. Six sites resolved currency with
`?? 'NGN'`; four were safe only by accident of their criteria, and
RefundAggregator re-resolved it three times inside nested loops with no control
over its caller.

Introduce OrderCurrencyResolver, which fails closed rather than guessing:
- RefundAggregator throws (and now resolves once, not per loop iteration)
- RefundInitializeService logs and aborts without creating capture/refund
- WebhookSubscriber refuses to finalize the refund
- RefundController returns an error response

No `?? 'NGN'` remains in src/.

Making the code fail closed broke 18 tests whose fixtures never set an
order/currency — they had been passing on the silent default while modelling an
entity graph that cannot exist. Fixtures now build the real association chain,
so a missing association fails loudly.

Add invariant-based tests rather than execution-based ones: minor-unit
round-trip stability and monotonicity across all supported currencies, exact
round-trips per decimal class, the over-refund guard proven in a 0-decimal
currency, and fail-closed coverage for every call site.
ApiResource::response() used $response->toArray(), which throws on any 4xx and
discarded Paystack's response body. Paystack returns errors as a normal JSON
payload — {"status": false, "message": "...", "meta": {"nextStep": "..."}} —
alongside the 4xx status, so every `status === false` branch in this plugin was
unreachable and the merchant-facing message never surfaced. The admin refund UI
even renders errorData.meta.nextStep, which could never populate.

Use toArray(false) so the body always reaches the caller, and wrap genuine
transport failures (DNS, timeout, TLS, non-JSON bodies) in PaystackException so
the client has a coherent error contract.

Document the planned end-to-end test layers in the README roadmap rather than
shipping the suite now.
…tion

The plugin was versioned 1.0.0 despite never having run against a real
Paystack sandbox or live environment, and despite two full namespace
restructures this session. Per the release readiness assessment (74/100):
feature-complete but unproven, with no API stability guarantee yet — that is
a pre-1.0 beta, not a stable release.

Bump composer.json to 0.9.0-beta.1. Update all three changelogs (heading +
pre-release notice) and fix CHANGELOG_fr-FR.md, which had been missed in an
earlier pass and still claimed African currency/language seeding that no
longer exists. Add a "Pre-1.0 status" note to the README explaining the
0.x -> 1.0.0 -> Shopware Store workflow. Update the hardcoded plugin-version
fixtures in the kernel lifecycle test to match.

1.0.0 is reserved for once sandbox/live testing is complete and all critical
issues are resolved.
@KommandHub KommandHub self-assigned this Jul 15, 2026
@KommandHub
KommandHub merged commit 6cb7bd3 into main Jul 15, 2026
2 checks passed
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.

1 participant