From 296d7eba177f3fcd7746b80a23f84ea4380b84ad Mon Sep 17 00:00:00 2001 From: Anitche Chisom Date: Sun, 7 Jun 2026 12:25:56 +0200 Subject: [PATCH 01/49] Update --- Dockerfile | 16 - Makefile | 240 ++++----- composer.json | 38 +- docker-compose.yml | 12 +- .../Payment/PaystackPaymentHandler.php | 465 +++++++++++------- src/Contracts/HttpClientInterface.php | 46 ++ src/Event/PaystackPaymentFinalizedEvent.php | 12 + src/Exceptions/PaystackException.php | 12 + src/KommandhubPaystackSW.php | 2 +- src/Resources/config/config.xml | 161 +++++- src/Resources/config/services.yml | 22 +- src/Service/Http/PaystackHttpClient.php | 123 +++++ src/Service/OrderTransactionService.php | 31 +- src/Service/PayloadBuilder.php | 155 +++++- src/Service/PaymentFinalizedEventService.php | 47 ++ src/Service/Paystack.php | 120 +++++ src/Service/PaystackFactory.php | 48 -- src/Service/Resources/ApiResource.php | 28 ++ src/Service/Resources/Customer.php | 62 +++ src/Service/Resources/Miscellaneous.php | 50 ++ src/Service/Resources/Plan.php | 62 +++ src/Service/Resources/Refund.php | 50 ++ src/Service/Resources/Settlement.php | 37 ++ src/Service/Resources/Split.php | 86 ++++ src/Service/Resources/Subaccount.php | 61 +++ src/Service/Resources/Subscription.php | 98 ++++ src/Service/Resources/Transaction.php | 61 +++ src/Service/Resources/Transfer.php | 74 +++ src/Service/Resources/Verification.php | 41 ++ src/Service/TransactionService.php | 3 +- .../Payment/PaystackPaymentHandlerTest.php | 122 ++++- .../Setup/config/packages/test/shopware.yaml | 9 - tests/TestBootstrap.php | 8 +- tests/TestBootstrapper.php | 197 ++++++++ .../Service/OrderTransactionServiceTest.php | 75 +++ tests/Unit/Service/PayloadBuilderTest.php | 89 +++- .../PaymentFinalizedEventServiceTest.php | 34 ++ tests/Unit/Service/PaystackFactoryTest.php | 59 --- tests/Unit/Service/TransactionServiceTest.php | 4 +- tests/bootstrap.php | 1 + 40 files changed, 2354 insertions(+), 507 deletions(-) delete mode 100644 Dockerfile create mode 100644 src/Contracts/HttpClientInterface.php create mode 100644 src/Event/PaystackPaymentFinalizedEvent.php create mode 100644 src/Exceptions/PaystackException.php create mode 100644 src/Service/Http/PaystackHttpClient.php create mode 100644 src/Service/PaymentFinalizedEventService.php create mode 100644 src/Service/Paystack.php delete mode 100644 src/Service/PaystackFactory.php create mode 100644 src/Service/Resources/ApiResource.php create mode 100644 src/Service/Resources/Customer.php create mode 100644 src/Service/Resources/Miscellaneous.php create mode 100644 src/Service/Resources/Plan.php create mode 100644 src/Service/Resources/Refund.php create mode 100644 src/Service/Resources/Settlement.php create mode 100644 src/Service/Resources/Split.php create mode 100644 src/Service/Resources/Subaccount.php create mode 100644 src/Service/Resources/Subscription.php create mode 100644 src/Service/Resources/Transaction.php create mode 100644 src/Service/Resources/Transfer.php create mode 100644 src/Service/Resources/Verification.php delete mode 100644 tests/Setup/config/packages/test/shopware.yaml create mode 100644 tests/TestBootstrapper.php create mode 100644 tests/Unit/Service/OrderTransactionServiceTest.php create mode 100644 tests/Unit/Service/PaymentFinalizedEventServiceTest.php delete mode 100644 tests/Unit/Service/PaystackFactoryTest.php diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 197a2dd..0000000 --- a/Dockerfile +++ /dev/null @@ -1,16 +0,0 @@ -FROM dockware/shopware:6.7.8.0 - -USER root - -# Install useful tools (optional) -RUN apt-get update && \ - apt-get install -y make nano build-essential php-pear php-dev && \ - echo "extension=pcov.so" > /etc/php/8.3/cli/conf.d/20-pcov.ini && \ - echo "pcov.enabled=1" >> /etc/php/8.3/cli/conf.d/20-pcov.ini && \ - echo "pcov.directory=/var/www/html/custom/plugins/KommandhubPaystackSW/src" >> /etc/php/8.3/cli/conf.d/20-pcov.ini && \ - apt-get clean && \ - rm -rf /var/lib/apt/lists/* - -# Set proper permissions -RUN chown -R www-data:www-data /var/www/html && \ - chmod -R 755 /var/www/html diff --git a/Makefile b/Makefile index c66fb9d..350e7fa 100644 --- a/Makefile +++ b/Makefile @@ -1,154 +1,130 @@ -.SILENT: -.PHONY: help up up-quick down build wait-for-container prepare test test-coverage cs cs-fix analyse shell logs status restart clean clean-all info - -## Color -COLOR_RESET=\033[0m -COLOR_INFO=\033[32m -COLOR_COMMENT=\033[33m - -# Configuration Variable -CONTAINER_NAME ?= kommandhub-paystack-shopware -PLUGIN_NAME ?= KommandhubPaystackSW -PLUGIN_REL_PATH := custom/plugins/$(PLUGIN_NAME) - -# Determine the absolute path to the plugin directory -PLUGIN_ABS_PATH := $(shell cd $(dir $(lastword $(MAKEFILE_LIST))) && pwd) -PROJECT_ROOT := $(shell cd $(PLUGIN_ABS_PATH)/../../.. && pwd) - -# Detect if we're running inside Docker container -IS_DOCKER := $(shell test -f /.dockerenv && echo true || echo false) -DOCKER_RUN := $(if $(filter true,$(IS_DOCKER)),,docker exec $(CONTAINER_NAME)) - -# Path inside container (assuming standard Shopware layout) -CONTAINER_PLUGIN_DIR := /var/www/html/$(PLUGIN_REL_PATH) +.PHONY: help up down build restart shell plugin-list test test-coverage cs cs-fix analyse fixture-load resync prepare + +CONTAINER := shopware +PLUGIN_DIR := custom/static-plugins/KommandhubPaystackSW + +# Plugins installed via composer +STATIC_PLUGINS := \ + kommandhub/foundation-sw:KommandhubFoundationSW \ + kommandhub/paystack-sw:KommandhubPaystackSW + +# Only plugins that should be copied into custom/static-plugins +STATIC_COPY_PLUGINS := \ + kommandhub/foundation-sw:KommandhubFoundationSW + +# Composer install list (includes all) +COMPOSER_PLUGINS := $(foreach p,$(STATIC_PLUGINS),$(word 1,$(subst :, ,$(p)))) + +define CHECK_READY +@if [ -z "$$(docker compose ps $(CONTAINER) --status running --quiet)" ]; then \ + echo "Error: Container '$(CONTAINER)' is not running. Please run 'make up' first."; \ + exit 1; \ +fi; \ +HEALTH=$$(docker compose ps $(CONTAINER) --format '{{.Health}}'); \ +if [ "$$HEALTH" != "healthy" ] && [ -n "$$HEALTH" ]; then \ + echo "Waiting for container '$(CONTAINER)' to be healthy..."; \ + while [ "$$(docker compose ps $(CONTAINER) --format '{{.Health}}')" != "healthy" ]; do \ + printf "."; \ + sleep 1; \ + done; \ + echo " Ready!"; \ +fi +endef + +define EXEC +docker compose exec $(CONTAINER) bash -c "$(1)" +endef + +define EXEC_IN_PLUGIN +$(call EXEC,cd $(PLUGIN_DIR) && $(1)) +endef help: @echo "Available commands:" - @echo " make up - Start containers and install tools" - @echo " make up-quick - Start containers only" - @echo " make down - Stop containers" - @echo " make build - Rebuild containers" - @echo " make prepare - Prepare test environment" - @echo " make test - Run PHPUnit tests" - @echo " make test-coverage- Run tests with coverage" - @echo " make cs - Run code style checks" - @echo " make cs-fix - Fix code style issues" - @echo " make analyse - Run PHPStan analysis" - @echo " make shell - Open shell in container" - @echo " make clean - Clean build artifacts" - @echo " make clean-all - Clean everything" - @echo "" - @echo "Configuration:" - @echo " CONTAINER_NAME=$(CONTAINER_NAME)" - @echo " PLUGIN_NAME=$(PLUGIN_NAME)" - @echo " PLUGIN_ABS_PATH=$(PLUGIN_ABS_PATH)" - @echo " Running in container: $(IS_DOCKER)" - -up: up-quick wait-for-container - @echo "✅ Container $(CONTAINER_NAME) is ready!" - -up-quick: - @echo "Starting Docker container $(CONTAINER_NAME)..." - docker-compose up -d --build - -wait-for-container: - @echo "Waiting for container $(CONTAINER_NAME) to be ready..." - @for i in 1 2 3 4 5; do \ - if docker ps --filter name=$(CONTAINER_NAME) --filter status=running | grep -q $(CONTAINER_NAME); then \ - echo "Container $(CONTAINER_NAME) is running!"; \ - break; \ - fi; \ - echo "Waiting... (attempt $$i)"; \ - sleep 5; \ - if [ $$i -eq 5 ]; then \ - echo "❌ Container $(CONTAINER_NAME) failed to start"; \ - exit 1; \ - fi; \ - done + @echo " up - Start the shopware container" + @echo " down - Stop the shopware container" + @echo " build - Rebuild the shopware container" + @echo " restart - Restart the environment" + @echo " shell - Open a shell session in the shopware container" + @echo " plugin-list - List all plugins" + @echo " test - Run phpunit tests" + @echo " test-coverage - Run phpunit tests with coverage report" + @echo " cs - Run php-cs-fixer checks" + @echo " cs-fix - Run php-cs-fixer fix" + @echo " analyse - Run phpstan analysis" + @echo " fixture-load - Load fixtures" + @echo " resync - Sync config directory into the root project" + @echo " prepare - Full project preparation" + +up: + docker compose up -d --build + $(MAKE) prepare down: - docker-compose down + docker compose down -v build: - docker-compose build + docker compose build -prepare: - @echo "Preparing test environment..." - rm -rf vendor/ - composer require --dev shopware/dev-tools --no-interaction --optimize-autoloader - cd $(PLUGIN_DIR) - rm -rf vendor/ - composer install --no-interaction --optimize-autoloader - cd - - rsync -rq /var/www/html/$(PLUGIN_DIR)/tests/Setup/config config/ - @echo "✅ Test environment is ready!" +restart: down up + +shell: + $(CHECK_READY) + docker compose exec $(CONTAINER) bash + +plugin-list: + $(CHECK_READY) + docker compose exec $(CONTAINER) bin/console plugin:list test: - @echo "Running PHPUnit tests..." - $(DOCKER_RUN) bash -c "cd $(CONTAINER_PLUGIN_DIR) && PROJECT_ROOT=/var/www/html ./vendor/bin/phpunit \ - --testdox \ - --configuration=. \ - --colors=always \ - ${FILTER}" + $(CHECK_READY) + $(call EXEC_IN_PLUGIN,php ../../../bin/phpunit -c phpunit.dist.xml --testdox --color=always $${FILTER}) test-coverage: - @echo "Running tests with coverage..." - $(DOCKER_RUN) bash -c "cd $(CONTAINER_PLUGIN_DIR) && PROJECT_ROOT=/var/www/html ./vendor/bin/phpunit --testdox \ - --coverage-html build/coverage \ - --coverage-text \ - --configuration=. \ - --coverage-clover build/logs/clover.xml \ - --coverage-cobertura build/logs/cobertura.xml \ - --colors=always \ - ${FILTER}" + $(CHECK_READY) + $(call EXEC_IN_PLUGIN,php ../../../bin/phpunit -c phpunit.dist.xml --coverage-text --color=always) cs: - @echo "Running code style checks..." - $(DOCKER_RUN) bash -c "cd $(CONTAINER_PLUGIN_DIR) && PROJECT_ROOT=/var/www/html ./vendor/bin/php-cs-fixer fix --dry-run --diff" + $(CHECK_READY) + $(call EXEC_IN_PLUGIN,./vendor/bin/php-cs-fixer fix --dry-run --diff) cs-fix: - @echo "Fixing code style issues..." - $(DOCKER_RUN) bash -c "cd $(CONTAINER_PLUGIN_DIR) && PROJECT_ROOT=/var/www/html ./vendor/bin/php-cs-fixer fix" + $(CHECK_READY) + $(call EXEC_IN_PLUGIN,./vendor/bin/php-cs-fixer fix) analyse: - @echo "Running PHPStan analysis..." - $(DOCKER_RUN) bash -c "cd $(CONTAINER_PLUGIN_DIR) && PROJECT_ROOT=/var/www/html ./vendor/bin/phpstan analyse src -c phpstan.dist.neon --memory-limit=1G" - -shell: - @if [ "$(IS_DOCKER)" = "true" ]; then \ - echo "Already in container. Starting bash..."; \ - bash; \ - else \ - echo "Opening shell in container $(CONTAINER_NAME)..."; \ - docker exec -it $(CONTAINER_NAME) bash; \ - fi - -logs: - docker-compose logs -f + $(CHECK_READY) + $(call EXEC_IN_PLUGIN,./vendor/bin/phpstan analyse src -c phpstan.dist.neon --memory-limit=1G) -status: - docker-compose ps +fixture-load: + $(CHECK_READY) + docker compose exec $(CONTAINER) bin/console fixture:load --no-interaction -restart: down up +resync: + @echo "Resyncing config directory..." + $(CHECK_READY) + docker compose exec $(CONTAINER) cp -R $(PLUGIN_DIR)/tests/Setup/config/. config/ -clean: - @echo "Cleaning build artifacts..." - @if [ "$(IS_DOCKER)" = "true" ]; then \ - rm -rf build/ vendor/ composer.lock; \ - else \ - docker exec $(CONTAINER_NAME) bash -c "cd $(CONTAINER_PLUGIN_DIR) && rm -rf build/ vendor/ composer.lock"; \ - fi - -clean-all: down - @echo "Cleaning everything..." - docker-compose down -v - rm -rf build/ vendor/ composer.lock - -info: - @echo "Current Configuration:" - @echo " Container Name: $(CONTAINER_NAME)" - @echo " Plugin Directory: $(PLUGIN_DIR)" - @echo " Running in container: $(IS_DOCKER)" +prepare: @echo "" - @echo "Running containers:" - @docker ps --filter name=$(CONTAINER_NAME) 2>/dev/null || echo "Docker not available" \ No newline at end of file + @echo "Preparing the project..." + $(CHECK_READY) + + docker compose exec $(CONTAINER) rm -rf custom/plugins/* + + @echo "Installing required plugins via composer..." + docker compose exec $(CONTAINER) composer require $(COMPOSER_PLUGINS) --no-interaction + + @echo "Copying vendor plugins to static-plugins (excluding main plugin)..." + @$(foreach plugin,$(STATIC_COPY_PLUGINS), \ + VENDOR_DIR=$(word 1,$(subst :, ,$(plugin))); \ + TARGET_DIR=$(word 2,$(subst :, ,$(plugin))); \ + echo " $$VENDOR_DIR -> $$TARGET_DIR"; \ + docker compose exec $(CONTAINER) mkdir -p custom/static-plugins/$$TARGET_DIR; \ + docker compose exec $(CONTAINER) cp -R vendor/$$VENDOR_DIR/. custom/static-plugins/$$TARGET_DIR/; \ + ) + + @echo "Installing plugin dependencies..." + $(call EXEC_IN_PLUGIN,composer install --no-interaction) + + # $(MAKE) resync diff --git a/composer.json b/composer.json index 40f499c..09a81e6 100644 --- a/composer.json +++ b/composer.json @@ -15,16 +15,6 @@ "africa", "kommandhub" ], - "autoload": { - "psr-4": { - "Kommandhub\\PaystackSW\\": "src/" - } - }, - "autoload-dev": { - "psr-4": { - "Kommandhub\\PaystackSW\\Tests\\": "tests/" - } - }, "authors": [ { "name": "Kommandhub Limited", @@ -33,8 +23,9 @@ } ], "require": { + "kommandhub/foundation-sw": "^1.0.1", "shopware/core": "~6.6.0 || ~6.7.0", - "kommandhub/paystack": "^1.0" + "shopware/fixture-bundle": "^0.1.0" }, "require-dev": { "phpunit/phpunit": "^11.5", @@ -43,6 +34,16 @@ "phpstan/phpstan": "^2.1", "rregeer/phpunit-coverage-check": "^0.3.1" }, + "autoload": { + "psr-4": { + "Kommandhub\\PaystackSW\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Kommandhub\\PaystackSW\\Tests\\": "tests/" + } + }, "extra": { "shopware-plugin-class": "Kommandhub\\PaystackSW\\KommandhubPaystackSW", "label": { @@ -54,11 +55,22 @@ "de-DE": "Integriert die Paystack-Zahlungs-Gateway in Shopware 6.", "en-GB": "Integrates the Paystack payment gateway into Shopware 6.", "fr-FR": "Intègre la passerelle de paiement Paystack dans Shopware 6." + }, + "manufacturerLink": { + "de-DE": "https://kommandhub.com", + "en-GB": "https://kommandhub.com" + }, + "supportLink": { + "de-DE": "https://kommandhub.com/support", + "en-GB": "https://kommandhub.com/support" } }, "config": { "allow-plugins": { "symfony/runtime": true - } - } + }, + "sort-packages": true + }, + "minimum-stability": "dev", + "prefer-stable": true } diff --git a/docker-compose.yml b/docker-compose.yml index a26e459..11b6b7e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,22 +1,22 @@ services: shopware: - build: ./ - container_name: kommandhub-paystack-shopware + image: 'dockware/shopware:6.7.8.0' + container_name: kommandhub-paystack-plugin environment: - 'XDEBUG_ENABLED=0' - 'PHP_VERSION=8.3' volumes: # ---------------------------------------------------------------------------------------------------------------------------------- # PLUGINS - - "./:/var/www/html/custom/plugins/KommandhubPaystackSW" + - "./:/var/www/html/custom/static-plugins/KommandhubPaystackSW" - "database:/var/lib/mysql" - "./Makefile:/var/www/html/Makefile" # - ".env.test:/var/www/html/.env.test" # ---------------------------------------------------------------------------------------------------------------------------------- # EXCLUDE - - "/var/www/html/custom/plugins/KommandhubPaystackSW/.git/" - - "/var/www/html/custom/plugins/KommandhubPaystackSW/node_modules/" - - "/var/www/html/custom/plugins/KommandhubPaystackSW/vendor/" + - "/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/" # ---------------------------------------------------------------------------------------------------------------------------------- volumes: diff --git a/src/Checkout/Payment/PaystackPaymentHandler.php b/src/Checkout/Payment/PaystackPaymentHandler.php index 7eacfa4..5a8b01b 100644 --- a/src/Checkout/Payment/PaystackPaymentHandler.php +++ b/src/Checkout/Payment/PaystackPaymentHandler.php @@ -4,15 +4,18 @@ namespace Kommandhub\PaystackSW\Checkout\Payment; -use Kommandhub\Paystack\Exceptions\PaystackException; -use Kommandhub\PaystackSW\Util\PaystackConstants; +use DateTimeImmutable; use Kommandhub\PaystackSW\Service\Config; +use Kommandhub\PaystackSW\Exceptions\PaystackException; use Kommandhub\PaystackSW\Service\OrderTransactionService; use Kommandhub\PaystackSW\Service\PayloadBuilder; +use Kommandhub\PaystackSW\Service\PaymentFinalizedEventService; use Kommandhub\PaystackSW\Service\TransactionService; +use Kommandhub\PaystackSW\Util\PaystackConstants; use Psr\Log\LoggerInterface; use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionEntity; use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionStateHandler; +use Shopware\Core\Checkout\Order\OrderEntity; use Shopware\Core\Checkout\Payment\Cart\PaymentTransactionStruct; use Shopware\Core\Checkout\Payment\PaymentException; use Shopware\Core\Framework\Context; @@ -21,12 +24,9 @@ use Symfony\Component\HttpFoundation\Request; /** - * PaystackPaymentHandler is responsible for handling payment transactions with Paystack in a Shopware environment. - * - * This class implements the necessary methods to initialize payments, handle callbacks from Paystack, and update - * the order transaction state accordingly. It also manages custom fields to store Paystack transaction details. + * Handles Paystack payment initialization and finalization. */ -class PaystackPaymentHandler extends AbstractPaystackPaymentHandler +final class PaystackPaymentHandler extends AbstractPaystackPaymentHandler { public function __construct( private readonly OrderTransactionService $orderTransactionService, @@ -34,228 +34,349 @@ public function __construct( private readonly PayloadBuilder $payloadBuilder, private readonly OrderTransactionStateHandler $transactionStateHandler, private readonly Config $config, + private readonly PaymentFinalizedEventService $paymentFinalizedEventService, private readonly LoggerInterface $logger ) { } /** - * Initializes the payment process by preparing the payload and redirecting to Paystack's checkout page. - * - * @param Request $request The HTTP request object containing request data. - * @param PaymentTransactionStruct $transaction The payment transaction struct from Shopware. - * @param Context $context The Shopware context for the operation. - * @param Struct|null $validateStruct Optional struct for additional validation (not used in this implementation). + * Initializes a Paystack payment session. * - * @return RedirectResponse|null A redirect response to Paystack's checkout page or null if initialization fails. - * - * @throws PaymentException If there is an error during payment initialization or communication with Paystack. + * @throws PaymentException */ - public function pay(Request $request, PaymentTransactionStruct $transaction, Context $context, ?Struct $validateStruct): ?RedirectResponse - { - // 1. Retrieve the full order transaction entity including associated order and customer data. - $orderTransaction = $this->orderTransactionService->get($transaction->getOrderTransactionId(), $context); + public function pay( + Request $request, + PaymentTransactionStruct $transaction, + Context $context, + ?Struct $validateStruct + ): RedirectResponse { + $transactionId = $transaction->getOrderTransactionId(); + + $orderTransaction = $this->orderTransactionService->get( + $transactionId, + $context + ); try { - // 2. Prepare the payment payload for Paystack initialization. - $payload = $this->payloadBuilder->build($orderTransaction, $transaction); - } catch (\RuntimeException $e) { - // Handle cases where required order data might be missing. - if ($this->config->getBool('enableDebugging', null)) { - $this->logger->error('Failed to build payment payload for Paystack.', [ - 'transaction_id' => $transaction->getOrderTransactionId(), - 'error' => $e->getMessage(), - ]); - } + $payload = $this->payloadBuilder->build( + $orderTransaction, + $transaction + ); + + $response = $this->transactionService->initialize($payload); + } catch (\RuntimeException $exception) { + $this->logError( + 'Failed to build Paystack payment payload.', + $transactionId, + ['exception' => $exception] + ); + + throw PaymentException::asyncProcessInterrupted( + $transactionId, + sprintf( + 'Unable to prepare payment payload: %s', + $exception->getMessage() + ) + ); + } catch (PaystackException $exception) { + $this->logError( + 'Paystack communication error during initialization.', + $transactionId, + ['exception' => $exception] + ); throw PaymentException::asyncProcessInterrupted( - $transaction->getOrderTransactionId(), - 'Unable to prepare payment data: ' . $e->getMessage() + $transactionId, + 'A communication error occurred with the payment gateway' ); } - try { - // 3. Initialize the transaction with Paystack API. - $response = $this->transactionService->initialize($payload); + if (($response['status'] ?? false) !== true) { + throw PaymentException::asyncProcessInterrupted( + $transactionId, + sprintf( + 'Paystack declined to initialize the payment: %s', + $response['message'] ?? 'Unknown error' + ) + ); + } + + $authorizationUrl = $response['data']['authorization_url'] ?? null; - // 4. Validate the response status. Status 'true' indicates successful initialization. - if (($response['status'] ?? '') !== true) { - throw PaymentException::asyncProcessInterrupted( - $transaction->getOrderTransactionId(), - 'Paystack declined to initialize the payment: ' . ($response['message'] ?? 'No reason provided') - ); - } - - // Log initialization success if debugging is enabled. - if ($this->config->getBool('enableDebugging', null)) { - $this->logger->info('Paystack payment session initialized successfully.', [ - 'transaction_id' => $transaction->getOrderTransactionId(), - 'paystack_response' => $response, - ]); - } - - // 5. Redirect the customer to Paystack's hosted checkout page. - if (!isset($response['data']['authorization_url'])) { - throw PaymentException::asyncProcessInterrupted( - $transaction->getOrderTransactionId(), - 'Paystack did not return a checkout URL. Please try again or contact support.' - ); - } - - return new RedirectResponse($response['data']['authorization_url']); - } catch (PaystackException $e) { - // Handle network errors or API-specific failures. - // @codeCoverageIgnoreStart - if ($this->config->getBool('enableDebugging', null)) { - $this->logger->error('Communication error with Paystack during payment initialization.', [ - 'transaction_id' => $transaction->getOrderTransactionId(), - 'error' => $e->getMessage(), - ]); - } - // @codeCoverageIgnoreEnd + if (!is_string($authorizationUrl) || $authorizationUrl === '') { throw PaymentException::asyncProcessInterrupted( - $transaction->getOrderTransactionId(), - 'A communication error occurred with the payment gateway. Please try again.' . PHP_EOL . $e->getMessage() + $transactionId, + 'Paystack did not return a checkout URL' ); } + + $this->logInfo( + 'Paystack payment initialized successfully.', + $transactionId, + ['response' => $response] + ); + + return new RedirectResponse($authorizationUrl); } /** - * Finalizes the payment process after returning from the payment gateway. - * - * @param Request $request - * @param PaymentTransactionStruct $transaction - * @param Context $context - * - * @return void + * Finalizes a Paystack payment. * * @throws PaystackException + * @throws PaymentException */ - public function finalize(Request $request, PaymentTransactionStruct $transaction, Context $context): void - { - // 1. Retrieve the order transaction. - $orderTransaction = $this->orderTransactionService->get($transaction->getOrderTransactionId(), $context); + public function finalize( + Request $request, + PaymentTransactionStruct $transaction, + Context $context + ): void { + $transactionId = $transaction->getOrderTransactionId(); + + $orderTransaction = $this->orderTransactionService->get( + $transactionId, + $context + ); + + $reference = $this->extractReference( + $request, + $orderTransaction + ); + + $verification = $this->verifyTransaction( + $reference, + $orderTransaction, + $context + ); + + $this->markTransactionAsPaid( + $transaction, + $context + ); - // 2. Extract query parameters from the callback URL (e.g., 'reference'). - $queryParams = $request->query->all(); + $this->persistTransactionMetadata( + $transactionId, + $reference, + $verification, + $context + ); - // 3. Verify the payment status with Paystack's verification endpoint using the reference. - $verificationResult = $this->verifyPayment($orderTransaction, $queryParams); + $this->dispatchFinalizedEvent( + $orderTransaction, + $transaction, + $context + ); - // 4. Update the order transaction state and store relevant transaction metadata. - $this->completePaymentProcessing($orderTransaction, $transaction, $context, $queryParams, $verificationResult); + $data = $verification['data'] ?? []; + $paystackTransactionId = null; + if (is_array($data) && isset($data['id'])) { + $paystackTransactionId = $data['id']; + } + + $this->logInfo( + 'Paystack payment finalized successfully.', + $transactionId, + [ + 'reference' => $reference, + 'paystack_transaction_id' => $paystackTransactionId, + ] + ); } /** - * Verifies a payment transaction with Paystack. - * - * @param OrderTransactionEntity $orderTransaction The Shopware order transaction entity. - * @param array $queryParams Query parameters containing at least the 'transaction_id'. + * Extracts and validates Paystack reference. + */ + private function extractReference( + Request $request, + OrderTransactionEntity $transaction + ): string { + $reference = $request->query->getString('reference'); + + if ($reference === '') { + $this->logError( + 'Missing Paystack transaction reference.', + $transaction->getId(), + ['query' => $request->query->all()] + ); + + throw PaymentException::customerCanceled( + $transaction->getId(), + 'Payment reference is missing from the request.' + ); + } + + return $reference; + } + + /** + * Verifies transaction against Paystack API. * - * @return array The verification result from Paystack. + * @return array * - * @throws PaystackException If the transaction ID is missing or verification fails. + * @throws PaystackException + * @throws PaymentException */ - private function verifyPayment(OrderTransactionEntity $orderTransaction, array $queryParams): array - { - // 1. Check for the 'reference' parameter in the query parameters. - $reference = $queryParams['reference'] ?? null; - - if (!$reference) { - if ($this->config->getBool('enableDebugging', null)) { - $this->logger->error('Payment callback received without a transaction reference.', [ - 'transaction_id' => $orderTransaction->getId(), - 'query_params' => $queryParams, - ]); - } - throw PaymentException::invalidTransaction($orderTransaction->getId()); - } + private function verifyTransaction( + string $reference, + OrderTransactionEntity $transaction, + Context $context + ): array { + $verification = $this->transactionService->verify($reference); + + if (($verification['status'] ?? false) !== true) { + $this->transactionStateHandler->fail($transaction->getId(), $context); + + $this->logError( + 'Paystack payment verification failed.', + $transaction->getId(), + ['verification' => $verification] + ); - // 2. Call the Paystack verification service. - $verificationResult = $this->transactionService->verify($reference); - - // 3. Validate the verification response status. - if (($verificationResult['status'] ?? '') !== true) { - if ($this->config->getBool('enableDebugging', null)) { - $this->logger->error('Paystack payment verification failed.', [ - 'transaction_id' => $orderTransaction->getId(), - 'verification_result' => $verificationResult, - ]); - } throw PaymentException::asyncFinalizeInterrupted( - $orderTransaction->getId(), - 'Payment could not be verified: ' . ($verificationResult['message'] ?? 'No reason provided') + $transaction->getId(), + sprintf( + 'Unable to verify payment: %s', + $verification['message'] ?? 'Unknown error' + ) ); } - // Log success if debugging is enabled. - if ($this->config->getBool('enableDebugging', null)) { - $this->logger->info('Paystack payment verified successfully.', [ - 'transaction_id' => $orderTransaction->getId(), - 'verification_result' => $verificationResult, - ]); - } + return $verification; + } - return $verificationResult; + /** + * Marks Shopware transaction as paid. + */ + private function markTransactionAsPaid( + PaymentTransactionStruct $transaction, + Context $context + ): void { + $this->transactionStateHandler->paid( + $transaction->getOrderTransactionId(), + $context + ); } /** - * Completes the payment processing by updating transaction state and custom fields. + * Persists Paystack metadata into transaction custom fields. * - * @param OrderTransactionEntity $orderTransaction The order transaction entity. - * @param PaymentTransactionStruct $transaction Payment transaction data. - * @param Context $context Shopware context. - * @param array $queryParams Query parameters from the payment gateway. - * @param array $verificationResult Result from payment verification. + * @param array $verification + */ + private function persistTransactionMetadata( + string $transactionId, + string $reference, + array $verification, + Context $context + ): void { + $data = $verification['data'] ?? []; + + if (!is_array($data)) { + $data = []; + } + + $this->orderTransactionService->updateCustomFields( + $transactionId, + [ + PaystackConstants::FIELD_REFERENCE => $reference, + PaystackConstants::FIELD_TRANSACTION_ID => $data['id'] ?? null, + PaystackConstants::FIELD_PAYMENT_TYPE => $data['channel'] ?? null, + PaystackConstants::FIELD_TRANSACTION_FEE => isset($data['fees']) && is_numeric($data['fees']) + ? ((float)$data['fees'] / 100) + : null, + PaystackConstants::FIELD_AMOUNT => isset($data['amount']) && is_numeric($data['amount']) + ? ((float)$data['amount'] / 100) + : null, + PaystackConstants::FIELD_CURRENCY => $data['currency'] ?? null, + PaystackConstants::FIELD_VERIFIED_AT => ( + new DateTimeImmutable() + )->format('Y-m-d H:i:s'), + ], + $context + ); + } + + /** + * Dispatches finalized payment event. */ - protected function completePaymentProcessing( + private function dispatchFinalizedEvent( OrderTransactionEntity $orderTransaction, PaymentTransactionStruct $transaction, - Context $context, - array $queryParams, - array $verificationResult + Context $context ): void { - // Mark the transaction as paid in Shopware. - $this->transactionStateHandler->paid($transaction->getOrderTransactionId(), $context); - - // Update the order transaction with custom fields built from the payment gateway response and verification result. - $this->orderTransactionService->updateCustomFields($transaction->getOrderTransactionId(), [ - PaystackConstants::FIELD_REFERENCE => $queryParams['reference'] ?? null, - PaystackConstants::FIELD_TRANSACTION_ID => $verificationResult['data']['id'] ?? null, - PaystackConstants::FIELD_PAYMENT_TYPE => $verificationResult['data']['channel'] ?? null, - PaystackConstants::FIELD_TRANSACTION_FEE => isset($verificationResult['data']['fees']) ? ($verificationResult['data']['fees'] / 100) : null, - PaystackConstants::FIELD_AMOUNT => isset($verificationResult['data']['amount']) ? ($verificationResult['data']['amount'] / 100) : null, - PaystackConstants::FIELD_CURRENCY => $verificationResult['data']['currency'] ?? null, - PaystackConstants::FIELD_VERIFIED_AT => (new \DateTime())->format('Y-m-d H:i:s'), - ], $context); - - // If debugging is enabled in the plugin configuration, log payment finalization details for troubleshooting. - if ($this->config->getBool('enableDebugging', $orderTransaction->getOrder()?->getSalesChannelId())) { - $this->logger->info('Payment finalized and order transaction updated.', [ - 'transaction_id' => $transaction->getOrderTransactionId(), - 'paystack_transaction_id' => $verificationResult['data']['id'] ?? null, - 'paystack_reference' => $queryParams['reference'] ?? null, - ]); + $order = $orderTransaction->getOrder(); + + if (!$order instanceof OrderEntity) { + return; } + + $this->paymentFinalizedEventService->fireEvent( + $order, + $orderTransaction, + $transaction, + $context + ); } /** - * @param string $transactionId - * @param Context $context + * Retrieves the order transaction entity. * - * @return OrderTransactionEntity - * - * @deprecated Use OrderTransactionService::get() instead + * @throws PaymentException */ public function getOrderTransaction(string $transactionId, Context $context): OrderTransactionEntity { - $orderTransaction = $this->orderTransactionService->get($transactionId, $context); + return $this->orderTransactionService->get($transactionId, $context); + } + + /** + * Logs informational messages when debugging is enabled. + * + * @param array $contextData + */ + private function logInfo( + string $message, + string $transactionId, + array $contextData = [] + ): void { + if (!$this->isDebugEnabled()) { + return; + } - if ($this->config->getBool('enableDebugging', $orderTransaction->getOrder()?->getSalesChannelId())) { - $this->logger->info('Order transaction loaded successfully.', [ - 'transaction_id' => $transactionId, - ]); + $this->logger->info( + $message, + array_merge( + ['transaction_id' => $transactionId], + $contextData + ) + ); + } + + /** + * Logs errors when debugging is enabled. + * + * @param array $contextData + */ + private function logError( + string $message, + string $transactionId, + array $contextData = [] + ): void { + if (!$this->isDebugEnabled()) { + return; } - return $orderTransaction; + $this->logger->error( + $message, + array_merge( + ['transaction_id' => $transactionId], + $contextData + ) + ); + } + + /** + * Determines whether debugging is enabled. + */ + private function isDebugEnabled(): bool + { + return $this->config->getBool('enableDebugging', null); } } diff --git a/src/Contracts/HttpClientInterface.php b/src/Contracts/HttpClientInterface.php new file mode 100644 index 0000000..79326ae --- /dev/null +++ b/src/Contracts/HttpClientInterface.php @@ -0,0 +1,46 @@ +container) || $this->container === null) { - return null; + return null; // @codeCoverageIgnore } /** @var EntityRepository $paymentMethodRepository */ diff --git a/src/Resources/config/config.xml b/src/Resources/config/config.xml index 85cd7d0..cd95fe4 100644 --- a/src/Resources/config/config.xml +++ b/src/Resources/config/config.xml @@ -3,8 +3,9 @@ xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/shopware/shopware/6.7/src/Core/System/SystemConfig/Schema/config.xsd"> - Live Configuration - Live-Konfiguration + Credentials + Zugangsdaten + Identifiants apiSecretKey @@ -18,11 +19,6 @@ true - - - - Sandbox / Test Configuration - Sandbox- / Testkonfiguration enableSandbox @@ -50,6 +46,157 @@ + + Split payment + Splitte Zahlung + Paiement divisé + + + enableSplitPayment + + + + false + + Enable this to split payments between your main account and a subaccount. + + + Aktivieren Sie dies, um Zahlungen zwischen Ihrem Hauptkonto und einem Unterkonto aufzuteilen. + + + Activez cette option pour diviser les paiements entre votre compte principal et un sous-compte. + + + + + subaccountCode + + + + + The code for the subaccount that should receive a split of the payment (e.g., ACCT_xxxxxxxxx). + + + Der Code für das Unterkonto, das einen Teil der Zahlung erhalten soll (z. B. ACCT_xxxxxxxxx). + + + Le code du sous-compte qui doit recevoir une partie du paiement (ex: ACCT_xxxxxxxxx). + + + + + splitPaymentTransactionCharge + + + + + A flat fee to charge the subaccount for this transaction, in Naira (₦). This overrides the split percentage set when the subaccount was created. Ideally, you will need to use this if you are splitting in flat rates (since subaccount creation only allows for percentage split). e.g. 100 for a ₦100 flat fee. + + + Eine Pauschalgebühr, die dem Unterkonto für diese Transaktion in Naira (₦) berechnet wird. Dies überschreibt den bei der Erstellung des Unterkontos festgelegten Split-Prozentsatz. Idealerweise verwenden Sie dies, wenn Sie mit Pauschalbeträgen aufteilen (da die Erstellung von Unterkonten nur eine prozentuale Aufteilung zulässt). z.B. 100 für eine Pauschalgebühr von ₦100. + + + Des frais fixes à facturer au sous-compte pour cette transaction, en Naira (₦). Cela remplace le pourcentage de répartition défini lors de la création du sous-compte. Idéalement, vous devrez l'utiliser si vous effectuez une répartition à taux fixe (car la création de sous-compte ne permet qu'une répartition en pourcentage). par exemple 100 pour des frais fixes de ₦100. + + + + + paystackChargesBearer + + + + + + + + + Choose who bears the Paystack transaction charges. + + + Wählen Sie aus, wer die Paystack-Transaktionsgebühren trägt. + + + Choisissez qui supporte les frais de transaction Paystack. + + + + + + Meta Information + Metainformationen + Informations méta + + + metaData + + + + + + + + + + + + + + Select which additional order information should be sent to Paystack as metadata. This can help with transaction tracking and reconciliation in your Paystack dashboard. + + + Wählen Sie aus, welche zusätzlichen Bestellinformationen als Metadaten an Paystack gesendet werden sollen. Dies kann bei der Transaktionsverfolgung und -abstimmung in Ihrem Paystack-Dashboard helfen. + + + Sélectionnez les informations supplémentaires sur la commande qui doivent être envoyées à Paystack en tant que métadonnées. Cela peut aider à la surveillance et à la réconciliation des transactions dans votre tableau de bord Paystack. + + + + Debugging Fehlerdiagnose diff --git a/src/Resources/config/services.yml b/src/Resources/config/services.yml index 47d802f..ccfada7 100644 --- a/src/Resources/config/services.yml +++ b/src/Resources/config/services.yml @@ -8,26 +8,6 @@ services: resource: '../../*' exclude: '../../{DependencyInjection,Entity,Migrations,Tests,Kernel.php}' - Kommandhub\PaystackSW\Service\OrderTransactionService: - arguments: - $orderTransactionRepository: '@order_transaction.repository' - Kommandhub\PaystackSW\Checkout\Payment\PaystackPaymentHandler: - arguments: - $orderTransactionService: '@Kommandhub\PaystackSW\Service\OrderTransactionService' - $transactionService: '@Kommandhub\PaystackSW\Service\TransactionService' - $payloadBuilder: '@Kommandhub\PaystackSW\Service\PayloadBuilder' tags: - - { name: 'shopware.payment_handler' } - - Kommandhub\PaystackSW\Service\PaystackFactory: - arguments: - $config: '@Kommandhub\PaystackSW\Service\Config' - $client: '@GuzzleHttp\Client' - $requestFactory: '@Nyholm\Psr7\Factory\Psr17Factory' - $streamFactory: '@Nyholm\Psr7\Factory\Psr17Factory' - - GuzzleHttp\Client: ~ - - Kommandhub\Paystack\Paystack: - factory: ['@Kommandhub\PaystackSW\Service\PaystackFactory', 'create'] \ No newline at end of file + - { name: 'shopware.payment_handler' } \ No newline at end of file diff --git a/src/Service/Http/PaystackHttpClient.php b/src/Service/Http/PaystackHttpClient.php new file mode 100644 index 0000000..8b59eb5 --- /dev/null +++ b/src/Service/Http/PaystackHttpClient.php @@ -0,0 +1,123 @@ +config->getBool('enableSandbox', $salesChannelId); + + return $sandbox + ? $this->config->getString('apiSecretKeySandbox', $salesChannelId) + : $this->config->getString('apiSecretKey', $salesChannelId); + } + + /** + * Send a GET request. + * + * + * @throws PaystackException + */ + public function get(string $endpoint, array $queryParams = [], ?string $salesChannelId = null): ResponseInterface + { + try { + return $this->client->request('GET', self::BASE_URL.$endpoint, [ + 'query' => $queryParams, + 'headers' => [ + 'Authorization' => 'Bearer '.$this->getSecretKey($salesChannelId), + 'Content-Type' => 'application/json', + ], + ]); + } catch (\Throwable $e) { + throw new PaystackException($e->getMessage(), $e->getCode(), $e); + } + } + + /** + * Send a POST request. + * + * + * @throws PaystackException + */ + public function post(string $endpoint, array $payload = [], ?string $salesChannelId = null): ResponseInterface + { + try { + return $this->client->request('POST', self::BASE_URL.$endpoint, [ + 'json' => $payload, + 'headers' => [ + 'Authorization' => 'Bearer '.$this->getSecretKey($salesChannelId), + 'Content-Type' => 'application/json', + ], + ]); + } catch (\Throwable $e) { + throw new PaystackException($e->getMessage(), $e->getCode(), $e); + } + } + + /** + * Send a PUT request. + * + * + * @throws PaystackException + */ + public function put(string $endpoint, array $payload = [], ?string $salesChannelId = null): ResponseInterface + { + try { + return $this->client->request('PUT', self::BASE_URL.$endpoint, [ + 'json' => $payload, + 'headers' => [ + 'Authorization' => 'Bearer '.$this->getSecretKey($salesChannelId), + 'Content-Type' => 'application/json', + ], + ]); + } catch (\Throwable $e) { + throw new PaystackException($e->getMessage(), $e->getCode(), $e); + } + } + + /** + * Send a DELETE request. + * + * + * @throws PaystackException + */ + public function delete(string $endpoint, ?string $salesChannelId = null): ResponseInterface + { + try { + return $this->client->request('DELETE', self::BASE_URL.$endpoint, [ + 'headers' => [ + 'Authorization' => 'Bearer '.$this->getSecretKey($salesChannelId), + 'Content-Type' => 'application/json', + ], + ]); + } catch (\Throwable $e) { + throw new PaystackException($e->getMessage(), $e->getCode(), $e); + } + } +} diff --git a/src/Service/OrderTransactionService.php b/src/Service/OrderTransactionService.php index f535826..7f9620c 100644 --- a/src/Service/OrderTransactionService.php +++ b/src/Service/OrderTransactionService.php @@ -4,16 +4,18 @@ namespace Kommandhub\PaystackSW\Service; +use Kommandhub\Foundation\EntityHandler\OrderTransaction\OrderTransactionReader; +use Kommandhub\Foundation\EntityHandler\OrderTransaction\OrderTransactionWriter; use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionEntity; use Shopware\Core\Framework\Context; -use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository; use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria; use Shopware\Core\Checkout\Payment\PaymentException; -class OrderTransactionService +readonly class OrderTransactionService { public function __construct( - private readonly EntityRepository $orderTransactionRepository + private OrderTransactionReader $orderTransactionReader, + private OrderTransactionWriter $orderTransactionWriter, ) { } @@ -25,8 +27,11 @@ public function __construct( */ public function get(string $transactionId, Context $context): OrderTransactionEntity { - $criteria = $this->getCriteria([$transactionId]); - $orderTransaction = $this->orderTransactionRepository->search($criteria, $context)->first(); + $orderTransaction = $this->orderTransactionReader->readOneById( + $transactionId, + $context, + $this->getCriteria() + ); if (!$orderTransaction instanceof OrderTransactionEntity) { throw PaymentException::asyncProcessInterrupted( @@ -45,16 +50,22 @@ public function get(string $transactionId, Context $context): OrderTransactionEn */ public function updateCustomFields(string $transactionId, array $customFields, Context $context): void { - $this->orderTransactionRepository->update([[ + $this->orderTransactionWriter->write([ 'id' => $transactionId, 'customFields' => $customFields, - ]], $context); + ], $context); } - private function getCriteria(array $ids = []): Criteria + private function getCriteria(): Criteria { - $criteria = empty($ids) ? new Criteria() : new Criteria($ids); - $criteria->addAssociations(['order.currency', 'order.orderCustomer.salutation']); + $criteria = new Criteria(); + $criteria->addAssociations([ + 'order.currency', + 'order.lineItems', + 'order.orderCustomer.salutation', + 'order.billingAddress.country', + 'order.deliveries.shippingOrderAddress.country', + ]); return $criteria; } diff --git a/src/Service/PayloadBuilder.php b/src/Service/PayloadBuilder.php index cdf884d..5f5728c 100644 --- a/src/Service/PayloadBuilder.php +++ b/src/Service/PayloadBuilder.php @@ -4,7 +4,10 @@ namespace Kommandhub\PaystackSW\Service; +use Shopware\Core\Checkout\Order\Aggregate\OrderAddress\OrderAddressEntity; +use Shopware\Core\Checkout\Order\Aggregate\OrderLineItem\OrderLineItemCollection; use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionEntity; +use Shopware\Core\Checkout\Order\OrderEntity; use Shopware\Core\Checkout\Payment\Cart\PaymentTransactionStruct; readonly class PayloadBuilder @@ -62,6 +65,12 @@ public function build(OrderTransactionEntity $orderTransaction, PaymentTransacti salesChannelId: $salesChannelId ); + $selectedMetaData = $this->config->get( + key: 'metaData', + default: [], + salesChannelId: $salesChannelId + ); + // 6. Build the final payload array according to Paystack API specifications. // The amount is multiplied by 100 to convert from the major currency unit (e.g., Naira) // to the minor unit (e.g., kobo) as expected by Paystack. @@ -71,9 +80,149 @@ public function build(OrderTransactionEntity $orderTransaction, PaymentTransacti 'email' => $customer->getEmail(), 'callback_url' => $returnUrl, 'channels' => $paymentOptions, - 'metadata' => [ - 'cancel_action' => $returnUrl, - ], + 'metadata' => $this->buildMetadata($order, $selectedMetaData, (string)$returnUrl), + ]; + } + + /** + * Build the metadata object for Paystack. + * + * @param OrderEntity $order + * @param array $selectedMetaData + * @param string $returnUrl + * + * @return array + */ + private function buildMetadata(OrderEntity $order, array $selectedMetaData, string $returnUrl): array + { + $metadata = [ + 'cancel_action' => $returnUrl, + 'custom_fields' => [], ]; + + if (empty($selectedMetaData)) { + unset($metadata['custom_fields']); + + return $metadata; + } + + foreach ($selectedMetaData as $id) { + switch ($id) { + case 'orderId': + $metadata['custom_fields'][] = [ + 'display_name' => 'Order ID', + 'variable_name' => 'order_id', + 'value' => $order->getOrderNumber(), + ]; + break; + case 'customerName': + $customer = $order->getOrderCustomer(); + if ($customer) { + $metadata['custom_fields'][] = [ + 'display_name' => 'Customer Name', + 'variable_name' => 'customer_name', + 'value' => sprintf('%s %s', $customer->getFirstName(), $customer->getLastName()), + ]; + } + break; + case 'customerEmail': + $customer = $order->getOrderCustomer(); + if ($customer) { + $metadata['custom_fields'][] = [ + 'display_name' => 'Customer Email', + 'variable_name' => 'customer_email', + 'value' => $customer->getEmail(), + ]; + } + break; + case 'customerPhone': + $billing = $order->getBillingAddress(); + if ($billing && $billing->getPhoneNumber()) { + $metadata['custom_fields'][] = [ + 'display_name' => 'Customer Phone', + 'variable_name' => 'customer_phone', + 'value' => $billing->getPhoneNumber(), + ]; + } + break; + case 'billingAddress': + $billing = $order->getBillingAddress(); + if ($billing) { + $metadata['custom_fields'][] = [ + 'display_name' => 'Order Billing Address', + 'variable_name' => 'order_billing_address', + 'value' => $this->formatAddress($billing), + ]; + } + break; + case 'shippingAddress': + $shipping = null; + $deliveries = $order->getDeliveries(); + if ($deliveries && $deliveries->first()) { + $shipping = $deliveries->first()->getShippingOrderAddress(); + } + if ($shipping) { + $metadata['custom_fields'][] = [ + 'display_name' => 'Order Shipping Address', + 'variable_name' => 'order_shipping_address', + 'value' => $this->formatAddress($shipping), + ]; + } + break; + case 'products': + $lineItems = $order->getLineItems(); + if ($lineItems && $lineItems->count() > 0) { + $metadata['custom_fields'][] = [ + 'display_name' => 'Product(s) Purchased', + 'variable_name' => 'products_purchased', + 'value' => $this->formatLineItems($lineItems), + ]; + } + break; + } + } + + if (empty($metadata['custom_fields'])) { + unset($metadata['custom_fields']); + } + + return $metadata; + } + + /** + * Format an address as a single line string. + * + * @param OrderAddressEntity $address + * + * @return string + */ + private function formatAddress(OrderAddressEntity $address): string + { + return sprintf( + '%s %s, %s, %s %s, %s', + $address->getFirstName(), + $address->getLastName(), + $address->getStreet(), + $address->getZipcode(), + $address->getCity(), + $address->getCountry() ? $address->getCountry()->getName() : '' + ); + } + + /** + * Format line items as a single line string. + * + * @param OrderLineItemCollection $lineItems + * + * @return string + */ + private function formatLineItems(OrderLineItemCollection $lineItems): string + { + $items = []; + foreach ($lineItems as $lineItem) { + $items[] = sprintf('%dx %s', $lineItem->getQuantity(), $lineItem->getLabel()); + } + + return implode(', ', $items); } } diff --git a/src/Service/PaymentFinalizedEventService.php b/src/Service/PaymentFinalizedEventService.php new file mode 100644 index 0000000..8664a0f --- /dev/null +++ b/src/Service/PaymentFinalizedEventService.php @@ -0,0 +1,47 @@ +eventDispatcher->dispatch( + new PaystackPaymentFinalizedEvent($order, $orderTransaction, $paymentTransactionStruct, $context) + ); + } +} diff --git a/src/Service/Paystack.php b/src/Service/Paystack.php new file mode 100644 index 0000000..5c68e19 --- /dev/null +++ b/src/Service/Paystack.php @@ -0,0 +1,120 @@ +httpClient); + } + + /** + * Get the customer's resource. + */ + public function customers(): Customer + { + return new Customer($this->httpClient); + } + + /** + * Get the plan resource. + */ + public function plans(): Plan + { + return new Plan($this->httpClient); + } + + /** + * Get the split resource. + */ + public function splits(): Split + { + return new Split($this->httpClient); + } + + /** + * Get the subaccounts resource. + */ + public function subaccounts(): Subaccount + { + return new Subaccount($this->httpClient); + } + + /** + * Get the subscription resource. + */ + public function subscriptions(): Subscription + { + return new Subscription($this->httpClient); + } + + /** + * Get the refund resource. + */ + public function refunds(): Refund + { + return new Refund($this->httpClient); + } + + /** + * Get the miscellaneous resource. + */ + public function miscellaneous(): Miscellaneous + { + return new Miscellaneous($this->httpClient); + } + + /** + * Get the transfer resource. + */ + public function transfers(): Transfer + { + return new Transfer($this->httpClient); + } + + /** + * Get the settlement resource. + */ + public function settlements(): Settlement + { + return new Settlement($this->httpClient); + } + + /** + * Get the verification resource. + */ + public function verification(): Verification + { + return new Verification($this->httpClient); + } +} diff --git a/src/Service/PaystackFactory.php b/src/Service/PaystackFactory.php deleted file mode 100644 index 134e8d2..0000000 --- a/src/Service/PaystackFactory.php +++ /dev/null @@ -1,48 +0,0 @@ -config->getBool('enableSandbox', $salesChannelId); - - // 2. Retrieve the appropriate secret key based on the environment (Live vs Sandbox). - $secretKey = $sandbox - ? $this->config->getString('apiSecretKeySandbox', $salesChannelId) - : $this->config->getString('apiSecretKey', $salesChannelId); - - // 3. Instantiate the Paystack client with PSR-18 and PSR-17 dependencies. - return new Paystack( - $secretKey, - null, - $this->client, - $this->requestFactory, - $this->streamFactory - ); - } -} diff --git a/src/Service/Resources/ApiResource.php b/src/Service/Resources/ApiResource.php new file mode 100644 index 0000000..925db97 --- /dev/null +++ b/src/Service/Resources/ApiResource.php @@ -0,0 +1,28 @@ +toArray(); + } +} diff --git a/src/Service/Resources/Customer.php b/src/Service/Resources/Customer.php new file mode 100644 index 0000000..80ff13f --- /dev/null +++ b/src/Service/Resources/Customer.php @@ -0,0 +1,62 @@ +response($this->httpClient->post('/customer', $payload)); + } + + /** + * List customers. + * + * @see https://paystack.com/docs/api/customer/#list + * + * @throws PaystackException + */ + public function list(array $queryParams = []): array + { + return $this->response($this->httpClient->get('/customer', $queryParams)); + } + + /** + * Fetch a customer. + * + * @see https://paystack.com/docs/api/customer/#fetch + * + * @throws PaystackException + */ + public function fetch(string $emailOrCode): array + { + return $this->response($this->httpClient->get("/customer/{$emailOrCode}")); + } + + /** + * Update a customer. + * + * @see https://paystack.com/docs/api/customer/#update + * + * @throws PaystackException + */ + public function update(string $code, array $payload): array + { + return $this->response($this->httpClient->put("/customer/{$code}", $payload)); + } +} diff --git a/src/Service/Resources/Miscellaneous.php b/src/Service/Resources/Miscellaneous.php new file mode 100644 index 0000000..a446e7e --- /dev/null +++ b/src/Service/Resources/Miscellaneous.php @@ -0,0 +1,50 @@ +response($this->httpClient->get('/bank', $queryParams)); + } + + /** + * Get a list of all supported countries and their properties. + * + * @see https://paystack.com/docs/api/miscellaneous/#country + * + * @throws PaystackException + */ + public function listCountries(): array + { + return $this->response($this->httpClient->get('/country')); + } + + /** + * Get a list of states for a specific country for Address Verification Service (AVS). + * + * @see https://paystack.com/docs/api/miscellaneous/#avs-states + * + * @throws PaystackException + */ + public function listStates(string $countryCode): array + { + return $this->response($this->httpClient->get('/address_verification/states', ['country' => $countryCode])); + } +} diff --git a/src/Service/Resources/Plan.php b/src/Service/Resources/Plan.php new file mode 100644 index 0000000..9ff9a8d --- /dev/null +++ b/src/Service/Resources/Plan.php @@ -0,0 +1,62 @@ +response($this->httpClient->post('/plan', $payload)); + } + + /** + * List plans. + * + * @see https://paystack.com/docs/api/plan/#list + * + * @throws PaystackException + */ + public function list(array $queryParams = []): array + { + return $this->response($this->httpClient->get('/plan', $queryParams)); + } + + /** + * Fetch a plan. + * + * @see https://paystack.com/docs/api/plan/#fetch + * + * @throws PaystackException + */ + public function fetch(string $idOrCode): array + { + return $this->response($this->httpClient->get("/plan/{$idOrCode}")); + } + + /** + * Update a plan. + * + * @see https://paystack.com/docs/api/plan/#update + * + * @throws PaystackException + */ + public function update(string $idOrCode, array $payload): array + { + return $this->response($this->httpClient->put("/plan/{$idOrCode}", $payload)); + } +} diff --git a/src/Service/Resources/Refund.php b/src/Service/Resources/Refund.php new file mode 100644 index 0000000..8634456 --- /dev/null +++ b/src/Service/Resources/Refund.php @@ -0,0 +1,50 @@ +response($this->httpClient->post('/refund', $payload)); + } + + /** + * List refunds. + * + * @see https://paystack.com/docs/api/refund/#list + * + * @throws PaystackException + */ + public function list(array $queryParams = []): array + { + return $this->response($this->httpClient->get('/refund', $queryParams)); + } + + /** + * Fetch a refund. + * + * @see https://paystack.com/docs/api/refund/#fetch + * + * @throws PaystackException + */ + public function fetch(string $reference): array + { + return $this->response($this->httpClient->get("/refund/{$reference}")); + } +} diff --git a/src/Service/Resources/Settlement.php b/src/Service/Resources/Settlement.php new file mode 100644 index 0000000..be30a40 --- /dev/null +++ b/src/Service/Resources/Settlement.php @@ -0,0 +1,37 @@ +response($this->httpClient->get('/settlement', $queryParams)); + } + + /** + * Fetch settlement transactions. + * + * @see https://paystack.com/docs/api/settlement/#transactions + * + * @throws PaystackException + */ + public function transactions(string $id, array $queryParams = []): array + { + return $this->response($this->httpClient->get("/settlement/{$id}/transaction", $queryParams)); + } +} diff --git a/src/Service/Resources/Split.php b/src/Service/Resources/Split.php new file mode 100644 index 0000000..970ecbf --- /dev/null +++ b/src/Service/Resources/Split.php @@ -0,0 +1,86 @@ +response($this->httpClient->post('/split', $payload)); + } + + /** + * List splits. + * + * @see https://paystack.com/docs/api/split/#list + * + * @throws PaystackException + */ + public function list(array $queryParams = []): array + { + return $this->response($this->httpClient->get('/split', $queryParams)); + } + + /** + * Fetch a split. + * + * @see https://paystack.com/docs/api/split/#fetch + * + * @throws PaystackException + */ + public function fetch(string $id): array + { + return $this->response($this->httpClient->get("/split/{$id}")); + } + + /** + * Update a split. + * + * @see https://paystack.com/docs/api/split/#update + * + * @throws PaystackException + */ + public function update(string $id, array $payload): array + { + return $this->response($this->httpClient->put("/split/{$id}", $payload)); + } + + /** + * Add a subaccount to a split. + * + * @see https://paystack.com/docs/api/split/#add-subaccount + * + * @throws PaystackException + */ + public function addSubaccount(string $id, array $payload): array + { + return $this->response($this->httpClient->post("/split/{$id}/subaccount/add", $payload)); + } + + /** + * Remove a subaccount from a split. + * + * @see https://paystack.com/docs/api/split/#remove-subaccount + * + * @throws PaystackException + */ + public function removeSubaccount(string $id, array $payload): array + { + return $this->response($this->httpClient->post("/split/{$id}/subaccount/remove", $payload)); + } +} diff --git a/src/Service/Resources/Subaccount.php b/src/Service/Resources/Subaccount.php new file mode 100644 index 0000000..9df66e8 --- /dev/null +++ b/src/Service/Resources/Subaccount.php @@ -0,0 +1,61 @@ +response($this->httpClient->post('/subaccount', $payload)); + } + + /** + * List subaccounts. + * + * @see https://paystack.com/docs/api/subaccount/#list + * + * @throws PaystackException + */ + public function list(array $queryParams = []): array + { + return $this->response($this->httpClient->get('/subaccount', $queryParams)); + } + + /** + * Fetch a subaccount. + * + * @see https://paystack.com/docs/api/subaccount/#fetch + * + * @throws PaystackException + */ + public function fetch(string $idOrCode): array + { + return $this->response($this->httpClient->get("/subaccount/{$idOrCode}")); + } + + /** + * Update a subaccount. + * + * @see https://paystack.com/docs/api/subaccount/#update + * + * @throws PaystackException + */ + public function update(string $idOrCode, array $payload): array + { + return $this->response($this->httpClient->put("/subaccount/{$idOrCode}", $payload)); + } +} diff --git a/src/Service/Resources/Subscription.php b/src/Service/Resources/Subscription.php new file mode 100644 index 0000000..f25436c --- /dev/null +++ b/src/Service/Resources/Subscription.php @@ -0,0 +1,98 @@ +response($this->httpClient->post('/subscription', $payload)); + } + + /** + * List subscriptions. + * + * @see https://paystack.com/docs/api/subscription/#list + * + * @throws PaystackException + */ + public function list(array $queryParams = []): array + { + return $this->response($this->httpClient->get('/subscription', $queryParams)); + } + + /** + * Fetch a subscription. + * + * @see https://paystack.com/docs/api/subscription/#fetch + * + * @throws PaystackException + */ + public function fetch(string $idOrCode): array + { + return $this->response($this->httpClient->get("/subscription/{$idOrCode}")); + } + + /** + * Enable a subscription. + * + * @see https://paystack.com/docs/api/subscription/#enable + * + * @throws PaystackException + */ + public function enable(array $payload): array + { + return $this->response($this->httpClient->post('/subscription/enable', $payload)); + } + + /** + * Disable a subscription. + * + * @see https://paystack.com/docs/api/subscription/#disable + * + * @throws PaystackException + */ + public function disable(array $payload): array + { + return $this->response($this->httpClient->post('/subscription/disable', $payload)); + } + + /** + * Generate a link for managing a subscription. + * + * @see https://paystack.com/docs/api/subscription/#manage-link + * + * @throws PaystackException + */ + public function manageLink(string $code): array + { + return $this->response($this->httpClient->get("/subscription/{$code}/manage/link")); + } + + /** + * Send a link for managing a subscription. + * + * @see https://paystack.com/docs/api/subscription/#manage-email + * + * @throws PaystackException + */ + public function sendManageLink(string $code): array + { + return $this->response($this->httpClient->post("/subscription/{$code}/manage/email")); + } +} diff --git a/src/Service/Resources/Transaction.php b/src/Service/Resources/Transaction.php new file mode 100644 index 0000000..4e5d0cc --- /dev/null +++ b/src/Service/Resources/Transaction.php @@ -0,0 +1,61 @@ +response($this->httpClient->post('/transaction/initialize', $payload)); + } + + /** + * Verify a transaction. + * + * @see https://paystack.com/docs/api/transaction/#verify + * + * @throws PaystackException + */ + public function verify(string $reference): array + { + return $this->response($this->httpClient->get("/transaction/verify/{$reference}")); + } + + /** + * List transactions. + * + * @see https://paystack.com/docs/api/transaction/#list + * + * @throws PaystackException + */ + public function list(array $queryParams = []): array + { + return $this->response($this->httpClient->get('/transaction', $queryParams)); + } + + /** + * Fetch a transaction. + * + * @see https://paystack.com/docs/api/transaction/#fetch + * + * @throws PaystackException + */ + public function fetch(string $id): array + { + return $this->response($this->httpClient->get("/transaction/{$id}")); + } +} diff --git a/src/Service/Resources/Transfer.php b/src/Service/Resources/Transfer.php new file mode 100644 index 0000000..ed0503f --- /dev/null +++ b/src/Service/Resources/Transfer.php @@ -0,0 +1,74 @@ +response($this->httpClient->post('/transferrecipient', $payload)); + } + + /** + * Initiate a transfer. + * + * @see https://paystack.com/docs/api/transfer/#initiate + * + * @throws PaystackException + */ + public function initiate(array $payload): array + { + return $this->response($this->httpClient->post('/transfer', $payload)); + } + + /** + * List transfers. + * + * @see https://paystack.com/docs/api/transfer/#list + * + * @throws PaystackException + */ + public function list(array $queryParams = []): array + { + return $this->response($this->httpClient->get('/transfer', $queryParams)); + } + + /** + * Fetch a transfer. + * + * @see https://paystack.com/docs/api/transfer/#fetch + * + * @throws PaystackException + */ + public function fetch(string $idOrCode): array + { + return $this->response($this->httpClient->get("/transfer/{$idOrCode}")); + } + + /** + * Verify a transfer. + * + * @see https://paystack.com/docs/api/transfer/#verify + * + * @throws PaystackException + */ + public function verify(string $reference): array + { + return $this->response($this->httpClient->get("/transfer/verify/{$reference}")); + } +} diff --git a/src/Service/Resources/Verification.php b/src/Service/Resources/Verification.php new file mode 100644 index 0000000..be5b0f5 --- /dev/null +++ b/src/Service/Resources/Verification.php @@ -0,0 +1,41 @@ +response($this->httpClient->get('/bank/resolve', [ + 'account_number' => $accountNumber, + 'bank_code' => $bankCode, + ])); + } + + /** + * Resolve card BIN. + * + * @see https://paystack.com/docs/api/verification/#resolve-card-bin + * + * @throws PaystackException + */ + public function resolveCardBin(string $bin): array + { + return $this->response($this->httpClient->get("/decision/bin/{$bin}")); + } +} diff --git a/src/Service/TransactionService.php b/src/Service/TransactionService.php index 20c765e..e071431 100644 --- a/src/Service/TransactionService.php +++ b/src/Service/TransactionService.php @@ -4,8 +4,7 @@ namespace Kommandhub\PaystackSW\Service; -use Kommandhub\Paystack\Paystack; -use Kommandhub\Paystack\Exceptions\PaystackException; +use Kommandhub\PaystackSW\Exceptions\PaystackException; class TransactionService { diff --git a/tests/Integration/Checkout/Payment/PaystackPaymentHandlerTest.php b/tests/Integration/Checkout/Payment/PaystackPaymentHandlerTest.php index 64d436d..3f64f49 100644 --- a/tests/Integration/Checkout/Payment/PaystackPaymentHandlerTest.php +++ b/tests/Integration/Checkout/Payment/PaystackPaymentHandlerTest.php @@ -6,20 +6,22 @@ use Kommandhub\PaystackSW\Checkout\Payment\PaystackPaymentHandler; use Kommandhub\PaystackSW\Service\Config; +use Kommandhub\PaystackSW\Exceptions\PaystackException; use Kommandhub\PaystackSW\Service\OrderTransactionService; use Kommandhub\PaystackSW\Service\PayloadBuilder; +use Kommandhub\PaystackSW\Service\PaymentFinalizedEventService; use Kommandhub\PaystackSW\Service\TransactionService; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionEntity; use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionStateHandler; -use Shopware\Core\Checkout\Payment\Cart\PaymentTransactionStruct; +use Shopware\Core\Checkout\Order\OrderEntity; use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\PaymentHandlerType; +use Shopware\Core\Checkout\Payment\Cart\PaymentTransactionStruct; use Shopware\Core\Checkout\Payment\PaymentException; use Shopware\Core\Framework\Context; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; -use Kommandhub\Paystack\Exceptions\PaystackException; class PaystackPaymentHandlerTest extends TestCase { @@ -28,6 +30,7 @@ class PaystackPaymentHandlerTest extends TestCase private PayloadBuilder $payloadBuilder; private OrderTransactionStateHandler $transactionStateHandler; private Config $config; + private PaymentFinalizedEventService $paymentFinalizedEventService; private LoggerInterface $logger; private PaystackPaymentHandler $handler; @@ -38,6 +41,7 @@ protected function setUp(): void $this->payloadBuilder = $this->createMock(PayloadBuilder::class); $this->transactionStateHandler = $this->createMock(OrderTransactionStateHandler::class); $this->config = $this->createMock(Config::class); + $this->paymentFinalizedEventService = $this->createMock(PaymentFinalizedEventService::class); $this->logger = $this->createMock(LoggerInterface::class); $this->handler = new PaystackPaymentHandler( @@ -46,6 +50,7 @@ protected function setUp(): void $this->payloadBuilder, $this->transactionStateHandler, $this->config, + $this->paymentFinalizedEventService, $this->logger ); } @@ -113,8 +118,10 @@ public function testFinalizeSuccessful(): void $request = new Request(['reference' => 'test_ref']); $transaction = new PaymentTransactionStruct($transactionId, 'https://return.url'); + $order = $this->createMock(OrderEntity::class); $orderTransaction = $this->createMock(OrderTransactionEntity::class); $orderTransaction->method('getId')->willReturn($transactionId); + $orderTransaction->method('getOrder')->willReturn($order); $this->orderTransactionService->method('get')->willReturn($orderTransaction); @@ -132,6 +139,8 @@ public function testFinalizeSuccessful(): void $this->transactionStateHandler->expects($this->once())->method('paid'); $this->orderTransactionService->expects($this->once())->method('updateCustomFields'); + $this->paymentFinalizedEventService->expects($this->once())->method('fireEvent') + ->with($order, $orderTransaction, $transaction, $context); $this->handler->finalize($request, $transaction, $context); } @@ -149,6 +158,7 @@ public function testFinalizeFailsWithoutReference(): void $this->orderTransactionService->method('get')->willReturn($orderTransaction); $this->expectException(PaymentException::class); + $this->expectExceptionMessage('Payment reference is missing from the request.'); $this->handler->finalize($request, $transaction, $context); } @@ -211,7 +221,7 @@ public function testFinalizeFailsWhenVerificationStatusIsFalse(): void $this->transactionService->method('verify')->willReturn(['status' => false, 'message' => 'Verification failed']); $this->expectException(PaymentException::class); - $this->expectExceptionMessage('Verification failed'); + $this->expectExceptionMessage('Unable to verify payment: Verification failed'); $this->handler->finalize($request, $transaction, $context); } @@ -296,6 +306,40 @@ public function testLoggingErrorPaths(): void } } + public function testFinalizeSuccessfulWithMissingOrderInTransaction(): void + { + $context = Context::createDefaultContext(); + $transactionId = 'transaction-id'; + $request = new Request(['reference' => 'test_ref']); + $transaction = new PaymentTransactionStruct($transactionId, 'https://return.url'); + + $orderTransaction = $this->createMock(OrderTransactionEntity::class); + $orderTransaction->method('getId')->willReturn($transactionId); + $orderTransaction->method('getOrder')->willReturn(null); + + $this->orderTransactionService->method('get')->willReturn($orderTransaction); + + $verificationResult = [ + 'status' => true, + 'data' => [ + 'id' => 123, + 'channel' => 'card', + 'fees' => 150, + 'amount' => 10000, + 'currency' => 'NGN', + ], + ]; + $this->transactionService->method('verify')->with('test_ref')->willReturn($verificationResult); + + $this->transactionStateHandler->expects($this->once())->method('paid'); + $this->orderTransactionService->expects($this->once())->method('updateCustomFields'); + + // This should not call fireEvent because order is null + $this->paymentFinalizedEventService->expects($this->never())->method('fireEvent'); + + $this->handler->finalize($request, $transaction, $context); + } + public function testPayFailsWhenAuthorizationUrlIsMissing(): void { $context = Context::createDefaultContext(); @@ -315,4 +359,76 @@ public function testPayFailsWhenAuthorizationUrlIsMissing(): void $this->handler->pay($request, $transaction, $context, null); } + + public function testLoggingDisabled(): void + { + $this->config->method('getBool')->willReturn(false); + $this->logger->expects($this->never())->method('info'); + $this->logger->expects($this->never())->method('error'); + + $context = Context::createDefaultContext(); + $request = new Request(['reference' => 'test_ref']); + $transactionId = 'transaction-id'; + $transaction = new PaymentTransactionStruct($transactionId, 'https://return.url'); + + $orderTransaction = $this->createMock(OrderTransactionEntity::class); + $orderTransaction->method('getId')->willReturn($transactionId); + $this->orderTransactionService->method('get')->willReturn($orderTransaction); + + $this->payloadBuilder->method('build')->willReturn(['payload']); + $this->transactionService->method('initialize')->willReturn(['status' => true, 'data' => ['authorization_url' => 'http://url']]); + $this->transactionService->method('verify')->willReturn(['status' => true, 'data' => ['id' => 'paystack_id']]); + + $this->handler->pay($request, $transaction, $context, null); + $this->handler->finalize($request, $transaction, $context); + + // Also trigger an error path with debugging disabled + $this->transactionService->method('verify')->willReturn(['status' => false, 'message' => 'failed']); + + try { + $this->handler->finalize($request, $transaction, $context); + } catch (PaymentException) { + } + } + + public function testPersistTransactionMetadataWithMissingData(): void + { + $context = Context::createDefaultContext(); + $transactionId = 'transaction-id'; + $request = new Request(['reference' => 'test_ref']); + $transaction = new PaymentTransactionStruct($transactionId, 'https://return.url'); + + $orderTransaction = $this->createMock(OrderTransactionEntity::class); + $orderTransaction->method('getId')->willReturn($transactionId); + $this->orderTransactionService->method('get')->willReturn($orderTransaction); + + // Verification data with missing optional fields + $verificationResult = [ + 'status' => true, + 'data' => [ + // 'id' missing + // 'channel' missing + // 'fees' missing + // 'amount' missing + // 'currency' missing + ], + ]; + $this->transactionService->method('verify')->willReturn($verificationResult); + + $this->orderTransactionService->expects($this->once()) + ->method('updateCustomFields') + ->with( + $transactionId, + $this->callback(function (array $fields) { + return array_key_exists('paystack_transaction_id', $fields) && $fields['paystack_transaction_id'] === null + && array_key_exists('paystack_payment_type', $fields) && $fields['paystack_payment_type'] === null + && array_key_exists('paystack_transaction_fee', $fields) && $fields['paystack_transaction_fee'] === null + && array_key_exists('paystack_amount', $fields) && $fields['paystack_amount'] === null + && array_key_exists('paystack_currency', $fields) && $fields['paystack_currency'] === null; + }), + $context + ); + + $this->handler->finalize($request, $transaction, $context); + } } diff --git a/tests/Setup/config/packages/test/shopware.yaml b/tests/Setup/config/packages/test/shopware.yaml deleted file mode 100644 index 749d4df..0000000 --- a/tests/Setup/config/packages/test/shopware.yaml +++ /dev/null @@ -1,9 +0,0 @@ -shopware: - filesystem: - private: - type: local - root: '%kernel.project_dir%/var/files-test' - - public: - type: local - root: '%kernel.project_dir%/public/files-test' \ No newline at end of file diff --git a/tests/TestBootstrap.php b/tests/TestBootstrap.php index 993f5e8..1c6bdd6 100644 --- a/tests/TestBootstrap.php +++ b/tests/TestBootstrap.php @@ -2,12 +2,16 @@ declare(strict_types=1); -use Shopware\Core\TestBootstrapper; +use Kommandhub\PaystackSW\Tests\TestBootstrapper; $loader = (new TestBootstrapper()) + ->setPlatformEmbedded(true) ->addCallingPlugin() - ->addActivePlugins('KommandhubPaystackSW') ->setForceInstallPlugins(true) + ->addActivePlugins( + 'KommandhubFoundationSW', + 'KommandhubPaystackSW', + ) ->bootstrap() ->getClassLoader(); diff --git a/tests/TestBootstrapper.php b/tests/TestBootstrapper.php new file mode 100644 index 0000000..053218a --- /dev/null +++ b/tests/TestBootstrapper.php @@ -0,0 +1,197 @@ + + */ + private array $activePlugins = []; + + private string $fixtureGroup = 'paystack'; + + protected bool $forceLoadFixtures = false; + + /** + * Optional fixture loading hook (kept for extensibility). + */ + public function setFixtureGroup(string $fixtureGroup): void + { + $this->fixtureGroup = $fixtureGroup; + } + + /** + * Optional fixture loading hook (kept for extensibility). + */ + public function setForceLoadFixtures(bool $forceLoadFixtures): void + { + $this->forceLoadFixtures = $forceLoadFixtures; + } + + public function bootstrap(): ShopwareTestBootstrapper + { + $_SERVER['PROJECT_ROOT'] = $_ENV['PROJECT_ROOT'] = $this->getProjectDir(); + + if (!\defined('TEST_PROJECT_DIR')) { + \define('TEST_PROJECT_DIR', $_SERVER['PROJECT_ROOT']); + } + + if ($this->commercialEnabled && $this->getPluginPath('SwagCommercial')) { + $this->addActivePlugins('SwagCommercial'); + } + + $classLoader = $this->getClassLoader(); + + if ($this->loadEnvFile) { + $this->loadEnvFile(); + } + + $_SERVER['DATABASE_URL'] = $_ENV['DATABASE_URL'] = $this->getDatabaseUrl(); + + KernelLifecycleManager::prepare($classLoader); + + if ($this->isForceInstall() || !$this->dbExists()) { + $this->install(); + + if ($this->activePlugins !== []) { + $this->installPlugins(); + } + + $this->loadFixtures(); + } elseif ($this->forceInstallPlugins) { + $this->installPlugins(); + } + + if ($this->forceLoadFixtures && $this->dbExists()) { + $this->loadFixtures(); + } + + return $this; + } + + /** + * Optional fixture loader (disabled by default). + */ + private function loadFixtures(): void + { + $application = new Application($this->getKernel()); + + $application->doRun( + new ArrayInput([ + 'command' => 'fixture:load', + '--group' => $this->fixtureGroup, + '--env' => 'test', + ]), + $this->getOutput() + ); + + KernelLifecycleManager::bootKernel(); + } + + private function getKernel(): KernelInterface + { + return KernelLifecycleManager::getKernel(); + } + + private function getKernelContainer(): ContainerInterface + { + return $this->getKernel()->getContainer(); + } + + private function dbExists(): bool + { + try { + $connection = $this->getKernelContainer()->get(Connection::class); + $connection->executeQuery('SELECT 1 FROM `plugin`')->fetchAllAssociative(); + + return true; + } catch (\Throwable) { + return false; + } + } + + private function loadEnvFile(): void + { + if (!class_exists(Dotenv::class)) { + throw new \RuntimeException('APP_ENV environment variable is not defined. You need to define environment variables for configuration or add "symfony/dotenv" as a Composer dependency to load variables from a .env file.'); + } + + $envFilePath = $this->getProjectDir() . '/.env'; + + if (\is_file($envFilePath) || \is_file($envFilePath . '.dist') || \is_file($envFilePath . '.local.php')) { + (new Dotenv())->usePutenv()->bootEnv($envFilePath); + } + } + + private function install(): void + { + $application = new Application($this->getKernel()); + + $returnCode = $application->doRun( + new ArrayInput( + [ + 'command' => 'system:install', + '--create-database' => true, + '--force' => true, + '--drop-database' => true, + '--basic-setup' => true, + '--no-assign-theme' => true, + ] + ), + $this->getOutput() + ); + + if ($returnCode !== Command::SUCCESS) { + throw new \RuntimeException('system:install failed'); + } + + // create new kernel after install + KernelLifecycleManager::bootKernel(false); + } + + private function installPlugins(): void + { + $application = new Application($this->getKernel()); + $application->doRun(new ArrayInput(['command' => 'plugin:refresh']), $this->getOutput()); + + $kernel = KernelLifecycleManager::bootKernel(); + + $application = new Application($kernel); + + foreach ($this->activePlugins as $activePlugin) { + $args = [ + 'command' => 'plugin:install', + '--activate' => true, + '--reinstall' => true, + 'plugins' => [$activePlugin], + ]; + + $returnCode = $application->doRun(new ArrayInput($args), $this->getOutput()); + + if ($returnCode !== Command::SUCCESS) { + throw new \RuntimeException('system:install failed'); + } + } + + KernelLifecycleManager::bootKernel(); + } +} diff --git a/tests/Unit/Service/OrderTransactionServiceTest.php b/tests/Unit/Service/OrderTransactionServiceTest.php new file mode 100644 index 0000000..a590f0a --- /dev/null +++ b/tests/Unit/Service/OrderTransactionServiceTest.php @@ -0,0 +1,75 @@ +reader = $this->createMock(OrderTransactionReader::class); + $this->writer = $this->createMock(OrderTransactionWriter::class); + $this->service = new OrderTransactionService($this->reader, $this->writer); + } + + public function testGetSuccessful(): void + { + $transactionId = 'test-id'; + $context = Context::createDefaultContext(); + $orderTransaction = $this->createMock(OrderTransactionEntity::class); + + $this->reader->expects($this->once()) + ->method('readOneById') + ->with($transactionId, $context, $this->isInstanceOf(Criteria::class)) + ->willReturn($orderTransaction); + + $result = $this->service->get($transactionId, $context); + + $this->assertSame($orderTransaction, $result); + } + + public function testGetThrowsExceptionWhenNotFound(): void + { + $transactionId = 'test-id'; + $context = Context::createDefaultContext(); + + $this->reader->method('readOneById')->willReturn(null); + + $this->expectException(PaymentException::class); + $this->expectExceptionMessage(sprintf('Order transaction "%s" could not be found.', $transactionId)); + + $this->service->get($transactionId, $context); + } + + public function testUpdateCustomFields(): void + { + $transactionId = 'test-id'; + $customFields = ['key' => 'value']; + $context = Context::createDefaultContext(); + + $this->writer->expects($this->once()) + ->method('write') + ->with([ + 'id' => $transactionId, + 'customFields' => $customFields, + ], $context); + + $this->service->updateCustomFields($transactionId, $customFields, $context); + } +} diff --git a/tests/Unit/Service/PayloadBuilderTest.php b/tests/Unit/Service/PayloadBuilderTest.php index 270daef..c450d41 100644 --- a/tests/Unit/Service/PayloadBuilderTest.php +++ b/tests/Unit/Service/PayloadBuilderTest.php @@ -8,10 +8,14 @@ use Kommandhub\PaystackSW\Service\PayloadBuilder; use PHPUnit\Framework\TestCase; use Shopware\Core\Checkout\Cart\Price\Struct\CalculatedPrice; +use Shopware\Core\Checkout\Order\Aggregate\OrderAddress\OrderAddressEntity; use Shopware\Core\Checkout\Order\Aggregate\OrderCustomer\OrderCustomerEntity; +use Shopware\Core\Checkout\Order\Aggregate\OrderLineItem\OrderLineItemCollection; +use Shopware\Core\Checkout\Order\Aggregate\OrderLineItem\OrderLineItemEntity; use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionEntity; use Shopware\Core\Checkout\Order\OrderEntity; use Shopware\Core\Checkout\Payment\Cart\PaymentTransactionStruct; +use Shopware\Core\System\Country\CountryEntity; use Shopware\Core\System\Currency\CurrencyEntity; class PayloadBuilderTest extends TestCase @@ -47,7 +51,10 @@ public function testBuildSuccessful(): void $transaction->method('getReturnUrl')->willReturn('https://return.url'); - $this->config->method('get')->with('paymentOptions', null, 'sales-channel-id')->willReturn(['card', 'bank']); + $this->config->method('get')->willReturnMap([ + ['paymentOptions', null, 'sales-channel-id', ['card', 'bank']], + ['metaData', [], 'sales-channel-id', []], + ]); $payload = $this->payloadBuilder->build($orderTransaction, $transaction); @@ -129,4 +136,84 @@ public function testBuildThrowsExceptionWhenReturnUrlIsMissing(): void $this->payloadBuilder->build($orderTransaction, $transaction); } + + public function testBuildWithMetadata(): void + { + $orderTransaction = $this->createMock(OrderTransactionEntity::class); + $transaction = $this->createMock(PaymentTransactionStruct::class); + $order = $this->createMock(OrderEntity::class); + $customer = $this->createMock(OrderCustomerEntity::class); + $currency = $this->createMock(CurrencyEntity::class); + $amount = $this->createMock(CalculatedPrice::class); + $billingAddress = $this->createMock(OrderAddressEntity::class); + $country = $this->createMock(CountryEntity::class); + $lineItem = $this->createMock(OrderLineItemEntity::class); + $lineItems = new OrderLineItemCollection([$lineItem]); + + $orderTransaction->method('getOrder')->willReturn($order); + $orderTransaction->method('getAmount')->willReturn($amount); + $amount->method('getTotalPrice')->willReturn(100.00); + + $order->method('getOrderCustomer')->willReturn($customer); + $order->method('getCurrency')->willReturn($currency); + $order->method('getSalesChannelId')->willReturn('sales-channel-id'); + $order->method('getOrderNumber')->willReturn('ORDER-123'); + $order->method('getBillingAddress')->willReturn($billingAddress); + $order->method('getLineItems')->willReturn($lineItems); + + $customer->method('getEmail')->willReturn('test@example.com'); + $customer->method('getFirstName')->willReturn('John'); + $customer->method('getLastName')->willReturn('Doe'); + + $currency->method('getIsoCode')->willReturn('NGN'); + + $billingAddress->method('getFirstName')->willReturn('John'); + $billingAddress->method('getLastName')->willReturn('Doe'); + $billingAddress->method('getStreet')->willReturn('Main St 123'); + $billingAddress->method('getZipcode')->willReturn('12345'); + $billingAddress->method('getCity')->willReturn('Lagos'); + $billingAddress->method('getCountry')->willReturn($country); + $billingAddress->method('getPhoneNumber')->willReturn('08012345678'); + $country->method('getName')->willReturn('Nigeria'); + + $lineItem->method('getQuantity')->willReturn(2); + $lineItem->method('getLabel')->willReturn('Test Product'); + + $transaction->method('getReturnUrl')->willReturn('https://return.url'); + + $this->config->method('get')->willReturnMap([ + ['paymentOptions', null, 'sales-channel-id', ['card']], + ['metaData', [], 'sales-channel-id', ['orderId', 'customerName', 'customerPhone', 'products']], + ]); + + $payload = $this->payloadBuilder->build($orderTransaction, $transaction); + + $expectedMetadata = [ + 'cancel_action' => 'https://return.url', + 'custom_fields' => [ + [ + 'display_name' => 'Order ID', + 'variable_name' => 'order_id', + 'value' => 'ORDER-123', + ], + [ + 'display_name' => 'Customer Name', + 'variable_name' => 'customer_name', + 'value' => 'John Doe', + ], + [ + 'display_name' => 'Customer Phone', + 'variable_name' => 'customer_phone', + 'value' => '08012345678', + ], + [ + 'display_name' => 'Product(s) Purchased', + 'variable_name' => 'products_purchased', + 'value' => '2x Test Product', + ], + ], + ]; + + $this->assertEquals($expectedMetadata, $payload['metadata']); + } } diff --git a/tests/Unit/Service/PaymentFinalizedEventServiceTest.php b/tests/Unit/Service/PaymentFinalizedEventServiceTest.php new file mode 100644 index 0000000..a446366 --- /dev/null +++ b/tests/Unit/Service/PaymentFinalizedEventServiceTest.php @@ -0,0 +1,34 @@ +createMock(EventDispatcherInterface::class); + $service = new PaymentFinalizedEventService($eventDispatcher); + + $order = $this->createMock(OrderEntity::class); + $orderTransaction = $this->createMock(OrderTransactionEntity::class); + $paymentTransactionStruct = $this->createMock(PaymentTransactionStruct::class); + $context = Context::createDefaultContext(); + + $eventDispatcher->expects($this->once()) + ->method('dispatch') + ->with($this->isInstanceOf(PaystackPaymentFinalizedEvent::class)); + + $service->fireEvent($order, $orderTransaction, $paymentTransactionStruct, $context); + } +} diff --git a/tests/Unit/Service/PaystackFactoryTest.php b/tests/Unit/Service/PaystackFactoryTest.php deleted file mode 100644 index fe610be..0000000 --- a/tests/Unit/Service/PaystackFactoryTest.php +++ /dev/null @@ -1,59 +0,0 @@ -config = $this->createMock(Config::class); - $this->client = $this->createMock(ClientInterface::class); - $this->requestFactory = $this->createMock(RequestFactoryInterface::class); - $this->streamFactory = $this->createMock(StreamFactoryInterface::class); - $this->paystackFactory = new PaystackFactory( - $this->config, - $this->client, - $this->requestFactory, - $this->streamFactory - ); - } - - public function testCreateLiveMode(): void - { - $this->config->method('getBool')->with('enableSandbox', 'sales-channel-id')->willReturn(false); - $this->config->method('get')->with('apiSecretKey', '', 'sales-channel-id')->willReturn('live_secret_key'); - - $paystack = $this->paystackFactory->create('sales-channel-id'); - - $this->assertInstanceOf(Paystack::class, $paystack); - - // We can't easily verify the internal state of Paystack without reflection or exposing it, - // but the factory logic itself is tested by ensuring it uses the correct keys. - } - - public function testCreateSandboxMode(): void - { - $this->config->method('getBool')->with('enableSandbox', 'sales-channel-id')->willReturn(true); - $this->config->method('get')->with('apiSecretKeySandbox', '', 'sales-channel-id')->willReturn('sandbox_secret_key'); - - $paystack = $this->paystackFactory->create('sales-channel-id'); - - $this->assertInstanceOf(Paystack::class, $paystack); - } -} diff --git a/tests/Unit/Service/TransactionServiceTest.php b/tests/Unit/Service/TransactionServiceTest.php index 76bb238..f2437b3 100644 --- a/tests/Unit/Service/TransactionServiceTest.php +++ b/tests/Unit/Service/TransactionServiceTest.php @@ -4,8 +4,8 @@ namespace Kommandhub\PaystackSW\Tests\Unit\Service; -use Kommandhub\Paystack\Paystack; -use Kommandhub\Paystack\Resources\Transaction; +use Kommandhub\PaystackSW\Service\Paystack; +use Kommandhub\PaystackSW\Service\Resources\Transaction; use Kommandhub\PaystackSW\Service\TransactionService; use PHPUnit\Framework\TestCase; diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 55ed182..fce267f 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -8,4 +8,5 @@ } // Otherwise (local dev) → use Shopware bootstrap +require __DIR__ . '/TestBootstrapper.php'; require __DIR__ . '/TestBootstrap.php'; From 9fabd69e9959729d8d00616592b81a59f41cb7c1 Mon Sep 17 00:00:00 2001 From: Anitche Chisom Date: Sun, 7 Jun 2026 19:52:53 +0200 Subject: [PATCH 02/49] Add split payment transaction. --- .../Payment/PaystackPaymentHandler.php | 1 + src/Contracts/HttpClientInterface.php | 2 +- src/Exceptions/PaystackException.php | 2 +- src/Resources/config/config.xml | 16 ++++ src/Service/Http/PaystackHttpClient.php | 18 ++-- src/Service/PayloadBuilder.php | 43 ++++++++- src/Service/Paystack.php | 2 +- src/Service/Resources/ApiResource.php | 3 +- src/Service/Resources/Customer.php | 1 - tests/Unit/Service/PayloadBuilderTest.php | 92 +++++++++++++++++++ 10 files changed, 164 insertions(+), 16 deletions(-) diff --git a/src/Checkout/Payment/PaystackPaymentHandler.php b/src/Checkout/Payment/PaystackPaymentHandler.php index 5a8b01b..eeb1b8c 100644 --- a/src/Checkout/Payment/PaystackPaymentHandler.php +++ b/src/Checkout/Payment/PaystackPaymentHandler.php @@ -168,6 +168,7 @@ public function finalize( $data = $verification['data'] ?? []; $paystackTransactionId = null; + if (is_array($data) && isset($data['id'])) { $paystackTransactionId = $data['id']; } diff --git a/src/Contracts/HttpClientInterface.php b/src/Contracts/HttpClientInterface.php index 79326ae..567ed07 100644 --- a/src/Contracts/HttpClientInterface.php +++ b/src/Contracts/HttpClientInterface.php @@ -8,7 +8,7 @@ use Symfony\Contracts\HttpClient\ResponseInterface; /** - * Interface HttpClientInterface + * Interface HttpClientInterface. */ interface HttpClientInterface { diff --git a/src/Exceptions/PaystackException.php b/src/Exceptions/PaystackException.php index 73e1aaf..bfe723f 100644 --- a/src/Exceptions/PaystackException.php +++ b/src/Exceptions/PaystackException.php @@ -5,7 +5,7 @@ namespace Kommandhub\PaystackSW\Exceptions; /** - * Class PaystackException + * Class PaystackException. */ class PaystackException extends \Exception { diff --git a/src/Resources/config/config.xml b/src/Resources/config/config.xml index cd95fe4..47ef695 100644 --- a/src/Resources/config/config.xml +++ b/src/Resources/config/config.xml @@ -84,6 +84,22 @@ + + splitCode + + + + + The code for the split group that should receive a split of the payment (e.g., SPL_xxxxxxxxx). If both Subaccount Code and Split Code are provided, Split Code will take precedence. + + + Der Code für die Split-Gruppe, die eine Aufteilung der Zahlung erhalten soll (z. B. SPL_xxxxxxxxx). Wenn sowohl der Unterkonto-Code als auch der Split-Code angegeben sind, hat der Split-Code Vorrang. + + + Le code du groupe de répartition qui doit recevoir une partie du paiement (ex: SPL_xxxxxxxxx). Si le code du sous-compte et le code de répartition sont tous deux fournis, le code de répartition sera prioritaire. + + + splitPaymentTransactionCharge diff --git a/src/Service/Http/PaystackHttpClient.php b/src/Service/Http/PaystackHttpClient.php index 8b59eb5..c28b0e2 100644 --- a/src/Service/Http/PaystackHttpClient.php +++ b/src/Service/Http/PaystackHttpClient.php @@ -11,7 +11,7 @@ use Symfony\Contracts\HttpClient\ResponseInterface; /** - * Class PaystackHttpClient + * Class PaystackHttpClient. */ class PaystackHttpClient implements HttpClientInterface { @@ -47,10 +47,10 @@ private function getSecretKey(?string $salesChannelId = null): string public function get(string $endpoint, array $queryParams = [], ?string $salesChannelId = null): ResponseInterface { try { - return $this->client->request('GET', self::BASE_URL.$endpoint, [ + return $this->client->request('GET', self::BASE_URL . $endpoint, [ 'query' => $queryParams, 'headers' => [ - 'Authorization' => 'Bearer '.$this->getSecretKey($salesChannelId), + 'Authorization' => 'Bearer ' . $this->getSecretKey($salesChannelId), 'Content-Type' => 'application/json', ], ]); @@ -68,10 +68,10 @@ public function get(string $endpoint, array $queryParams = [], ?string $salesCha public function post(string $endpoint, array $payload = [], ?string $salesChannelId = null): ResponseInterface { try { - return $this->client->request('POST', self::BASE_URL.$endpoint, [ + return $this->client->request('POST', self::BASE_URL . $endpoint, [ 'json' => $payload, 'headers' => [ - 'Authorization' => 'Bearer '.$this->getSecretKey($salesChannelId), + 'Authorization' => 'Bearer ' . $this->getSecretKey($salesChannelId), 'Content-Type' => 'application/json', ], ]); @@ -89,10 +89,10 @@ public function post(string $endpoint, array $payload = [], ?string $salesChanne public function put(string $endpoint, array $payload = [], ?string $salesChannelId = null): ResponseInterface { try { - return $this->client->request('PUT', self::BASE_URL.$endpoint, [ + return $this->client->request('PUT', self::BASE_URL . $endpoint, [ 'json' => $payload, 'headers' => [ - 'Authorization' => 'Bearer '.$this->getSecretKey($salesChannelId), + 'Authorization' => 'Bearer ' . $this->getSecretKey($salesChannelId), 'Content-Type' => 'application/json', ], ]); @@ -110,9 +110,9 @@ public function put(string $endpoint, array $payload = [], ?string $salesChannel public function delete(string $endpoint, ?string $salesChannelId = null): ResponseInterface { try { - return $this->client->request('DELETE', self::BASE_URL.$endpoint, [ + return $this->client->request('DELETE', self::BASE_URL . $endpoint, [ 'headers' => [ - 'Authorization' => 'Bearer '.$this->getSecretKey($salesChannelId), + 'Authorization' => 'Bearer ' . $this->getSecretKey($salesChannelId), 'Content-Type' => 'application/json', ], ]); diff --git a/src/Service/PayloadBuilder.php b/src/Service/PayloadBuilder.php index 5f5728c..7e1b99e 100644 --- a/src/Service/PayloadBuilder.php +++ b/src/Service/PayloadBuilder.php @@ -57,7 +57,7 @@ public function build(OrderTransactionEntity $orderTransaction, PaymentTransacti throw new \RuntimeException('Return URL is missing in the payment transaction struct.'); } - // 5. Fetch sales channel specific configuration for payment options. + // 5. Fetch sales channel-specific configuration for payment options. $salesChannelId = $order->getSalesChannelId(); $paymentOptions = $this->config->get( @@ -65,6 +65,7 @@ public function build(OrderTransactionEntity $orderTransaction, PaymentTransacti salesChannelId: $salesChannelId ); + /** @var array $selectedMetaData */ $selectedMetaData = $this->config->get( key: 'metaData', default: [], @@ -74,7 +75,7 @@ public function build(OrderTransactionEntity $orderTransaction, PaymentTransacti // 6. Build the final payload array according to Paystack API specifications. // The amount is multiplied by 100 to convert from the major currency unit (e.g., Naira) // to the minor unit (e.g., kobo) as expected by Paystack. - return [ + $payload = [ 'amount' => (int)round($orderTransaction->getAmount()->getTotalPrice() * 100), 'currency' => $currency->getIsoCode(), 'email' => $customer->getEmail(), @@ -82,6 +83,36 @@ public function build(OrderTransactionEntity $orderTransaction, PaymentTransacti 'channels' => $paymentOptions, 'metadata' => $this->buildMetadata($order, $selectedMetaData, (string)$returnUrl), ]; + + // 7. Add split payment parameters if enabled. + $enableSplitPayment = $this->config->getBool('enableSplitPayment', $salesChannelId); + + if ($enableSplitPayment) { + $subaccountCode = $this->config->getString('subaccountCode', $salesChannelId); + $splitCode = $this->config->getString('splitCode', $salesChannelId); + + if ($splitCode !== '') { + $payload['split_code'] = $splitCode; + } elseif ($subaccountCode !== '') { + $payload['subaccount'] = $subaccountCode; + } + + if (isset($payload['split_code']) || isset($payload['subaccount'])) { + $transactionCharge = $this->config->get('splitPaymentTransactionCharge', null, $salesChannelId); + + if ($transactionCharge !== null && (int)$transactionCharge > 0) { + $payload['transaction_charge'] = (int)$transactionCharge * 100; + } + + $bearer = $this->config->getString('paystackChargesBearer', $salesChannelId); + + if ($bearer !== '') { + $payload['bearer'] = $bearer; + } + } + } + + return $payload; } /** @@ -117,6 +148,7 @@ private function buildMetadata(OrderEntity $order, array $selectedMetaData, stri break; case 'customerName': $customer = $order->getOrderCustomer(); + if ($customer) { $metadata['custom_fields'][] = [ 'display_name' => 'Customer Name', @@ -127,6 +159,7 @@ private function buildMetadata(OrderEntity $order, array $selectedMetaData, stri break; case 'customerEmail': $customer = $order->getOrderCustomer(); + if ($customer) { $metadata['custom_fields'][] = [ 'display_name' => 'Customer Email', @@ -137,6 +170,7 @@ private function buildMetadata(OrderEntity $order, array $selectedMetaData, stri break; case 'customerPhone': $billing = $order->getBillingAddress(); + if ($billing && $billing->getPhoneNumber()) { $metadata['custom_fields'][] = [ 'display_name' => 'Customer Phone', @@ -147,6 +181,7 @@ private function buildMetadata(OrderEntity $order, array $selectedMetaData, stri break; case 'billingAddress': $billing = $order->getBillingAddress(); + if ($billing) { $metadata['custom_fields'][] = [ 'display_name' => 'Order Billing Address', @@ -158,9 +193,11 @@ private function buildMetadata(OrderEntity $order, array $selectedMetaData, stri case 'shippingAddress': $shipping = null; $deliveries = $order->getDeliveries(); + if ($deliveries && $deliveries->first()) { $shipping = $deliveries->first()->getShippingOrderAddress(); } + if ($shipping) { $metadata['custom_fields'][] = [ 'display_name' => 'Order Shipping Address', @@ -171,6 +208,7 @@ private function buildMetadata(OrderEntity $order, array $selectedMetaData, stri break; case 'products': $lineItems = $order->getLineItems(); + if ($lineItems && $lineItems->count() > 0) { $metadata['custom_fields'][] = [ 'display_name' => 'Product(s) Purchased', @@ -219,6 +257,7 @@ private function formatAddress(OrderAddressEntity $address): string private function formatLineItems(OrderLineItemCollection $lineItems): string { $items = []; + foreach ($lineItems as $lineItem) { $items[] = sprintf('%dx %s', $lineItem->getQuantity(), $lineItem->getLabel()); } diff --git a/src/Service/Paystack.php b/src/Service/Paystack.php index 5c68e19..12db8e6 100644 --- a/src/Service/Paystack.php +++ b/src/Service/Paystack.php @@ -18,7 +18,7 @@ use Kommandhub\PaystackSW\Service\Resources\Subaccount; /** - * Class Paystack + * Class Paystack. */ class Paystack { diff --git a/src/Service/Resources/ApiResource.php b/src/Service/Resources/ApiResource.php index 925db97..bd2d5aa 100644 --- a/src/Service/Resources/ApiResource.php +++ b/src/Service/Resources/ApiResource.php @@ -5,6 +5,7 @@ namespace Kommandhub\PaystackSW\Service\Resources; use Kommandhub\PaystackSW\Contracts\HttpClientInterface; +use Symfony\Contracts\HttpClient\ResponseInterface; /** * Class ApiResource @@ -21,7 +22,7 @@ public function __construct(protected HttpClientInterface $httpClient) /** * Parse the response from the API. */ - protected function response(mixed $response): array + protected function response(ResponseInterface $response): array { return $response->toArray(); } diff --git a/src/Service/Resources/Customer.php b/src/Service/Resources/Customer.php index 80ff13f..0884b72 100644 --- a/src/Service/Resources/Customer.php +++ b/src/Service/Resources/Customer.php @@ -5,7 +5,6 @@ namespace Kommandhub\PaystackSW\Service\Resources; use Kommandhub\PaystackSW\Exceptions\PaystackException; -use Kommandhub\PaystackSW\Service\Resources\ApiResource; /** * Class Customer diff --git a/tests/Unit/Service/PayloadBuilderTest.php b/tests/Unit/Service/PayloadBuilderTest.php index c450d41..971ddc7 100644 --- a/tests/Unit/Service/PayloadBuilderTest.php +++ b/tests/Unit/Service/PayloadBuilderTest.php @@ -216,4 +216,96 @@ public function testBuildWithMetadata(): void $this->assertEquals($expectedMetadata, $payload['metadata']); } + + public function testBuildWithSplitPayment(): void + { + $orderTransaction = $this->createMock(OrderTransactionEntity::class); + $transaction = $this->createMock(PaymentTransactionStruct::class); + $order = $this->createMock(OrderEntity::class); + $customer = $this->createMock(OrderCustomerEntity::class); + $currency = $this->createMock(CurrencyEntity::class); + $amount = $this->createMock(CalculatedPrice::class); + + $orderTransaction->method('getOrder')->willReturn($order); + $orderTransaction->method('getAmount')->willReturn($amount); + $amount->method('getTotalPrice')->willReturn(100.00); + + $order->method('getOrderCustomer')->willReturn($customer); + $order->method('getCurrency')->willReturn($currency); + $order->method('getSalesChannelId')->willReturn('sales-channel-id'); + + $customer->method('getEmail')->willReturn('test@example.com'); + $currency->method('getIsoCode')->willReturn('NGN'); + + $transaction->method('getReturnUrl')->willReturn('https://return.url'); + + $this->config->method('get')->willReturnMap([ + ['paymentOptions', null, 'sales-channel-id', ['card']], + ['metaData', [], 'sales-channel-id', []], + ['splitPaymentTransactionCharge', null, 'sales-channel-id', 50], + ]); + + $this->config->method('getBool')->willReturnMap([ + ['enableSplitPayment', 'sales-channel-id', true], + ]); + + $this->config->method('getString')->willReturnMap([ + ['subaccountCode', 'sales-channel-id', 'ACCT_12345'], + ['splitCode', 'sales-channel-id', ''], + ['paystackChargesBearer', 'sales-channel-id', 'subaccount'], + ]); + + $payload = $this->payloadBuilder->build($orderTransaction, $transaction); + + $this->assertEquals('ACCT_12345', $payload['subaccount']); + $this->assertEquals(5000, $payload['transaction_charge']); + $this->assertEquals('subaccount', $payload['bearer']); + $this->assertArrayNotHasKey('split_code', $payload); + } + + public function testBuildWithSplitGroup(): void + { + $orderTransaction = $this->createMock(OrderTransactionEntity::class); + $transaction = $this->createMock(PaymentTransactionStruct::class); + $order = $this->createMock(OrderEntity::class); + $customer = $this->createMock(OrderCustomerEntity::class); + $currency = $this->createMock(CurrencyEntity::class); + $amount = $this->createMock(CalculatedPrice::class); + + $orderTransaction->method('getOrder')->willReturn($order); + $orderTransaction->method('getAmount')->willReturn($amount); + $amount->method('getTotalPrice')->willReturn(100.00); + + $order->method('getOrderCustomer')->willReturn($customer); + $order->method('getCurrency')->willReturn($currency); + $order->method('getSalesChannelId')->willReturn('sales-channel-id'); + + $customer->method('getEmail')->willReturn('test@example.com'); + $currency->method('getIsoCode')->willReturn('NGN'); + + $transaction->method('getReturnUrl')->willReturn('https://return.url'); + + $this->config->method('get')->willReturnMap([ + ['paymentOptions', null, 'sales-channel-id', ['card']], + ['metaData', [], 'sales-channel-id', []], + ['splitPaymentTransactionCharge', null, 'sales-channel-id', 100], + ]); + + $this->config->method('getBool')->willReturnMap([ + ['enableSplitPayment', 'sales-channel-id', true], + ]); + + $this->config->method('getString')->willReturnMap([ + ['subaccountCode', 'sales-channel-id', ''], + ['splitCode', 'sales-channel-id', 'SPL_67890'], + ['paystackChargesBearer', 'sales-channel-id', 'account'], + ]); + + $payload = $this->payloadBuilder->build($orderTransaction, $transaction); + + $this->assertEquals('SPL_67890', $payload['split_code']); + $this->assertEquals(10000, $payload['transaction_charge']); + $this->assertEquals('account', $payload['bearer']); + $this->assertArrayNotHasKey('subaccount', $payload); + } } From e6284f6d00da0eeccc8d6e83a30d5e65c2293180 Mon Sep 17 00:00:00 2001 From: Anitche Chisom Date: Tue, 9 Jun 2026 17:29:12 +0200 Subject: [PATCH 03/49] Implement Bank data collection and verification. --- .../Payment/PaystackPaymentHandler.php | 2 +- src/KommandhubPaystackSW.php | 35 +- .../kommandhub-paystack-s-w.js | 1 + ...aystack-bank-verification.plugin.d99562.js | 1 + src/Resources/app/storefront/src/main.js | 7 + .../paystack-bank-verification.plugin.js | 340 +++++++++++ src/Resources/config/config.xml | 44 ++ src/Resources/config/plugin.png | Bin 12570 -> 1611 bytes src/Resources/config/routes.yml | 3 + src/Resources/snippet/storefront.de-DE.json | 14 + src/Resources/snippet/storefront.en-GB.json | 14 + src/Resources/snippet/storefront.fr-FR.json | 14 + .../storefront/page/account/bank.html.twig | 45 ++ .../storefront/page/account/index.html.twig | 6 + .../page/account/profile/index.html.twig | 113 ++++ src/Service/CustomFieldsInstaller.php | 180 ++++++ src/Service/PayloadBuilder.php | 16 +- .../Controller/BankVerificationController.php | 174 ++++++ .../Validation/BankValidationFactory.php | 48 ++ .../Payment/PaystackPaymentHandlerTest.php | 108 ++++ tests/Unit/KommandhubPaystackSWTest.php | 165 ++--- .../Service/CustomFieldsInstallerTest.php | 111 ++++ .../Service/Http/PaystackHttpClientTest.php | 196 ++++++ .../Service/OrderTransactionServiceTest.php | 42 +- tests/Unit/Service/PayloadBuilderTest.php | 451 +++++++++----- .../PaymentFinalizedEventServiceTest.php | 12 +- tests/Unit/Service/PaystackTest.php | 87 +++ tests/Unit/Service/Resources/CustomerTest.php | 82 +++ .../Service/Resources/MiscellaneousTest.php | 64 ++ tests/Unit/Service/Resources/PlanTest.php | 80 +++ tests/Unit/Service/Resources/RefundTest.php | 65 ++ .../Unit/Service/Resources/SettlementTest.php | 50 ++ tests/Unit/Service/Resources/SplitTest.php | 110 ++++ .../Unit/Service/Resources/SubaccountTest.php | 80 +++ .../Service/Resources/SubscriptionTest.php | 123 ++++ .../Service/Resources/TransactionTest.php | 81 +++ tests/Unit/Service/Resources/TransferTest.php | 97 +++ .../Service/Resources/VerificationTest.php | 56 ++ .../BankVerificationControllerTest.php | 564 ++++++++++++++++++ .../Validation/BankValidationFactoryTest.php | 91 +++ 40 files changed, 3472 insertions(+), 300 deletions(-) create mode 100644 src/Resources/app/storefront/dist/storefront/js/kommandhub-paystack-s-w/kommandhub-paystack-s-w.js create mode 100644 src/Resources/app/storefront/dist/storefront/js/kommandhub-paystack-s-w/kommandhub-paystack-s-w.paystack-bank-verification.plugin.d99562.js create mode 100644 src/Resources/app/storefront/src/main.js create mode 100644 src/Resources/app/storefront/src/paystack-bank-verification-plugin/paystack-bank-verification.plugin.js create mode 100644 src/Resources/config/routes.yml create mode 100644 src/Resources/snippet/storefront.de-DE.json create mode 100644 src/Resources/snippet/storefront.en-GB.json create mode 100644 src/Resources/snippet/storefront.fr-FR.json create mode 100644 src/Resources/views/storefront/page/account/bank.html.twig create mode 100644 src/Resources/views/storefront/page/account/index.html.twig create mode 100644 src/Resources/views/storefront/page/account/profile/index.html.twig create mode 100644 src/Service/CustomFieldsInstaller.php create mode 100644 src/Storefront/Controller/BankVerificationController.php create mode 100644 src/Storefront/Validation/BankValidationFactory.php create mode 100644 tests/Unit/Checkout/Payment/PaystackPaymentHandlerTest.php create mode 100644 tests/Unit/Service/CustomFieldsInstallerTest.php create mode 100644 tests/Unit/Service/Http/PaystackHttpClientTest.php create mode 100644 tests/Unit/Service/PaystackTest.php create mode 100644 tests/Unit/Service/Resources/CustomerTest.php create mode 100644 tests/Unit/Service/Resources/MiscellaneousTest.php create mode 100644 tests/Unit/Service/Resources/PlanTest.php create mode 100644 tests/Unit/Service/Resources/RefundTest.php create mode 100644 tests/Unit/Service/Resources/SettlementTest.php create mode 100644 tests/Unit/Service/Resources/SplitTest.php create mode 100644 tests/Unit/Service/Resources/SubaccountTest.php create mode 100644 tests/Unit/Service/Resources/SubscriptionTest.php create mode 100644 tests/Unit/Service/Resources/TransactionTest.php create mode 100644 tests/Unit/Service/Resources/TransferTest.php create mode 100644 tests/Unit/Service/Resources/VerificationTest.php create mode 100644 tests/Unit/Storefront/Controller/BankVerificationControllerTest.php create mode 100644 tests/Unit/Storefront/Validation/BankValidationFactoryTest.php diff --git a/src/Checkout/Payment/PaystackPaymentHandler.php b/src/Checkout/Payment/PaystackPaymentHandler.php index eeb1b8c..dbdb511 100644 --- a/src/Checkout/Payment/PaystackPaymentHandler.php +++ b/src/Checkout/Payment/PaystackPaymentHandler.php @@ -271,7 +271,7 @@ private function persistTransactionMetadata( $data = $verification['data'] ?? []; if (!is_array($data)) { - $data = []; + $data = []; // @codeCoverageIgnore } $this->orderTransactionService->updateCustomFields( diff --git a/src/KommandhubPaystackSW.php b/src/KommandhubPaystackSW.php index 006aedc..e252c90 100644 --- a/src/KommandhubPaystackSW.php +++ b/src/KommandhubPaystackSW.php @@ -5,6 +5,7 @@ namespace Kommandhub\PaystackSW; use Kommandhub\PaystackSW\Checkout\Payment\PaystackPaymentHandler; +use Kommandhub\PaystackSW\Service\CustomFieldsInstaller; use Shopware\Core\Checkout\Payment\PaymentMethodCollection; use Shopware\Core\Framework\Context; use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository; @@ -27,6 +28,8 @@ public function executeComposerCommands(): bool public function install(InstallContext $installContext): void { $this->addPaymentMethod($installContext->getContext()); + $this->getCustomFieldsInstaller()->install($installContext->getContext()); + $this->getCustomFieldsInstaller()->addRelations($installContext->getContext()); } public function uninstall(UninstallContext $uninstallContext): void @@ -38,10 +41,10 @@ public function uninstall(UninstallContext $uninstallContext): void $this->setPaymentMethodIsActive(false, $uninstallContext->getContext()); if ($uninstallContext->keepUserData()) { - return; + return; // @codeCoverageIgnore } - // Remove or deactivate the data created by the plugin + $this->getCustomFieldsInstaller()->uninstall($uninstallContext->getContext()); // @codeCoverageIgnore } public function activate(ActivateContext $activateContext): void @@ -60,17 +63,17 @@ private function addPaymentMethod(Context $context): void { /** @phpstan-ignore-next-line */ if (!isset($this->container) || $this->container === null) { - return; + return; // @codeCoverageIgnore } $paymentMethodExists = $this->getPaymentMethodId(); // Payment method exists already, no need to continue here - if ($paymentMethodExists) { + if ($paymentMethodExists) { // @codeCoverageIgnoreStart $this->setPaymentMethodIsActive(true, $context); return; - } + } // @codeCoverageIgnoreEnd /** @var PluginIdProvider $pluginIdProvider */ $pluginIdProvider = $this->container->get(PluginIdProvider::class); @@ -97,7 +100,7 @@ private function setPaymentMethodIsActive(bool $active, Context $context): void { /** @phpstan-ignore-next-line */ if (!isset($this->container) || $this->container === null) { - return; + return; // @codeCoverageIgnore } /** @var EntityRepository $paymentRepository */ @@ -133,4 +136,24 @@ private function getPaymentMethodId(): ?string return $paymentMethodRepository->searchIds($paymentCriteria, Context::createDefaultContext())->firstId(); } + + private function getCustomFieldsInstaller(): CustomFieldsInstaller + { + /** @phpstan-ignore-next-line */ + if (!isset($this->container) || $this->container === null) { + throw new \RuntimeException('The container is not available.'); // @codeCoverageIgnore + } + + $customFieldSetRepository = $this->container->get('custom_field_set.repository'); + $customFieldSetRelationRepository = $this->container->get('custom_field_set_relation.repository'); + + if (!$customFieldSetRelationRepository instanceof EntityRepository || !$customFieldSetRepository instanceof EntityRepository) { + throw new \RuntimeException('Required repositories are not available in the container.'); // @codeCoverageIgnore + } + + return new CustomFieldsInstaller( + $customFieldSetRepository, + $customFieldSetRelationRepository + ); + } } diff --git a/src/Resources/app/storefront/dist/storefront/js/kommandhub-paystack-s-w/kommandhub-paystack-s-w.js b/src/Resources/app/storefront/dist/storefront/js/kommandhub-paystack-s-w/kommandhub-paystack-s-w.js new file mode 100644 index 0000000..43f36a7 --- /dev/null +++ b/src/Resources/app/storefront/dist/storefront/js/kommandhub-paystack-s-w/kommandhub-paystack-s-w.js @@ -0,0 +1 @@ +(()=>{var e={},r={};function t(o){var n=r[o];if(void 0!==n)return n.exports;var a=r[o]={exports:{}};return e[o](a,a.exports,t),a.exports}t.m=e,t.d=(e,r)=>{for(var o in r)t.o(r,o)&&!t.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:r[o]})},t.f={},t.e=e=>Promise.all(Object.keys(t.f).reduce((r,o)=>(t.f[o](e,r),r),[])),t.u=e=>"./js/kommandhub-paystack-s-w/kommandhub-paystack-s-w.paystack-bank-verification.plugin.d99562.js",t.miniCssF=e=>{},t.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}}(),t.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r),(()=>{var e={};t.l=(r,o,n,a)=>{if(e[r]){e[r].push(o);return}if(void 0!==n)for(var i,c,s=document.getElementsByTagName("script"),l=0;l{i.onerror=i.onload=null,clearTimeout(d);var n=e[r];if(delete e[r],i.parentNode&&i.parentNode.removeChild(i),n&&n.forEach(e=>e(o)),t)return t(o)},d=setTimeout(p.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=p.bind(null,i.onerror),i.onload=p.bind(null,i.onload),c&&document.head.appendChild(i)}})(),t.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{t.g.importScripts&&(e=t.g.location+"");var e,r=t.g.document;if(!e&&r&&(r.currentScript&&"SCRIPT"===r.currentScript.tagName.toUpperCase()&&(e=r.currentScript.src),!e)){var o=r.getElementsByTagName("script");if(o.length)for(var n=o.length-1;n>-1&&(!e||!/^http(s?):/.test(e));)e=o[n--].src}if(!e)throw Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),t.p=e+"../../"})(),(()=>{var e={46170:0};t.f.j=(r,o)=>{var n=t.o(e,r)?e[r]:void 0;if(0!==n){if(n)o.push(n[2]);else{var a=new Promise((t,o)=>n=e[r]=[t,o]);o.push(n[2]=a);var i=t.p+t.u(r),c=Error();t.l(i,o=>{if(t.o(e,r)&&(0!==(n=e[r])&&(e[r]=void 0),n)){var a=o&&("load"===o.type?"missing":o.type),i=o&&o.target&&o.target.src;c.message="Loading chunk "+r+" failed.\n("+a+": "+i+")",c.name="ChunkLoadError",c.type=a,c.request=i,n[1](c)}},"chunk-"+r,r)}}};var r=(r,o)=>{var n,a,[i,c,s]=o,l=0;if(i.some(r=>0!==e[r])){for(n in c)t.o(c,n)&&(t.m[n]=c[n]);s&&s(t)}for(r&&r(o);lt.e(99382).then(t.bind(t,382)),"[data-paystack-bank-verification]")})(); \ No newline at end of file diff --git a/src/Resources/app/storefront/dist/storefront/js/kommandhub-paystack-s-w/kommandhub-paystack-s-w.paystack-bank-verification.plugin.d99562.js b/src/Resources/app/storefront/dist/storefront/js/kommandhub-paystack-s-w/kommandhub-paystack-s-w.paystack-bank-verification.plugin.d99562.js new file mode 100644 index 0000000..831b320 --- /dev/null +++ b/src/Resources/app/storefront/dist/storefront/js/kommandhub-paystack-s-w/kommandhub-paystack-s-w.paystack-bank-verification.plugin.d99562.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[99382],{382(e,t,n){n.r(t),n.d(t,{default:()=>a});class s{constructor(){this._request=null,this._errorHandlingInternal=!1}get(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"application/json",s=this._createPreparedRequest("GET",e,n);return this._sendRequest(s,null,t)}post(e,t,n){let s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"application/json";s=this._getContentType(t,s);let i=this._createPreparedRequest("POST",e,s);return this._sendRequest(i,t,n)}delete(e,t,n){let s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"application/json";s=this._getContentType(t,s);let i=this._createPreparedRequest("DELETE",e,s);return this._sendRequest(i,t,n)}patch(e,t,n){let s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"application/json";s=this._getContentType(t,s);let i=this._createPreparedRequest("PATCH",e,s);return this._sendRequest(i,t,n)}abort(){if(this._request)return this._request.abort()}setErrorHandlingInternal(e){this._errorHandlingInternal=e}_registerOnLoaded(e,t){t&&(!0===this._errorHandlingInternal?(e.addEventListener("load",()=>{t(e.responseText,e)}),e.addEventListener("abort",()=>{console.warn(`the request to ${e.responseURL} was aborted`)}),e.addEventListener("error",()=>{console.warn(`the request to ${e.responseURL} failed with status ${e.status}`)}),e.addEventListener("timeout",()=>{console.warn(`the request to ${e.responseURL} timed out`)})):e.addEventListener("loadend",()=>{t(e.responseText,e)}))}_sendRequest(e,t,n){return this._registerOnLoaded(e,n),e.send(t),e}_getContentType(e,t){return e instanceof FormData&&(t=!1),t}_createPreparedRequest(e,t,n){return this._request=new XMLHttpRequest,this._request.open(e,t),this._request.setRequestHeader("X-Requested-With","XMLHttpRequest"),n&&this._request.setRequestHeader("Content-type",n),this._request}}let{PluginBaseClass:i}=window;class a extends i{static #e=this.options={banksUrl:"",verifyUrl:"",bankSelectSelector:"#bankName",accountNumberSelector:"#accountNumber",bvnSelector:"#bvn",accountNameSelector:"#accountName",submitButtonSelector:'button[type="submit"]',initialBankCode:""};static #t=this.ACCOUNT_NUMBER_LENGTH=10;static #n=this.BVN_LENGTH=11;init(){this._client=new s,this._bankSelect=this.el.querySelector(this.options.bankSelectSelector),this._accountNumberInput=this.el.querySelector(this.options.accountNumberSelector),this._bvnInput=this.el.querySelector(this.options.bvnSelector),this._accountNameInput=this.el.querySelector(this.options.accountNameSelector),this._submitButton=this.el.querySelector(this.options.submitButtonSelector),this._bankSelect&&this._accountNumberInput&&(this._registerEvents(),this._loadBanks())}_registerEvents(){this._accountNumberInput.addEventListener("blur",this._onAccountNumberBlur.bind(this)),this._bankSelect.addEventListener("change",this._onBankChange.bind(this)),this.el.addEventListener("submit",this._onFormSubmit.bind(this))}_loadBanks(){this.options.banksUrl&&this._client.get(this.options.banksUrl,e=>{try{let t=JSON.parse(e);t.status&&Array.isArray(t.data)&&this._populateBankSelect(t.data)}catch(e){console.error("Failed to parse banks response.",e)}})}_populateBankSelect(e){for(;this._bankSelect.options.length>1;)this._bankSelect.remove(1);e.forEach(e=>{let t=document.createElement("option");t.value=e.code,t.text=e.name,t.dataset.bankName=e.name,e.code===this.options.initialBankCode&&(t.selected=!0),this._bankSelect.add(t)}),this._bankSelect.value&&this._accountNumberInput.value&&!this._accountNameInput.value&&this._verifyAccount()}_onAccountNumberBlur(){this._verifyAccount()}_onBankChange(){this._verifyAccount()}_verifyAccount(){if(!this.options.verifyUrl)return;let e=this._accountNumberInput.value.trim(),t=this._bankSelect.value;if(e.length0&&e.length{this._setLoading(!1,this._accountNumberInput);try{let t=JSON.parse(e);t.status&&t.data?(this._accountNameInput.value=t.data.account_name,this._markValidationState(this._accountNumberInput,!0,`Account verified: ${t.data.account_name}`)):this._markValidationState(this._accountNumberInput,!1,t.message||"Account verification failed")}catch(e){console.error("Failed to parse verification response.",e),this._markValidationState(this._accountNumberInput,!1,"Verification service unavailable")}})}_setLoading(e,t){t.classList.toggle("is-loading",e)}_markValidationState(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",s=e.closest(".form-group"),i=s?.querySelector(".invalid-feedback"),a=s?.querySelector(".valid-feedback");if(null===t){e.classList.remove("is-valid","is-invalid"),i&&(i.textContent=""),a&&(a.textContent="");return}e.classList.toggle("is-valid",t),e.classList.toggle("is-invalid",!t),a&&(a.textContent=t?n:""),i&&(i.textContent=t?"":n)}_onFormSubmit(){let e=this._bankSelect.options[this._bankSelect.selectedIndex];e&&(this._createOrUpdateHiddenField("hiddenBankName","bankName",e.dataset.bankName||""),this._createOrUpdateHiddenField("hiddenBankCode","bankCode",this._bankSelect.value))}_createOrUpdateHiddenField(e,t,n){let s=this.el.querySelector(`#${e}`);s||((s=document.createElement("input")).type="hidden",s.id=e,s.name=t,this.el.appendChild(s)),s.value=n}}}}]); \ No newline at end of file diff --git a/src/Resources/app/storefront/src/main.js b/src/Resources/app/storefront/src/main.js new file mode 100644 index 0000000..f202df6 --- /dev/null +++ b/src/Resources/app/storefront/src/main.js @@ -0,0 +1,7 @@ +const PluginManager = window.PluginManager; + +PluginManager.register( + 'PaystackBankVerification', + () => import('./paystack-bank-verification-plugin/paystack-bank-verification.plugin'), + '[data-paystack-bank-verification]' +); diff --git a/src/Resources/app/storefront/src/paystack-bank-verification-plugin/paystack-bank-verification.plugin.js b/src/Resources/app/storefront/src/paystack-bank-verification-plugin/paystack-bank-verification.plugin.js new file mode 100644 index 0000000..87464d9 --- /dev/null +++ b/src/Resources/app/storefront/src/paystack-bank-verification-plugin/paystack-bank-verification.plugin.js @@ -0,0 +1,340 @@ +const { PluginBaseClass } = window; +import HttpClient from 'src/service/http-client.service'; + +/** + * Paystack Bank Verification Plugin + * + * Responsibilities: + * - Load available banks from Paystack. + * - Verify account number against a selected bank. + * - Populate verified account name automatically. + * - Attach bank name and bank code to the submitted form. + */ +export default class PaystackBankVerificationPlugin extends PluginBaseClass { + static options = { + banksUrl: '', + verifyUrl: '', + + bankSelectSelector: '#bankName', + accountNumberSelector: '#accountNumber', + bvnSelector: '#bvn', + accountNameSelector: '#accountName', + + submitButtonSelector: 'button[type="submit"]', + + initialBankCode: '', + }; + + /** + * Nigerian bank account numbers are always 10 digits. + */ + static ACCOUNT_NUMBER_LENGTH = 10; + + /** + * BVN is always 11 digits. + */ + static BVN_LENGTH = 11; + + init() { + this._client = new HttpClient(); + + this._bankSelect = this.el.querySelector(this.options.bankSelectSelector); + this._accountNumberInput = this.el.querySelector(this.options.accountNumberSelector); + this._bvnInput = this.el.querySelector(this.options.bvnSelector); + this._accountNameInput = this.el.querySelector(this.options.accountNameSelector); + this._submitButton = this.el.querySelector(this.options.submitButtonSelector); + + if (!this._bankSelect || !this._accountNumberInput) { + return; + } + + this._registerEvents(); + this._loadBanks(); + } + + /** + * Register DOM event listeners. + * + * @private + */ + _registerEvents() { + this._accountNumberInput.addEventListener( + 'blur', + this._onAccountNumberBlur.bind(this) + ); + + this._bankSelect.addEventListener( + 'change', + this._onBankChange.bind(this) + ); + + this.el.addEventListener( + 'submit', + this._onFormSubmit.bind(this) + ); + } + + /** + * Load available banks from backend endpoint. + * + * @private + */ + _loadBanks() { + if (!this.options.banksUrl) { + return; + } + + this._client.get(this.options.banksUrl, (response) => { + try { + const result = JSON.parse(response); + + if (result.status && Array.isArray(result.data)) { + this._populateBankSelect(result.data); + } + } catch (error) { + console.error('Failed to parse banks response.', error); + } + }); + } + + /** + * Populate bank select dropdown. + * + * @param {Array} banks + * @private + */ + _populateBankSelect(banks) { + while (this._bankSelect.options.length > 1) { + this._bankSelect.remove(1); + } + + banks.forEach((bank) => { + const option = document.createElement('option'); + + option.value = bank.code; + option.text = bank.name; + option.dataset.bankName = bank.name; + + if (bank.code === this.options.initialBankCode) { + option.selected = true; + } + + this._bankSelect.add(option); + }); + + // Re-run verification when editing existing profile data. + if ( + this._bankSelect.value && + this._accountNumberInput.value && + !this._accountNameInput.value + ) { + this._verifyAccount(); + } + } + + /** + * Handle account number blur. + * + * @private + */ + _onAccountNumberBlur() { + this._verifyAccount(); + } + + /** + * Handle bank selection changes. + * + * @private + */ + _onBankChange() { + this._verifyAccount(); + } + + + /** + * Verify account number against selected bank. + * + * Uses Paystack's account resolution endpoint through + * the plugin backend controller. + * + * @private + */ + _verifyAccount() { + if (!this.options.verifyUrl) { + return; + } + + const accountNumber = this._accountNumberInput.value.trim(); + const bankCode = this._bankSelect.value; + + if ( + accountNumber.length < PaystackBankVerificationPlugin.ACCOUNT_NUMBER_LENGTH || + !bankCode + ) { + if ( + accountNumber.length > 0 && + accountNumber.length < PaystackBankVerificationPlugin.ACCOUNT_NUMBER_LENGTH + ) { + this._markValidationState( + this._accountNumberInput, + false, + 'Account number must be 10 digits' + ); + } else { + this._markValidationState(this._accountNumberInput, null); + } + + return; + } + + this._setLoading(true, this._accountNumberInput); + + const formData = new FormData(); + formData.append('account_number', accountNumber); + formData.append('bank_code', bankCode); + + this._client.post(this.options.verifyUrl, formData, (response) => { + this._setLoading(false, this._accountNumberInput); + + try { + const result = JSON.parse(response); + + if (result.status && result.data) { + this._accountNameInput.value = result.data.account_name; + + this._markValidationState( + this._accountNumberInput, + true, + `Account verified: ${result.data.account_name}` + ); + } else { + this._markValidationState( + this._accountNumberInput, + false, + result.message || 'Account verification failed' + ); + } + } catch (error) { + console.error('Failed to parse verification response.', error); + + this._markValidationState( + this._accountNumberInput, + false, + 'Verification service unavailable' + ); + } + }); + } + + + /** + * Toggle loading state. + * + * @param {boolean} loading + * @param {HTMLElement} input + * @private + */ + _setLoading(loading, input) { + input.classList.toggle('is-loading', loading); + } + + /** + * Update validation UI. + * + * valid: + * - true => success state + * - false => error state + * - null => reset state + * + * @param {HTMLElement} input + * @param {boolean|null} valid + * @param {string} message + * @private + */ + _markValidationState(input, valid, message = '') { + const container = input.closest('.form-group'); + + const invalidFeedback = + container?.querySelector('.invalid-feedback'); + + const validFeedback = + container?.querySelector('.valid-feedback'); + + if (valid === null) { + input.classList.remove('is-valid', 'is-invalid'); + + if (invalidFeedback) { + invalidFeedback.textContent = ''; + } + + if (validFeedback) { + validFeedback.textContent = ''; + } + + return; + } + + input.classList.toggle('is-valid', valid); + input.classList.toggle('is-invalid', !valid); + + if (validFeedback) { + validFeedback.textContent = valid ? message : ''; + } + + if (invalidFeedback) { + invalidFeedback.textContent = valid ? '' : message; + } + } + + /** + * Add hidden bank fields before form submission. + * + * We store both the selected bank name and code + * so they can be persisted on the customer record. + * + * @private + */ + _onFormSubmit() { + const selectedOption = + this._bankSelect.options[this._bankSelect.selectedIndex]; + + if (!selectedOption) { + return; + } + + this._createOrUpdateHiddenField( + 'hiddenBankName', + 'bankName', + selectedOption.dataset.bankName || '' + ); + + this._createOrUpdateHiddenField( + 'hiddenBankCode', + 'bankCode', + this._bankSelect.value + ); + } + + /** + * Create or update hidden form fields. + * + * @param {string} id + * @param {string} name + * @param {string} value + * @private + */ + _createOrUpdateHiddenField(id, name, value) { + let field = this.el.querySelector(`#${id}`); + + if (!field) { + field = document.createElement('input'); + field.type = 'hidden'; + field.id = id; + field.name = name; + + this.el.appendChild(field); + } + + field.value = value; + } +} \ No newline at end of file diff --git a/src/Resources/config/config.xml b/src/Resources/config/config.xml index 47ef695..c3eda0f 100644 --- a/src/Resources/config/config.xml +++ b/src/Resources/config/config.xml @@ -213,6 +213,50 @@ + + Bank Data Collection + Bankdatenerfassung + + + collectBankData + + + false + + Enable or disable the collection of bank account details from customers. + + + Aktivieren oder deaktivieren Sie die Erfassung von Bankverbindungen von Kunden. + + + + + showBvnField + + + true + + Toggle visibility of the BVN (Bank Verification Number) field in the bank data form. + + + Schalten Sie die Sichtbarkeit des BVN-Feldes (Bank Verification Number) im Bankdatenformular um. + + + + + requireBvn + + + false + + If enabled, the BVN field will be mandatory for form submission. + + + Wenn aktiviert, ist das BVN-Feld für die Formularübermittlung obligatorisch. + + + + Debugging Fehlerdiagnose diff --git a/src/Resources/config/plugin.png b/src/Resources/config/plugin.png index 452cd927da45a0bbdcc1e5c4bdd0227d01561651..c437641728e76476c4912e705e918d1b9775b17d 100644 GIT binary patch literal 1611 zcmc(gZBUX~6vrteOJqtiU1@-dGS|hm+S*b=!|(;Ov`EdDG}O&pX0_CE!_WrJ)m*7m za5PPG(^4?8R4hTqH4AKOeGH!6C^OwOP|GnNL@;C@XJ=>nP+xaH+uA+Aj=L@x z;??mFnp2Zfg!86syHwvvztMosZsSfhFC~pwPf9U52gW}QCG*>6?tr`GT z--`{Yvz1jXJNDbpQ9gk1Yc9Q6p9!f=HOI5_a#{i?>sZu%a zs;MaXB`si`zEnS1uP}Dbn6?S@=8g#4A(x6Z7p6U;U5?uh0 z-#Z9zp7om3kM-7QzLfNu+L-fRrZ@EM5}!$V!$IKP4jq^ekP{1M7bURT@fqO-XYJ*O z{5QH7>oSzJSsZ}jxS``=cqg@`1t4CC9U-WI)sz@7P>j9Oe1Z<;R)^{S&>&ac&QYoH zvZ{0L7*m%A>##J&Oo=o0-Of4BC4SmMaxB=#*C3IpZa|$##H^t34e|DcYBLq$E)VN2 zgdPYq$n#r+LI$sDY*t|i(70#4G0Zr1TZ8jHq2*pZ6G_|ykR4xpl#%M@HW?pzKA0Zv z8+_~B|LP1!x|b|rO|YS|E7w<`dWvW9C~u#StgMZ0YOGTwg$i$k>ZCEQ1=deNxrMZ*cg_Yyc7wdS@IUUb5xvjfux-F~I0vxA`^t?ngeTkIb$S;xK~2g6W`W<(|Z8^YDw;-jG4dRXbV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