diff --git a/CHANGELOG.md b/CHANGELOG.md index a01a529..4eafd46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,15 @@ +# 0.9.0-beta.3 + +Third pre-release. Still for internal development, QA and sandbox/staging +testing; not yet submitted to the Shopware Store. + +**Upgrade note: the plugin was renamed.** Its technical name changed from `KommandhubPaystackSW` to `KmhPaystackSW`, so Shopware treats it as a different plugin and `0.9.0-beta.1` / `0.9.0-beta.2` installs are not updated in place. Install `KmhPaystackSW`, re-enter your Paystack API keys and settings (they now live under the `KmhPaystackSW.config.*` domain), and then remove the old plugin. The custom field set and the bank fields were renamed as well (`kmh_paystack_*`); bank details saved by earlier versions are not migrated. + +- Fresh installs are now ready to use: the Paystack payment method is assigned to all sales channels when it is first created, and Sandbox Mode is on by default, so a new install never calls live Paystack until it is switched off. Updating the plugin never re-adds the method to a channel it was removed from. +- A declined card is now recorded as a failed payment instead of a cancelled one. When Paystack sends the customer back without a reference (cancel/back, some failures), the plugin verifies the reference stored at checkout and lets Paystack's real status decide: failed payments fail, abandoned ones are cancelled, successful ones are marked paid, and pending ones stay open. +- A late `charge.success` webhook for an earlier payment attempt is now matched to its order. Every retry overwrites the stored reference, so the order transaction id is also sent in the Paystack metadata and used as a fallback lookup; the payment is still verified with Paystack before the order is marked paid. +- Documentation: first-install behaviour, the requirement that the checkout currency is enabled on your Paystack account, and troubleshooting for sandbox "Insufficient Funds" on large amounts and for Shopware's default status-email wording. + # 0.9.0-beta.2 Second pre-release. Still for internal development, QA and sandbox/staging diff --git a/CHANGELOG_de-DE.md b/CHANGELOG_de-DE.md index 775c733..f677168 100644 --- a/CHANGELOG_de-DE.md +++ b/CHANGELOG_de-DE.md @@ -1,3 +1,15 @@ +# 0.9.0-beta.3 + +Dritte Vorabversion. Weiterhin für interne Entwicklung, QA und Sandbox-/ +Staging-Tests; noch nicht im Shopware Store eingereicht. + +**Hinweis zum Update: Das Plugin wurde umbenannt.** Der technische Name wurde von `KommandhubPaystackSW` in `KmhPaystackSW` geändert. Shopware behandelt es daher als anderes Plugin, und Installationen von `0.9.0-beta.1` / `0.9.0-beta.2` werden nicht direkt aktualisiert. Installieren Sie `KmhPaystackSW`, geben Sie Ihre Paystack-API-Schlüssel und Einstellungen erneut ein (sie liegen jetzt unter der Domain `KmhPaystackSW.config.*`) und entfernen Sie anschließend das alte Plugin. Auch das Zusatzfeld-Set und die Bankfelder wurden umbenannt (`kmh_paystack_*`); von früheren Versionen gespeicherte Bankdaten werden nicht migriert. + +- Neue Installationen sind sofort einsatzbereit: Die Paystack-Zahlungsart wird bei der erstmaligen Anlage allen Verkaufskanälen zugewiesen, und der Sandbox-Modus ist standardmäßig aktiv, sodass eine neue Installation nie die Live-Umgebung von Paystack aufruft, bevor er deaktiviert wird. Ein Plugin-Update fügt die Zahlungsart nie wieder zu einem Verkaufskanal hinzu, aus dem sie entfernt wurde. +- Eine abgelehnte Karte wird jetzt als fehlgeschlagene statt als abgebrochene Zahlung erfasst. Schickt Paystack den Kunden ohne Referenz zurück (Abbruch/Zurück, einige Fehlerfälle), prüft das Plugin die beim Checkout gespeicherte Referenz und lässt den tatsächlichen Paystack-Status entscheiden: fehlgeschlagene Zahlungen schlagen fehl, abgebrochene werden storniert, erfolgreiche als bezahlt markiert und ausstehende bleiben offen. +- Ein verspäteter `charge.success`-Webhook für einen früheren Zahlungsversuch wird nun der Bestellung zugeordnet. Jeder erneute Versuch überschreibt die gespeicherte Referenz; deshalb wird die Bestelltransaktions-ID zusätzlich in den Paystack-Metadaten gesendet und als Ersatz-Suche genutzt. Die Zahlung wird weiterhin bei Paystack verifiziert, bevor die Bestellung als bezahlt markiert wird. +- Dokumentation: Verhalten bei der Erstinstallation, die Anforderung, dass die Checkout-Währung in Ihrem Paystack-Konto aktiviert ist, sowie Hinweise zu „Insufficient Funds" in der Sandbox bei hohen Beträgen und zum Standardtext der Shopware-Statusmails. + # 0.9.0-beta.2 Zweite Vorabversion. Weiterhin für interne Entwicklung, QA und Sandbox-/ diff --git a/CHANGELOG_fr-FR.md b/CHANGELOG_fr-FR.md index 64bc6f6..2b48c9b 100644 --- a/CHANGELOG_fr-FR.md +++ b/CHANGELOG_fr-FR.md @@ -1,3 +1,16 @@ +# 0.9.0-beta.3 + +Troisième version préliminaire. Toujours destinée au développement interne, à +l'assurance qualité et aux tests sandbox/staging ; pas encore soumise au +Shopware Store. + +**Note de mise à jour : le plugin a été renommé.** Son nom technique est passé de `KommandhubPaystackSW` à `KmhPaystackSW` ; Shopware le considère donc comme un autre plugin et les installations de `0.9.0-beta.1` / `0.9.0-beta.2` ne sont pas mises à jour sur place. Installez `KmhPaystackSW`, saisissez à nouveau vos clés API et réglages Paystack (ils se trouvent désormais sous le domaine `KmhPaystackSW.config.*`), puis supprimez l'ancien plugin. L'ensemble de champs personnalisés et les champs bancaires ont aussi été renommés (`kmh_paystack_*`) ; les coordonnées bancaires enregistrées par les versions précédentes ne sont pas migrées. + +- Les nouvelles installations sont immédiatement utilisables : le moyen de paiement Paystack est affecté à tous les canaux de vente lors de sa première création, et le mode sandbox est activé par défaut, de sorte qu'une nouvelle installation n'appelle jamais Paystack en production tant qu'il n'est pas désactivé. Une mise à jour du plugin ne réaffecte jamais le moyen de paiement à un canal dont il a été retiré. +- Une carte refusée est désormais enregistrée comme un paiement échoué et non comme un paiement annulé. Lorsque Paystack renvoie le client sans référence (annulation/retour, certains échecs), le plugin vérifie la référence enregistrée lors de la commande et laisse le statut réel de Paystack décider : les paiements échoués échouent, les paiements abandonnés sont annulés, les paiements réussis sont marqués comme payés et les paiements en attente restent ouverts. +- Un webhook `charge.success` tardif pour une tentative de paiement antérieure est désormais rattaché à sa commande. Chaque nouvelle tentative écrase la référence enregistrée ; l'identifiant de la transaction de commande est donc aussi envoyé dans les métadonnées Paystack et utilisé comme recherche de secours. Le paiement est toujours vérifié auprès de Paystack avant que la commande soit marquée comme payée. +- Documentation : comportement à la première installation, obligation que la devise du paiement soit activée sur votre compte Paystack, et dépannage pour « Insufficient Funds » en sandbox sur les montants élevés et pour le libellé par défaut des e-mails de statut de Shopware. + # 0.9.0-beta.2 Deuxième version préliminaire. Toujours destinée au développement interne, à diff --git a/CLAUDE.md b/CLAUDE.md index 6cc2810..a0acf96 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,4 +1,4 @@ -# KommandhubPaystackSW +# KmhPaystackSW Shopware 6 payment plugin integrating Paystack (cards, bank transfer, USSD) with refunds, webhooks, bank-account verification, and African currency/language @@ -7,7 +7,7 @@ support. PHP namespace root: `Kommandhub\PaystackSW\` → `src/`. ## Commands All commands run inside the Docker dev stack (see `Makefile`). The plugin lives -at `custom/static-plugins/KommandhubPaystackSW` inside a Shopware install. +at `custom/static-plugins/KmhPaystackSW` inside a Shopware install. - `make up` / `make down` — start / tear down the stack - `make test` — PHPUnit (`phpunit.dist.xml`). Filter: `make test FILTER=SomeTest` diff --git a/Makefile b/Makefile index 7b241f9..084bc55 100644 --- a/Makefile +++ b/Makefile @@ -1,16 +1,14 @@ .PHONY: help up down build restart shell plugin-list test test-coverage cs cs-fix analyse fixture-load resync prepare validate-plugin cli changelog zip CONTAINER := shopware -PLUGIN_DIR := custom/static-plugins/KommandhubPaystackSW +PLUGIN_DIR := custom/static-plugins/KmhPaystackSW # Plugins installed via composer STATIC_PLUGINS := \ - kommandhub/foundation-sw:KommandhubFoundationSW \ - kommandhub/paystack-sw:KommandhubPaystackSW + kommandhub/paystack-sw:KmhPaystackSW # Only plugins that should be copied into custom/static-plugins STATIC_COPY_PLUGINS := \ - kommandhub/foundation-sw:KommandhubFoundationSW # This plugin may ship at any stability (see "version" in composer.json), while # the Shopware install it is tested against pins minimum-stability to "stable". diff --git a/README.md b/README.md index 597061f..26be785 100644 --- a/README.md +++ b/README.md @@ -163,9 +163,9 @@ Paystack refund created ──► refund.pending / refund.processed webhooks upd ## Directory Structure ```text -KommandhubPaystackSW/ +KmhPaystackSW/ ├── src/ -│ ├── KommandhubPaystackSW.php # Plugin base class (lifecycle hooks) +│ ├── KmhPaystackSW.php # Plugin base class (lifecycle hooks) │ ├── Administration/ │ │ └── Controller/RefundController.php # Admin refund API endpoint │ ├── BankVerification/ @@ -239,7 +239,7 @@ KommandhubPaystackSW/ ```bash composer require kommandhub/paystack-sw bin/console plugin:refresh -bin/console plugin:install --activate KommandhubPaystackSW +bin/console plugin:install --activate KmhPaystackSW bin/console cache:clear ``` @@ -249,7 +249,9 @@ bin/console cache:clear 2. In the Administration, go to **Extensions → My Extensions → Upload Extension**. 3. Install and activate **Paystack Payment**. -After installation, assign the **Paystack Payment** method to your sales channel under **Settings → Shop → Payment Methods**. +On first installation the **Paystack Payment** method is assigned to all of your sales channels and **Sandbox Mode is on by default**, so a fresh install never talks to live Paystack until you switch it off. The method cannot be used for an order until a secret key is configured. If you only want it on some channels, adjust the assignment in the sales channel settings. Updating the plugin never re-adds the method to a channel you removed it from. + +Paystack only accepts currencies enabled on your Paystack account (for example NGN, GHS, ZAR, KES), and the plugin does not create currencies. Make sure the currency a customer checks out in is both enabled on your Paystack account and added to the sales channel. --- @@ -259,8 +261,8 @@ The repository ships a Docker Compose stack based on [`dockware`](https://dockwa ```bash # 1. Clone the repository -git clone KommandhubPaystackSW -cd KommandhubPaystackSW +git clone KmhPaystackSW +cd KmhPaystackSW # 2. Start the stack (builds the container and prepares the shop) make up @@ -268,12 +270,12 @@ make up # 3. Install and activate the plugin inside the container make shell bin/console plugin:refresh -bin/console plugin:install --activate KommandhubPaystackSW +bin/console plugin:install --activate KmhPaystackSW bin/console cache:clear exit ``` -The plugin directory is mounted at `/var/www/html/custom/static-plugins/KommandhubPaystackSW`; `.git/`, `node_modules/`, and `vendor/` are excluded from the mount. Changes to source files on the host are reflected immediately in the container. +The plugin directory is mounted at `/var/www/html/custom/static-plugins/KmhPaystackSW`; `.git/`, `node_modules/`, and `vendor/` are excluded from the mount. Changes to source files on the host are reflected immediately in the container. Default dockware credentials: @@ -294,7 +296,7 @@ a small [`Dockerfile`](Dockerfile): runs `shopware-cli --version` so a broken install fails the image build rather than the first `make validate-plugin`. Pin it for a reproducible build by passing `--build-arg SHOPWARE_CLI_IMAGE=shopware/shopware-cli:bin@sha256:`. -- **Container**: `kommandhub-paystack-plugin` +- **Container**: `kmh-paystack-plugin` - **PHP**: 8.3 (`XDEBUG_ENABLED` toggle available) - **Persistent volume**: `database` (MySQL data) @@ -345,12 +347,12 @@ make cs-fix && make analyse && make test ## Configuration Options -Configure the plugin under **Extensions → My Extensions → Paystack → Configuration**. Options are stored in Shopware's system configuration under the `KommandhubPaystackSW.config.*` domain and read through `Setting\Service\Config`. +Configure the plugin under **Extensions → My Extensions → Paystack → Configuration**. Options are stored in Shopware's system configuration under the `KmhPaystackSW.config.*` domain and read through `Setting\Service\Config`. | Key | Type | Purpose | | --- | --- | --- | | `apiSecretKey` | password | Live secret key (`sk_live_...`) | -| `enableSandbox` | bool | Use the sandbox/test key instead of live | +| `enableSandbox` | bool | Use the sandbox/test key instead of live (**on by default** for new installs) | | `apiSecretKeySandbox` | password | Test secret key (`sk_test_...`) | | `enableSplitPayment` | bool | Enable Paystack split payments | | `subaccountCode` | text | Split payment subaccount code | @@ -470,7 +472,7 @@ Logging goes through `Logging\ConfigurableLogger`, wired to the `paystack_channe 2. Run: ```bash bin/console plugin:refresh - bin/console plugin:update KommandhubPaystackSW # migrates handler identifier + custom fields + bin/console plugin:update KmhPaystackSW # migrates handler identifier + custom fields bin/console cache:clear ``` 3. Ensure compiled Administration and Storefront assets are built and committed as part of the release. @@ -517,6 +519,16 @@ A single plugin release supports both Shopware 6.6 and 6.7 (`shopware/core: ~6.6 > **Pre-1.0 status:** the plugin is on a `0.x` version while it completes sandbox/staging validation (see [Roadmap](#roadmap)). Namespaces and the public API may still change before `1.0.0`. Once testing is complete and all critical issues are resolved, this will be promoted to `1.0.0` and submitted to the Shopware Store. +### Upgrading from `0.9.0-beta.1` / `0.9.0-beta.2` + +In `0.9.0-beta.3` the plugin's technical name changed from `KommandhubPaystackSW` to `KmhPaystackSW`. Shopware treats a renamed plugin as a different plugin, so existing installs are **not updated in place**: + +1. Install and activate `KmhPaystackSW`. +2. Re-enter your Paystack API keys and settings — they now live under the `KmhPaystackSW.config.*` configuration domain. +3. Remove the old `KommandhubPaystackSW` plugin. + +The custom field set and the bank fields were renamed too (`kmh_paystack_*`); bank details saved by earlier versions are not migrated. Orders and their `paystack_*` transaction fields are unaffected. + --- ## Troubleshooting @@ -525,6 +537,18 @@ A single plugin release supports both Shopware 6.6 and 6.7 (`shopware/core: ~6.6 - Confirm the webhook endpoint is reachable from Paystack and the secret key matches the mode (test vs live). - Check `var/log/` for verification or signature errors. +**Test payments fail with "Insufficient Funds"** +- Paystack's sandbox test cards reject large amounts. Test with small orders (a few hundred in the currency, not hundreds of thousands) — an order of NGN 150 succeeds where NGN 790,000 is declined. + +**Payment fails with "No active channel to process transaction" or "Currency not supported by merchant"** +- The order currency is not enabled on your Paystack account. Enable it in the Paystack dashboard, or have customers check out in a currency your account supports. + +**Status emails say "New document for your order" or contain "he status…"** +- These are Shopware's own default mail templates (they are not shipped by this plugin). Edit them under **Settings → Shop → Email templates** — for example the templates for "Payment status paid / cancelled / open". + +**A payment was made but the order stayed open** +- Paystack's webhook delivers `charge.success` even when the customer never returned to the shop, and the order is then finalized. Orders are matched by the stored reference or, for an earlier retry attempt, by the order transaction id the plugin sends in the Paystack metadata. Check the webhook URL and secret key. + **Plugin not visible in the Administration** ```bash bin/console plugin:refresh diff --git a/composer.json b/composer.json index 96b80a6..e86abb1 100644 --- a/composer.json +++ b/composer.json @@ -2,7 +2,7 @@ "name": "kommandhub/paystack-sw", "description": "Independent, third-party Shopware 6 integration for the Paystack payment gateway: accept secure payments via cards, bank transfers, USSD, and mobile money across Africa. Not affiliated with, endorsed by, or officially connected to Paystack.", "type": "shopware-platform-plugin", - "version": "0.9.0-beta.2", + "version": "0.9.0-beta.3", "license": "Apache-2.0", "keywords": [ "shopware", @@ -22,7 +22,7 @@ "nigeria", "ecommerce" ], - "homepage": "https://github.com/KommandHub/KommandhubPaystackSW", + "homepage": "https://github.com/KommandHub/KmhPaystackSW", "authors": [ { "name": "Kommandhub Limited", @@ -33,9 +33,9 @@ ], "support": { "email": "info@kommandhub.com", - "issues": "https://github.com/KommandHub/KommandhubPaystackSW/issues", - "source": "https://github.com/KommandHub/KommandhubPaystackSW", - "docs": "https://github.com/KommandHub/KommandhubPaystackSW/blob/main/README.md" + "issues": "https://github.com/KommandHub/KmhPaystackSW/issues", + "source": "https://github.com/KommandHub/KmhPaystackSW", + "docs": "https://github.com/KommandHub/KmhPaystackSW/blob/main/README.md" }, "require": { "shopware/core": "~6.6.0 || ~6.7.0", @@ -59,7 +59,7 @@ } }, "extra": { - "shopware-plugin-class": "Kommandhub\\PaystackSW\\KommandhubPaystackSW", + "shopware-plugin-class": "Kommandhub\\PaystackSW\\KmhPaystackSW", "label": { "de-DE": "Paystack-Zahlung von Kommandhub", "en-GB": "Paystack Payment by Kommandhub", diff --git a/docker-compose.yml b/docker-compose.yml index 4cdc17e..4c8ff6e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -5,23 +5,23 @@ services: build: context: . dockerfile: Dockerfile - image: 'kommandhub-paystack-plugin:6.7.8.0' - container_name: kommandhub-paystack-plugin + image: 'kmh-paystack-plugin:6.7.8.0' + container_name: kmh-paystack-plugin environment: - 'XDEBUG_ENABLED=0' - 'PHP_VERSION=8.3' volumes: # ---------------------------------------------------------------------------------------------------------------------------------- # PLUGINS - - "./:/var/www/html/custom/static-plugins/KommandhubPaystackSW" + - "./:/var/www/html/custom/static-plugins/KmhPaystackSW" - "database:/var/lib/mysql" - "./Makefile:/var/www/html/Makefile" # - ".env.test:/var/www/html/.env.test" # ---------------------------------------------------------------------------------------------------------------------------------- # EXCLUDE - - "/var/www/html/custom/static-plugins/KommandhubPaystackSW/.git/" - - "/var/www/html/custom/static-plugins/KommandhubPaystackSW/node_modules/" - - "/var/www/html/custom/static-plugins/KommandhubPaystackSW/vendor/" + - "/var/www/html/custom/static-plugins/KmhPaystackSW/.git/" + - "/var/www/html/custom/static-plugins/KmhPaystackSW/node_modules/" + - "/var/www/html/custom/static-plugins/KmhPaystackSW/vendor/" # ---------------------------------------------------------------------------------------------------------------------------------- volumes: diff --git a/phpunit.dist.xml b/phpunit.dist.xml index 302ef98..92bb854 100644 --- a/phpunit.dist.xml +++ b/phpunit.dist.xml @@ -49,7 +49,7 @@ Shopware kernel. Covered by the @group kernel integration tests in the full suite; excluded here so the no-kernel CI coverage gate reflects code it can actually run. --> - src/KommandhubPaystackSW.php + src/KmhPaystackSW.php diff --git a/src/BankVerification/Controller/BankVerificationController.php b/src/BankVerification/Controller/BankVerificationController.php index 36498a8..48b7902 100644 --- a/src/BankVerification/Controller/BankVerificationController.php +++ b/src/BankVerification/Controller/BankVerificationController.php @@ -139,11 +139,11 @@ public function saveBank(RequestDataBag $data, SalesChannelContext $context, Cus [ 'id' => $customer->getId(), 'customFields' => [ - 'kommandhub_paystack_bank_name' => $data->get('bankName'), - 'kommandhub_paystack_bank_code' => $data->get('bankCode'), - 'kommandhub_paystack_account_number' => $data->get('accountNumber'), - 'kommandhub_paystack_account_name' => $data->get('accountName'), - 'kommandhub_paystack_bvn' => $data->get('bvn'), + 'kmh_paystack_bank_name' => $data->get('bankName'), + 'kmh_paystack_bank_code' => $data->get('bankCode'), + 'kmh_paystack_account_number' => $data->get('accountNumber'), + 'kmh_paystack_account_name' => $data->get('accountName'), + 'kmh_paystack_bvn' => $data->get('bvn'), ], ], ], $context->getContext()); diff --git a/src/Checkout/Payment/Service/FinalizeProcessor.php b/src/Checkout/Payment/Service/FinalizeProcessor.php index 7cf7025..c7cfef9 100644 --- a/src/Checkout/Payment/Service/FinalizeProcessor.php +++ b/src/Checkout/Payment/Service/FinalizeProcessor.php @@ -7,6 +7,7 @@ use Kommandhub\PaystackSW\Checkout\Payment\Enum\PaystackTransactionStatus; use Kommandhub\PaystackSW\Exception\PaymentException; use Kommandhub\PaystackSW\Logging\ConfigurableLogger; +use Kommandhub\PaystackSW\Util\PaystackConstants; use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionEntity; use Shopware\Core\Checkout\Order\OrderEntity; use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionStateHandler; @@ -56,7 +57,7 @@ public function process( // loaded it) to avoid re-hydrating the full association graph. $orderTransaction ??= $this->orderTransactionService->readOneById($transactionId, $context); - $reference = $this->extractReference($request, $transactionId); + [$reference, $returnedWithoutReference] = $this->resolveReference($request, $orderTransaction, $transactionId); if ($this->isAlreadyProcessed($orderTransaction)) { $this->logger->info('[Paystack] Payment already processed.', [ @@ -75,6 +76,20 @@ public function process( ); if (!$this->isSuccessfulVerification($verification)) { + // A redirect that carries no reference is the customer pressing + // cancel/back on Paystack's page; Paystack reports that attempt as + // abandoned. Treat it as a cancellation (the order stays retryable). + // Pending-type statuses are left open, and declined/failed payments + // were already rejected by the verification step above. + if ($returnedWithoutReference + && $this->getVerificationStatus($verification) === PaystackTransactionStatus::ABANDONED->value + ) { + throw PaymentException::customerCanceled( + $transactionId, + 'The payment was abandoned on the Paystack page.' + ); + } + return; } @@ -107,32 +122,51 @@ public function process( } /** - * Extracts the Paystack reference from the request. + * Resolves the Paystack reference to verify. * - * @param Request $request - * @param string $transactionId + * Paystack appends `reference` when the customer pays, but the return after + * pressing cancel/back (and after some failures) arrives without one. In that + * case the reference stored when the payment was initialized is used, so the + * outcome is decided by Paystack's real status rather than guessed. * - * @return string + * @return array{0: string, 1: bool} The reference, and whether the redirect carried none. * - * @throws PaymentException + * @throws PaymentException When neither the request nor the transaction has a reference. */ - private function extractReference(Request $request, string $transactionId): string - { + private function resolveReference( + Request $request, + OrderTransactionEntity $orderTransaction, + string $transactionId + ): array { $reference = $request->query->getString('reference'); - if ($reference === '') { - $this->logger->error('[Paystack] Missing transaction reference.', [ + if ($reference !== '') { + return [$reference, false]; + } + + $customFields = $orderTransaction->getCustomFields() ?? []; + $stored = $customFields[PaystackConstants::FIELD_REFERENCE] ?? ''; + + if (is_string($stored) && $stored !== '') { + $this->logger->info('[Paystack] Redirect carried no reference; verifying the stored one.', [ + ConfigurableLogger::CONTEXT_SALES_CHANNEL_ID => $orderTransaction->getOrder()?->getSalesChannelId(), 'transaction_id' => $transactionId, - 'query' => $request->query->all(), + 'reference' => $stored, ]); - throw PaymentException::customerCanceled( - $transactionId, - 'Payment reference is missing from request.' - ); + return [$stored, true]; } - return $reference; + $this->logger->error('[Paystack] Missing transaction reference.', [ + ConfigurableLogger::CONTEXT_SALES_CHANNEL_ID => $orderTransaction->getOrder()?->getSalesChannelId(), + 'transaction_id' => $transactionId, + 'query' => $request->query->all(), + ]); + + throw PaymentException::customerCanceled( + $transactionId, + 'Payment reference is missing from request.' + ); } /** diff --git a/src/Checkout/Payment/Service/OrderTransactionService.php b/src/Checkout/Payment/Service/OrderTransactionService.php index 99449e0..7e96fc0 100644 --- a/src/Checkout/Payment/Service/OrderTransactionService.php +++ b/src/Checkout/Payment/Service/OrderTransactionService.php @@ -30,13 +30,9 @@ public function __construct( */ public function readOneById(string $transactionId, Context $context): OrderTransactionEntity { - $orderTransaction = $this->orderTransactionReader->readOneById( - $transactionId, - $context, - $this->getCriteria() - ); + $orderTransaction = $this->findOneById($transactionId, $context); - if (!$orderTransaction instanceof OrderTransactionEntity) { + if ($orderTransaction === null) { throw PaymentException::asyncProcessInterrupted( $transactionId, sprintf('Order transaction "%s" could not be found.', $transactionId) @@ -46,6 +42,20 @@ public function readOneById(string $transactionId, Context $context): OrderTrans return $orderTransaction; } + /** + * Loads an order transaction by id, or null when it does not exist. + */ + public function findOneById(string $transactionId, Context $context): ?OrderTransactionEntity + { + $orderTransaction = $this->orderTransactionReader->readOneById( + $transactionId, + $context, + $this->getCriteria() + ); + + return $orderTransaction instanceof OrderTransactionEntity ? $orderTransaction : null; + } + /** * @param Criteria $criteria * @param Context $context diff --git a/src/Checkout/Payment/Service/PayloadBuilder.php b/src/Checkout/Payment/Service/PayloadBuilder.php index dffb88e..cc4f039 100644 --- a/src/Checkout/Payment/Service/PayloadBuilder.php +++ b/src/Checkout/Payment/Service/PayloadBuilder.php @@ -5,6 +5,7 @@ namespace Kommandhub\PaystackSW\Checkout\Payment\Service; use Kommandhub\PaystackSW\Setting\Service\Config; +use Kommandhub\PaystackSW\Util\PaystackConstants; use Kommandhub\PaystackSW\Util\PaystackCurrencyHelper; use Shopware\Core\Checkout\Order\Aggregate\OrderAddress\OrderAddressEntity; use Shopware\Core\Checkout\Order\Aggregate\OrderLineItem\OrderLineItemCollection; @@ -86,7 +87,7 @@ public function build(OrderTransactionEntity $orderTransaction, PaymentTransacti 'currency' => $currency->getIsoCode(), 'email' => $customer->getEmail(), 'callback_url' => $returnUrl, - 'metadata' => $this->buildMetadata($order, $selectedMetaData, (string)$returnUrl), + 'metadata' => $this->buildMetadata($order, $selectedMetaData, (string)$returnUrl, $orderTransaction->getId()), ]; // Only restrict channels when the merchant actually configured a list; @@ -138,10 +139,14 @@ public function build(OrderTransactionEntity $orderTransaction, PaymentTransacti * * @return array */ - private function buildMetadata(OrderEntity $order, array $selectedMetaData, string $returnUrl): array + private function buildMetadata(OrderEntity $order, array $selectedMetaData, string $returnUrl, string $orderTransactionId): array { + // The order transaction id is always sent. Paystack echoes metadata back in + // webhooks, so a late charge.success for an earlier attempt (whose reference + // has since been overwritten by a retry) can still be matched to its order. $metadata = [ 'cancel_action' => $returnUrl, + PaystackConstants::METADATA_ORDER_TRANSACTION_ID => $orderTransactionId, 'custom_fields' => [], ]; @@ -255,12 +260,13 @@ private function buildMetadata(OrderEntity $order, array $selectedMetaData, stri private function formatAddress(OrderAddressEntity $address): string { return sprintf( - '%s %s, %s, %s %s, %s', + '%s %s, %s, %s %s, %s, %s', $address->getFirstName(), $address->getLastName(), $address->getStreet(), $address->getZipcode(), $address->getCity(), + $address->getCountryState() ? $address->getCountryState()->getName() : '', $address->getCountry() ? $address->getCountry()->getName() : '' ); } diff --git a/src/DataAbstractionLayer/OrderTransaction/AbstractEntityReader.php b/src/DataAbstractionLayer/OrderTransaction/AbstractEntityReader.php index 27378a8..d198712 100644 --- a/src/DataAbstractionLayer/OrderTransaction/AbstractEntityReader.php +++ b/src/DataAbstractionLayer/OrderTransaction/AbstractEntityReader.php @@ -166,6 +166,7 @@ public function readOneById( $this->withIds([$id], $criteria), $context ) + ->getEntities() ->first(); return $entity; diff --git a/src/Installer/CustomFieldsInstaller.php b/src/Installer/CustomFieldsInstaller.php index 868300b..ee7a71b 100644 --- a/src/Installer/CustomFieldsInstaller.php +++ b/src/Installer/CustomFieldsInstaller.php @@ -14,7 +14,7 @@ class CustomFieldsInstaller { - private const CUSTOM_FIELDSET_NAME = 'kommandhub_paystack_fieldset'; + private const CUSTOM_FIELDSET_NAME = 'kmh_paystack_fieldset'; private const CUSTOM_FIELDSET = [ 'name' => self::CUSTOM_FIELDSET_NAME, @@ -28,7 +28,7 @@ class CustomFieldsInstaller ], 'customFields' => [ [ - 'name' => 'kommandhub_paystack_bank_name', + 'name' => 'kmh_paystack_bank_name', 'type' => CustomFieldTypes::TEXT, 'config' => [ 'label' => [ @@ -41,7 +41,7 @@ class CustomFieldsInstaller ], ], [ - 'name' => 'kommandhub_paystack_bank_code', + 'name' => 'kmh_paystack_bank_code', 'type' => CustomFieldTypes::TEXT, 'config' => [ 'label' => [ @@ -54,7 +54,7 @@ class CustomFieldsInstaller ], ], [ - 'name' => 'kommandhub_paystack_account_number', + 'name' => 'kmh_paystack_account_number', 'type' => CustomFieldTypes::TEXT, 'config' => [ 'label' => [ @@ -67,7 +67,7 @@ class CustomFieldsInstaller ], ], [ - 'name' => 'kommandhub_paystack_account_name', + 'name' => 'kmh_paystack_account_name', 'type' => CustomFieldTypes::TEXT, 'config' => [ 'label' => [ @@ -80,7 +80,7 @@ class CustomFieldsInstaller ], ], [ - 'name' => 'kommandhub_paystack_bvn', + 'name' => 'kmh_paystack_bvn', 'type' => CustomFieldTypes::TEXT, 'config' => [ 'label' => [ diff --git a/src/Installer/PaymentMethodInstaller.php b/src/Installer/PaymentMethodInstaller.php index 055278b..6fb56a0 100644 --- a/src/Installer/PaymentMethodInstaller.php +++ b/src/Installer/PaymentMethodInstaller.php @@ -11,21 +11,30 @@ use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria; use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter; use Shopware\Core\Framework\Plugin\Util\PluginIdProvider; +use Shopware\Core\System\SalesChannel\SalesChannelCollection; readonly class PaymentMethodInstaller { /** * @param EntityRepository $paymentMethodRepository + * @param EntityRepository $salesChannelRepository */ public function __construct( private EntityRepository $paymentMethodRepository, - private PluginIdProvider $pluginIdProvider + private PluginIdProvider $pluginIdProvider, + private EntityRepository $salesChannelRepository ) { } /** * Installs the Paystack payment method if it doesn't exist. * + * On first creation the method is assigned to the shop's sales channels so + * it is selectable at checkout straight after installation; the cart + * validator keeps it from being used until the API keys are configured. + * An existing method is only refreshed, never re-assigned, so a merchant who + * deliberately removed it from a channel does not get it back on every update. + * * @param string $pluginClass The base class of the plugin * @param Context $context The Shopware context */ @@ -53,13 +62,29 @@ public function install(string $pluginClass, Context $context): void 'name' => 'Pay with Paystack', 'description' => 'Securely pay with card, bank transfer or mobile money via Paystack.', 'pluginId' => $pluginId, - 'technicalName' => 'kommandhub_paystack_payment', + 'technicalName' => 'kmh_paystack_payment', 'afterOrderEnabled' => true, 'active' => true, + 'salesChannels' => $this->getSalesChannelAssignments($context), ], ], $context); } + /** + * Builds the sales channel association payload for every sales channel. + * + * @return list + */ + private function getSalesChannelAssignments(Context $context): array + { + $ids = $this->salesChannelRepository->searchIds(new Criteria(), $context)->getIds(); + + return array_map( + static fn (string $id): array => ['id' => $id], + $ids + ); + } + /** * Activates the Paystack payment method. * @@ -113,7 +138,7 @@ private function getPaymentMethodId(Context $context): ?string { $criteria = new Criteria(); $criteria->addFilter( - new EqualsFilter('technicalName', 'kommandhub_paystack_payment') + new EqualsFilter('technicalName', 'kmh_paystack_payment') ); $paymentId = $this->paymentMethodRepository diff --git a/src/KommandhubPaystackSW.php b/src/KmhPaystackSW.php similarity index 94% rename from src/KommandhubPaystackSW.php rename to src/KmhPaystackSW.php index 511bc9c..46fbf94 100644 --- a/src/KommandhubPaystackSW.php +++ b/src/KmhPaystackSW.php @@ -15,6 +15,7 @@ use Shopware\Core\Framework\Plugin\Context\UninstallContext; use Shopware\Core\Framework\Plugin\Context\UpdateContext; use Shopware\Core\Framework\Plugin\Util\PluginIdProvider; +use Shopware\Core\System\SalesChannel\SalesChannelCollection; use Symfony\Component\Config\FileLocator; use Symfony\Component\Config\Loader\DelegatingLoader; use Symfony\Component\Config\Loader\LoaderResolver; @@ -24,7 +25,7 @@ use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; /** - * Main Shopware plugin class for Kommandhub Paystack integration. + * Main Shopware plugin class for Kmh Paystack integration. * * Responsibilities: * - Registers plugin services (via Symfony container) @@ -32,7 +33,7 @@ * - Creates and maintains Paystack payment method * - Installs custom fields required for integration */ -class KommandhubPaystackSW extends Plugin +class KmhPaystackSW extends Plugin { /** * Allow composer commands during plugin execution. @@ -162,9 +163,13 @@ private function getPaymentMethodInstaller(): PaymentMethodInstaller /** @var PluginIdProvider $pluginIdProvider */ $pluginIdProvider = $this->container->get(PluginIdProvider::class); + /** @var EntityRepository $salesChannelRepo */ + $salesChannelRepo = $this->container->get('sales_channel.repository'); + return new PaymentMethodInstaller( $paymentMethodRepo, - $pluginIdProvider + $pluginIdProvider, + $salesChannelRepo ); } diff --git a/src/Resources/app/administration/src/main.js b/src/Resources/app/administration/src/main.js index 5cfc06e..92487cf 100644 --- a/src/Resources/app/administration/src/main.js +++ b/src/Resources/app/administration/src/main.js @@ -15,18 +15,18 @@ Shopware.Service().register('paystackRefundService', (container) => { import './acl'; import './module/sw-order/page/sw-order-detail' -import './view/kommandhub-paystack-detail' +import './view/kmh-paystack-detail' -Shopware.Module.register('kommandhub-paystack-detail', { +Shopware.Module.register('kmh-paystack-detail', { routeMiddleware(next, currentRoute) { if (currentRoute.name === 'sw.order.detail') { - const paystackRoute = 'kommandhub.paystack.detail'; + const paystackRoute = 'kmh.paystack.detail'; if (!currentRoute.children.some(child => child.name === paystackRoute)) { currentRoute.children.push({ name: paystackRoute, - path: 'kommandhub/paystack', - component: 'kommandhub-paystack-detail', + path: 'kmh/paystack', + component: 'kmh-paystack-detail', meta: { parentPath: 'sw.order.detail', privilege: 'order.viewer', diff --git a/src/Resources/app/administration/src/module/sw-order/page/sw-order-detail/index.js b/src/Resources/app/administration/src/module/sw-order/page/sw-order-detail/index.js index f1899b9..5614ac9 100644 --- a/src/Resources/app/administration/src/module/sw-order/page/sw-order-detail/index.js +++ b/src/Resources/app/administration/src/module/sw-order/page/sw-order-detail/index.js @@ -104,7 +104,7 @@ Shopware.Component.override('sw-order-detail', { if (this.paystackOrder?.salesChannelId) { this.config = await this.systemConfigApiService.getValues( - 'KommandhubPaystackSW.config', + 'KmhPaystackSW.config', this.paystackOrder.salesChannelId ); } diff --git a/src/Resources/app/administration/src/module/sw-order/page/sw-order-detail/sw-order-detail.html.twig b/src/Resources/app/administration/src/module/sw-order/page/sw-order-detail/sw-order-detail.html.twig index cc4f842..5f2f20d 100644 --- a/src/Resources/app/administration/src/module/sw-order/page/sw-order-detail/sw-order-detail.html.twig +++ b/src/Resources/app/administration/src/module/sw-order/page/sw-order-detail/sw-order-detail.html.twig @@ -4,7 +4,7 @@ {% block sw_order_detail_content_tabs_paystack_label %} diff --git a/src/Resources/app/administration/src/snippet/de-DE.json b/src/Resources/app/administration/src/snippet/de-DE.json index 6ef1d1d..93d2a8d 100644 --- a/src/Resources/app/administration/src/snippet/de-DE.json +++ b/src/Resources/app/administration/src/snippet/de-DE.json @@ -1,5 +1,5 @@ { - "kommandhub-paystack-detail": { + "kmh-paystack-detail": { "title": "Paystack", "summary": { "chargedAmount": "Abgerechneter Betrag", diff --git a/src/Resources/app/administration/src/snippet/en-GB.json b/src/Resources/app/administration/src/snippet/en-GB.json index a59f84f..d61c154 100644 --- a/src/Resources/app/administration/src/snippet/en-GB.json +++ b/src/Resources/app/administration/src/snippet/en-GB.json @@ -1,5 +1,5 @@ { - "kommandhub-paystack-detail": { + "kmh-paystack-detail": { "title": "Paystack", "summary": { "chargedAmount": "Charged Amount", diff --git a/src/Resources/app/administration/src/snippet/fr-FR.json b/src/Resources/app/administration/src/snippet/fr-FR.json index 6b07b76..afe5e04 100644 --- a/src/Resources/app/administration/src/snippet/fr-FR.json +++ b/src/Resources/app/administration/src/snippet/fr-FR.json @@ -1,5 +1,5 @@ { - "kommandhub-paystack-detail": { + "kmh-paystack-detail": { "title": "Paystack", "summary": { "chargedAmount": "Montant débité", diff --git a/src/Resources/app/administration/src/view/kommandhub-paystack-detail/icon.png b/src/Resources/app/administration/src/view/kmh-paystack-detail/icon.png similarity index 100% rename from src/Resources/app/administration/src/view/kommandhub-paystack-detail/icon.png rename to src/Resources/app/administration/src/view/kmh-paystack-detail/icon.png diff --git a/src/Resources/app/administration/src/view/kommandhub-paystack-detail/index.js b/src/Resources/app/administration/src/view/kmh-paystack-detail/index.js similarity index 90% rename from src/Resources/app/administration/src/view/kommandhub-paystack-detail/index.js rename to src/Resources/app/administration/src/view/kmh-paystack-detail/index.js index 68c7f8b..66d8d32 100644 --- a/src/Resources/app/administration/src/view/kommandhub-paystack-detail/index.js +++ b/src/Resources/app/administration/src/view/kmh-paystack-detail/index.js @@ -1,5 +1,5 @@ -import template from './kommandhub-paystack-detail.html.twig'; -import './kommandhub-paystack-detail.scss'; +import template from './kmh-paystack-detail.html.twig'; +import './kmh-paystack-detail.scss'; import icon from './icon.png'; import { PAYSTACK_HANDLER_IDENTIFIER, isAbortError } from '../../util/paystack'; import { @@ -11,7 +11,7 @@ import { const { Store, Mixin } = Shopware; const { Criteria } = Shopware.Data; -Shopware.Component.register('kommandhub-paystack-detail', { +Shopware.Component.register('kmh-paystack-detail', { template, mixins: [ @@ -21,7 +21,7 @@ Shopware.Component.register('kommandhub-paystack-detail', { /** @private */ metaInfo() { return { - title: this.$t('kommandhub-paystack-detail.title'), + title: this.$t('kmh-paystack-detail.title'), }; }, @@ -151,28 +151,28 @@ Shopware.Component.register('kommandhub-paystack-detail', { return [ { property: 'amount', - label: 'kommandhub-paystack-detail.summary.chargedAmount', + label: 'kmh-paystack-detail.summary.chargedAmount', primary: true, }, { property: 'reference', - label: 'kommandhub-paystack-detail.grid.reference', + label: 'kmh-paystack-detail.grid.reference', }, { property: 'transactionId', - label: 'kommandhub-paystack-detail.grid.transactionId', + label: 'kmh-paystack-detail.grid.transactionId', }, { property: 'fee', - label: 'kommandhub-paystack-detail.grid.processingFee', + label: 'kmh-paystack-detail.grid.processingFee', }, { property: 'state', - label: 'kommandhub-paystack-detail.grid.state', + label: 'kmh-paystack-detail.grid.state', }, { property: 'verifiedAt', - label: 'kommandhub-paystack-detail.grid.verifiedAt', + label: 'kmh-paystack-detail.grid.verifiedAt', }, ]; }, @@ -186,20 +186,20 @@ Shopware.Component.register('kommandhub-paystack-detail', { return [ { property: 'amount', - label: 'kommandhub-paystack-detail.captures.grid.amount', + label: 'kmh-paystack-detail.captures.grid.amount', primary: true, }, { property: 'state', - label: 'kommandhub-paystack-detail.captures.grid.state', + label: 'kmh-paystack-detail.captures.grid.state', }, { property: 'externalReference', - label: 'kommandhub-paystack-detail.captures.grid.externalReference', + label: 'kmh-paystack-detail.captures.grid.externalReference', }, { property: 'createdAt', - label: 'kommandhub-paystack-detail.captures.grid.createdAt', + label: 'kmh-paystack-detail.captures.grid.createdAt', }, ]; }, @@ -213,24 +213,24 @@ Shopware.Component.register('kommandhub-paystack-detail', { return [ { property: 'amount', - label: 'kommandhub-paystack-detail.refunds.grid.amount', + label: 'kmh-paystack-detail.refunds.grid.amount', primary: true, }, { property: 'state', - label: 'kommandhub-paystack-detail.refunds.grid.state', + label: 'kmh-paystack-detail.refunds.grid.state', }, { property: 'externalReference', - label: 'kommandhub-paystack-detail.refunds.grid.externalReference', + label: 'kmh-paystack-detail.refunds.grid.externalReference', }, { property: 'reason', - label: 'kommandhub-paystack-detail.refunds.grid.reason', + label: 'kmh-paystack-detail.refunds.grid.reason', }, { property: 'createdAt', - label: 'kommandhub-paystack-detail.refunds.grid.createdAt', + label: 'kmh-paystack-detail.refunds.grid.createdAt', }, ]; }, @@ -313,7 +313,7 @@ Shopware.Component.register('kommandhub-paystack-detail', { * @returns {Boolean} */ refundEnabled() { - return this.config['KommandhubPaystackSW.config.refundEnabled'] !== false; + return this.config['KmhPaystackSW.config.refundEnabled'] !== false; }, /** * Returns the minimum refund amount for Paystack (in minor units). @@ -321,7 +321,7 @@ Shopware.Component.register('kommandhub-paystack-detail', { * @returns {Number} */ minPaystackRefundAmount() { - return this.config['KommandhubPaystackSW.config.minimumRefundAmount'] ?? 50; + return this.config['KmhPaystackSW.config.minimumRefundAmount'] ?? 50; }, /** * Returns the minimum refund amount in major units. @@ -373,7 +373,7 @@ Shopware.Component.register('kommandhub-paystack-detail', { */ async loadConfig(salesChannelId) { this.config = await this.systemConfigApiService.getValues( - 'KommandhubPaystackSW.config', + 'KmhPaystackSW.config', salesChannelId ); }, @@ -509,7 +509,7 @@ Shopware.Component.register('kommandhub-paystack-detail', { onConfirmRefund() { if (this.refundAmount < this.minRefundableAmount) { this.createNotificationError({ - message: this.$t('kommandhub-paystack-detail.refund.errorAmountTooLow', { + message: this.$t('kmh-paystack-detail.refund.errorAmountTooLow', { minAmount: this.currencyFilter(this.minRefundableAmount, this.refundCurrency), }), }); @@ -518,7 +518,7 @@ Shopware.Component.register('kommandhub-paystack-detail', { if (this.refundAmount > this.maxRefundableAmount) { this.createNotificationError({ - message: this.$t('kommandhub-paystack-detail.refund.errorAmountTooHigh', { + message: this.$t('kmh-paystack-detail.refund.errorAmountTooHigh', { maxAmount: this.currencyFilter(this.maxRefundableAmount, this.refundCurrency), }), }); diff --git a/src/Resources/app/administration/src/view/kommandhub-paystack-detail/kommandhub-paystack-detail.html.twig b/src/Resources/app/administration/src/view/kmh-paystack-detail/kmh-paystack-detail.html.twig similarity index 62% rename from src/Resources/app/administration/src/view/kommandhub-paystack-detail/kommandhub-paystack-detail.html.twig rename to src/Resources/app/administration/src/view/kmh-paystack-detail/kmh-paystack-detail.html.twig index 4a70c7f..eee0d86 100644 --- a/src/Resources/app/administration/src/view/kommandhub-paystack-detail/kommandhub-paystack-detail.html.twig +++ b/src/Resources/app/administration/src/view/kmh-paystack-detail/kmh-paystack-detail.html.twig @@ -1,83 +1,83 @@ {% block sw_order_document_card %} - {% block kommandhub_paystack_detail_card %} + {% block kmh_paystack_detail_card %} - {% block kommandhub_paystack_detail_card_banner %} - {% block kommandhub_paystack_detail_card_banner_wrapper %} + {% block kmh_paystack_detail_card_banner %} + {% block kmh_paystack_detail_card_banner_wrapper %}
- {% block kommandhub_paystack_detail_card_banner_icon %} + {% block kmh_paystack_detail_card_banner_icon %} Paystack logo {% endblock %} - {% block kommandhub_paystack_detail_card_banner_title %} -

- {{ $t('kommandhub-paystack-detail.header') }} + {% block kmh_paystack_detail_card_banner_title %} +

+ {{ $t('kmh-paystack-detail.header') }}

{% endblock %}
{% endblock %} {% endblock %} - {% block kommandhub_paystack_detail_card_grid %} + {% block kmh_paystack_detail_card_grid %}