From 1f92764a8fe10323aad7cfa945fa0ee4aa002d37 Mon Sep 17 00:00:00 2001 From: peterojo Date: Mon, 4 Jul 2022 14:22:55 +0200 Subject: [PATCH 1/4] Revert prepared payment for patch release --- composer.json | 2 +- src/Controller/AdminController.php | 38 +- .../PaymentResponse/PaymentResponseEntity.php | 19 +- .../PaymentResponseEntityDefinition.php | 3 +- src/Handlers/AbstractPaymentMethodHandler.php | 558 +++++++++++++----- .../AfterpayDefaultPaymentMethodHandler.php | 6 +- .../AlbelliGiftCardPaymentMethodHandler.php | 5 +- src/Handlers/AlipayHkPaymentMethodHandler.php | 4 +- src/Handlers/AlipayPaymentMethodHandler.php | 5 +- .../AmazonPayPaymentMethodHandler.php | 5 +- src/Handlers/ApplePayPaymentMethodHandler.php | 5 +- .../BancontactCardPaymentMethodHandler.php | 6 +- .../BeautyGiftCardPaymentMethodHandler.php | 5 +- .../BijenkorfGiftCardPaymentMethodHandler.php | 5 +- src/Handlers/BlikPaymentMethodHandler.php | 5 +- src/Handlers/CardsPaymentMethodHandler.php | 5 +- src/Handlers/ClearpayPaymentMethodHandler.php | 4 +- ...adeaukaartGiftCardPaymentMethodHandler.php | 5 +- src/Handlers/DotpayPaymentMethodHandler.php | 5 +- src/Handlers/EpsPaymentMethodHandler.php | 5 +- .../Facilypay10xPaymentMethodHandler.php | 5 +- .../Facilypay12xPaymentMethodHandler.php | 5 +- .../Facilypay3xPaymentMethodHandler.php | 6 +- .../Facilypay4xPaymentMethodHandler.php | 5 +- .../Facilypay6xPaymentMethodHandler.php | 5 +- ...hionChequeGiftCardPaymentMethodHandler.php | 5 +- .../GallGallGiftCardPaymentMethodHandler.php | 5 +- .../GenericGiftCardPaymentMethodHandler.php | 5 +- src/Handlers/GiroPayPaymentMethodHandler.php | 5 +- .../GivexGiftCardPaymentMethodHandler.php | 5 +- .../GooglePayPaymentMethodHandler.php | 5 +- ...erLingerieGiftCardPaymentMethodHandler.php | 5 +- src/Handlers/IdealPaymentMethodHandler.php | 5 +- ...KadowereldGiftCardPaymentMethodHandler.php | 5 +- .../KlarnaAccountPaymentMethodHandler.php | 6 +- .../KlarnaPayLaterPaymentMethodHandler.php | 6 +- .../KlarnaPayNowPaymentMethodHandler.php | 6 +- src/Handlers/OneClickPaymentMethodHandler.php | 5 +- src/Handlers/PaymentResponseHandler.php | 67 +-- src/Handlers/PaymentResponseHandlerResult.php | 19 +- src/Handlers/PaypalPaymentMethodHandler.php | 5 +- .../PaysafecardPaymentMethodHandler.php | 6 +- ...RatepayDirectdebitPaymentMethodHandler.php | 5 +- src/Handlers/RatepayPaymentMethodHandler.php | 4 +- src/Handlers/ResultHandler.php | 6 +- .../SVSGiftCardPaymentMethodHandler.php | 5 +- src/Handlers/SepaPaymentMethodHandler.php | 5 +- src/Handlers/SofortPaymentMethodHandler.php | 5 +- src/Handlers/SwishPaymentMethodHandler.php | 5 +- .../TCSTestGiftCardPaymentMethodHandler.php | 5 +- src/Handlers/TrustlyPaymentMethodHandler.php | 5 +- src/Handlers/TwintPaymentMethodHandler.php | 5 +- .../VVVGiftCardPaymentMethodHandler.php | 5 +- .../WebshopGiftCardPaymentMethodHandler.php | 5 +- ...igration1653031120AdyenPaymentResponse.php | 27 - .../adyen-payment-reference.html.twig | 6 - .../adyen-payment-reference/index.js | 47 -- src/Resources/app/administration/src/main.js | 2 - .../src/service/adyenService.js | 15 - .../src/sw-order-detail-override/index.js | 5 - .../sw-order-detail.html.twig | 4 - src/Resources/config/config.xml | 11 - src/Resources/config/services.xml | 1 - .../config/services/checkout-api.xml | 17 +- .../config/services/payment-handlers.xml | 62 +- .../ProcessNotificationsHandler.php | 8 +- src/Service/CaptureService.php | 15 +- src/Service/ConfigurationService.php | 9 - src/Service/PaymentDetailsService.php | 14 +- src/Service/PaymentMethodsService.php | 31 + src/Service/PaymentRequestService.php | 455 -------------- src/Service/PaymentStatusService.php | 36 +- src/Service/RefundService.php | 2 +- .../Repository/OrderTransactionRepository.php | 14 +- src/Subscriber/PaymentSubscriber.php | 12 +- 75 files changed, 685 insertions(+), 1054 deletions(-) delete mode 100644 src/Migration/Migration1653031120AdyenPaymentResponse.php delete mode 100644 src/Resources/app/administration/src/component/adyen-payment-reference/adyen-payment-reference.html.twig delete mode 100644 src/Resources/app/administration/src/component/adyen-payment-reference/index.js delete mode 100644 src/Resources/app/administration/src/sw-order-detail-override/index.js delete mode 100644 src/Resources/app/administration/src/sw-order-detail-override/sw-order-detail.html.twig delete mode 100644 src/Service/PaymentRequestService.php diff --git a/composer.json b/composer.json index 4eb919d2..2912509f 100644 --- a/composer.json +++ b/composer.json @@ -6,7 +6,7 @@ } ], "description": "Official Shopware 6 Plugin to connect to Payment Service Provider Adyen", - "version": "3.5.0", + "version": "3.4.1", "type": "shopware-platform-plugin", "license": "MIT", "require": { diff --git a/src/Controller/AdminController.php b/src/Controller/AdminController.php index 185d687d..c5177de1 100644 --- a/src/Controller/AdminController.php +++ b/src/Controller/AdminController.php @@ -33,12 +33,10 @@ use Adyen\Shopware\Service\CaptureService; use Adyen\Shopware\Service\ConfigurationService; use Adyen\Shopware\Service\NotificationService; -use Adyen\Shopware\Service\PaymentResponseService; use Adyen\Shopware\Service\RefundService; use Adyen\Shopware\Service\Repository\AdyenPaymentCaptureRepository; use Adyen\Shopware\Service\Repository\AdyenRefundRepository; use Adyen\Shopware\Service\Repository\OrderRepository; -use Adyen\Shopware\Service\Repository\OrderTransactionRepository; use Adyen\Util\Currency; use Psr\Log\LoggerInterface; use Shopware\Core\Checkout\Order\OrderEntity; @@ -47,7 +45,6 @@ use Shopware\Core\Framework\Routing\Annotation\RouteScope; use Shopware\Core\Framework\Validation\DataBag\RequestDataBag; use Shopware\Core\System\Currency\CurrencyFormatter; -use Shopware\Core\System\SalesChannel\SalesChannelContext; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; @@ -77,7 +74,7 @@ class AdminController /** * @var NotificationService */ - private $notificationService; + private NotificationService $notificationService; /** @var CurrencyFormatter */ private $currencyFormatter; @@ -91,20 +88,12 @@ class AdminController /** @var AdyenPaymentCaptureRepository */ private $adyenPaymentCaptureRepository; - /** @var OrderTransactionRepository */ - private $orderTransactionRepository; - - /** @var ConfigurationService */ - private $configurationService; - /** * AdminController constructor. * * @param LoggerInterface $logger * @param OrderRepository $orderRepository * @param RefundService $refundService - * @param OrderTransactionRepository $orderTransactionRepository - * @param ConfigurationService $configurationService * @param AdyenRefundRepository $adyenRefundRepository * @param AdyenPaymentCaptureRepository $adyenPaymentCaptureRepository * @param NotificationService $notificationService @@ -116,8 +105,6 @@ public function __construct( LoggerInterface $logger, OrderRepository $orderRepository, RefundService $refundService, - OrderTransactionRepository $orderTransactionRepository, - ConfigurationService $configurationService, AdyenRefundRepository $adyenRefundRepository, AdyenPaymentCaptureRepository $adyenPaymentCaptureRepository, NotificationService $notificationService, @@ -134,8 +121,6 @@ public function __construct( $this->captureService = $captureService; $this->currencyFormatter = $currencyFormatter; $this->currencyUtil = $currencyUtil; - $this->orderTransactionRepository = $orderTransactionRepository; - $this->configurationService = $configurationService; } /** @@ -211,7 +196,7 @@ public function sendCaptureRequest(Request $request) try { $results = $this->captureService - ->capture($context, $order->getOrderNumber(), $amountInMinorUnit); + ->doOpenInvoiceCapture($order->getOrderNumber(), $amountInMinorUnit, $context); } catch (CaptureException $e) { $this->logger->error($e->getMessage()); @@ -378,25 +363,6 @@ public function getOrderNotifications(string $orderId): JsonResponse return new JsonResponse($response); } - /** - * @Route( - * "/api/adyen/orders/{orderId}/payment-details", - * methods={"GET"} - * ) - */ - public function getPaymentDetails(string $orderId): JsonResponse - { - $orderTransaction = $this->orderTransactionRepository->getFirstAdyenOrderTransaction($orderId); - $customFields = $orderTransaction->getCustomFields(); - $response = [ - 'paymentReference' => $customFields['paymentReference'] ?? null, - 'pspReference' => $customFields['originalPspReference'] ?? null, - 'environment' => $this->configurationService->getEnvironment() - ]; - - return new JsonResponse($response); - } - /** * Build a response containing the data to be displayed * diff --git a/src/Entity/PaymentResponse/PaymentResponseEntity.php b/src/Entity/PaymentResponse/PaymentResponseEntity.php index 0f5d6921..b2ff3f77 100644 --- a/src/Entity/PaymentResponse/PaymentResponseEntity.php +++ b/src/Entity/PaymentResponse/PaymentResponseEntity.php @@ -41,11 +41,6 @@ class PaymentResponseEntity extends Entity */ protected $orderTransaction; - /** - * @var string - */ - protected $paymentReference; - /** * @var string */ @@ -67,9 +62,9 @@ class PaymentResponseEntity extends Entity protected $response; /** - * @return string|null + * @return string */ - public function getOrderTransactionId(): ?string + public function getOrderTransactionId(): string { return $this->orderTransactionId; } @@ -98,16 +93,6 @@ public function setOrderTransaction(OrderTransactionEntity $orderTransaction): v $this->orderTransaction = $orderTransaction; } - public function getPaymentReference(): ?string - { - return $this->paymentReference; - } - - public function setPaymentReference(string $paymentReference): void - { - $this->paymentReference = $paymentReference; - } - /** * @return string */ diff --git a/src/Entity/PaymentResponse/PaymentResponseEntityDefinition.php b/src/Entity/PaymentResponse/PaymentResponseEntityDefinition.php index c31e07af..408b4d15 100644 --- a/src/Entity/PaymentResponse/PaymentResponseEntityDefinition.php +++ b/src/Entity/PaymentResponse/PaymentResponseEntityDefinition.php @@ -65,8 +65,7 @@ protected function defineFields(): FieldCollection 'order_transaction_id', 'orderTransactionId', OrderTransactionDefinition::class - )), - new StringField('payment_reference', 'paymentReference'), + ))->addFlags(new Required()), new StringField('result_code', 'resultCode'), new LongTextField('response', 'response'), new CreatedAtField(), diff --git a/src/Handlers/AbstractPaymentMethodHandler.php b/src/Handlers/AbstractPaymentMethodHandler.php index 6dcf29b5..a08b4ce2 100644 --- a/src/Handlers/AbstractPaymentMethodHandler.php +++ b/src/Handlers/AbstractPaymentMethodHandler.php @@ -26,45 +26,48 @@ namespace Adyen\Shopware\Handlers; use Adyen\AdyenException; -use Adyen\Shopware\Exception\CaptureException; +use Adyen\Service\Builder\Address; +use Adyen\Service\Builder\Browser; +use Adyen\Service\Builder\Customer; +use Adyen\Service\Builder\Payment; +use Adyen\Service\Builder\OpenInvoice; +use Adyen\Service\Validator\CheckoutStateDataValidator; use Adyen\Shopware\Exception\PaymentCancelledException; -use Adyen\Shopware\Exception\PaymentException; use Adyen\Shopware\Exception\PaymentFailedException; -use Adyen\Shopware\Service\CaptureService; use Adyen\Shopware\Service\CheckoutService; use Adyen\Shopware\Service\ClientService; use Adyen\Shopware\Service\ConfigurationService; -use Adyen\Shopware\Service\PaymentRequestService; -use Adyen\Shopware\Service\PaymentResponseService; +use Adyen\Shopware\Service\PaymentMethodsService; use Adyen\Shopware\Service\PaymentStateDataService; use Adyen\Shopware\Service\Repository\SalesChannelRepository; use Adyen\Shopware\Storefront\Controller\RedirectResultController; use Adyen\Util\Currency; +use Exception; use Psr\Log\LoggerInterface; -use Shopware\Core\Checkout\Cart\Cart; use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionStateHandler; use Shopware\Core\Checkout\Payment\Cart\AsyncPaymentTransactionStruct; -use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; -use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\PreparedPaymentHandlerInterface; -use Shopware\Core\Checkout\Payment\Cart\PreparedPaymentTransactionStruct; use Shopware\Core\Checkout\Payment\Exception\AsyncPaymentFinalizeException; use Shopware\Core\Checkout\Payment\Exception\AsyncPaymentProcessException; -use Shopware\Core\Checkout\Payment\Exception\CapturePreparedPaymentException; use Shopware\Core\Checkout\Payment\Exception\CustomerCanceledAsyncPaymentException; use Shopware\Core\Checkout\Payment\Exception\PaymentProcessException; -use Shopware\Core\Checkout\Payment\Exception\ValidatePreparedPaymentException; -use Shopware\Core\Framework\Struct\ArrayStruct; -use Shopware\Core\Framework\Struct\Struct; +use Shopware\Core\Content\Product\Exception\ProductNotFoundException; +use Shopware\Core\Content\Product\ProductCollection; +use Shopware\Core\Content\Product\ProductEntity; +use Shopware\Core\Framework\Context; +use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface; +use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria; use Shopware\Core\Framework\Validation\DataBag\RequestDataBag; +use Shopware\Core\System\Currency\CurrencyCollection; +use Shopware\Core\System\Currency\CurrencyEntity; +use Adyen\Shopware\Exception\CurrencyNotFoundException; use Shopware\Core\System\SalesChannel\SalesChannelContext; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\Routing\RouterInterface; use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; -abstract class AbstractPaymentMethodHandler implements - AsynchronousPaymentHandlerInterface, - PreparedPaymentHandlerInterface +abstract class AbstractPaymentMethodHandler { const PROMOTION = 'promotion'; @@ -83,14 +86,44 @@ abstract class AbstractPaymentMethodHandler implements protected $clientService; /** - * @var CaptureService + * @var Browser */ - private $captureService; + protected $browserBuilder; + + /** + * @var Address + */ + protected $addressBuilder; + + /** + * @var Payment + */ + protected $paymentBuilder; + + /** + * @var OpenInvoice + */ + protected $openInvoiceBuilder; + + /** + * @var Currency + */ + protected $currency; /** * @var ConfigurationService */ - private $configurationService; + protected $configurationService; + + /** + * @var Customer + */ + protected $customerBuilder; + + /** + * @var CheckoutStateDataValidator + */ + protected $checkoutStateDataValidator; /** * @var PaymentStateDataService @@ -112,11 +145,6 @@ abstract class AbstractPaymentMethodHandler implements */ protected $paymentResponseHandler; - /** - * @var PaymentResponseHandlerResult - */ - protected $paymentResponseHandlerResult; - /** * @var ResultHandler */ @@ -128,80 +156,102 @@ abstract class AbstractPaymentMethodHandler implements protected $orderTransactionStateHandler; /** - * @var PaymentRequestService + * @var RouterInterface */ - protected $paymentRequestService; + protected $router; /** * @var CsrfTokenManagerInterface */ - private $csrfTokenManager; + protected $csrfTokenManager; /** - * @var RouterInterface + * @var EntityRepositoryInterface */ - private $router; + protected $currencyRepository; /** - * @var PaymentResponseService + * @var EntityRepositoryInterface */ - private $paymentResponseService; + protected $productRepository; /** - * @var Currency + * @var Session */ - private $currency; + protected Session $session; + + /** + * @var PaymentMethodsService + */ + protected $paymentMethodsService; /** * AbstractPaymentMethodHandler constructor. + * @param ConfigurationService $configurationService * @param ClientService $clientService - * @param CaptureService $captureService + * @param Browser $browserBuilder + * @param Address $addressBuilder + * @param Payment $paymentBuilder + * @param OpenInvoice $openInvoiceBuilder * @param Currency $currency - * @param ConfigurationService $configurationService + * @param Customer $customerBuilder + * @param CheckoutStateDataValidator $checkoutStateDataValidator * @param PaymentStateDataService $paymentStateDataService * @param SalesChannelRepository $salesChannelRepository * @param PaymentResponseHandler $paymentResponseHandler * @param ResultHandler $resultHandler * @param OrderTransactionStateHandler $orderTransactionStateHandler * @param RouterInterface $router - * @param PaymentResponseHandlerResult $paymentResponseHandlerResult - * @param PaymentResponseService $paymentResponseService * @param CsrfTokenManagerInterface $csrfTokenManager - * @param PaymentRequestService $paymentRequestService + * @param EntityRepositoryInterface $currencyRepository + * @param EntityRepositoryInterface $productRepository + * @param PaymentMethodsService $paymentMethodsService * @param LoggerInterface $logger */ public function __construct( + ConfigurationService $configurationService, ClientService $clientService, - CaptureService $captureService, + Browser $browserBuilder, + Address $addressBuilder, + Payment $paymentBuilder, + OpenInvoice $openInvoiceBuilder, Currency $currency, - ConfigurationService $configurationService, + Customer $customerBuilder, + CheckoutStateDataValidator $checkoutStateDataValidator, PaymentStateDataService $paymentStateDataService, SalesChannelRepository $salesChannelRepository, PaymentResponseHandler $paymentResponseHandler, ResultHandler $resultHandler, OrderTransactionStateHandler $orderTransactionStateHandler, RouterInterface $router, - PaymentResponseHandlerResult $paymentResponseHandlerResult, - PaymentResponseService $paymentResponseService, CsrfTokenManagerInterface $csrfTokenManager, - PaymentRequestService $paymentRequestService, + Session $session, + EntityRepositoryInterface $currencyRepository, + EntityRepositoryInterface $productRepository, + PaymentMethodsService $paymentMethodsService, LoggerInterface $logger ) { $this->clientService = $clientService; + $this->browserBuilder = $browserBuilder; + $this->addressBuilder = $addressBuilder; + $this->openInvoiceBuilder = $openInvoiceBuilder; + $this->currency = $currency; $this->configurationService = $configurationService; + $this->customerBuilder = $customerBuilder; + $this->paymentBuilder = $paymentBuilder; + $this->checkoutStateDataValidator = $checkoutStateDataValidator; $this->paymentStateDataService = $paymentStateDataService; $this->salesChannelRepository = $salesChannelRepository; $this->paymentResponseHandler = $paymentResponseHandler; - $this->paymentResponseHandlerResult = $paymentResponseHandlerResult; $this->resultHandler = $resultHandler; + $this->logger = $logger; $this->orderTransactionStateHandler = $orderTransactionStateHandler; $this->router = $router; - $this->paymentResponseService = $paymentResponseService; $this->csrfTokenManager = $csrfTokenManager; - $this->paymentRequestService = $paymentRequestService; - $this->logger = $logger; - $this->captureService = $captureService; - $this->currency = $currency; + $this->session = $session; + $this->currencyRepository = $currencyRepository; + $this->productRepository = $productRepository; + $this->paymentMethodsService = $paymentMethodsService; } abstract public static function getPaymentMethodCode(); @@ -228,10 +278,9 @@ public function pay( $this->clientService->getClient($salesChannelContext->getSalesChannel()->getId()) ); $stateData = $dataBag->get('stateData'); - $returnUrl = $this->getAdyenReturnUrl($transaction); try { - $request = $this->preparePaymentsRequest($salesChannelContext, $transaction, $returnUrl, $stateData); + $request = $this->preparePaymentsRequest($salesChannelContext, $transaction, $stateData); } catch (AsyncPaymentProcessException $exception) { $this->logger->error($exception->getMessage()); throw $exception; @@ -253,7 +302,7 @@ public function pay( $transaction->getOrder()->getOrderNumber(), $exception->getMessage() ); - $this->paymentRequestService->displaySafeErrorMessages($exception); + $this->displaySafeErrorMessages($exception); $this->logger->error($message); throw new AsyncPaymentProcessException($transactionId, $message); } @@ -265,8 +314,7 @@ public function pay( throw new AsyncPaymentProcessException($transactionId, $message); } - $result = $this->paymentResponseHandler - ->handlePaymentResponse($response, $transaction->getOrderTransaction()->getId()); + $result = $this->paymentResponseHandler->handlePaymentResponse($response, $transaction->getOrderTransaction()); try { $this->paymentResponseHandler->handleShopwareApis($transaction, $salesChannelContext, $result); @@ -277,7 +325,7 @@ public function pay( } // Payment had no error, continue the process - return new RedirectResponse($returnUrl); + return new RedirectResponse($this->getAdyenReturnUrl($transaction)); } /** @@ -303,107 +351,28 @@ public function finalize( } /** - * @param Cart $cart - * @param RequestDataBag $requestDataBag - * @param SalesChannelContext $context - * @return Struct - * @throws ValidatePreparedPaymentException + * @param string $address + * @return array + * + * @deprecated Use PaymentMethodsService instead. */ - public function validate(Cart $cart, RequestDataBag $requestDataBag, SalesChannelContext $context): Struct + private function splitStreetAddressHouseNumber(string $address): array { - if ($this->configurationService->usesPreparedPaymentFlow($context->getSalesChannelId())) { - $paymentReference = $requestDataBag->get('paymentReference'); - if (empty($paymentReference)) { - throw new ValidatePreparedPaymentException('Error: Payment reference is required.'); - } - $response = $this->paymentResponseService->getWithPaymentReference($paymentReference); - if (empty($response)) { - throw new ValidatePreparedPaymentException('Error: Payment result not found.'); - } - - $valid = $response->getResultCode() === PaymentResponseHandler::AUTHORISED; - - return new ArrayStruct(['isValid' => $valid]); - } - - return new ArrayStruct([]); - } - - /** - * @param PreparedPaymentTransactionStruct $transaction - * @param RequestDataBag $requestDataBag - * @param SalesChannelContext $context - * @param Struct $preOrderPaymentStruct - * @return void - * @throws PaymentProcessException - */ - public function capture( - PreparedPaymentTransactionStruct $transaction, - RequestDataBag $requestDataBag, - SalesChannelContext $context, - Struct $preOrderPaymentStruct - ): void { - if (!$this->configurationService->usesPreparedPaymentFlow($context->getSalesChannelId())) { - return; - } - if (!$preOrderPaymentStruct->get('isValid')) { - return; - } - - $paymentReference = $requestDataBag->get('paymentReference'); - if (empty($paymentReference)) { - throw new CapturePreparedPaymentException( - $transaction->getOrderTransaction()->getId(), - 'Error: Payment reference is required.' - ); - } - $paymentResponse = $this->paymentResponseService->getWithPaymentReference($paymentReference); - try { - $result = $this->paymentResponseHandlerResult->createFromPaymentResponse($paymentResponse); - $this->paymentResponseHandler->handleShopwareApis($transaction, $context, $result); - } catch (PaymentException $e) { - $this->logger->error('Error occurred in updating order transaction: ' . $e->getMessage()); - throw new CapturePreparedPaymentException( - $transaction->getOrderTransaction()->getId(), - 'An error occurred. Please contact administrator.' - ); - } - - if ($this->captureService - ->requiresManualCapture($transaction->getOrderTransaction()->getPaymentMethod()->getHandlerIdentifier())) { - return; - } - - $currency = $transaction->getOrder()->getCurrency()->getIsoCode(); - $captureAmount = $this->currency->sanitize($transaction->getOrder()->getAmountTotal(), $currency); - - try { - $this->captureService->capture( - $context->getContext(), - $transaction->getOrder()->getOrderNumber(), - $captureAmount, - true - ); - } catch (CaptureException $e) { - $this->logger->error($e->getMessage()); - throw new CapturePreparedPaymentException( - $transaction->getOrderTransaction()->getId(), - 'An error occurred. Please contact administrator.' - ); - } + return [ + 'street' => $address, + 'houseNumber' => 'N/A' + ]; } /** * @param SalesChannelContext $salesChannelContext * @param AsyncPaymentTransactionStruct $transaction - * @param string $returnUrl * @param string|null $stateData * @return array */ protected function preparePaymentsRequest( SalesChannelContext $salesChannelContext, AsyncPaymentTransactionStruct $transaction, - string $returnUrl, ?string $stateData = null ): array { $request = []; @@ -427,27 +396,251 @@ protected function preparePaymentsRequest( ); } - $currency = $this->paymentRequestService->getCurrency( - $transaction->getOrder()->getCurrencyId(), - $salesChannelContext->getContext() + if (!empty($request['additionalData'])) { + $stateDataAdditionalData = $request['additionalData']; + } + + //Validate state.data for payment and build request object + $request = $this->checkoutStateDataValidator->getValidatedAdditionalData($request); + + //Setting payment method type if not present in statedata + if (empty($request['paymentMethod']['type'])) { + $paymentMethodType = static::getPaymentMethodCode(); + } else { + $paymentMethodType = $request['paymentMethod']['type']; + } + + if (static::$isGiftCard) { + $request['paymentMethod']['brand'] = static::getBrand(); + } + + if (!empty($request['storePaymentMethod']) && $request['storePaymentMethod'] === true) { + $request['recurringProcessingModel'] = 'CardOnFile'; + $request['shopperInteraction'] = 'Ecommerce'; + } + + //Setting browser info if not present in statedata + if (empty($request['browserInfo']['acceptHeader'])) { + $acceptHeader = $_SERVER['HTTP_ACCEPT']; + } else { + $acceptHeader = $request['browserInfo']['acceptHeader']; + } + if (empty($request['browserInfo']['userAgent'])) { + $userAgent = $_SERVER['HTTP_USER_AGENT']; + } else { + $userAgent = $request['browserInfo']['userAgent']; + } + + //Setting delivery address info if not present in statedata + if (empty($request['deliveryAddress'])) { + if ($salesChannelContext->getShippingLocation()->getAddress()->getCountryState()) { + $shippingState = $salesChannelContext->getShippingLocation() + ->getAddress()->getCountryState()->getShortCode(); + } else { + $shippingState = ''; + } + + $shippingStreetAddress = $this->paymentMethodsService->getSplitStreetAddressHouseNumber( + $salesChannelContext->getShippingLocation()->getAddress()->getStreet() + ); + $request = $this->addressBuilder->buildDeliveryAddress( + $shippingStreetAddress['street'], + $shippingStreetAddress['houseNumber'], + $salesChannelContext->getShippingLocation()->getAddress()->getZipcode(), + $salesChannelContext->getShippingLocation()->getAddress()->getCity(), + $shippingState, + $salesChannelContext->getShippingLocation()->getAddress()->getCountry()->getIso(), + $request + ); + } + + //Setting billing address info if not present in statedata + if (empty($request['billingAddress'])) { + if ($salesChannelContext->getCustomer()->getActiveBillingAddress()->getCountryState()) { + $billingState = $salesChannelContext->getCustomer() + ->getActiveBillingAddress()->getCountryState()->getShortCode(); + } else { + $billingState = ''; + } + + $billingStreetAddress = $this->paymentMethodsService->getSplitStreetAddressHouseNumber( + $salesChannelContext->getCustomer()->getActiveBillingAddress()->getStreet() + ); + $request = $this->addressBuilder->buildBillingAddress( + $billingStreetAddress['street'], + $billingStreetAddress['houseNumber'], + $salesChannelContext->getCustomer()->getActiveBillingAddress()->getZipcode(), + $salesChannelContext->getCustomer()->getActiveBillingAddress()->getCity(), + $billingState, + $salesChannelContext->getCustomer()->getActiveBillingAddress()->getCountry()->getIso(), + $request + ); + } + + //Setting customer data if not present in statedata + if (empty($request['shopperName'])) { + $shopperFirstName = $salesChannelContext->getCustomer()->getFirstName(); + $shopperLastName = $salesChannelContext->getCustomer()->getLastName(); + } else { + $shopperFirstName = $request['shopperName']['firstName']; + $shopperLastName = $request['shopperName']['lastName']; + } + + if (empty($request['shopperEmail'])) { + $shopperEmail = $salesChannelContext->getCustomer()->getEmail(); + } else { + $shopperEmail = $request['shopperEmail']; + } + + if (empty($request['paymentMethod']['personalDetails']['telephoneNumber'])) { + $shopperPhone = $salesChannelContext->getShippingLocation()->getAddress()->getPhoneNumber(); + } else { + $shopperPhone = $request['paymentMethod']['personalDetails']['telephoneNumber']; + } + + if (empty($request['paymentMethod']['personalDetails']['dateOfBirth'])) { + if ($salesChannelContext->getCustomer()->getBirthday()) { + $shopperDob = $salesChannelContext->getCustomer()->getBirthday()->format('Y-m-d'); + } else { + $shopperDob = ''; + } + } else { + $shopperDob = $request['paymentMethod']['personalDetails']['dateOfBirth']; + } + + if (empty($request['shopperLocale'])) { + $shopperLocale = $this->salesChannelRepository->getSalesChannelAssocLocale($salesChannelContext) + ->getLanguage()->getLocale()->getCode(); + } else { + $shopperLocale = $request['shopperLocale']; + } + + if (empty($request['shopperIP'])) { + $shopperIp = $salesChannelContext->getCustomer()->getRemoteAddress(); + } else { + $shopperIp = $request['shopperIP']; + } + + if (empty($request['shopperReference'])) { + $shopperReference = $salesChannelContext->getCustomer()->getId(); + } else { + $shopperReference = $request['shopperReference']; + } + + if (empty($request['countryCode'])) { + $countryCode = $salesChannelContext->getCustomer()->getActiveBillingAddress()->getCountry()->getIso(); + } else { + $countryCode = $request['countryCode']; + } + + $request = $this->browserBuilder->buildBrowserData( + $userAgent, + $acceptHeader, + isset($request['browserInfo']['screenWidth']) ? $request['browserInfo']['screenWidth'] : null, + isset($request['browserInfo']['screenHeight']) ? $request['browserInfo']['screenHeight'] : null, + isset($request['browserInfo']['colorDepth']) ? $request['browserInfo']['colorDepth'] : null, + isset($request['browserInfo']['timeZoneOffset']) ? $request['browserInfo']['timeZoneOffset'] : null, + isset($request['browserInfo']['language']) ? $request['browserInfo']['language'] : null, + isset($request['browserInfo']['javaEnabled']) ? $request['browserInfo']['javaEnabled'] : null, + $request ); - $lineItems = $this->paymentRequestService->getLineItems( - $transaction->getOrder()->getLineItems(), - $salesChannelContext->getContext(), - $currency, - $transaction->getOrder()->getTaxStatus() + + $request = $this->customerBuilder->buildCustomerData( + false, + $shopperEmail, + $shopperPhone, + '', + $shopperDob, + $shopperFirstName, + $shopperLastName, + $countryCode, + $shopperLocale, + $shopperIp, + $shopperReference, + $request ); - $request = $this->paymentRequestService->buildPaymentRequest( - $request, - $salesChannelContext, - static::class, - $transaction->getOrder()->getPrice()->getTotalPrice(), + //Building payment data + $request = $this->paymentBuilder->buildPaymentData( + $salesChannelContext->getCurrency()->getIsoCode(), + $this->currency->sanitize( + $transaction->getOrder()->getPrice()->getTotalPrice(), + $salesChannelContext->getCurrency()->getIsoCode() + ), $transaction->getOrder()->getOrderNumber(), - $returnUrl, - $lineItems + $this->configurationService->getMerchantAccount($salesChannelContext->getSalesChannel()->getId()), + $this->getAdyenReturnUrl($transaction), + $request ); + $request = $this->paymentBuilder->buildAlternativePaymentMethodData( + $paymentMethodType, + '', + $request + ); + + if (static::$isOpenInvoice) { + $orderLines = $transaction->getOrder()->getLineItems(); + $lineItems = []; + foreach ($orderLines->getElements() as $orderLine) { + //Getting line price + $price = $orderLine->getPrice(); + + // Skip promotion line items. + if (empty($orderLine->getProductId()) && $orderLine->getType() === self::PROMOTION) { + continue; + } + + $product = $this->getProduct($orderLine->getProductId(), $salesChannelContext->getContext()); + $productName = $product->getTranslation('name'); + $productNumber = $product->getProductNumber(); + + //Getting line tax amount and rate + $lineTax = $price->getCalculatedTaxes()->getAmount() / $orderLine->getQuantity(); + $taxRate = $price->getCalculatedTaxes()->first(); + if (!empty($taxRate)) { + $taxRate = $taxRate->getTaxRate(); + } else { + $taxRate = 0; + } + + $currency = $this->getCurrency( + $transaction->getOrder()->getCurrencyId(), + $salesChannelContext->getContext() + ); + //Building open invoice line + $lineItems[] = $this->openInvoiceBuilder->buildOpenInvoiceLineItem( + $productName, + $this->currency->sanitize( + $price->getUnitPrice() - + ($transaction->getOrder()->getTaxStatus() == 'gross' ? $lineTax : 0), + $currency + ), + $this->currency->sanitize( + $lineTax, + $currency + ), + $taxRate * 100, + $orderLine->getQuantity(), + '', + $productNumber + ); + } + + $request['lineItems'] = $lineItems; + } + + //Setting info from statedata additionalData if present + if (!empty($stateDataAdditionalData['origin'])) { + $request['origin'] = $stateDataAdditionalData['origin']; + } else { + $request['origin'] = $this->salesChannelRepository->getSalesChannelUrl($salesChannelContext); + } + + $request['additionalData']['allow3DS2'] = true; + + $request['channel'] = 'web'; + // Remove the used state.data if (isset($stateDataEntity)) { $this->paymentStateDataService->deletePaymentStateData($stateDataEntity); @@ -462,6 +655,7 @@ protected function preparePaymentsRequest( * * @param AsyncPaymentTransactionStruct $transaction * @return string + * @throws AsyncPaymentProcessException */ private function getAdyenReturnUrl(AsyncPaymentTransactionStruct $transaction): string { @@ -490,4 +684,52 @@ private function getAdyenReturnUrl(AsyncPaymentTransactionStruct $transaction): // Create the adyen redirect result URL with the same query as the original return URL return $adyenReturnUrl . '&' . $returnUrlQuery; } + + /** + * @param string $currencyId + * @param Context $context + * @return CurrencyEntity + */ + private function getCurrency(string $currencyId, Context $context): CurrencyEntity + { + $criteria = new Criteria([$currencyId]); + + /** @var CurrencyCollection $currencyCollection */ + $currencyCollection = $this->currencyRepository->search($criteria, $context); + + $currency = $currencyCollection->get($currencyId); + if ($currency === null) { + throw new CurrencyNotFoundException($currencyId); + } + + return $currency; + } + + /** + * @param string $productId + * @param Context $context + * @return ProductEntity + */ + private function getProduct(string $productId, Context $context): ProductEntity + { + $criteria = new Criteria([$productId]); + + /** @var ProductCollection $productCollection */ + $productCollection = $this->productRepository->search($criteria, $context); + + $product = $productCollection->get($productId); + if ($product === null) { + throw new ProductNotFoundException($productId); + } + + return $product; + } + + private function displaySafeErrorMessages(AdyenException $exception) + { + if ('validation' === $exception->getErrorType() + && in_array($exception->getAdyenErrorCode(), self::SAFE_ERROR_CODES)) { + $this->session->getFlashBag()->add('warning', $exception->getMessage()); + } + } } diff --git a/src/Handlers/AfterpayDefaultPaymentMethodHandler.php b/src/Handlers/AfterpayDefaultPaymentMethodHandler.php index 58a81eb0..e288ec4e 100644 --- a/src/Handlers/AfterpayDefaultPaymentMethodHandler.php +++ b/src/Handlers/AfterpayDefaultPaymentMethodHandler.php @@ -26,8 +26,12 @@ namespace Adyen\Shopware\Handlers; -class AfterpayDefaultPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class AfterpayDefaultPaymentMethodHandler extends AbstractPaymentMethodHandler implements + AsynchronousPaymentHandlerInterface { + public static $isOpenInvoice = true; public static function getPaymentMethodCode() diff --git a/src/Handlers/AlbelliGiftCardPaymentMethodHandler.php b/src/Handlers/AlbelliGiftCardPaymentMethodHandler.php index 04801af7..d08ea31f 100644 --- a/src/Handlers/AlbelliGiftCardPaymentMethodHandler.php +++ b/src/Handlers/AlbelliGiftCardPaymentMethodHandler.php @@ -25,7 +25,10 @@ namespace Adyen\Shopware\Handlers; -class AlbelliGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class AlbelliGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler implements + AsynchronousPaymentHandlerInterface { public static $isGiftCard = true; diff --git a/src/Handlers/AlipayHkPaymentMethodHandler.php b/src/Handlers/AlipayHkPaymentMethodHandler.php index fbc331f1..dceca699 100644 --- a/src/Handlers/AlipayHkPaymentMethodHandler.php +++ b/src/Handlers/AlipayHkPaymentMethodHandler.php @@ -25,7 +25,9 @@ namespace Adyen\Shopware\Handlers; -class AlipayHkPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class AlipayHkPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { public static function getPaymentMethodCode() diff --git a/src/Handlers/AlipayPaymentMethodHandler.php b/src/Handlers/AlipayPaymentMethodHandler.php index bb70d782..bf1dedd4 100644 --- a/src/Handlers/AlipayPaymentMethodHandler.php +++ b/src/Handlers/AlipayPaymentMethodHandler.php @@ -25,8 +25,11 @@ namespace Adyen\Shopware\Handlers; -class AlipayPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class AlipayPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { + public static function getPaymentMethodCode() { return 'alipay'; diff --git a/src/Handlers/AmazonPayPaymentMethodHandler.php b/src/Handlers/AmazonPayPaymentMethodHandler.php index 767410e8..b581a76d 100644 --- a/src/Handlers/AmazonPayPaymentMethodHandler.php +++ b/src/Handlers/AmazonPayPaymentMethodHandler.php @@ -25,8 +25,11 @@ namespace Adyen\Shopware\Handlers; -class AmazonPayPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class AmazonPayPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { + public static function getPaymentMethodCode() { return 'amazonpay'; diff --git a/src/Handlers/ApplePayPaymentMethodHandler.php b/src/Handlers/ApplePayPaymentMethodHandler.php index 6333d117..36c63e47 100644 --- a/src/Handlers/ApplePayPaymentMethodHandler.php +++ b/src/Handlers/ApplePayPaymentMethodHandler.php @@ -25,8 +25,11 @@ namespace Adyen\Shopware\Handlers; -class ApplePayPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class ApplePayPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { + public static function getPaymentMethodCode() { return 'applepay'; diff --git a/src/Handlers/BancontactCardPaymentMethodHandler.php b/src/Handlers/BancontactCardPaymentMethodHandler.php index ecc18de9..8be9219e 100644 --- a/src/Handlers/BancontactCardPaymentMethodHandler.php +++ b/src/Handlers/BancontactCardPaymentMethodHandler.php @@ -25,8 +25,12 @@ namespace Adyen\Shopware\Handlers; -class BancontactCardPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +// phpcs:ignore Generic.Files.LineLength.TooLong +class BancontactCardPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { + public static function getPaymentMethodCode() { return 'bcmc'; diff --git a/src/Handlers/BeautyGiftCardPaymentMethodHandler.php b/src/Handlers/BeautyGiftCardPaymentMethodHandler.php index 70321bcb..4e1f31e6 100644 --- a/src/Handlers/BeautyGiftCardPaymentMethodHandler.php +++ b/src/Handlers/BeautyGiftCardPaymentMethodHandler.php @@ -25,7 +25,10 @@ namespace Adyen\Shopware\Handlers; -class BeautyGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class BeautyGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler implements + AsynchronousPaymentHandlerInterface { public static $isGiftCard = true; diff --git a/src/Handlers/BijenkorfGiftCardPaymentMethodHandler.php b/src/Handlers/BijenkorfGiftCardPaymentMethodHandler.php index 56c2e578..92bd1b86 100644 --- a/src/Handlers/BijenkorfGiftCardPaymentMethodHandler.php +++ b/src/Handlers/BijenkorfGiftCardPaymentMethodHandler.php @@ -25,7 +25,10 @@ namespace Adyen\Shopware\Handlers; -class BijenkorfGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class BijenkorfGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler implements + AsynchronousPaymentHandlerInterface { public static $isGiftCard = true; diff --git a/src/Handlers/BlikPaymentMethodHandler.php b/src/Handlers/BlikPaymentMethodHandler.php index 9ec45c28..883608e1 100644 --- a/src/Handlers/BlikPaymentMethodHandler.php +++ b/src/Handlers/BlikPaymentMethodHandler.php @@ -25,8 +25,11 @@ namespace Adyen\Shopware\Handlers; -class BlikPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class BlikPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { + public static function getPaymentMethodCode() { return 'blik'; diff --git a/src/Handlers/CardsPaymentMethodHandler.php b/src/Handlers/CardsPaymentMethodHandler.php index ba09228f..4ab83d4d 100644 --- a/src/Handlers/CardsPaymentMethodHandler.php +++ b/src/Handlers/CardsPaymentMethodHandler.php @@ -25,8 +25,11 @@ namespace Adyen\Shopware\Handlers; -class CardsPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class CardsPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { + public static function getPaymentMethodCode() { return 'scheme'; diff --git a/src/Handlers/ClearpayPaymentMethodHandler.php b/src/Handlers/ClearpayPaymentMethodHandler.php index ffff77a9..652c9549 100644 --- a/src/Handlers/ClearpayPaymentMethodHandler.php +++ b/src/Handlers/ClearpayPaymentMethodHandler.php @@ -25,7 +25,9 @@ namespace Adyen\Shopware\Handlers; -class ClearpayPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class ClearpayPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { public static $isOpenInvoice = true; diff --git a/src/Handlers/DeCadeaukaartGiftCardPaymentMethodHandler.php b/src/Handlers/DeCadeaukaartGiftCardPaymentMethodHandler.php index 588680c2..70049df8 100644 --- a/src/Handlers/DeCadeaukaartGiftCardPaymentMethodHandler.php +++ b/src/Handlers/DeCadeaukaartGiftCardPaymentMethodHandler.php @@ -25,7 +25,10 @@ namespace Adyen\Shopware\Handlers; -class DeCadeaukaartGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class DeCadeaukaartGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler implements + AsynchronousPaymentHandlerInterface { public static $isGiftCard = true; diff --git a/src/Handlers/DotpayPaymentMethodHandler.php b/src/Handlers/DotpayPaymentMethodHandler.php index cc9ae051..a0d7f383 100644 --- a/src/Handlers/DotpayPaymentMethodHandler.php +++ b/src/Handlers/DotpayPaymentMethodHandler.php @@ -25,8 +25,11 @@ namespace Adyen\Shopware\Handlers; -class DotpayPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class DotpayPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { + public static function getPaymentMethodCode() { return 'dotpay'; diff --git a/src/Handlers/EpsPaymentMethodHandler.php b/src/Handlers/EpsPaymentMethodHandler.php index a0ebe372..5988fb02 100644 --- a/src/Handlers/EpsPaymentMethodHandler.php +++ b/src/Handlers/EpsPaymentMethodHandler.php @@ -25,8 +25,11 @@ namespace Adyen\Shopware\Handlers; -class EpsPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class EpsPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { + public static function getPaymentMethodCode() { return 'eps'; diff --git a/src/Handlers/Facilypay10xPaymentMethodHandler.php b/src/Handlers/Facilypay10xPaymentMethodHandler.php index 58eea1f2..76f8a304 100644 --- a/src/Handlers/Facilypay10xPaymentMethodHandler.php +++ b/src/Handlers/Facilypay10xPaymentMethodHandler.php @@ -26,7 +26,10 @@ namespace Adyen\Shopware\Handlers; -class Facilypay10xPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class Facilypay10xPaymentMethodHandler extends AbstractPaymentMethodHandler implements + AsynchronousPaymentHandlerInterface { public static $isOpenInvoice = true; diff --git a/src/Handlers/Facilypay12xPaymentMethodHandler.php b/src/Handlers/Facilypay12xPaymentMethodHandler.php index af404139..6082bcf3 100644 --- a/src/Handlers/Facilypay12xPaymentMethodHandler.php +++ b/src/Handlers/Facilypay12xPaymentMethodHandler.php @@ -26,7 +26,10 @@ namespace Adyen\Shopware\Handlers; -class Facilypay12xPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class Facilypay12xPaymentMethodHandler extends AbstractPaymentMethodHandler implements + AsynchronousPaymentHandlerInterface { public static $isOpenInvoice = true; diff --git a/src/Handlers/Facilypay3xPaymentMethodHandler.php b/src/Handlers/Facilypay3xPaymentMethodHandler.php index fd83c293..3232503e 100644 --- a/src/Handlers/Facilypay3xPaymentMethodHandler.php +++ b/src/Handlers/Facilypay3xPaymentMethodHandler.php @@ -26,8 +26,12 @@ namespace Adyen\Shopware\Handlers; -class Facilypay3xPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class Facilypay3xPaymentMethodHandler extends AbstractPaymentMethodHandler implements + AsynchronousPaymentHandlerInterface { + public static $isOpenInvoice = true; public static function getPaymentMethodCode() diff --git a/src/Handlers/Facilypay4xPaymentMethodHandler.php b/src/Handlers/Facilypay4xPaymentMethodHandler.php index b3031862..260ea2d7 100644 --- a/src/Handlers/Facilypay4xPaymentMethodHandler.php +++ b/src/Handlers/Facilypay4xPaymentMethodHandler.php @@ -26,7 +26,10 @@ namespace Adyen\Shopware\Handlers; -class Facilypay4xPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class Facilypay4xPaymentMethodHandler extends AbstractPaymentMethodHandler implements + AsynchronousPaymentHandlerInterface { public static $isOpenInvoice = true; diff --git a/src/Handlers/Facilypay6xPaymentMethodHandler.php b/src/Handlers/Facilypay6xPaymentMethodHandler.php index 8cda7708..6df15797 100644 --- a/src/Handlers/Facilypay6xPaymentMethodHandler.php +++ b/src/Handlers/Facilypay6xPaymentMethodHandler.php @@ -26,7 +26,10 @@ namespace Adyen\Shopware\Handlers; -class Facilypay6xPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class Facilypay6xPaymentMethodHandler extends AbstractPaymentMethodHandler implements + AsynchronousPaymentHandlerInterface { public static $isOpenInvoice = true; diff --git a/src/Handlers/FashionChequeGiftCardPaymentMethodHandler.php b/src/Handlers/FashionChequeGiftCardPaymentMethodHandler.php index e0e93f17..fbdd76ec 100644 --- a/src/Handlers/FashionChequeGiftCardPaymentMethodHandler.php +++ b/src/Handlers/FashionChequeGiftCardPaymentMethodHandler.php @@ -25,7 +25,10 @@ namespace Adyen\Shopware\Handlers; -class FashionChequeGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class FashionChequeGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler implements + AsynchronousPaymentHandlerInterface { public static $isGiftCard = true; diff --git a/src/Handlers/GallGallGiftCardPaymentMethodHandler.php b/src/Handlers/GallGallGiftCardPaymentMethodHandler.php index b834a72a..b747a5cc 100644 --- a/src/Handlers/GallGallGiftCardPaymentMethodHandler.php +++ b/src/Handlers/GallGallGiftCardPaymentMethodHandler.php @@ -25,7 +25,10 @@ namespace Adyen\Shopware\Handlers; -class GallGallGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class GallGallGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler implements + AsynchronousPaymentHandlerInterface { public static $isGiftCard = true; diff --git a/src/Handlers/GenericGiftCardPaymentMethodHandler.php b/src/Handlers/GenericGiftCardPaymentMethodHandler.php index 78efefac..7279276b 100644 --- a/src/Handlers/GenericGiftCardPaymentMethodHandler.php +++ b/src/Handlers/GenericGiftCardPaymentMethodHandler.php @@ -25,7 +25,10 @@ namespace Adyen\Shopware\Handlers; -class GenericGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class GenericGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler implements + AsynchronousPaymentHandlerInterface { public static $isGiftCard = true; diff --git a/src/Handlers/GiroPayPaymentMethodHandler.php b/src/Handlers/GiroPayPaymentMethodHandler.php index 424f9e2f..d5bf07f2 100644 --- a/src/Handlers/GiroPayPaymentMethodHandler.php +++ b/src/Handlers/GiroPayPaymentMethodHandler.php @@ -25,8 +25,11 @@ namespace Adyen\Shopware\Handlers; -class GiroPayPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class GiroPayPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { + public static function getPaymentMethodCode() { return 'giropay'; diff --git a/src/Handlers/GivexGiftCardPaymentMethodHandler.php b/src/Handlers/GivexGiftCardPaymentMethodHandler.php index 7bbd8fb6..abe2a8e3 100644 --- a/src/Handlers/GivexGiftCardPaymentMethodHandler.php +++ b/src/Handlers/GivexGiftCardPaymentMethodHandler.php @@ -25,7 +25,10 @@ namespace Adyen\Shopware\Handlers; -class GivexGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class GivexGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler implements + AsynchronousPaymentHandlerInterface { public static $isGiftCard = true; diff --git a/src/Handlers/GooglePayPaymentMethodHandler.php b/src/Handlers/GooglePayPaymentMethodHandler.php index c5cd8d53..52b5483a 100644 --- a/src/Handlers/GooglePayPaymentMethodHandler.php +++ b/src/Handlers/GooglePayPaymentMethodHandler.php @@ -25,8 +25,11 @@ namespace Adyen\Shopware\Handlers; -class GooglePayPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class GooglePayPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { + public static function getPaymentMethodCode() { return 'paywithgoogle'; diff --git a/src/Handlers/HunkemollerLingerieGiftCardPaymentMethodHandler.php b/src/Handlers/HunkemollerLingerieGiftCardPaymentMethodHandler.php index 2e1a533f..abf6e866 100644 --- a/src/Handlers/HunkemollerLingerieGiftCardPaymentMethodHandler.php +++ b/src/Handlers/HunkemollerLingerieGiftCardPaymentMethodHandler.php @@ -25,7 +25,10 @@ namespace Adyen\Shopware\Handlers; -class HunkemollerLingerieGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class HunkemollerLingerieGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler implements + AsynchronousPaymentHandlerInterface { public static $isGiftCard = true; diff --git a/src/Handlers/IdealPaymentMethodHandler.php b/src/Handlers/IdealPaymentMethodHandler.php index da8b1878..e283d7f7 100644 --- a/src/Handlers/IdealPaymentMethodHandler.php +++ b/src/Handlers/IdealPaymentMethodHandler.php @@ -25,8 +25,11 @@ namespace Adyen\Shopware\Handlers; -class IdealPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class IdealPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { + public static function getPaymentMethodCode() { return 'ideal'; diff --git a/src/Handlers/KadowereldGiftCardPaymentMethodHandler.php b/src/Handlers/KadowereldGiftCardPaymentMethodHandler.php index d4055bac..95b6b11f 100644 --- a/src/Handlers/KadowereldGiftCardPaymentMethodHandler.php +++ b/src/Handlers/KadowereldGiftCardPaymentMethodHandler.php @@ -25,7 +25,10 @@ namespace Adyen\Shopware\Handlers; -class KadowereldGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class KadowereldGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler implements + AsynchronousPaymentHandlerInterface { public static $isGiftCard = true; diff --git a/src/Handlers/KlarnaAccountPaymentMethodHandler.php b/src/Handlers/KlarnaAccountPaymentMethodHandler.php index a8bc68bc..1247994e 100644 --- a/src/Handlers/KlarnaAccountPaymentMethodHandler.php +++ b/src/Handlers/KlarnaAccountPaymentMethodHandler.php @@ -25,8 +25,12 @@ namespace Adyen\Shopware\Handlers; -class KlarnaAccountPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +// phpcs:ignore Generic.Files.LineLength.TooLong +class KlarnaAccountPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { + public static $isOpenInvoice = true; public static function getPaymentMethodCode() diff --git a/src/Handlers/KlarnaPayLaterPaymentMethodHandler.php b/src/Handlers/KlarnaPayLaterPaymentMethodHandler.php index 46b5cd1c..d75c3e1f 100644 --- a/src/Handlers/KlarnaPayLaterPaymentMethodHandler.php +++ b/src/Handlers/KlarnaPayLaterPaymentMethodHandler.php @@ -25,8 +25,12 @@ namespace Adyen\Shopware\Handlers; -class KlarnaPayLaterPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +// phpcs:ignore Generic.Files.LineLength.TooLong +class KlarnaPayLaterPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { + public static $isOpenInvoice = true; public static function getPaymentMethodCode() diff --git a/src/Handlers/KlarnaPayNowPaymentMethodHandler.php b/src/Handlers/KlarnaPayNowPaymentMethodHandler.php index aefff99a..bdc6dd2d 100644 --- a/src/Handlers/KlarnaPayNowPaymentMethodHandler.php +++ b/src/Handlers/KlarnaPayNowPaymentMethodHandler.php @@ -25,8 +25,12 @@ namespace Adyen\Shopware\Handlers; -class KlarnaPayNowPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +// phpcs:ignore Generic.Files.LineLength.TooLong +class KlarnaPayNowPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { + public static $isOpenInvoice = true; public static function getPaymentMethodCode() diff --git a/src/Handlers/OneClickPaymentMethodHandler.php b/src/Handlers/OneClickPaymentMethodHandler.php index 34315739..f849da2f 100644 --- a/src/Handlers/OneClickPaymentMethodHandler.php +++ b/src/Handlers/OneClickPaymentMethodHandler.php @@ -25,8 +25,11 @@ namespace Adyen\Shopware\Handlers; -class OneClickPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class OneClickPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { + public static function getPaymentMethodCode() { return 'storedPaymentMethods'; diff --git a/src/Handlers/PaymentResponseHandler.php b/src/Handlers/PaymentResponseHandler.php index be0a6131..a7d94034 100644 --- a/src/Handlers/PaymentResponseHandler.php +++ b/src/Handlers/PaymentResponseHandler.php @@ -28,14 +28,13 @@ use Adyen\Shopware\Exception\PaymentCancelledException; use Adyen\Shopware\Exception\PaymentFailedException; -use Adyen\Shopware\Exception\ValidationException; use Adyen\Shopware\Service\CaptureService; use Psr\Log\LoggerInterface; use Adyen\Shopware\Service\PaymentResponseService; use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionEntity; use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionStateHandler; use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionStates; -use Shopware\Core\Checkout\Payment\Cart\SyncPaymentTransactionStruct; +use Shopware\Core\Checkout\Payment\Cart\AsyncPaymentTransactionStruct; use Shopware\Core\Framework\Context; use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface; use Shopware\Core\System\SalesChannel\SalesChannelContext; @@ -64,9 +63,6 @@ class PaymentResponseHandler // Merchant reference key in API response const MERCHANT_REFERENCE = 'merchantReference'; - - const PAYMENT_REFERENCE = 'paymentReference'; - const ORDER_TRANSACTION_ID = 'orderTransactionId'; /** * @var LoggerInterface */ @@ -115,19 +111,13 @@ public function __construct( /** * @param array $response - * @param string|null $orderTransactionId - * @param string|null $paymentReference + * @param OrderTransactionEntity $orderTransaction * @return PaymentResponseHandlerResult - * @throws ValidationException */ public function handlePaymentResponse( array $response, - string $orderTransactionId = null, - string $paymentReference = null + OrderTransactionEntity $orderTransaction ): PaymentResponseHandlerResult { - if (is_null($orderTransactionId) && is_null($paymentReference)) { - throw new ValidationException('Error: either orderTransactionId or paymentReference is required'); - } // Retrieve result code from response array $resultCode = $response['resultCode']; if (array_key_exists('refusalReason', $response)) { @@ -156,20 +146,10 @@ public function handlePaymentResponse( } // Store response for cart until the payment is finalised - if ($orderTransactionId) { - $this->paymentResponseService->insertPaymentResponse( - $response, - $orderTransactionId, - self::ORDER_TRANSACTION_ID - ); - } else { - $this->paymentResponseHandlerResult->setPaymentReference($paymentReference); - $this->paymentResponseService->insertPaymentResponse( - $response, - $paymentReference, - self::PAYMENT_REFERENCE - ); - } + $this->paymentResponseService->insertPaymentResponse( + $response, + $orderTransaction + ); // Based on the result code start different payment flows switch ($resultCode) { @@ -211,16 +191,14 @@ public function handlePaymentResponse( } /** - * Update Order Transaction state based on payment response. - * - * @param SyncPaymentTransactionStruct $transaction + * @param AsyncPaymentTransactionStruct $transaction * @param SalesChannelContext $salesChannelContext * @param PaymentResponseHandlerResult $paymentResponseHandlerResult * @throws PaymentCancelledException * @throws PaymentFailedException */ public function handleShopwareApis( - SyncPaymentTransactionStruct $transaction, + AsyncPaymentTransactionStruct $transaction, SalesChannelContext $salesChannelContext, PaymentResponseHandlerResult $paymentResponseHandlerResult ): void { @@ -243,24 +221,19 @@ public function handleShopwareApis( $transactionCustomFields = []; // Only store psp reference for the transaction if this is the first/original pspreference - $pspReference = $paymentResponseHandlerResult->getPspReference(); + $pspReference = $this->paymentResponseHandlerResult->getPspReference(); if (empty($storedTransactionCustomFields[self::ORIGINAL_PSP_REFERENCE]) && !empty($pspReference)) { $transactionCustomFields[self::ORIGINAL_PSP_REFERENCE] = $pspReference; } - $paymentReference = $paymentResponseHandlerResult->getPaymentReference(); - if (empty($storedTransactionCustomFields[self::PAYMENT_REFERENCE]) && !empty($paymentReference)) { - $transactionCustomFields[self::PAYMENT_REFERENCE] = $paymentReference; - } - // Only store action for the transaction if this is the first action - $action = $paymentResponseHandlerResult->getAction(); + $action = $this->paymentResponseHandlerResult->getAction(); if (empty($storedTransactionCustomFields[self::ACTION]) && !empty($action)) { $transactionCustomFields[self::ACTION] = $action; } // Only store additional data for the transaction if this is the first additional data - $additionalData = $paymentResponseHandlerResult->getAdditionalData(); + $additionalData = $this->paymentResponseHandlerResult->getAdditionalData(); if (empty($storedTransactionCustomFields[self::ADDITIONAL_DATA]) && !empty($additionalData)) { $transactionCustomFields[self::ADDITIONAL_DATA] = $additionalData; } @@ -339,49 +312,43 @@ public function handleAdyenApis( switch ($resultCode) { case self::AUTHORISED: - $response = [ + return [ "isFinal" => true, "resultCode" => $resultCode, ]; - break; case self::REFUSED: case self::ERROR: case self::CANCELLED: - $response = [ + return [ "isFinal" => true, "resultCode" => $resultCode, "refusalReason" => $refusalReason, "refusalReasonCode" => $refusalReasonCode ]; - break; case self::REDIRECT_SHOPPER: case self::IDENTIFY_SHOPPER: case self::CHALLENGE_SHOPPER: case self::PRESENT_TO_SHOPPER: case self::PENDING: - $response = [ + return [ "isFinal" => false, "resultCode" => $resultCode, "action" => $action ]; break; case self::RECEIVED: - $response = [ + return [ "isFinal" => true, "resultCode" => $resultCode, "additionalData" => $additionalData ]; break; default: - $response = [ + return [ "isFinal" => true, "resultCode" => self::ERROR, ]; } - - $response['paymentReference'] = $paymentResponseHandlerResult->getPaymentReference() ?: null; - - return $response; } /** diff --git a/src/Handlers/PaymentResponseHandlerResult.php b/src/Handlers/PaymentResponseHandlerResult.php index df1e4a8d..a67d24db 100644 --- a/src/Handlers/PaymentResponseHandlerResult.php +++ b/src/Handlers/PaymentResponseHandlerResult.php @@ -11,7 +11,6 @@ class PaymentResponseHandlerResult private $refusalReason; private $refusalReasonCode; private $pspReference; - private $paymentReference; private $action; private $additionalData; @@ -22,10 +21,10 @@ class PaymentResponseHandlerResult */ public function createFromPaymentResponse(PaymentResponseEntity $paymentResponse): PaymentResponseHandlerResult { + // Set result code $this->setResultCode($paymentResponse->getResultCode()); $this->setRefusalReason($paymentResponse->getRefusalReason()); $this->setRefusalReasonCode($paymentResponse->getRefusalReasonCode()); - $this->setPaymentReference($paymentResponse->getPaymentReference()); $response = $paymentResponse->getResponse(); @@ -153,20 +152,4 @@ public function setAdditionalData($additionalData): void { $this->additionalData = $additionalData; } - - /** - * @return null|string - */ - public function getPaymentReference(): ?string - { - return $this->paymentReference; - } - - /** - * @param null|string $paymentReference - */ - public function setPaymentReference(?string $paymentReference): void - { - $this->paymentReference = $paymentReference; - } } diff --git a/src/Handlers/PaypalPaymentMethodHandler.php b/src/Handlers/PaypalPaymentMethodHandler.php index b35cf950..ba95adf8 100644 --- a/src/Handlers/PaypalPaymentMethodHandler.php +++ b/src/Handlers/PaypalPaymentMethodHandler.php @@ -25,7 +25,10 @@ namespace Adyen\Shopware\Handlers; -class PaypalPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +// phpcs:ignore Generic.Files.LineLength.TooLong +class PaypalPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { public static function getPaymentMethodCode() { diff --git a/src/Handlers/PaysafecardPaymentMethodHandler.php b/src/Handlers/PaysafecardPaymentMethodHandler.php index 320919c5..3be2c44d 100644 --- a/src/Handlers/PaysafecardPaymentMethodHandler.php +++ b/src/Handlers/PaysafecardPaymentMethodHandler.php @@ -26,8 +26,12 @@ namespace Adyen\Shopware\Handlers; -class PaysafecardPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class PaysafecardPaymentMethodHandler extends AbstractPaymentMethodHandler implements + AsynchronousPaymentHandlerInterface { + public static function getPaymentMethodCode() { return 'paysafecard'; diff --git a/src/Handlers/RatepayDirectdebitPaymentMethodHandler.php b/src/Handlers/RatepayDirectdebitPaymentMethodHandler.php index 0d59f044..c0fd7e7f 100644 --- a/src/Handlers/RatepayDirectdebitPaymentMethodHandler.php +++ b/src/Handlers/RatepayDirectdebitPaymentMethodHandler.php @@ -26,7 +26,10 @@ namespace Adyen\Shopware\Handlers; -class RatepayDirectdebitPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class RatepayDirectdebitPaymentMethodHandler extends AbstractPaymentMethodHandler implements + AsynchronousPaymentHandlerInterface { public static $isOpenInvoice = true; diff --git a/src/Handlers/RatepayPaymentMethodHandler.php b/src/Handlers/RatepayPaymentMethodHandler.php index 87dc414f..62ef5a80 100644 --- a/src/Handlers/RatepayPaymentMethodHandler.php +++ b/src/Handlers/RatepayPaymentMethodHandler.php @@ -25,7 +25,9 @@ namespace Adyen\Shopware\Handlers; -class RatepayPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class RatepayPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { public static $isOpenInvoice = true; diff --git a/src/Handlers/ResultHandler.php b/src/Handlers/ResultHandler.php index a750221f..875d5a91 100644 --- a/src/Handlers/ResultHandler.php +++ b/src/Handlers/ResultHandler.php @@ -105,8 +105,7 @@ public function processResult( SalesChannelContext $salesChannelContext ) { // Retrieve paymentResponse and if it exists - $paymentResponse = $this->paymentResponseService - ->getWithOrderTransaction($transaction->getOrderTransaction()->getId()); + $paymentResponse = $this->paymentResponseService->getWithOrderTransaction($transaction->getOrderTransaction()); if (!$paymentResponse) { throw new PaymentFailedException('Payment response not found.'); @@ -137,8 +136,7 @@ public function processResult( // Validate the return $result = $this->paymentDetailsService->getPaymentDetails( $requestData, - $transaction->getOrder()->getSalesChannelId(), - $transaction->getOrderTransaction()->getId() + $transaction->getOrderTransaction() ); } diff --git a/src/Handlers/SVSGiftCardPaymentMethodHandler.php b/src/Handlers/SVSGiftCardPaymentMethodHandler.php index 5358e6c5..ba2320b2 100644 --- a/src/Handlers/SVSGiftCardPaymentMethodHandler.php +++ b/src/Handlers/SVSGiftCardPaymentMethodHandler.php @@ -25,7 +25,10 @@ namespace Adyen\Shopware\Handlers; -class SVSGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class SVSGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler implements + AsynchronousPaymentHandlerInterface { public static $isGiftCard = true; diff --git a/src/Handlers/SepaPaymentMethodHandler.php b/src/Handlers/SepaPaymentMethodHandler.php index 2bebd6d7..73378943 100644 --- a/src/Handlers/SepaPaymentMethodHandler.php +++ b/src/Handlers/SepaPaymentMethodHandler.php @@ -25,8 +25,11 @@ namespace Adyen\Shopware\Handlers; -class SepaPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class SepaPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { + public static function getPaymentMethodCode() { return 'sepadirectdebit'; diff --git a/src/Handlers/SofortPaymentMethodHandler.php b/src/Handlers/SofortPaymentMethodHandler.php index 0c17a4f3..88124e7c 100644 --- a/src/Handlers/SofortPaymentMethodHandler.php +++ b/src/Handlers/SofortPaymentMethodHandler.php @@ -25,8 +25,11 @@ namespace Adyen\Shopware\Handlers; -class SofortPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class SofortPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { + public static function getPaymentMethodCode() { return 'directEbanking'; diff --git a/src/Handlers/SwishPaymentMethodHandler.php b/src/Handlers/SwishPaymentMethodHandler.php index b9ff42f7..deb93de2 100644 --- a/src/Handlers/SwishPaymentMethodHandler.php +++ b/src/Handlers/SwishPaymentMethodHandler.php @@ -25,8 +25,11 @@ namespace Adyen\Shopware\Handlers; -class SwishPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class SwishPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { + public static function getPaymentMethodCode() { return 'swish'; diff --git a/src/Handlers/TCSTestGiftCardPaymentMethodHandler.php b/src/Handlers/TCSTestGiftCardPaymentMethodHandler.php index 9b63cb73..d2eee156 100644 --- a/src/Handlers/TCSTestGiftCardPaymentMethodHandler.php +++ b/src/Handlers/TCSTestGiftCardPaymentMethodHandler.php @@ -25,7 +25,10 @@ namespace Adyen\Shopware\Handlers; -class TCSTestGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class TCSTestGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler implements + AsynchronousPaymentHandlerInterface { public static $isGiftCard = true; diff --git a/src/Handlers/TrustlyPaymentMethodHandler.php b/src/Handlers/TrustlyPaymentMethodHandler.php index 95eaa9b9..ce44dfdf 100644 --- a/src/Handlers/TrustlyPaymentMethodHandler.php +++ b/src/Handlers/TrustlyPaymentMethodHandler.php @@ -25,8 +25,11 @@ namespace Adyen\Shopware\Handlers; -class TrustlyPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class TrustlyPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { + public static function getPaymentMethodCode() { return 'trustly'; diff --git a/src/Handlers/TwintPaymentMethodHandler.php b/src/Handlers/TwintPaymentMethodHandler.php index 14ef7ee5..30793b77 100644 --- a/src/Handlers/TwintPaymentMethodHandler.php +++ b/src/Handlers/TwintPaymentMethodHandler.php @@ -25,8 +25,11 @@ namespace Adyen\Shopware\Handlers; -class TwintPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class TwintPaymentMethodHandler extends AbstractPaymentMethodHandler implements AsynchronousPaymentHandlerInterface { + public static function getPaymentMethodCode() { return 'twint'; diff --git a/src/Handlers/VVVGiftCardPaymentMethodHandler.php b/src/Handlers/VVVGiftCardPaymentMethodHandler.php index d877e29d..2fdb659c 100644 --- a/src/Handlers/VVVGiftCardPaymentMethodHandler.php +++ b/src/Handlers/VVVGiftCardPaymentMethodHandler.php @@ -25,7 +25,10 @@ namespace Adyen\Shopware\Handlers; -class VVVGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class VVVGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler implements + AsynchronousPaymentHandlerInterface { public static $isGiftCard = true; diff --git a/src/Handlers/WebshopGiftCardPaymentMethodHandler.php b/src/Handlers/WebshopGiftCardPaymentMethodHandler.php index 2afa12f4..eaded4af 100644 --- a/src/Handlers/WebshopGiftCardPaymentMethodHandler.php +++ b/src/Handlers/WebshopGiftCardPaymentMethodHandler.php @@ -25,7 +25,10 @@ namespace Adyen\Shopware\Handlers; -class WebshopGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AsynchronousPaymentHandlerInterface; + +class WebshopGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler implements + AsynchronousPaymentHandlerInterface { public static $isGiftCard = true; diff --git a/src/Migration/Migration1653031120AdyenPaymentResponse.php b/src/Migration/Migration1653031120AdyenPaymentResponse.php deleted file mode 100644 index b814d867..00000000 --- a/src/Migration/Migration1653031120AdyenPaymentResponse.php +++ /dev/null @@ -1,27 +0,0 @@ -executeUpdate(" - alter table `adyen_payment_response` - add column payment_reference varchar(64) NULL after order_transaction_id; - "); - } - - public function updateDestructive(Connection $connection): void - { - // No destructive changes - } -} diff --git a/src/Resources/app/administration/src/component/adyen-payment-reference/adyen-payment-reference.html.twig b/src/Resources/app/administration/src/component/adyen-payment-reference/adyen-payment-reference.html.twig deleted file mode 100644 index 0fa3a36a..00000000 --- a/src/Resources/app/administration/src/component/adyen-payment-reference/adyen-payment-reference.html.twig +++ /dev/null @@ -1,6 +0,0 @@ - - Adyen Payment Reference: - - {{ paymentReference }} - - diff --git a/src/Resources/app/administration/src/component/adyen-payment-reference/index.js b/src/Resources/app/administration/src/component/adyen-payment-reference/index.js deleted file mode 100644 index c07cbc7b..00000000 --- a/src/Resources/app/administration/src/component/adyen-payment-reference/index.js +++ /dev/null @@ -1,47 +0,0 @@ -const { Component } = Shopware; -import template from './adyen-payment-reference.html.twig'; - -Component.register('adyen-payment-reference', { - template, - - inject: ['adyenService'], - - props: { - orderId: { - type: String, - required: true - } - }, - - mounted() { - this.getPaymentResponse(); - }, - - data () { - return { - refAvailable: false, - paymentReference: null, - pspReference: null, - env: 'test' - } - }, - - computed: { - caLink() { - return 'https://ca-' + this.env + '.adyen.com/ca/ca/accounts/showTx.shtml?pspReference=' - + this.pspReference; - } - }, - - methods: { - getPaymentResponse() { - this.adyenService.getPaymentDetails(this.orderId).then(res => { - this.paymentReference = res.paymentReference; - this.refAvailable = !!res.paymentReference; - this.pspReference = res.pspReference; - this.env = res.environment; - }); - - } - } -}) \ No newline at end of file diff --git a/src/Resources/app/administration/src/main.js b/src/Resources/app/administration/src/main.js index 6389d79f..37caac12 100644 --- a/src/Resources/app/administration/src/main.js +++ b/src/Resources/app/administration/src/main.js @@ -25,8 +25,6 @@ import './component/adyen-config-check-button'; import './component/adyen-payment-capture'; import './component/adyen-refund'; import './component/adyen-notifications'; -import './component/adyen-payment-reference'; -import './sw-order-detail-override/index'; import './sw-order-detail-base-override/index'; import './component/entity/sw-entity-single-select-override'; diff --git a/src/Resources/app/administration/src/service/adyenService.js b/src/Resources/app/administration/src/service/adyenService.js index c2dd20b9..835e425c 100644 --- a/src/Resources/app/administration/src/service/adyenService.js +++ b/src/Resources/app/administration/src/service/adyenService.js @@ -127,21 +127,6 @@ class ApiClient extends ApiService { return isAdyen; } - - getPaymentDetails(orderId) { - const headers = this.getBasicHeaders({}); - - return this.httpClient - .get(this.getApiBasePath() + '/orders/' + orderId + '/payment-details', { - headers - }) - .then((response) => { - return ApiService.handleResponse(response); - }).catch((error) => { - console.error('An error occurred: ' + error.message); - throw error; - }); - } } Application.addServiceProvider('adyenService', (container) => { diff --git a/src/Resources/app/administration/src/sw-order-detail-override/index.js b/src/Resources/app/administration/src/sw-order-detail-override/index.js deleted file mode 100644 index b997e65c..00000000 --- a/src/Resources/app/administration/src/sw-order-detail-override/index.js +++ /dev/null @@ -1,5 +0,0 @@ -import template from './sw-order-detail.html.twig'; - -Shopware.Component.override('sw-order-detail', { - template -}) diff --git a/src/Resources/app/administration/src/sw-order-detail-override/sw-order-detail.html.twig b/src/Resources/app/administration/src/sw-order-detail-override/sw-order-detail.html.twig deleted file mode 100644 index 1e5b69b9..00000000 --- a/src/Resources/app/administration/src/sw-order-detail-override/sw-order-detail.html.twig +++ /dev/null @@ -1,4 +0,0 @@ -{% block sw_order_detail_header_title_new %} - {% parent %} - -{% endblock %} diff --git a/src/Resources/config/config.xml b/src/Resources/config/config.xml index 8030083e..a6cf86fb 100644 --- a/src/Resources/config/config.xml +++ b/src/Resources/config/config.xml @@ -141,15 +141,4 @@ - - Payment Flow - - usePreparedPayment - - - This flow enables merchants with a custom checkout flow (e.g. headless integrations) to create a payment request before creating an order. - See https://github.com/shopware/platform/blob/trunk/adr/2021-10-01-payment-flow.md#accepting-pre-created-payments for more information. - - - diff --git a/src/Resources/config/services.xml b/src/Resources/config/services.xml index 3b359dac..04063647 100644 --- a/src/Resources/config/services.xml +++ b/src/Resources/config/services.xml @@ -66,7 +66,6 @@ - diff --git a/src/Resources/config/services/checkout-api.xml b/src/Resources/config/services/checkout-api.xml index 800c3b5b..29e4a09a 100644 --- a/src/Resources/config/services/checkout-api.xml +++ b/src/Resources/config/services/checkout-api.xml @@ -37,7 +37,8 @@ - + + @@ -50,20 +51,6 @@ - - - - - - - - - - - - - - diff --git a/src/Resources/config/services/payment-handlers.xml b/src/Resources/config/services/payment-handlers.xml index cb27d950..dfb1c837 100644 --- a/src/Resources/config/services/payment-handlers.xml +++ b/src/Resources/config/services/payment-handlers.xml @@ -27,10 +27,15 @@ https://symfony.com/schema/dic/services/services-1.0.xsd"> + - + + + + - + + @@ -38,241 +43,196 @@ - - - + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/ScheduledTask/ProcessNotificationsHandler.php b/src/ScheduledTask/ProcessNotificationsHandler.php index 7f60d1c8..9808578e 100644 --- a/src/ScheduledTask/ProcessNotificationsHandler.php +++ b/src/ScheduledTask/ProcessNotificationsHandler.php @@ -166,7 +166,7 @@ public function run(): void $logContext['orderId'] = $order->getId(); $logContext['orderNumber'] = $order->getOrderNumber(); - $orderTransaction = $this->orderTransactionRepository->getFirstAdyenOrderTransaction( + $orderTransaction = $this->orderTransactionRepository->getFirstAdyenOrderTransactionByStates( $order->getId(), self::WEBHOOK_TRANSACTION_STATES ); @@ -281,10 +281,10 @@ private function transitionToState( 'Attempting capture for open invoice payment.', ['notification' => $notification->getVars()] ); - $this->captureService->capture( - $context, + $this->captureService->doOpenInvoiceCapture( $notification->getMerchantReference(), - (int) $notification->getAmountValue() + $notification->getAmountValue(), + $context ); } else { $this->transactionStateHandler->paid($orderTransaction->getId(), $context); diff --git a/src/Service/CaptureService.php b/src/Service/CaptureService.php index 75e5b5bf..f1eb20e7 100644 --- a/src/Service/CaptureService.php +++ b/src/Service/CaptureService.php @@ -100,12 +100,12 @@ public function __construct( } /** - * Send capture request + * Send capture request for open invoice payments * @throws CaptureException */ - public function capture(Context $context, string $orderNumber, int $amount, bool $preparedPaymentFlow = false) + public function doOpenInvoiceCapture(string $orderNumber, $captureAmount, Context $context) { - if ($preparedPaymentFlow || $this->configurationService->isManualCaptureActive()) { + if ($this->configurationService->isManualCaptureActive()) { $this->logger->info('Capture for order_number ' . $orderNumber . ' start.'); $order = $this->orderRepository->getOrderByOrderNumber( $orderNumber, @@ -119,7 +119,7 @@ public function capture(Context $context, string $orderNumber, int $amount, bool ); } $orderTransaction = $this->orderTransactionRepository - ->getFirstAdyenOrderTransaction($order->getId(), [OrderTransactionStates::STATE_AUTHORIZED]); + ->getFirstAdyenOrderTransactionByStates($order->getId(), [OrderTransactionStates::STATE_AUTHORIZED]); if (!$orderTransaction) { $error = 'Unable to find original authorized transaction.'; @@ -144,8 +144,7 @@ public function capture(Context $context, string $orderNumber, int $amount, bool $results = []; foreach ($deliveries as $delivery) { - if ($preparedPaymentFlow || - ($delivery->getStateMachineState()->getId() === $this->configurationService->getOrderState())) { + if ($delivery->getStateMachineState()->getId() === $this->configurationService->getOrderState()) { $lineItems = $order->getLineItems(); $lineItemsArray = $this->getLineItemsArray($lineItems, $order->getCurrency()->getIsoCode()); @@ -156,7 +155,7 @@ public function capture(Context $context, string $orderNumber, int $amount, bool $request = $this->buildCaptureRequest( $customFields[PaymentResponseHandler::ORIGINAL_PSP_REFERENCE], - $amount, + $captureAmount, $currencyIso, $additionalData ); @@ -168,7 +167,7 @@ public function capture(Context $context, string $orderNumber, int $amount, bool $response['pspReference'], PaymentCaptureEntity::SOURCE_SHOPWARE, PaymentCaptureEntity::STATUS_PENDING_WEBHOOK, - intval($amount), + intval($captureAmount), $context ); } diff --git a/src/Service/ConfigurationService.php b/src/Service/ConfigurationService.php index 43e89329..125c2736 100644 --- a/src/Service/ConfigurationService.php +++ b/src/Service/ConfigurationService.php @@ -222,13 +222,4 @@ public function getOrderState(string $salesChannelId = null) { return $this->systemConfigService->get(self::BUNDLE_NAME . '.config.orderState', $salesChannelId); } - - /** - * @param string|null $salesChannelId - * @return array|bool|float|int|string|null - */ - public function usesPreparedPaymentFlow(string $salesChannelId = null) - { - return $this->systemConfigService->get(self::BUNDLE_NAME . '.config.usePreparedPayment', $salesChannelId); - } } diff --git a/src/Service/PaymentDetailsService.php b/src/Service/PaymentDetailsService.php index 6a5c1f7a..85a83943 100644 --- a/src/Service/PaymentDetailsService.php +++ b/src/Service/PaymentDetailsService.php @@ -66,27 +66,21 @@ public function __construct( /** * @param array $requestData - * @param string $salesChannelId - * @param string|null $orderTransactionId - * @param string|null $paymentReference + * @param OrderTransactionEntity $orderTransaction * @return PaymentResponseHandlerResult * @throws PaymentFailedException - * @throws \Adyen\Shopware\Exception\ValidationException */ public function getPaymentDetails( array $requestData, - string $salesChannelId, - string $orderTransactionId = null, - string $paymentReference = null + OrderTransactionEntity $orderTransaction ): PaymentResponseHandlerResult { try { $checkoutService = new CheckoutService( - $this->clientService->getClient($salesChannelId) + $this->clientService->getClient($orderTransaction->getOrder()->getSalesChannelId()) ); $response = $checkoutService->paymentsDetails($requestData); - return $this->paymentResponseHandler - ->handlePaymentResponse($response, $orderTransactionId, $paymentReference); + return $this->paymentResponseHandler->handlePaymentResponse($response, $orderTransaction); } catch (AdyenException $exception) { $this->logger->error($exception->getMessage()); throw new PaymentFailedException($exception->getMessage()); diff --git a/src/Service/PaymentMethodsService.php b/src/Service/PaymentMethodsService.php index 7e12b1c8..8a73f87f 100644 --- a/src/Service/PaymentMethodsService.php +++ b/src/Service/PaymentMethodsService.php @@ -119,6 +119,37 @@ public function getPaymentMethods(SalesChannelContext $context, $orderId = ''): return $responseData; } + /** + * @param string $address + * @return array + */ + public function getSplitStreetAddressHouseNumber(string $address): array + { + $streetFirstRegex = '/(?[\w\W]+)\s+(?\d{1,10}((\s)?\w{1,3})?)$/m'; + $numberFirstRegex = '/^(?\d{1,10}((\s)?\w{1,3})?)\s+(?[\w\W]+)/m'; + + preg_match($streetFirstRegex, $address, $streetFirstAddress); + preg_match($numberFirstRegex, $address, $numberFirstAddress); + + if ($streetFirstAddress) { + return [ + 'street' => $streetFirstAddress['streetName'], + 'houseNumber' => $streetFirstAddress['houseNumber'] + ]; + } + else if ($numberFirstAddress) { + return [ + 'street' => $numberFirstAddress['streetName'], + 'houseNumber' => $numberFirstAddress['houseNumber'] + ]; + } + + return [ + 'street' => $address, + 'houseNumber' => 'N/A' + ]; + } + /** * @param SalesChannelContext $context * @param string $orderId diff --git a/src/Service/PaymentRequestService.php b/src/Service/PaymentRequestService.php deleted file mode 100644 index 76033944..00000000 --- a/src/Service/PaymentRequestService.php +++ /dev/null @@ -1,455 +0,0 @@ - - */ - -namespace Adyen\Shopware\Service; - -use Adyen\AdyenException; -use Adyen\Service\Builder\Address; -use Adyen\Service\Builder\Browser; -use Adyen\Service\Builder\Customer; -use Adyen\Service\Builder\OpenInvoice; -use Adyen\Service\Builder\Payment; -use Adyen\Service\Validator\CheckoutStateDataValidator; -use Adyen\Shopware\Exception\CurrencyNotFoundException; -use Adyen\Shopware\Handlers\AbstractPaymentMethodHandler; -use Adyen\Shopware\Service\Repository\SalesChannelRepository; -use Adyen\Util\Currency; -use Shopware\Core\Checkout\Cart\LineItem\LineItem; -use Shopware\Core\Checkout\Cart\LineItem\LineItemCollection; -use Shopware\Core\Checkout\Order\Aggregate\OrderLineItem\OrderLineItemCollection; -use Shopware\Core\Checkout\Order\Aggregate\OrderLineItem\OrderLineItemEntity; -use Shopware\Core\Content\Product\Exception\ProductNotFoundException; -use Shopware\Core\Content\Product\ProductCollection; -use Shopware\Core\Content\Product\ProductEntity; -use Shopware\Core\Framework\Context; -use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface; -use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria; -use Shopware\Core\Framework\Struct\Collection; -use Shopware\Core\System\Currency\CurrencyCollection; -use Shopware\Core\System\Currency\CurrencyEntity; -use Shopware\Core\System\SalesChannel\SalesChannelContext; -use Symfony\Component\HttpFoundation\Session\Session; - -class PaymentRequestService -{ - /** - * Error codes that are safe to display to the shopper. - * @see https://docs.adyen.com/development-resources/error-codes - */ - const SAFE_ERROR_CODES = ['124']; - const PROMOTION = 'promotion'; - - private Session $session; - private EntityRepositoryInterface $currencyRepository; - private EntityRepositoryInterface $productRepository; - private Currency $currency; - private Browser $browserBuilder; - private Address $addressBuilder; - private Customer $customerBuilder; - private Payment $paymentBuilder; - private SalesChannelRepository $salesChannelRepository; - private ConfigurationService $configurationService; - private CheckoutStateDataValidator $checkoutStateDataValidator; - private OpenInvoice $openInvoiceBuilder; - - public function __construct( - Address $addressBuilder, - Browser $browserBuilder, - CheckoutStateDataValidator $checkoutStateDataValidator, - ConfigurationService $configurationService, - Currency $currency, - Customer $customerBuilder, - EntityRepositoryInterface $currencyRepository, - EntityRepositoryInterface $productRepository, - OpenInvoice $openInvoiceBuilder, - Payment $paymentBuilder, - SalesChannelRepository $salesChannelRepository, - Session $session - ) { - $this->session = $session; - $this->currencyRepository = $currencyRepository; - $this->productRepository = $productRepository; - $this->browserBuilder = $browserBuilder; - $this->addressBuilder = $addressBuilder; - $this->customerBuilder = $customerBuilder; - $this->paymentBuilder = $paymentBuilder; - $this->openInvoiceBuilder = $openInvoiceBuilder; - $this->currency = $currency; - $this->salesChannelRepository = $salesChannelRepository; - $this->configurationService = $configurationService; - $this->checkoutStateDataValidator = $checkoutStateDataValidator; - } - - public function buildPaymentRequest( - array $request, - SalesChannelContext $salesChannelContext, - string $paymentMethodHandler, - float $totalPrice, - string $reference, - string $returnUrl, - ?array $lineItems = null - ): array { - //Validate state.data for payment and build request object - $request = $this->checkoutStateDataValidator->getValidatedAdditionalData($request); - - if (!empty($request['additionalData'])) { - $stateDataAdditionalData = $request['additionalData']; - } - - /** @var AbstractPaymentMethodHandler $paymentMethodHandler */ - if (empty($request['paymentMethod']['type'])) { - $paymentMethodType = $paymentMethodHandler::getPaymentMethodCode(); - } else { - $paymentMethodType = $request['paymentMethod']['type']; - } - - if ($paymentMethodHandler::$isGiftCard) { - $request['paymentMethod']['brand'] = $paymentMethodHandler::getBrand(); - } - - if (!empty($request['storePaymentMethod']) && $request['storePaymentMethod'] === true) { - $request['recurringProcessingModel'] = 'CardOnFile'; - $request['shopperInteraction'] = 'Ecommerce'; - } - - //Setting browser info if not present in statedata - if (empty($request['browserInfo']['acceptHeader'])) { - $acceptHeader = $_SERVER['HTTP_ACCEPT']; - } else { - $acceptHeader = $request['browserInfo']['acceptHeader']; - } - if (empty($request['browserInfo']['userAgent'])) { - $userAgent = $_SERVER['HTTP_USER_AGENT']; - } else { - $userAgent = $request['browserInfo']['userAgent']; - } - - //Setting delivery address info if not present in statedata - if (empty($request['deliveryAddress'])) { - if ($salesChannelContext->getShippingLocation()->getAddress()->getCountryState()) { - $shippingState = $salesChannelContext->getShippingLocation() - ->getAddress()->getCountryState()->getShortCode(); - } else { - $shippingState = ''; - } - - $shippingStreetAddress = $this->getSplitStreetAddressHouseNumber( - $salesChannelContext->getShippingLocation()->getAddress()->getStreet() - ); - $request = $this->addressBuilder->buildDeliveryAddress( - $shippingStreetAddress['street'], - $shippingStreetAddress['houseNumber'], - $salesChannelContext->getShippingLocation()->getAddress()->getZipcode(), - $salesChannelContext->getShippingLocation()->getAddress()->getCity(), - $shippingState, - $salesChannelContext->getShippingLocation()->getAddress()->getCountry()->getIso(), - $request - ); - } - - //Setting billing address info if not present in statedata - if (empty($request['billingAddress'])) { - if ($salesChannelContext->getCustomer()->getActiveBillingAddress()->getCountryState()) { - $billingState = $salesChannelContext->getCustomer() - ->getActiveBillingAddress()->getCountryState()->getShortCode(); - } else { - $billingState = ''; - } - - $billingStreetAddress = $this->getSplitStreetAddressHouseNumber( - $salesChannelContext->getCustomer()->getActiveBillingAddress()->getStreet() - ); - $request = $this->addressBuilder->buildBillingAddress( - $billingStreetAddress['street'], - $billingStreetAddress['houseNumber'], - $salesChannelContext->getCustomer()->getActiveBillingAddress()->getZipcode(), - $salesChannelContext->getCustomer()->getActiveBillingAddress()->getCity(), - $billingState, - $salesChannelContext->getCustomer()->getActiveBillingAddress()->getCountry()->getIso(), - $request - ); - } - - //Setting customer data if not present in statedata - if (empty($request['shopperName'])) { - $shopperFirstName = $salesChannelContext->getCustomer()->getFirstName(); - $shopperLastName = $salesChannelContext->getCustomer()->getLastName(); - } else { - $shopperFirstName = $request['shopperName']['firstName']; - $shopperLastName = $request['shopperName']['lastName']; - } - - if (empty($request['shopperEmail'])) { - $shopperEmail = $salesChannelContext->getCustomer()->getEmail(); - } else { - $shopperEmail = $request['shopperEmail']; - } - - if (empty($request['paymentMethod']['personalDetails']['telephoneNumber'])) { - $shopperPhone = $salesChannelContext->getShippingLocation()->getAddress()->getPhoneNumber(); - } else { - $shopperPhone = $request['paymentMethod']['personalDetails']['telephoneNumber']; - } - - if (empty($request['paymentMethod']['personalDetails']['dateOfBirth'])) { - if ($salesChannelContext->getCustomer()->getBirthday()) { - $shopperDob = $salesChannelContext->getCustomer()->getBirthday()->format('Y-m-d'); - } else { - $shopperDob = ''; - } - } else { - $shopperDob = $request['paymentMethod']['personalDetails']['dateOfBirth']; - } - - if (empty($request['shopperLocale'])) { - $shopperLocale = $this->salesChannelRepository->getSalesChannelAssocLocale($salesChannelContext) - ->getLanguage()->getLocale()->getCode(); - } else { - $shopperLocale = $request['shopperLocale']; - } - - if (empty($request['shopperIP'])) { - $shopperIp = $salesChannelContext->getCustomer()->getRemoteAddress(); - } else { - $shopperIp = $request['shopperIP']; - } - - if (empty($request['shopperReference'])) { - $shopperReference = $salesChannelContext->getCustomer()->getId(); - } else { - $shopperReference = $request['shopperReference']; - } - - if (empty($request['countryCode'])) { - $countryCode = $salesChannelContext->getCustomer()->getActiveBillingAddress()->getCountry()->getIso(); - } else { - $countryCode = $request['countryCode']; - } - - $request = $this->browserBuilder->buildBrowserData( - $userAgent, - $acceptHeader, - isset($request['browserInfo']['screenWidth']) ? $request['browserInfo']['screenWidth'] : null, - isset($request['browserInfo']['screenHeight']) ? $request['browserInfo']['screenHeight'] : null, - isset($request['browserInfo']['colorDepth']) ? $request['browserInfo']['colorDepth'] : null, - isset($request['browserInfo']['timeZoneOffset']) ? $request['browserInfo']['timeZoneOffset'] : null, - isset($request['browserInfo']['language']) ? $request['browserInfo']['language'] : null, - isset($request['browserInfo']['javaEnabled']) ? $request['browserInfo']['javaEnabled'] : null, - $request - ); - - $request = $this->customerBuilder->buildCustomerData( - false, - $shopperEmail, - $shopperPhone, - '', - $shopperDob, - $shopperFirstName, - $shopperLastName, - $countryCode, - $shopperLocale, - $shopperIp, - $shopperReference, - $request - ); - - //Building payment data - $request = $this->paymentBuilder->buildPaymentData( - $salesChannelContext->getCurrency()->getIsoCode(), - $this->currency->sanitize( - $totalPrice, - $salesChannelContext->getCurrency()->getIsoCode() - ), - $reference, - $this->configurationService->getMerchantAccount($salesChannelContext->getSalesChannel()->getId()), - $returnUrl, - $request - ); - - $request = $this->paymentBuilder->buildAlternativePaymentMethodData( - $paymentMethodType, - '', - $request - ); - - if ($paymentMethodHandler::$isOpenInvoice) { - $request['lineItems'] = $lineItems; - } - - //Setting info from statedata additionalData if present - if (!empty($stateDataAdditionalData['origin'])) { - $request['origin'] = $stateDataAdditionalData['origin']; - } else { - $request['origin'] = $this->salesChannelRepository->getSalesChannelUrl($salesChannelContext); - } - - $request['additionalData']['allow3DS2'] = true; - - $request['channel'] = 'web'; - - return $request; - } - - /** - * @param OrderLineItemCollection|LineItemCollection $lineItemsCollection - * @param Context $context - * @param CurrencyEntity $currency - * @param string $taxStatus - * @return array - */ - public function getLineItems( - Collection $lineItemsCollection, - Context $context, - CurrencyEntity $currency, - string $taxStatus - ): array { - $lineItems = []; - foreach ($lineItemsCollection as $lineItem) { - //Getting line price - $price = $lineItem->getPrice(); - - // Skip promotion line items. - if (LineItem::PROMOTION_LINE_ITEM_TYPE === $lineItem->getType()) { - continue; - } - - if ($lineItem instanceof LineItem) { - $productId = $lineItem->getReferencedId(); - } elseif ($lineItem instanceof OrderLineItemEntity) { - $productId = $lineItem->getProductId(); - } - - $product = $this->getProduct($productId, $context); - $productName = $product->getTranslation('name'); - $productNumber = $product->getProductNumber(); - - //Getting line tax amount and rate - $lineTax = $price->getCalculatedTaxes()->getAmount() / $lineItem->getQuantity(); - $taxRate = $price->getCalculatedTaxes()->first(); - if (!empty($taxRate)) { - $taxRate = $taxRate->getTaxRate(); - } else { - $taxRate = 0; - } - - //Building open invoice line - $lineItems[] = $this->openInvoiceBuilder->buildOpenInvoiceLineItem( - $productName, - $this->currency->sanitize( - $price->getUnitPrice() - - ($taxStatus == 'gross' ? $lineTax : 0), - $currency->getIsoCode() - ), - $this->currency->sanitize( - $lineTax, - $currency->getIsoCode() - ), - $taxRate * 100, - $lineItem->getQuantity(), - '', - $productNumber - ); - } - - return $lineItems; - } - - /** - * @param string $address - * @return array - */ - public function getSplitStreetAddressHouseNumber(string $address): array - { - $streetFirstRegex = '/(?[\w\W]+)\s+(?\d{1,10}((\s)?\w{1,3})?)$/m'; - $numberFirstRegex = '/^(?\d{1,10}((\s)?\w{1,3})?)\s+(?[\w\W]+)/m'; - - preg_match($streetFirstRegex, $address, $streetFirstAddress); - preg_match($numberFirstRegex, $address, $numberFirstAddress); - - if ($streetFirstAddress) { - return [ - 'street' => $streetFirstAddress['streetName'], - 'houseNumber' => $streetFirstAddress['houseNumber'] - ]; - } elseif ($numberFirstAddress) { - return [ - 'street' => $numberFirstAddress['streetName'], - 'houseNumber' => $numberFirstAddress['houseNumber'] - ]; - } - - return [ - 'street' => $address, - 'houseNumber' => 'N/A' - ]; - } - - /** - * @param string $currencyId - * @param Context $context - * @return CurrencyEntity - */ - public function getCurrency(string $currencyId, Context $context): CurrencyEntity - { - $criteria = new Criteria([$currencyId]); - - /** @var CurrencyCollection $currencyCollection */ - $currencyCollection = $this->currencyRepository->search($criteria, $context); - - $currency = $currencyCollection->get($currencyId); - if ($currency === null) { - throw new CurrencyNotFoundException($currencyId); - } - - return $currency; - } - - /** - * @param string $productId - * @param Context $context - * @return ProductEntity - */ - public function getProduct(string $productId, Context $context): ProductEntity - { - $criteria = new Criteria([$productId]); - - /** @var ProductCollection $productCollection */ - $productCollection = $this->productRepository->search($criteria, $context); - - $product = $productCollection->get($productId); - if ($product === null) { - throw new ProductNotFoundException($productId); - } - - return $product; - } - - public function displaySafeErrorMessages(AdyenException $exception) - { - if ('validation' === $exception->getErrorType() - && in_array($exception->getAdyenErrorCode(), self::SAFE_ERROR_CODES)) { - $this->session->getFlashBag()->add('warning', $exception->getMessage()); - } - } -} diff --git a/src/Service/PaymentStatusService.php b/src/Service/PaymentStatusService.php index 43843949..f1840988 100644 --- a/src/Service/PaymentStatusService.php +++ b/src/Service/PaymentStatusService.php @@ -50,7 +50,6 @@ public function __construct( } /** - * @deprecated * @param OrderTransactionEntity $orderTransaction * @return array * @throws MissingDataException @@ -58,7 +57,7 @@ public function __construct( */ public function getPaymentStatusWithOrderTransaction(OrderTransactionEntity $orderTransaction): array { - $paymentResponse = $this->paymentResponseService->getWithOrderTransaction($orderTransaction->getId()); + $paymentResponse = $this->paymentResponseService->getWithOrderTransaction($orderTransaction); if (empty($paymentResponse)) { throw new MissingDataException( @@ -78,36 +77,7 @@ public function getPaymentStatusWithOrderTransaction(OrderTransactionEntity $ord $result = $this->paymentResponseHandler->handlePaymentResponse( $responseData, - $orderTransaction->getId() - ); - - return $this->paymentResponseHandler->handleAdyenApis($result); - } - - public function getWithPaymentReference(string $paymentReference): array - { - $paymentResponse = $this->paymentResponseService->getWithPaymentReference($paymentReference); - - if (empty($paymentResponse)) { - throw new MissingDataException( - 'Payment response cannot be found for payment: ' . - $paymentReference - ); - } - - $responseData = json_decode($paymentResponse->getResponse(), true); - - if (json_last_error() !== JSON_ERROR_NONE) { - throw new JsonException( - 'Payment response is an invalid JSON for payment: ' . - $paymentReference - ); - } - - $result = $this->paymentResponseHandler->handlePaymentResponse( - $responseData, - null, - $paymentReference + $orderTransaction ); return $this->paymentResponseHandler->handleAdyenApis($result); @@ -134,7 +104,7 @@ public function getWithOrderId(string $orderId): array $result = $this->paymentResponseHandler->handlePaymentResponse( $responseData, - $paymentResponse->getOrderTransaction()->getId() + $paymentResponse->getOrderTransaction() ); return $this->paymentResponseHandler->handleAdyenApis($result); diff --git a/src/Service/RefundService.php b/src/Service/RefundService.php index fb781733..a1264131 100644 --- a/src/Service/RefundService.php +++ b/src/Service/RefundService.php @@ -304,7 +304,7 @@ public function doRefund(OrderTransactionEntity $orderTransaction, string $trans */ public function getAdyenOrderTransactionForRefund(OrderEntity $order, array $states): OrderTransactionEntity { - $orderTransaction = $this->transactionRepository->getFirstAdyenOrderTransaction( + $orderTransaction = $this->transactionRepository->getFirstAdyenOrderTransactionByStates( $order->getId(), $states ); diff --git a/src/Service/Repository/OrderTransactionRepository.php b/src/Service/Repository/OrderTransactionRepository.php index 529a8687..c0b27073 100644 --- a/src/Service/Repository/OrderTransactionRepository.php +++ b/src/Service/Repository/OrderTransactionRepository.php @@ -55,12 +55,12 @@ public function __construct(EntityRepositoryInterface $repository) /** * @param string $orderId - * @param array $statesFilter + * @param array $states * @return OrderTransactionEntity|null */ - public function getFirstAdyenOrderTransaction( + public function getFirstAdyenOrderTransactionByStates( string $orderId, - array $statesFilter = [] + array $states ): ?OrderTransactionEntity { $criteria = new Criteria(); $criteria->addAssociation('stateMachineState'); @@ -69,11 +69,9 @@ public function getFirstAdyenOrderTransaction( $criteria->addAssociation('paymentMethod'); $criteria->addAssociation('paymentMethod.plugin'); $criteria->addFilter(new EqualsFilter('order.id', $orderId)); - if (!empty($statesFilter)) { - $criteria->addFilter( - new EqualsAnyFilter('stateMachineState.technicalName', $statesFilter) - ); - } + $criteria->addFilter( + new EqualsAnyFilter('stateMachineState.technicalName', $states) + ); $criteria->addFilter( new EqualsFilter('paymentMethod.plugin.name', ConfigurationService::BUNDLE_NAME) ); diff --git a/src/Subscriber/PaymentSubscriber.php b/src/Subscriber/PaymentSubscriber.php index 77ded0b0..0db29bef 100644 --- a/src/Subscriber/PaymentSubscriber.php +++ b/src/Subscriber/PaymentSubscriber.php @@ -30,7 +30,6 @@ use Adyen\Shopware\Service\ConfigurationService; use Adyen\Shopware\Service\PaymentMethodsFilterService; use Adyen\Shopware\Service\PaymentMethodsService; -use Adyen\Shopware\Service\PaymentRequestService; use Adyen\Shopware\Service\PaymentStateDataService; use Adyen\Shopware\Service\Repository\SalesChannelRepository; use Adyen\Util\Currency; @@ -144,7 +143,6 @@ class PaymentSubscriber implements EventSubscriberInterface * @var AbstractSalesChannelContextFactory */ private $salesChannelContextFactory; - private PaymentRequestService $paymentRequestService; /** * PaymentSubscriber constructor. @@ -170,7 +168,6 @@ public function __construct( AdyenPluginProvider $adyenPluginProvider, PaymentMethodsFilterService $paymentMethodsFilterService, PaymentStateDataService $paymentStateDataService, - PaymentRequestService $paymentRequestService, RouterInterface $router, SalesChannelRepository $salesChannelRepository, ConfigurationService $configurationService, @@ -201,7 +198,6 @@ public function __construct( $this->currency = $currency; $this->logger = $logger; $this->adyenPluginProvider = $adyenPluginProvider; - $this->paymentRequestService = $paymentRequestService; } /** @@ -348,12 +344,8 @@ public function onCheckoutConfirmLoaded(PageLoadedEvent $event) 'selectedPaymentMethodHandler' => $paymentMethod->getFormattedHandlerIdentifier(), 'selectedPaymentMethodPluginId' => $paymentMethod->getPluginId(), 'displaySaveCreditCardOption' => $displaySaveCreditCardOption, - 'billingAddressStreetHouse' => $this->paymentRequestService->getSplitStreetAddressHouseNumber( - $salesChannelContext->getCustomer()->getActiveBillingAddress()->getStreet() - ), - 'shippingAddressStreetHouse' => $this->paymentRequestService->getSplitStreetAddressHouseNumber( - $salesChannelContext->getCustomer()->getActiveShippingAddress()->getStreet() - ), + 'billingAddressStreetHouse' => $this->paymentMethodsService->getSplitStreetAddressHouseNumber($salesChannelContext->getCustomer()->getActiveBillingAddress()->getStreet()), + 'shippingAddressStreetHouse' => $this->paymentMethodsService->getSplitStreetAddressHouseNumber($salesChannelContext->getCustomer()->getActiveShippingAddress()->getStreet()), ] ) ); From 0d358971bdcb1e99f86c0a4bf2f763efa992c40f Mon Sep 17 00:00:00 2001 From: peterojo Date: Mon, 4 Jul 2022 16:29:12 +0200 Subject: [PATCH 2/4] Undo remove cancel endpoint --- src/Controller/StoreApiController.php | 188 +----------------- src/Handlers/AbstractPaymentMethodHandler.php | 44 +++- .../config/services/payment-handlers.xml | 1 - .../js/adyen-payment-shopware6.js | 2 +- src/Service/PaymentResponseService.php | 52 +++-- 5 files changed, 63 insertions(+), 224 deletions(-) diff --git a/src/Controller/StoreApiController.php b/src/Controller/StoreApiController.php index 6510863a..7079fc54 100644 --- a/src/Controller/StoreApiController.php +++ b/src/Controller/StoreApiController.php @@ -24,26 +24,17 @@ namespace Adyen\Shopware\Controller; -use Adyen\AdyenException; use Adyen\Service\Validator\CheckoutStateDataValidator; use Adyen\Shopware\Exception\PaymentFailedException; -use Adyen\Shopware\Exception\ValidationException; -use Adyen\Shopware\Handlers\AbstractPaymentMethodHandler; use Adyen\Shopware\Handlers\PaymentResponseHandler; -use Adyen\Shopware\Service\CheckoutService; -use Adyen\Shopware\Service\ClientService; use Adyen\Shopware\Service\PaymentDetailsService; use Adyen\Shopware\Service\PaymentMethodsService; -use Adyen\Shopware\Service\PaymentRequestService; use Adyen\Shopware\Service\PaymentResponseService; use Adyen\Shopware\Service\PaymentStatusService; use Adyen\Shopware\Service\Repository\OrderRepository; use OpenApi\Annotations as OA; use Psr\Log\LoggerInterface; -use Shopware\Core\Checkout\Cart\Cart; -use Shopware\Core\Checkout\Cart\CartCalculator; use Shopware\Core\Checkout\Cart\Price\Struct\CalculatedPrice; -use Shopware\Core\Checkout\Cart\SalesChannel\CartService; use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionDefinition; use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionStates; use Shopware\Core\Checkout\Order\OrderEntity; @@ -75,10 +66,6 @@ class StoreApiController * @var PaymentDetailsService */ private $paymentDetailsService; - /** - * @var PaymentRequestService - */ - private $paymentRequestService; /** * @var CheckoutStateDataValidator */ @@ -111,28 +98,12 @@ class StoreApiController * @var LoggerInterface */ private $logger; - /** - * @var CartService - */ - private $cartService; - /** - * @var CartCalculator - */ - private $cartCalculator; - /** - * @var ClientService - */ - private $clientService; /** * StoreApiController constructor. * - * @param CartService $cartService - * @param CartCalculator $cartCalculator - * @param ClientService $clientService * @param PaymentMethodsService $paymentMethodsService * @param PaymentDetailsService $paymentDetailsService - * @param PaymentRequestService $paymentRequestService * @param CheckoutStateDataValidator $checkoutStateDataValidator * @param PaymentStatusService $paymentStatusService * @param PaymentResponseHandler $paymentResponseHandler @@ -143,12 +114,8 @@ class StoreApiController * @param LoggerInterface $logger */ public function __construct( - CartService $cartService, - CartCalculator $cartCalculator, - ClientService $clientService, PaymentMethodsService $paymentMethodsService, PaymentDetailsService $paymentDetailsService, - PaymentRequestService $paymentRequestService, CheckoutStateDataValidator $checkoutStateDataValidator, PaymentStatusService $paymentStatusService, PaymentResponseHandler $paymentResponseHandler, @@ -158,11 +125,8 @@ public function __construct( StateMachineRegistry $stateMachineRegistry, LoggerInterface $logger ) { - $this->cartService = $cartService; - $this->cartCalculator = $cartCalculator; $this->paymentMethodsService = $paymentMethodsService; $this->paymentDetailsService = $paymentDetailsService; - $this->paymentRequestService = $paymentRequestService; $this->checkoutStateDataValidator = $checkoutStateDataValidator; $this->paymentStatusService = $paymentStatusService; $this->paymentResponseHandler = $paymentResponseHandler; @@ -171,7 +135,6 @@ public function __construct( $this->orderService = $orderService; $this->stateMachineRegistry = $stateMachineRegistry; $this->logger = $logger; - $this->clientService = $clientService; } /** @@ -189,64 +152,6 @@ public function getPaymentMethods(SalesChannelContext $context): JsonResponse return new JsonResponse($this->paymentMethodsService->getPaymentMethods($context)); } - /** - * @Route( - * "/store-api/adyen/payments", - * name="store-api.action.adyen.payments", - * methods={"POST"} - * ) - * - * @param Request $request - * @param SalesChannelContext $context - * @return JsonResponse - * @throws \Adyen\AdyenException - */ - public function makePayment(Request $request, SalesChannelContext $context): JsonResponse - { - $returnUrl = $request->get('returnUrl'); - $stateData = $request->get('stateData'); - $data = json_decode($stateData, true); - $cart = $this->cartService->getCart($context->getToken(), $context); - $calculatedCart = $this->cartCalculator->calculate($cart, $context); - $totalPrice = $calculatedCart->getPrice()->getTotalPrice(); - $paymentMethod = $context->getPaymentMethod(); - $paymentHandler = $paymentMethod->getHandlerIdentifier(); - $reference = Uuid::fromStringToHex($calculatedCart->getToken()); - $currency = $this->paymentRequestService->getCurrency($context->getCurrencyId(), $context->getContext()); - $lineItems = $this->paymentRequestService->getLineItems( - $calculatedCart->getLineItems(), - $context->getContext(), - $currency, - $calculatedCart->getPrice()->getTaxStatus() - ); - - $request = $this->paymentRequestService->buildPaymentRequest( - $data, - $context, - $paymentHandler, - $totalPrice, - $reference, - $returnUrl, - $lineItems - ); - - $checkoutService = new CheckoutService( - $this->clientService->getClient($context->getSalesChannel()->getId()) - ); - - try { - $response = $checkoutService->payments($request); - } catch (AdyenException $exception) { - $this->logger->error($exception->getMessage()); - - return new JsonResponse('An error occurred.', 400); - } - - $result = $this->paymentResponseHandler->handlePaymentResponse($response, null, $reference); - - return new JsonResponse($this->paymentResponseHandler->handleAdyenApis($result)); - } - /** * @Route( * "/store-api/adyen/payment-details", @@ -290,8 +195,7 @@ public function postPaymentDetails( try { $result = $this->paymentDetailsService->getPaymentDetails( $stateData, - $context->getSalesChannelId(), - $paymentResponse->getOrderTransactionId() + $paymentResponse->getOrderTransaction() ); } catch (PaymentFailedException $exception) { $message = 'Error occurred finalizing payment'; @@ -305,67 +209,6 @@ public function postPaymentDetails( return new JsonResponse($this->paymentResponseHandler->handleAdyenApis($result)); } - /** - * @Route( - * "/store-api/adyen/prepared-payment-details", - * name="store-api.action.adyen.prepared-payment-details", - * methods={"POST"} - * ) - * - * @param Request $request - * @param SalesChannelContext $context - * @return JsonResponse - * @throws ValidationException - */ - public function getPreparedPaymentDetails( - Request $request, - SalesChannelContext $context - ): JsonResponse { - - $paymentReference = $request->request->get('paymentReference'); - $paymentResponse = $this->paymentResponseService->getWithPaymentReference($paymentReference); - if (!$paymentResponse) { - $message = 'Could not find a transaction'; - $this->logger->error($message, ['paymentReference' => $paymentReference]); - return new JsonResponse($message, 404); - } - - // Get state data object if sent - $stateData = $request->request->get('stateData'); - - // Validate stateData object - if (!empty($stateData)) { - $stateData = $this->checkoutStateDataValidator->getValidatedAdditionalData((array)$stateData); - } - - if (empty($stateData['details'])) { - $message = 'Details missing in $stateData'; - $this->logger->error( - $message, - ['stateData' => $stateData] - ); - return new JsonResponse($message, 400); - } - - try { - $result = $this->paymentDetailsService->getPaymentDetails( - $stateData, - $context->getSalesChannelId(), - null, - $paymentResponse->getPaymentReference() - ); - } catch (PaymentFailedException $exception) { - $message = 'Error occurred finalizing payment'; - $this->logger->error( - $message, - ['paymentReference' => $paymentReference, 'paymentDetails' => $stateData] - ); - return new JsonResponse($message, 500); - } - - return new JsonResponse($this->paymentResponseHandler->handleAdyenApis($result)); - } - /** * @Route( * "/store-api/adyen/payment-status", @@ -394,31 +237,6 @@ public function getPaymentStatus(Request $request, SalesChannelContext $context) } } - /** - * @Route( - * "/store-api/adyen/prepared-payment-status", - * name="store-api.action.adyen.prepared-payment-status", - * methods={"POST"} - * ) - * - * @param Request $request - * @param SalesChannelContext $context - * @return JsonResponse - * @throws \Adyen\Exception\MissingDataException - * @throws \JsonException - */ - public function getPreparedPaymentStatus(Request $request, SalesChannelContext $context): JsonResponse - { - $paymentReference = $request->get('paymentReference'); - if (empty($paymentReference)) { - return new JsonResponse('Payment reference not provided', 400); - } - - return new JsonResponse( - $this->paymentStatusService->getWithPaymentReference($paymentReference) - ); - } - /** * @OA\Post( * path="/adyen/set-payment", @@ -514,8 +332,10 @@ function () use ($order, $initialState, $orderId, $paymentMethodId, $context): v * ) * * @param Request $request - * @param SalesChannelContext $context + * @param SalesChannelContext $salesChannelContext * @return JsonResponse + * @throws \Adyen\Exception\MissingDataException + * @throws \JsonException */ public function cancelOrderTransaction( Request $request, diff --git a/src/Handlers/AbstractPaymentMethodHandler.php b/src/Handlers/AbstractPaymentMethodHandler.php index a08b4ce2..9a6d9bec 100644 --- a/src/Handlers/AbstractPaymentMethodHandler.php +++ b/src/Handlers/AbstractPaymentMethodHandler.php @@ -37,7 +37,6 @@ use Adyen\Shopware\Service\CheckoutService; use Adyen\Shopware\Service\ClientService; use Adyen\Shopware\Service\ConfigurationService; -use Adyen\Shopware\Service\PaymentMethodsService; use Adyen\Shopware\Service\PaymentStateDataService; use Adyen\Shopware\Service\Repository\SalesChannelRepository; use Adyen\Shopware\Storefront\Controller\RedirectResultController; @@ -180,11 +179,6 @@ abstract class AbstractPaymentMethodHandler */ protected Session $session; - /** - * @var PaymentMethodsService - */ - protected $paymentMethodsService; - /** * AbstractPaymentMethodHandler constructor. * @param ConfigurationService $configurationService @@ -205,7 +199,6 @@ abstract class AbstractPaymentMethodHandler * @param CsrfTokenManagerInterface $csrfTokenManager * @param EntityRepositoryInterface $currencyRepository * @param EntityRepositoryInterface $productRepository - * @param PaymentMethodsService $paymentMethodsService * @param LoggerInterface $logger */ public function __construct( @@ -228,7 +221,6 @@ public function __construct( Session $session, EntityRepositoryInterface $currencyRepository, EntityRepositoryInterface $productRepository, - PaymentMethodsService $paymentMethodsService, LoggerInterface $logger ) { $this->clientService = $clientService; @@ -251,7 +243,6 @@ public function __construct( $this->session = $session; $this->currencyRepository = $currencyRepository; $this->productRepository = $productRepository; - $this->paymentMethodsService = $paymentMethodsService; } abstract public static function getPaymentMethodCode(); @@ -440,7 +431,7 @@ protected function preparePaymentsRequest( $shippingState = ''; } - $shippingStreetAddress = $this->paymentMethodsService->getSplitStreetAddressHouseNumber( + $shippingStreetAddress = $this->getSplitStreetAddressHouseNumber( $salesChannelContext->getShippingLocation()->getAddress()->getStreet() ); $request = $this->addressBuilder->buildDeliveryAddress( @@ -463,7 +454,7 @@ protected function preparePaymentsRequest( $billingState = ''; } - $billingStreetAddress = $this->paymentMethodsService->getSplitStreetAddressHouseNumber( + $billingStreetAddress = $this->getSplitStreetAddressHouseNumber( $salesChannelContext->getCustomer()->getActiveBillingAddress()->getStreet() ); $request = $this->addressBuilder->buildBillingAddress( @@ -732,4 +723,35 @@ private function displaySafeErrorMessages(AdyenException $exception) $this->session->getFlashBag()->add('warning', $exception->getMessage()); } } + + /** + * @param string $address + * @return array + */ + private function getSplitStreetAddressHouseNumber(string $address): array + { + $streetFirstRegex = '/(?[\w\W]+)\s+(?\d{1,10}((\s)?\w{1,3})?)$/m'; + $numberFirstRegex = '/^(?\d{1,10}((\s)?\w{1,3})?)\s+(?[\w\W]+)/m'; + + preg_match($streetFirstRegex, $address, $streetFirstAddress); + preg_match($numberFirstRegex, $address, $numberFirstAddress); + + if ($streetFirstAddress) { + return [ + 'street' => $streetFirstAddress['streetName'], + 'houseNumber' => $streetFirstAddress['houseNumber'] + ]; + } + else if ($numberFirstAddress) { + return [ + 'street' => $numberFirstAddress['streetName'], + 'houseNumber' => $numberFirstAddress['houseNumber'] + ]; + } + + return [ + 'street' => $address, + 'houseNumber' => 'N/A' + ]; + } } diff --git a/src/Resources/config/services/payment-handlers.xml b/src/Resources/config/services/payment-handlers.xml index dfb1c837..4b31d73e 100644 --- a/src/Resources/config/services/payment-handlers.xml +++ b/src/Resources/config/services/payment-handlers.xml @@ -47,7 +47,6 @@ - \n{% endblock %}\n'},MTTW:function(e,t){var n=Shopware.Component,r=Shopware.Data.Criteria;n.extend("sw-entity-single-select-override","sw-entity-single-select",{props:{criteria:{type:Object,required:!1,default:function(){var e=new r(1,this.resultLimit);return e.addFilter(r.equals("stateMachine.technicalName","order_delivery.state")),e}}}})},RgpO:function(e,t,n){"use strict";n.r(t);n("UvA/");var r=n("wt28"),o=n.n(r),a=Shopware,i=a.Component,s=a.Mixin;i.register("adyen-config-check-button",{template:o.a,inject:["adyenService"],mixins:[s.getByName("notification")],data:function(){return{isLoading:!1,isSaveSuccessful:!1}},computed:{pluginConfig:function(){for(var e=this.$parent;!e.hasOwnProperty("actualConfigData");)e=e.$parent;var t=e.currentSalesChannelId,n=e.actualConfigData;return Object.assign({},n.null,n[t])}},methods:{saveFinish:function(){this.isSaveSuccessful=!1},check:function(){var e=this;this.isLoading=!0,this.adyenService.check(this.pluginConfig).then((function(t){t.success?(e.isSaveSuccessful=!0,e.createNotificationSuccess({title:e.$tc("adyen.configTestTitle"),message:e.$tc("adyen.configTestSuccess")})):e.createNotificationError({title:e.$tc("adyen.configTestTitle"),message:e.$tc(t.message?t.message:"adyen.configTestFail")}),e.isLoading=!1}))}}});var c=n("uQkf"),u=n.n(c),d=(n("hnQ+"),Shopware),l=d.Component,f=d.Mixin;l.register("adyen-payment-capture",{template:u.a,inject:["adyenService","systemConfigApiService"],mixins:[f.getByName("notification")],props:{order:{type:Object,required:!0}},data:function(){return{columns:[{property:"pspReference",label:this.$tc("adyen.columnHeaders.pspReference")},{property:"amount",label:this.$tc("adyen.columnHeaders.amount")},{property:"status",label:this.$tc("adyen.columnHeaders.status")},{property:"createdAt",label:this.$tc("adyen.columnHeaders.created")},{property:"updatedAt",label:this.$tc("adyen.columnHeaders.updated")}],showModal:!1,captureRequests:[],allowCapture:!0,captureEnabled:!1,errorOccurred:!1,isLoading:!0,showWidget:!1}},created:function(){this.createdComponent()},methods:{createdComponent:function(){var e=this;return this.systemConfigApiService.getValues("AdyenPaymentShopware6.config").then((function(t){e.captureEnabled=t["AdyenPaymentShopware6.config.manualCaptureEnabled"]||null})).finally((function(){e.isLoading=!1,e.showWidget=e.adyenService.isAdyenOrder(e.order)&&e.captureEnabled}))},openModal:function(){this.showModal=!0},onCloseModal:function(){this.showModal=!1},onSubmitCapture:function(){var e=this;this.isLoading=!0,this.adyenService.capture(this.order.id).then((function(t){t.success?(e.fetchCaptureRequests(),e.createNotificationSuccess({title:e.$tc("adyen.adyenPaymentCaptureTitle"),message:e.$tc("adyen.captureSuccessful")})):e.createNotificationError({title:e.$tc("adyen.adyenPaymentCaptureTitle"),message:e.$tc(t.message?t.message:"adyen.error")})})).catch((function(){e.createNotificationError({title:e.$tc("adyen.adyenPaymentCaptureTitle"),message:e.$tc("adyen.error")})})).finally((function(){e.isLoading=!1,e.showModal=!1}))},fetchCaptureRequests:function(){var e=this;this.isLoading=!0,this.adyenService.getCaptureRequests(this.order.id).then((function(t){e.captureRequests=t,e.isCaptureAllowed()})).catch((function(){e.errorOccurred=!0,e.captureRequests=[]})).finally((function(){e.isLoading=!1}))},isCaptureAllowed:function(){var e=this.getAuthorizedAdyenOrderTransaction(),t=this.captureRequests.filter((function(e){return"Pending Webhook"===e.status}));this.allowCapture=e.length>0&&0===t.length},getAuthorizedAdyenOrderTransaction:function(){return this.order.transactions.filter((function(e){var t="originalPspReference"in e.customFields,n="Authorized"===e.stateMachineState.name;return t&&n}))}},beforeMount:function(){this.fetchCaptureRequests()}});var p=n("w8Bj"),h=n.n(p);n("Fxip");function y(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return m(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return m(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,o=function(){};return{s:o,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,i=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return i=e.done,e},e:function(e){s=!0,a=e},f:function(){try{i||null==n.return||n.return()}finally{if(s)throw a}}}}function m(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);nt/100},isAdyenOrder:function(){for(var e=this.order.transactions,t=!1,n=0;nn.parts.length&&(r.parts.length=n.parts.length)}else{var i=[];for(o=0;o\n \n \n

{{ $tc(\'adyen.noNotificationsReceived\') }}

\n
\n'},"UvA/":function(e,t){function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){for(var n=0;n2&&void 0!==arguments[2]?arguments[2]:"adyen";return r(this,d),(n=c.call(this,e,t,o)).headers=n.getBasicHeaders({}),n}return t=d,(n=[{key:"check",value:function(e){var t=this.getBasicHeaders({});return this.httpClient.post("_action/".concat(this.getApiBasePath(),"/verify"),e,{headers:t}).then((function(e){return u.handleResponse(e)}))}},{key:"capture",value:function(e){return this.httpClient.post(this.getApiBasePath()+"/capture",{orderId:e},{headers:this.headers}).then((function(e){return u.handleResponse(e)})).catch((function(e){throw console.error("An error occurred during capture request: "+e.message),e}))}},{key:"getCaptureRequests",value:function(e){var t=this.getBasicHeaders({});return this.httpClient.get(this.getApiBasePath()+"/orders/"+e+"/captures",{headers:t}).then((function(e){return u.handleResponse(e)})).catch((function(e){throw console.error("An error occurred during capture request: "+e.message),e}))}},{key:"getRefunds",value:function(e){var t=this.getBasicHeaders({});return this.httpClient.get(this.getApiBasePath()+"/orders/"+e+"/refunds",{headers:t}).then((function(e){return u.handleResponse(e)})).catch((function(e){throw console.error("An error occurred during refunds request: "+e.message),e}))}},{key:"postRefund",value:function(e,t){var n=this.getBasicHeaders({});return this.httpClient.post(this.getApiBasePath()+"/refunds",{orderId:e,refundAmount:t},{headers:n}).then((function(e){return u.handleResponse(e)})).catch((function(e){throw console.error("An error occurred during post refund request: "+e.message),e}))}},{key:"fetchNotifications",value:function(e){var t=this.getBasicHeaders({});return this.httpClient.get(this.getApiBasePath()+"/orders/"+e+"/notifications",{headers:t}).then((function(e){return u.handleResponse(e)})).catch((function(e){throw console.error("An error occurred: "+e.message),e}))}},{key:"isAdyenOrder",value:function(e){for(var t=e.transactions,n=!1,r=0;r\n
\n
\n
\n {{ $tc(\'adyen.noCaptureRequests\') }}\n
\n
\n \n {{ $tc(\'adyen.sendCaptureRequest\') }}\n \n
\n \n \n \n
\n \n \n
\n
\n {{ $tc(\'adyen.error\') }}\n
\n\n'},w8Bj:function(e,t){e.exports='{% block adyen_refund %}\n \n
\n
\n
\n {{ $tc(\'adyen.noRefundsCreated\') }}\n
\n
\n \n {{ $tc(\'sw-order.documentCard.labelCreateNew\') }}\n \n
\n \n
\n \n
\n \n
\n
\n \n \n
\n
\n {{ $tc(\'adyen.refundFetchError\') }}\n
\n
\n{% endblock %}\n'},wt28:function(e,t){e.exports='\n'},xIYV:function(e,t,n){},xJoO:function(e,t){e.exports='{% block sw_order_detail_base_custom_fields %}\n {% parent %}\n \n \n \n{% endblock %}\n'}}); \ No newline at end of file +!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="/bundles/adyenpaymentshopware6/",n(n.s="RgpO")}({"6MJt":function(e,t,n){},Fxip:function(e,t,n){var r=n("xIYV");r.__esModule&&(r=r.default),"string"==typeof r&&(r=[[e.i,r,""]]),r.locals&&(e.exports=r.locals);(0,n("SZ7m").default)("3299a05e",r,!0,{})},MTTW:function(e,t){var n=Shopware.Component,r=Shopware.Data.Criteria;n.extend("sw-entity-single-select-override","sw-entity-single-select",{props:{criteria:{type:Object,required:!1,default:function(){var e=new r(1,this.resultLimit);return e.addFilter(r.equals("stateMachine.technicalName","order_delivery.state")),e}}}})},RgpO:function(e,t,n){"use strict";n.r(t);n("UvA/");var r=n("wt28"),o=n.n(r),a=Shopware,i=a.Component,s=a.Mixin;i.register("adyen-config-check-button",{template:o.a,inject:["adyenService"],mixins:[s.getByName("notification")],data:function(){return{isLoading:!1,isSaveSuccessful:!1}},computed:{pluginConfig:function(){for(var e=this.$parent;!e.hasOwnProperty("actualConfigData");)e=e.$parent;var t=e.currentSalesChannelId,n=e.actualConfigData;return Object.assign({},n.null,n[t])}},methods:{saveFinish:function(){this.isSaveSuccessful=!1},check:function(){var e=this;this.isLoading=!0,this.adyenService.check(this.pluginConfig).then((function(t){t.success?(e.isSaveSuccessful=!0,e.createNotificationSuccess({title:e.$tc("adyen.configTestTitle"),message:e.$tc("adyen.configTestSuccess")})):e.createNotificationError({title:e.$tc("adyen.configTestTitle"),message:e.$tc(t.message?t.message:"adyen.configTestFail")}),e.isLoading=!1}))}}});var c=n("uQkf"),u=n.n(c),d=(n("hnQ+"),Shopware),l=d.Component,f=d.Mixin;l.register("adyen-payment-capture",{template:u.a,inject:["adyenService","systemConfigApiService"],mixins:[f.getByName("notification")],props:{order:{type:Object,required:!0}},data:function(){return{columns:[{property:"pspReference",label:this.$tc("adyen.columnHeaders.pspReference")},{property:"amount",label:this.$tc("adyen.columnHeaders.amount")},{property:"status",label:this.$tc("adyen.columnHeaders.status")},{property:"createdAt",label:this.$tc("adyen.columnHeaders.created")},{property:"updatedAt",label:this.$tc("adyen.columnHeaders.updated")}],showModal:!1,captureRequests:[],allowCapture:!0,captureEnabled:!1,errorOccurred:!1,isLoading:!0,showWidget:!1}},created:function(){this.createdComponent()},methods:{createdComponent:function(){var e=this;return this.systemConfigApiService.getValues("AdyenPaymentShopware6.config").then((function(t){e.captureEnabled=t["AdyenPaymentShopware6.config.manualCaptureEnabled"]||null})).finally((function(){e.isLoading=!1,e.showWidget=e.adyenService.isAdyenOrder(e.order)&&e.captureEnabled}))},openModal:function(){this.showModal=!0},onCloseModal:function(){this.showModal=!1},onSubmitCapture:function(){var e=this;this.isLoading=!0,this.adyenService.capture(this.order.id).then((function(t){t.success?(e.fetchCaptureRequests(),e.createNotificationSuccess({title:e.$tc("adyen.adyenPaymentCaptureTitle"),message:e.$tc("adyen.captureSuccessful")})):e.createNotificationError({title:e.$tc("adyen.adyenPaymentCaptureTitle"),message:e.$tc(t.message?t.message:"adyen.error")})})).catch((function(){e.createNotificationError({title:e.$tc("adyen.adyenPaymentCaptureTitle"),message:e.$tc("adyen.error")})})).finally((function(){e.isLoading=!1,e.showModal=!1}))},fetchCaptureRequests:function(){var e=this;this.isLoading=!0,this.adyenService.getCaptureRequests(this.order.id).then((function(t){e.captureRequests=t,e.isCaptureAllowed()})).catch((function(){e.errorOccurred=!0,e.captureRequests=[]})).finally((function(){e.isLoading=!1}))},isCaptureAllowed:function(){var e=this.getAuthorizedAdyenOrderTransaction(),t=this.captureRequests.filter((function(e){return"Pending Webhook"===e.status}));this.allowCapture=e.length>0&&0===t.length},getAuthorizedAdyenOrderTransaction:function(){return this.order.transactions.filter((function(e){var t="originalPspReference"in e.customFields,n="Authorized"===e.stateMachineState.name;return t&&n}))}},beforeMount:function(){this.fetchCaptureRequests()}});var p=n("w8Bj"),h=n.n(p);n("Fxip");function y(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return m(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return m(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,o=function(){};return{s:o,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,i=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return i=e.done,e},e:function(e){s=!0,a=e},f:function(){try{i||null==n.return||n.return()}finally{if(s)throw a}}}}function m(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);nt/100},isAdyenOrder:function(){for(var e=this.order.transactions,t=!1,n=0;nn.parts.length&&(r.parts.length=n.parts.length)}else{var i=[];for(o=0;o\n \n \n

{{ $tc(\'adyen.noNotificationsReceived\') }}

\n
\n'},"UvA/":function(e,t){function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){for(var n=0;n2&&void 0!==arguments[2]?arguments[2]:"adyen";return r(this,d),(n=c.call(this,e,t,o)).headers=n.getBasicHeaders({}),n}return t=d,(n=[{key:"check",value:function(e){var t=this.getBasicHeaders({});return this.httpClient.post("_action/".concat(this.getApiBasePath(),"/verify"),e,{headers:t}).then((function(e){return u.handleResponse(e)}))}},{key:"capture",value:function(e){return this.httpClient.post(this.getApiBasePath()+"/capture",{orderId:e},{headers:this.headers}).then((function(e){return u.handleResponse(e)})).catch((function(e){throw console.error("An error occurred during capture request: "+e.message),e}))}},{key:"getCaptureRequests",value:function(e){var t=this.getBasicHeaders({});return this.httpClient.get(this.getApiBasePath()+"/orders/"+e+"/captures",{headers:t}).then((function(e){return u.handleResponse(e)})).catch((function(e){throw console.error("An error occurred during capture request: "+e.message),e}))}},{key:"getRefunds",value:function(e){var t=this.getBasicHeaders({});return this.httpClient.get(this.getApiBasePath()+"/orders/"+e+"/refunds",{headers:t}).then((function(e){return u.handleResponse(e)})).catch((function(e){throw console.error("An error occurred during refunds request: "+e.message),e}))}},{key:"postRefund",value:function(e,t){var n=this.getBasicHeaders({});return this.httpClient.post(this.getApiBasePath()+"/refunds",{orderId:e,refundAmount:t},{headers:n}).then((function(e){return u.handleResponse(e)})).catch((function(e){throw console.error("An error occurred during post refund request: "+e.message),e}))}},{key:"fetchNotifications",value:function(e){var t=this.getBasicHeaders({});return this.httpClient.get(this.getApiBasePath()+"/orders/"+e+"/notifications",{headers:t}).then((function(e){return u.handleResponse(e)})).catch((function(e){throw console.error("An error occurred: "+e.message),e}))}},{key:"isAdyenOrder",value:function(e){for(var t=e.transactions,n=!1,r=0;r\n
\n
\n
\n {{ $tc(\'adyen.noCaptureRequests\') }}\n
\n
\n \n {{ $tc(\'adyen.sendCaptureRequest\') }}\n \n
\n \n \n \n
\n \n \n
\n
\n {{ $tc(\'adyen.error\') }}\n
\n\n'},w8Bj:function(e,t){e.exports='{% block adyen_refund %}\n \n
\n
\n
\n {{ $tc(\'adyen.noRefundsCreated\') }}\n
\n
\n \n {{ $tc(\'sw-order.documentCard.labelCreateNew\') }}\n \n
\n \n
\n \n
\n \n
\n
\n \n \n
\n
\n {{ $tc(\'adyen.refundFetchError\') }}\n
\n
\n{% endblock %}\n'},wt28:function(e,t){e.exports='\n'},xIYV:function(e,t,n){},xJoO:function(e,t){e.exports='{% block sw_order_detail_base_custom_fields %}\n {% parent %}\n \n \n \n{% endblock %}\n'}}); \ No newline at end of file diff --git a/src/Service/PaymentResponseService.php b/src/Service/PaymentResponseService.php index c5e3976e..98025a14 100644 --- a/src/Service/PaymentResponseService.php +++ b/src/Service/PaymentResponseService.php @@ -24,12 +24,12 @@ namespace Adyen\Shopware\Service; use Adyen\Shopware\Entity\PaymentResponse\PaymentResponseEntity; -use Adyen\Shopware\Handlers\PaymentResponseHandler; -use Adyen\Shopware\Service\Repository\OrderTransactionRepository; +use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionEntity; use Shopware\Core\Framework\Context; use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface; use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria; use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter; +use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting; class PaymentResponseService { @@ -39,15 +39,22 @@ class PaymentResponseService private $repository; /** - * @var OrderTransactionRepository + * @var EntityRepositoryInterface + */ + private $orderRepository; + + /** + * @var EntityRepositoryInterface */ private $orderTransactionRepository; public function __construct( EntityRepositoryInterface $repository, - OrderTransactionRepository $orderTransactionRepository + EntityRepositoryInterface $orderRepository, + EntityRepositoryInterface $orderTransactionRepository ) { $this->repository = $repository; + $this->orderRepository = $orderRepository; $this->orderTransactionRepository = $orderTransactionRepository; } @@ -65,48 +72,39 @@ public function getWithOrderNumber(string $orderNumber): ?PaymentResponseEntity public function getWithOrderId(string $orderId): ?PaymentResponseEntity { $orderTransaction = $this->orderTransactionRepository - ->getFirstAdyenOrderTransaction($orderId); - return $this->getWithOrderTransaction($orderTransaction->getId()); - } - - public function getWithOrderTransaction(string $orderTransactionId): ?PaymentResponseEntity - { - return $this->repository ->search( (new Criteria()) - ->addFilter(new EqualsFilter('orderTransactionId', $orderTransactionId)) - ->addAssociation('orderTransaction.order'), + ->addFilter((new EqualsFilter('orderId', $orderId))) + ->addAssociation('order') + ->addSorting(new FieldSorting('createdAt', FieldSorting::DESCENDING)), Context::createDefaultContext() ) - ->last(); + ->first(); + return $this->getWithOrderTransaction($orderTransaction); } - public function getWithPaymentReference(string $paymentReference): ?PaymentResponseEntity + public function getWithOrderTransaction(OrderTransactionEntity $orderTransaction): ?PaymentResponseEntity { return $this->repository ->search( (new Criteria()) - ->addFilter(new EqualsFilter('paymentReference', $paymentReference)), + ->addFilter(new EqualsFilter('orderTransactionId', $orderTransaction->getId())) + ->addAssociation('orderTransaction.order'), Context::createDefaultContext() - )->first(); + ) + ->first(); } public function insertPaymentResponse( - array $paymentResponse, - string $value, - string $identifier + array $paymentResponse, + OrderTransactionEntity $orderTransaction ): void { - if ($identifier === PaymentResponseHandler::ORDER_TRANSACTION_ID) { - $storedPaymentResponse = $this->getWithOrderTransaction($value); - } else { - $storedPaymentResponse = $this->getWithPaymentReference($value); - } - + $storedPaymentResponse = $this->getWithOrderTransaction($orderTransaction); if ($storedPaymentResponse) { $fields['id'] = $storedPaymentResponse->getId(); } - $fields[$identifier] = $value; + $fields['orderTransactionId'] = $orderTransaction->getId(); $fields['resultCode'] = $paymentResponse["resultCode"]; $fields['response'] = json_encode($paymentResponse); From 50e9db681fafebe86e1770100e2441bec331ca4b Mon Sep 17 00:00:00 2001 From: peterojo Date: Mon, 4 Jul 2022 16:33:09 +0200 Subject: [PATCH 3/4] Version bump 3.4.2 --- composer.json | 2 +- composer.lock | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 2912509f..4b843a4a 100644 --- a/composer.json +++ b/composer.json @@ -6,7 +6,7 @@ } ], "description": "Official Shopware 6 Plugin to connect to Payment Service Provider Adyen", - "version": "3.4.1", + "version": "3.4.2", "type": "shopware-platform-plugin", "license": "MIT", "require": { diff --git a/composer.lock b/composer.lock index 5d5e8965..f39307a4 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "6daa73e6b14ae541e2e00611939cafb2", + "content-hash": "9a6733f97dfb648e47af99b39533b499", "packages": [ { "name": "adyen/php-api-library", From 359d1e6dca3376979cea6ce4ddb2789a973c0aa4 Mon Sep 17 00:00:00 2001 From: peterojo Date: Mon, 4 Jul 2022 16:39:01 +0200 Subject: [PATCH 4/4] code formatting --- src/Handlers/AbstractPaymentMethodHandler.php | 3 +-- src/Service/PaymentMethodsService.php | 3 +-- src/Subscriber/PaymentSubscriber.php | 8 ++++++-- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/Handlers/AbstractPaymentMethodHandler.php b/src/Handlers/AbstractPaymentMethodHandler.php index 9a6d9bec..ac83f14a 100644 --- a/src/Handlers/AbstractPaymentMethodHandler.php +++ b/src/Handlers/AbstractPaymentMethodHandler.php @@ -741,8 +741,7 @@ private function getSplitStreetAddressHouseNumber(string $address): array 'street' => $streetFirstAddress['streetName'], 'houseNumber' => $streetFirstAddress['houseNumber'] ]; - } - else if ($numberFirstAddress) { + } elseif ($numberFirstAddress) { return [ 'street' => $numberFirstAddress['streetName'], 'houseNumber' => $numberFirstAddress['houseNumber'] diff --git a/src/Service/PaymentMethodsService.php b/src/Service/PaymentMethodsService.php index 8a73f87f..f659281b 100644 --- a/src/Service/PaymentMethodsService.php +++ b/src/Service/PaymentMethodsService.php @@ -136,8 +136,7 @@ public function getSplitStreetAddressHouseNumber(string $address): array 'street' => $streetFirstAddress['streetName'], 'houseNumber' => $streetFirstAddress['houseNumber'] ]; - } - else if ($numberFirstAddress) { + } elseif ($numberFirstAddress) { return [ 'street' => $numberFirstAddress['streetName'], 'houseNumber' => $numberFirstAddress['houseNumber'] diff --git a/src/Subscriber/PaymentSubscriber.php b/src/Subscriber/PaymentSubscriber.php index 0db29bef..cf9109fd 100644 --- a/src/Subscriber/PaymentSubscriber.php +++ b/src/Subscriber/PaymentSubscriber.php @@ -344,8 +344,12 @@ public function onCheckoutConfirmLoaded(PageLoadedEvent $event) 'selectedPaymentMethodHandler' => $paymentMethod->getFormattedHandlerIdentifier(), 'selectedPaymentMethodPluginId' => $paymentMethod->getPluginId(), 'displaySaveCreditCardOption' => $displaySaveCreditCardOption, - 'billingAddressStreetHouse' => $this->paymentMethodsService->getSplitStreetAddressHouseNumber($salesChannelContext->getCustomer()->getActiveBillingAddress()->getStreet()), - 'shippingAddressStreetHouse' => $this->paymentMethodsService->getSplitStreetAddressHouseNumber($salesChannelContext->getCustomer()->getActiveShippingAddress()->getStreet()), + 'billingAddressStreetHouse' => $this->paymentMethodsService->getSplitStreetAddressHouseNumber( + $salesChannelContext->getCustomer()->getActiveBillingAddress()->getStreet() + ), + 'shippingAddressStreetHouse' => $this->paymentMethodsService->getSplitStreetAddressHouseNumber( + $salesChannelContext->getCustomer()->getActiveShippingAddress()->getStreet() + ), ] ) );