From ec4403d655294310a891c5033ddc02722dbd9b49 Mon Sep 17 00:00:00 2001 From: kpieloch <113994423+kpieloch@users.noreply.github.com> Date: Mon, 18 Mar 2024 10:40:47 +0100 Subject: [PATCH 1/4] [AD-156] Upgrade Java Lib in AdyenV6 plugin to the newest version + deprecated code removed --- ...dyenApplePayExpressCheckoutController.java | 6 +- .../pages/AdyenComponentController.java | 120 +--- .../AdyenSummaryCheckoutStepController.java | 222 +++---- .../account/AdyenStoredCardsController.java | 31 +- .../payments/AdyenAmazonpayController.java | 11 +- .../AdyenAmazonpayControllerTest.java | 14 +- .../checkout/multi/checkoutSummaryPage.jsp | 3 +- .../responsive/common/js/adyen.checkout.js | 35 +- adyenv6b2ccheckoutaddon/extensioninfo.xml | 1 + .../v6/facades/AdyenCheckoutFacadeTest.java | 139 +++-- .../AdyenCaptureConsignmentsAction.java | 8 +- adyenv6core/external-dependencies.xml | 12 +- adyenv6core/resources/adyenv6core-spring.xml | 20 +- .../order/AdyenCheckAuthorizationAction.java | 6 +- .../order/AdyenCheckCaptureAction.java | 6 +- .../v6/commands/AdyenCaptureCommand.java | 11 +- .../commands/AdyenFollowOnRefundCommand.java | 12 +- .../adyen/v6/commands/AdyenVoidCommand.java | 10 +- .../v6/constants/Adyenv6coreConstants.java | 1 + .../v6/converters/PaymentMethodConverter.java | 45 -- .../PaymentsDetailsResponseConverter.java | 45 -- .../converters/PaymentsResponseConverter.java | 43 -- .../PosPaymentResponseConverter.java | 10 +- .../AdyenNonAuthorizedPaymentException.java | 22 +- .../adyen/v6/facades/AdyenCheckoutFacade.java | 30 +- .../facades/AdyenExpressCheckoutFacade.java | 6 +- .../src/com/adyen/v6/facades/impl/Amount.java | 32 - .../impl/DefaultAdyenCheckoutFacade.java | 336 ++++------- .../DefaultAdyenExpressCheckoutFacade.java | 23 +- .../adyen/v6/facades/impl/SessionRequest.java | 2 + .../v6/facades/impl/SessionResponse.java | 2 + .../factory/AdyenPaymentServiceFactory.java | 23 +- .../adyen/v6/factory/AdyenRequestFactory.java | 415 ++++--------- ...enPaymentMethodDetailsBuilderStrategy.java | 39 -- ...rmPaymentMethodDetailsBuilderStrategy.java | 28 - ...enPaymentMethodDetailsBuilderStrategy.java | 36 -- ...ayPaymentMethodDetailsBuilderStrategy.java | 29 - ...enPaymentMethodDetailsBuilderStrategy.java | 31 - ...ayPaymentMethodDetailsBuilderStrategy.java | 28 - ...enPaymentMethodDetailsBuilderStrategy.java | 33 -- ...ayPaymentMethodDetailsBuilderStrategy.java | 28 - ...enPaymentMethodDetailsBuilderStrategy.java | 29 - ...ayPaymentMethodDetailsBuilderStrategy.java | 29 - ...enPaymentMethodDetailsBuilderStrategy.java | 28 - ...rdPaymentMethodDetailsBuilderStrategy.java | 31 - ...ayPaymentMethodDetailsBuilderStrategy.java | 27 - ...enPaymentMethodDetailsBuilderStrategy.java | 29 - ...acPaymentMethodDetailsBuilderStrategy.java | 28 - ...enPaymentMethodDetailsBuilderStrategy.java | 35 -- ...ayPaymentMethodDetailsBuilderStrategy.java | 31 - ...coPaymentMethodDetailsBuilderStrategy.java | 28 - ...eyPaymentMethodDetailsBuilderStrategy.java | 28 - ...ngPaymentMethodDetailsBuilderStrategy.java | 28 - ...htPaymentMethodDetailsBuilderStrategy.java | 30 - ...enPaymentMethodDetailsBuilderStrategy.java | 30 - ...tmPaymentMethodDetailsBuilderStrategy.java | 28 - ...ayPaymentMethodDetailsBuilderStrategy.java | 29 - ...itPaymentMethodDetailsBuilderStrategy.java | 29 - ...rtPaymentMethodDetailsBuilderStrategy.java | 28 - ...tyPaymentMethodDetailsBuilderStrategy.java | 28 - ...PIPaymentMethodDetailsBuilderStrategy.java | 28 - ...iaPaymentMethodDetailsBuilderStrategy.java | 28 - ...ebPaymentMethodDetailsBuilderStrategy.java | 29 - ...enPaymentMethodDetailsBuilderExecutor.java | 16 - ...mentMethodDetailsStrategyExecutorImpl.java | 30 - .../v6/service/AbstractAdyenApiService.java | 91 +++ ...vice.java => AdyenCheckoutApiService.java} | 62 +- .../service/AdyenModificationsApiService.java | 21 + .../v6/service/AdyenNotificationService.java | 4 +- .../adyen/v6/service/AdyenOrderService.java | 30 +- .../v6/service/AdyenTransactionService.java | 4 +- .../DefaultAdyenCheckoutApiService.java | 365 ++++++++++++ .../DefaultAdyenModificationsApiService.java | 78 +++ .../DefaultAdyenNotificationService.java | 7 +- .../v6/service/DefaultAdyenOrderService.java | 133 ++--- .../service/DefaultAdyenPaymentService.java | 560 ------------------ .../DefaultAdyenTransactionService.java | 12 +- .../src/com/adyen/v6/util/AmountUtil.java | 38 ++ .../AdyenCheckAuthorizationActionTest.java | 10 +- .../order/AdyenCheckCaptureActionTest.java | 10 +- .../v6/commands/AdyenCaptureCommandTest.java | 32 +- ...ymentMethodDetailsBuilderStrategyTest.java | 57 -- ...ymentMethodDetailsBuilderStrategyTest.java | 60 -- .../adyenv6ordermanagement-testclasses.xml | 1 - ...ubscriptionAdyenPaymentServiceFactory.java | 8 +- .../SubscriptionPaymentRequestFactory.java | 41 +- ...ltSubscriptionAdyenCheckoutApiService.java | 70 +++ ...efaultSubscriptionAdyenPaymentService.java | 112 ---- .../impl/SubscriptionOrderExecutor.java | 14 +- .../adyen/v6/utils/SubscriptionsUtils.java | 10 +- ...SubscriptionPaymentRequestFactoryTest.java | 10 +- 91 files changed, 1413 insertions(+), 3065 deletions(-) delete mode 100644 adyenv6core/src/com/adyen/v6/converters/PaymentMethodConverter.java delete mode 100644 adyenv6core/src/com/adyen/v6/converters/PaymentsDetailsResponseConverter.java delete mode 100644 adyenv6core/src/com/adyen/v6/converters/PaymentsResponseConverter.java delete mode 100644 adyenv6core/src/com/adyen/v6/facades/impl/Amount.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/AdyenPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/AffirmPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/AfterpayAdyenPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/AmazonpayPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/BoletoBancarioSantanderAdyenPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/ClearpayPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/CreditCardAdyenPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/DotpayPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/EPSAdyenPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/FacilpayPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/GenericAdyenPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/GiftcardPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/GiropayPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/IdealAdyenPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/InteracPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/KlarnaAdyenPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/MolpayPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/MultibancoPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/OneyPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/OnlineBankingPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/PaybrightPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/PaypalAdyenPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/PaytmPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/RatepayPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/SepaDirectDebitPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/SofortPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/TrustyPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/UPIPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/WalletsIndiaPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/WechatpayWebPaymentMethodDetailsBuilderStrategy.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/executors/AdyenPaymentMethodDetailsBuilderExecutor.java delete mode 100644 adyenv6core/src/com/adyen/v6/paymentmethoddetails/executors/impl/AdyenPaymentMethodDetailsStrategyExecutorImpl.java create mode 100644 adyenv6core/src/com/adyen/v6/service/AbstractAdyenApiService.java rename adyenv6core/src/com/adyen/v6/service/{AdyenPaymentService.java => AdyenCheckoutApiService.java} (63%) create mode 100644 adyenv6core/src/com/adyen/v6/service/AdyenModificationsApiService.java create mode 100644 adyenv6core/src/com/adyen/v6/service/DefaultAdyenCheckoutApiService.java create mode 100644 adyenv6core/src/com/adyen/v6/service/DefaultAdyenModificationsApiService.java delete mode 100644 adyenv6core/src/com/adyen/v6/service/DefaultAdyenPaymentService.java create mode 100644 adyenv6core/src/com/adyen/v6/util/AmountUtil.java delete mode 100644 adyenv6core/testsrc/com/adyen/v6/paymentmethoddetails/builders/impl/RatepayPaymentMethodDetailsBuilderStrategyTest.java delete mode 100644 adyenv6core/testsrc/com/adyen/v6/paymentmethoddetails/builders/impl/SepaDirectDebitPaymentMethodDetailsBuilderStrategyTest.java delete mode 100644 adyenv6ordermanagement/resources/adyenv6ordermanagement/adyenv6ordermanagement-testclasses.xml create mode 100644 adyenv6subscription/src/com/adyen/v6/service/impl/DefaultSubscriptionAdyenCheckoutApiService.java delete mode 100644 adyenv6subscription/src/com/adyen/v6/service/impl/DefaultSubscriptionAdyenPaymentService.java diff --git a/adyenv6b2ccheckoutaddon/acceleratoraddon/web/src/com/adyen/v6/controllers/checkout/AdyenApplePayExpressCheckoutController.java b/adyenv6b2ccheckoutaddon/acceleratoraddon/web/src/com/adyen/v6/controllers/checkout/AdyenApplePayExpressCheckoutController.java index 7fbedb252..9b78fa65e 100644 --- a/adyenv6b2ccheckoutaddon/acceleratoraddon/web/src/com/adyen/v6/controllers/checkout/AdyenApplePayExpressCheckoutController.java +++ b/adyenv6b2ccheckoutaddon/acceleratoraddon/web/src/com/adyen/v6/controllers/checkout/AdyenApplePayExpressCheckoutController.java @@ -1,6 +1,6 @@ package com.adyen.v6.controllers.checkout; -import com.adyen.model.checkout.PaymentsResponse; +import com.adyen.model.checkout.PaymentResponse; import com.adyen.v6.facades.AdyenExpressCheckoutFacade; import com.adyen.v6.request.ApplePayExpressCartRequest; import com.adyen.v6.request.ApplePayExpressPDPRequest; @@ -36,7 +36,7 @@ public class AdyenApplePayExpressCheckoutController { @PostMapping("/expressCheckout/applePayPDP") public ResponseEntity applePayExpressPDP(final HttpServletRequest request, final HttpServletResponse response, @RequestBody ApplePayExpressPDPRequest applePayExpressPDPRequest) throws Exception { - PaymentsResponse paymentsResponse = adyenExpressCheckoutFacade.expressPDPCheckout(applePayExpressPDPRequest.getAddressData(), applePayExpressPDPRequest.getProductCode(), + PaymentResponse paymentsResponse = adyenExpressCheckoutFacade.expressPDPCheckout(applePayExpressPDPRequest.getAddressData(), applePayExpressPDPRequest.getProductCode(), applePayExpressPDPRequest.getAdyenApplePayMerchantIdentifier(), applePayExpressPDPRequest.getAdyenApplePayMerchantName(), applePayExpressPDPRequest.getApplePayToken(), request); @@ -49,7 +49,7 @@ public ResponseEntity applePayExpressPDP(final HttpServletRequest request, final @PostMapping("/expressCheckout/cart") public ResponseEntity cartExpressCheckout(final HttpServletRequest request, final HttpServletResponse response, @RequestBody ApplePayExpressCartRequest applePayExpressCartRequest) throws Exception { - PaymentsResponse paymentsResponse = adyenExpressCheckoutFacade.expressCartCheckout(applePayExpressCartRequest.getAddressData(), + PaymentResponse paymentsResponse = adyenExpressCheckoutFacade.expressCartCheckout(applePayExpressCartRequest.getAddressData(), applePayExpressCartRequest.getAdyenApplePayMerchantIdentifier(), applePayExpressCartRequest.getAdyenApplePayMerchantName(), applePayExpressCartRequest.getApplePayToken(), request); diff --git a/adyenv6b2ccheckoutaddon/acceleratoraddon/web/src/com/adyen/v6/controllers/pages/AdyenComponentController.java b/adyenv6b2ccheckoutaddon/acceleratoraddon/web/src/com/adyen/v6/controllers/pages/AdyenComponentController.java index 34e8a2a5d..b762435dd 100644 --- a/adyenv6b2ccheckoutaddon/acceleratoraddon/web/src/com/adyen/v6/controllers/pages/AdyenComponentController.java +++ b/adyenv6b2ccheckoutaddon/acceleratoraddon/web/src/com/adyen/v6/controllers/pages/AdyenComponentController.java @@ -20,21 +20,17 @@ */ package com.adyen.v6.controllers.pages; -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.PaymentsDetailsResponse; -import com.adyen.model.checkout.PaymentsResponse; -import com.adyen.model.checkout.details.*; + +import com.adyen.model.checkout.GooglePayDetails; +import com.adyen.model.checkout.PaymentDetailsRequest; +import com.adyen.model.checkout.PaymentDetailsResponse; +import com.adyen.model.checkout.PaymentRequest; +import com.adyen.model.checkout.PaymentResponse; import com.adyen.service.exception.ApiException; -import com.adyen.v6.constants.Adyenv6coreConstants; import com.adyen.v6.controllers.dtos.PaymentResultDTO; import com.adyen.v6.exceptions.AdyenComponentException; import com.adyen.v6.exceptions.AdyenNonAuthorizedPaymentException; import com.adyen.v6.facades.AdyenCheckoutFacade; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.reflect.TypeToken; import de.hybris.platform.acceleratorfacades.flow.CheckoutFlowFacade; import de.hybris.platform.acceleratorfacades.order.AcceleratorCheckoutFacade; import de.hybris.platform.acceleratorservices.urlresolver.SiteBaseUrlResolutionService; @@ -42,26 +38,32 @@ import de.hybris.platform.basecommerce.model.site.BaseSiteModel; import de.hybris.platform.commercefacades.order.data.CartData; import de.hybris.platform.commercefacades.order.data.OrderData; -import de.hybris.platform.commercefacades.user.data.AddressData; import de.hybris.platform.order.InvalidCartException; import de.hybris.platform.site.BaseSiteService; -import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.web.bind.annotation.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; -import java.lang.reflect.Type; -import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; -import java.util.Map; import static com.adyen.v6.constants.AdyenControllerConstants.COMPONENT_PREFIX; import static com.adyen.v6.constants.AdyenControllerConstants.SUMMARY_CHECKOUT_PREFIX; -import static com.adyen.v6.constants.Adyenv6coreConstants.*; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_AMAZONPAY; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BCMC_MOBILE; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_PIX; @RestController @RequestMapping(COMPONENT_PREFIX) @@ -94,53 +96,24 @@ public String componentPaymentResultHandler(@RequestBody final PaymentResultDTO return redirectToOrderConfirmationPage(orderData); } - @RequestMapping(value = "/payment", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) + @PostMapping(value = "/payment", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody - public String componentPayment(final HttpServletRequest request) throws AdyenComponentException { + public ResponseEntity componentPayment(@RequestHeader String host, @RequestBody PaymentRequest body, final HttpServletRequest request) throws AdyenComponentException { try { - String requestJsonString = IOUtils.toString(request.getInputStream(), String.valueOf(StandardCharsets.UTF_8)); - JsonObject requestJson = new JsonParser().parse(requestJsonString).getAsJsonObject(); - Gson gson = new GsonBuilder().disableHtmlEscaping().create(); - - validateOrderForm(requestJson); + validateOrderForm(); final CartData cartData = getCheckoutFlowFacade().getCheckoutCart(); String paymentMethod = cartData.getAdyenPaymentMethod(); - PaymentMethodDetails paymentMethodDetails; - if (PayPalDetails.PAYPAL.equals(paymentMethod)) { - paymentMethodDetails = gson.fromJson(requestJson.get("paymentMethodDetails"), PayPalDetails.class); - } else if (MbwayDetails.MBWAY.equals(paymentMethod)) { - paymentMethodDetails = gson.fromJson(requestJson.get("paymentMethodDetails"), MbwayDetails.class); - } else if (ApplePayDetails.APPLEPAY.equals(paymentMethod)) { - paymentMethodDetails = gson.fromJson(requestJson.get("paymentMethodDetails"), ApplePayDetails.class); - } else if (Adyenv6coreConstants.PAYMENT_METHOD_GOOGLE.equals(paymentMethod)) { - paymentMethodDetails = gson.fromJson(requestJson.get("paymentMethodDetails"), GooglePayDetails.class); - } else if (UpiCollectDetails.UPI_COLLECT.equals(paymentMethod)) { - paymentMethodDetails = gson.fromJson(requestJson.get("paymentMethodDetails"), UpiCollectDetails.class); - } else if (UpiDetails.UPI.equals(paymentMethod)) { - paymentMethodDetails = gson.fromJson(requestJson.get("paymentMethodDetails"), UpiDetails.class); - } else if (PAYMENT_METHOD_PIX.equals(paymentMethod) || PAYMENT_METHOD_BCMC_MOBILE.equals(paymentMethod)) { - paymentMethodDetails = new CardDetails(); - paymentMethodDetails.setType(paymentMethod); - } else if (BlikDetails.BLIK.equals(paymentMethod)) { - paymentMethodDetails = gson.fromJson(requestJson.get("paymentMethodDetails"), BlikDetails.class); - } else if (CardDetails.GIFTCARD.equals(paymentMethod)) { - paymentMethodDetails = gson.fromJson(requestJson.get("paymentMethodDetails"), CardDetails.class); - paymentMethodDetails.setType(paymentMethod); - } else { - throw new InvalidCartException("checkout.error.paymentethod.formentry.invalid"); - } - cartData.setAdyenReturnUrl(getReturnUrl(paymentMethod)); - PaymentsResponse paymentsResponse = getAdyenCheckoutFacade().componentPayment(request, cartData, paymentMethodDetails); - return gson.toJson(paymentsResponse); + PaymentResponse paymentsResponse = getAdyenCheckoutFacade().componentPayment(request, cartData, body.getPaymentMethod()); + return ResponseEntity.ok().body(paymentsResponse); } catch (InvalidCartException e) { LOGGER.error("InvalidCartException: " + e.getMessage()); throw new AdyenComponentException(e.getMessage()); } catch (ApiException e) { - LOGGER.error("ApiException: " + e.toString()); + LOGGER.error("ApiException: " + e); throw new AdyenComponentException("checkout.error.authorization.payment.refused"); } catch (AdyenNonAuthorizedPaymentException e) { LOGGER.warn("AdyenNonAuthorizedPaymentException occurred. Payment " + e.getPaymentResult().getPspReference() + "is refused."); @@ -151,23 +124,13 @@ public String componentPayment(final HttpServletRequest request) throws AdyenCom } } - @RequestMapping(value = "/submit-details", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) - @ResponseBody - public String submitDetails(final HttpServletRequest request) throws AdyenComponentException { + @PostMapping(value = "/submit-details", consumes = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity submitDetails(@RequestBody PaymentDetailsRequest detailsRequest, final HttpServletRequest request) throws AdyenComponentException { try { - String requestJsonString = IOUtils.toString(request.getInputStream(), String.valueOf(StandardCharsets.UTF_8)); - JsonObject requestJson = new JsonParser().parse(requestJsonString).getAsJsonObject(); - - Gson gson = new GsonBuilder().disableHtmlEscaping().create(); - Type mapType = new TypeToken>() { - }.getType(); - Map details = gson.fromJson(requestJson.get("details"), mapType); - String paymentData = gson.fromJson(requestJson.get("paymentData"), String.class); - - PaymentsDetailsResponse paymentsResponse = getAdyenCheckoutFacade().componentDetails(request, details, paymentData); - return gson.toJson(paymentsResponse); + PaymentDetailsResponse paymentsResponse = getAdyenCheckoutFacade().componentDetails(detailsRequest); + return ResponseEntity.ok().body(paymentsResponse); } catch (ApiException e) { - LOGGER.error("ApiException: " + e.toString()); + LOGGER.error("ApiException: " + e); throw new AdyenComponentException("checkout.error.authorization.payment.refused"); } catch (Exception e) { LOGGER.error("Exception", e); @@ -187,17 +150,7 @@ public String adyenComponentExceptionHandler(AdyenComponentException e) { * @param requestJson * @return True if the order form is invalid and false if everything is valid. */ - protected void validateOrderForm(JsonObject requestJson) throws InvalidCartException { - Gson gson = new GsonBuilder().disableHtmlEscaping().create(); - Boolean termsCheck = gson.fromJson(requestJson.get("termsCheck"), Boolean.class); - JsonObject paymentMethodDetails = requestJson.get("paymentMethodDetails").getAsJsonObject(); - String paymentMethod = gson.fromJson(paymentMethodDetails.get("type"), String.class); - - // Some methods already have the terms validated on a previous step - if (!PAYMENT_METHODS_WITH_VALIDATED_TERMS.contains(paymentMethod) - && (termsCheck == null || !termsCheck)) { - throw new InvalidCartException("checkout.error.terms.not.accepted"); - } + protected void validateOrderForm() throws InvalidCartException { if (getCheckoutFlowFacade().hasNoDeliveryAddress()) { throw new InvalidCartException("checkout.deliveryAddress.notSelected"); @@ -226,7 +179,7 @@ protected void validateOrderForm(JsonObject requestJson) throws InvalidCartExcep private String getReturnUrl(String paymentMethod) { String url; - if (GooglePayDetails.GOOGLEPAY.equals(paymentMethod)) { + if (GooglePayDetails.TypeEnum.GOOGLEPAY.getValue().equals(paymentMethod)) { //Google Pay will only use returnUrl if redirected to 3DS authentication url = SUMMARY_CHECKOUT_PREFIX + "/authorise-3d-adyen-response"; } else { @@ -260,13 +213,4 @@ public void setCheckoutFacade(AcceleratorCheckoutFacade checkoutFacade) { this.checkoutFacade = checkoutFacade; } - private boolean isValidateSessionCart() { - CartData cart = getCheckoutFacade().getCheckoutCart(); - final AddressData deliveryAddress = cart.getDeliveryAddress(); - if (deliveryAddress == null || deliveryAddress.getCountry() == null || deliveryAddress.getCountry().getIsocode() == null) { - return false; - } - return true; - - } } diff --git a/adyenv6b2ccheckoutaddon/acceleratoraddon/web/src/com/adyen/v6/controllers/pages/AdyenSummaryCheckoutStepController.java b/adyenv6b2ccheckoutaddon/acceleratoraddon/web/src/com/adyen/v6/controllers/pages/AdyenSummaryCheckoutStepController.java index 1e8e2ac7c..55e99f525 100644 --- a/adyenv6b2ccheckoutaddon/acceleratoraddon/web/src/com/adyen/v6/controllers/pages/AdyenSummaryCheckoutStepController.java +++ b/adyenv6b2ccheckoutaddon/acceleratoraddon/web/src/com/adyen/v6/controllers/pages/AdyenSummaryCheckoutStepController.java @@ -21,24 +21,21 @@ package com.adyen.v6.controllers.pages; import com.adyen.constants.ApiConstants.RefusalReason; -import com.adyen.model.PaymentResult; -import com.adyen.model.checkout.CheckoutPaymentsAction; -import com.adyen.model.checkout.PaymentsDetailsResponse; -import com.adyen.model.checkout.PaymentsResponse; +import com.adyen.model.checkout.CheckoutRedirectAction; +import com.adyen.model.checkout.PaymentCompletionDetails; +import com.adyen.model.checkout.PaymentDetailsRequest; +import com.adyen.model.checkout.PaymentDetailsResponse; +import com.adyen.model.checkout.PaymentResponse; +import com.adyen.model.checkout.PaymentResponseAction; +import com.adyen.model.payment.PaymentResult; import com.adyen.service.exception.ApiException; import com.adyen.v6.constants.AdyenControllerConstants; import com.adyen.v6.exceptions.AdyenNonAuthorizedPaymentException; import com.adyen.v6.facades.AdyenCheckoutFacade; import com.adyen.v6.util.TerminalAPIUtil; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; +import com.fasterxml.jackson.core.JsonProcessingException; import de.hybris.platform.acceleratorservices.enums.CheckoutPciOptionEnum; import de.hybris.platform.acceleratorservices.urlresolver.SiteBaseUrlResolutionService; -import org.apache.commons.lang3.StringUtils; -import org.apache.http.HttpHeaders; -import org.json.JSONObject; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; import de.hybris.platform.acceleratorstorefrontcommons.annotations.PreValidateCheckoutStep; import de.hybris.platform.acceleratorstorefrontcommons.annotations.RequireHardLogIn; import de.hybris.platform.acceleratorstorefrontcommons.checkout.steps.CheckoutStep; @@ -59,22 +56,32 @@ import de.hybris.platform.order.exceptions.CalculationException; import de.hybris.platform.servicelayer.config.ConfigurationService; import de.hybris.platform.site.BaseSiteService; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; +import org.apache.http.HttpHeaders; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; -import java.lang.reflect.Type; +import java.io.IOException; import java.net.SocketTimeoutException; -import java.util.*; - -import static com.adyen.constants.HPPConstants.Response.SHOPPER_LOCALE; -import static com.adyen.model.checkout.PaymentsResponse.ResultCodeEnum.*; +import java.util.Arrays; +import java.util.Objects; + +import static com.adyen.model.checkout.PaymentResponse.ResultCodeEnum.CHALLENGESHOPPER; +import static com.adyen.model.checkout.PaymentResponse.ResultCodeEnum.ERROR; +import static com.adyen.model.checkout.PaymentResponse.ResultCodeEnum.IDENTIFYSHOPPER; +import static com.adyen.model.checkout.PaymentResponse.ResultCodeEnum.REDIRECTSHOPPER; +import static com.adyen.model.checkout.PaymentResponse.ResultCodeEnum.REFUSED; import static com.adyen.v6.constants.AdyenControllerConstants.CART_PREFIX; import static com.adyen.v6.constants.AdyenControllerConstants.SELECT_PAYMENT_METHOD_PREFIX; import static com.adyen.v6.constants.AdyenControllerConstants.SUMMARY_CHECKOUT_PREFIX; @@ -87,7 +94,7 @@ import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_ONECLICK; import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_POS; import static com.adyen.v6.constants.Adyenv6coreConstants.RATEPAY; -import static com.adyen.v6.facades.impl.DefaultAdyenCheckoutFacade.DETAILS; +import static com.adyen.v6.constants.Adyenv6coreConstants.SHOPPER_LOCALE; import static com.adyen.v6.facades.impl.DefaultAdyenCheckoutFacade.MODEL_CHECKOUT_SHOPPER_HOST; import static com.adyen.v6.facades.impl.DefaultAdyenCheckoutFacade.MODEL_CLIENT_KEY; import static com.adyen.v6.facades.impl.DefaultAdyenCheckoutFacade.MODEL_ENVIRONMENT_MODE; @@ -175,80 +182,12 @@ public String enterStep(final Model model, final RedirectAttributes redirectAttr return AdyenControllerConstants.Views.Pages.MultiStepCheckout.CheckoutSummaryPage; } - @PostMapping({"/placeOrderBizum"}) - @RequireHardLogIn - @ResponseBody - public String placeOrderResponseBody(@ModelAttribute("placeOrderForm") final PlaceOrderForm placeOrderForm, - final Model model, - final HttpServletRequest request, - final RedirectAttributes redirectModel) throws CMSItemNotFoundException, CommerceCartModificationException { - - final String error = validateOrderFormJson(placeOrderForm); - if (StringUtils.isNotEmpty(error)) { - return error; - } - - //Validate the cart - if (validateCart(redirectModel)) { - // Invalid cart. Bounce back to the cart page. - final Optional flashError = redirectModel.getFlashAttributes().entrySet().stream().findFirst().map(Map.Entry::getValue); - if (flashError.isPresent()) { - return flashError.get().toString(); - } else { - return CART_NOT_VALID; - } - } - - final CartData cartData = getCheckoutFlowFacade().getCheckoutCart(); - - final String adyenPaymentMethod = cartData.getAdyenPaymentMethod(); - - try { - cartData.setAdyenReturnUrl(getReturnUrl(cartData.getAdyenPaymentMethod())); - OrderData orderData = adyenCheckoutFacade.authorisePayment(request, cartData); - - return redirectToOrderConfirmationPage(orderData); - } catch (ApiException e) { - LOGGER.error(API_EXCEPTION_START_MESSAGE, e); - } catch (AdyenNonAuthorizedPaymentException e) { - LOGGER.info(NON_AUTHORIZED_ERROR); - final PaymentsResponse paymentsResponse = e.getPaymentsResponse(); - if (REDIRECTSHOPPER == paymentsResponse.getResultCode()) { - if (is3DSPaymentMethod(adyenPaymentMethod)) { - LOGGER.debug("PaymentResponse resultCode is REDIRECTSHOPPER, redirecting shopper to 3DS flow"); - return PAYMENT_NOT_SUPPORTED; - } - LOGGER.debug("PaymentResponse resultCode is REDIRECTSHOPPER, redirecting shopper to local payment method page"); - if (Objects.nonNull(paymentsResponse.getAction()) && "POST".equals(paymentsResponse.getAction().getMethod())) { - return makePostRedirect(paymentsResponse); - } - return makeGetRedirect(paymentsResponse); - } - if (REFUSED == paymentsResponse.getResultCode()) { - LOGGER.info("PaymentResponse is REFUSED, pspReference: " + paymentsResponse.getPspReference()); - return getErrorMessageByRefusalReason(paymentsResponse.getRefusalReason()); - } - if (CHALLENGESHOPPER == paymentsResponse.getResultCode() || IDENTIFYSHOPPER == paymentsResponse.getResultCode()) { - LOGGER.debug("PaymentResponse is " + paymentsResponse.getResultCode() + ", redirecting to 3DS2 flow"); - return PAYMENT_NOT_SUPPORTED; - } - if (ERROR == paymentsResponse.getResultCode()) { - LOGGER.error("PaymentResponse is ERROR, reason: " + paymentsResponse.getRefusalReason() - + " pspReference: " + paymentsResponse.getPspReference()); - } - } catch (Exception e) { - LOGGER.error(ExceptionUtils.getStackTrace(e)); - } - - return CHECKOUT_ERROR_AUTHORIZATION_FAILED; - } - @PostMapping({"/placeOrder"}) @RequireHardLogIn public String placeOrder(@ModelAttribute("placeOrderForm") final PlaceOrderForm placeOrderForm, final Model model, final HttpServletRequest request, - final RedirectAttributes redirectModel) throws CMSItemNotFoundException, CommerceCartModificationException { + final RedirectAttributes redirectModel) throws CMSItemNotFoundException, CommerceCartModificationException, JsonProcessingException { if (validateOrderForm(placeOrderForm, model)) { return enterStep(model, redirectModel); } @@ -275,7 +214,7 @@ public String placeOrder(@ModelAttribute("placeOrderForm") final PlaceOrderForm LOGGER.info(HANDLING_ADYEN_NON_AUTHORIZED_PAYMENT_EXCEPTION); PaymentResult paymentResult = e.getPaymentResult(); if (Objects.nonNull(paymentResult)) { - if (paymentResult.isRefused()) { + if (PaymentResult.ResultCodeEnum.REFUSED.equals(paymentResult.getResultCode())) { errorMessage = getErrorMessageByRefusalReason(paymentResult.getRefusalReason()); LOGGER.info("Payment " + paymentResult.getPspReference() + " is refused " + errorMessage); } @@ -340,7 +279,7 @@ public String placeOrder(@ModelAttribute("placeOrderForm") final PlaceOrderForm LOGGER.error(API_EXCEPTION_START_MESSAGE, e); } catch (AdyenNonAuthorizedPaymentException e) { LOGGER.info(NON_AUTHORIZED_ERROR); - PaymentsResponse paymentsResponse = e.getPaymentsResponse(); + PaymentResponse paymentsResponse = e.getPaymentsResponse(); if (REDIRECTSHOPPER == paymentsResponse.getResultCode()) { if (is3DSPaymentMethod(adyenPaymentMethod)) { LOGGER.debug("PaymentResponse resultCode is REDIRECTSHOPPER, redirecting shopper to 3DS flow"); @@ -348,10 +287,11 @@ public String placeOrder(@ModelAttribute("placeOrderForm") final PlaceOrderForm } if (AFTERPAY_TOUCH.equals(adyenPaymentMethod)) { LOGGER.debug("PaymentResponse resultCode is REDIRECTSHOPPER, redirecting shopper to afterpaytouch page"); - return REDIRECT_PREFIX + paymentsResponse.getAction().getUrl(); + + return REDIRECT_PREFIX + ((CheckoutRedirectAction) paymentsResponse.getAction().getActualInstance()).getUrl(); } LOGGER.debug("PaymentResponse resultCode is REDIRECTSHOPPER, redirecting shopper to local payment method page"); - return REDIRECT_PREFIX + paymentsResponse.getAction().getUrl(); + return REDIRECT_PREFIX + ((CheckoutRedirectAction) paymentsResponse.getAction().getActualInstance()).getUrl(); } if (REFUSED == paymentsResponse.getResultCode()) { LOGGER.info("PaymentResponse is REFUSED, pspReference: " + paymentsResponse.getPspReference()); @@ -373,40 +313,38 @@ public String placeOrder(@ModelAttribute("placeOrderForm") final PlaceOrderForm return enterStep(model, redirectModel); } - private String makePostRedirect(final PaymentsResponse paymentsResponse) { - final JSONObject json = new JSONObject(); - json.put("url", paymentsResponse.getAction().getUrl()); - json.put("data", paymentsResponse.getAction().getData()); - - return json.toString(); - } - - private String makeGetRedirect(final PaymentsResponse paymentsResponse) { - final JSONObject json = new JSONObject(); - json.put("url", paymentsResponse.getAction().getUrl()); - - return json.toString(); - } - @GetMapping(value = AUTHORISE_3D_SECURE_PAYMENT_URL) @RequireHardLogIn public String authorise3DS1Payment(final RedirectAttributes redirectModel, - final HttpServletRequest request) { - String redirectResult = request.getParameter(REDIRECT_RESULT); + final HttpServletRequest request) throws IOException, ApiException { try { - OrderData orderData = adyenCheckoutFacade.handle3DSResponse(Collections.singletonMap(REDIRECT_RESULT, redirectResult)); + String redirectResult = request.getParameter(REDIRECT_RESULT); + PaymentDetailsRequest paymentDetailsRequest = new PaymentDetailsRequest(); + if (redirectResult != null && !redirectResult.isEmpty()) { + PaymentCompletionDetails details = new PaymentCompletionDetails(); + details.setRedirectResult(redirectResult); + paymentDetailsRequest.details(details); + } else { + String payload = request.getParameter(PAYLOAD); + if (payload != null && !payload.isEmpty()) { + PaymentCompletionDetails details = new PaymentCompletionDetails(); + details.setPayload(payload); + paymentDetailsRequest.details(details); + } + } + OrderData orderData = adyenCheckoutFacade.handle3DSResponse(paymentDetailsRequest); LOGGER.debug("Redirecting to confirmation"); return redirectToOrderConfirmationPage(orderData); } catch (AdyenNonAuthorizedPaymentException e) { LOGGER.info(HANDLING_ADYEN_NON_AUTHORIZED_PAYMENT_EXCEPTION); String errorMessage = CHECKOUT_ERROR_AUTHORIZATION_FAILED; - PaymentsDetailsResponse response = e.getPaymentsDetailsResponse(); + PaymentDetailsResponse response = e.getPaymentsDetailsResponse(); if (response != null) { - if (REFUSED.equals(response.getResultCode())) { + if (PaymentDetailsResponse.ResultCodeEnum.REFUSED.equals(response.getResultCode())) { LOGGER.info("PaymentResponse " + response.getPspReference() + " is REFUSED: " + response); errorMessage = getErrorMessageByRefusalReason(response.getRefusalReason()); } - if (ERROR.equals(response.getResultCode())) { + if (PaymentDetailsResponse.ResultCodeEnum.ERROR.equals(response.getResultCode())) { LOGGER.error("Payment " + response.getPspReference() + " result is error, reason: " + response.getRefusalReason()); } @@ -427,17 +365,15 @@ public String authorise3DS1Payment(final RedirectAttributes redirectModel, @RequireHardLogIn public String authorise3DSPayment(final RedirectAttributes redirectModel, final HttpServletRequest request) { - - String detailsJson = request.getParameter(DETAILS); + PaymentDetailsRequest paymentDetailsRequest = new PaymentDetailsRequest(); try { - Map details = parseDetailsFromComponent(detailsJson); - OrderData orderData = adyenCheckoutFacade.handle3DSResponse(details); + OrderData orderData = adyenCheckoutFacade.handle3DSResponse(paymentDetailsRequest); LOGGER.debug("Redirecting to confirmation"); return redirectToOrderConfirmationPage(orderData); } catch (AdyenNonAuthorizedPaymentException e) { LOGGER.debug(NON_AUTHORIZED_ERROR); String errorMessage = CHECKOUT_ERROR_AUTHORIZATION_FAILED; - PaymentsDetailsResponse response = e.getPaymentsDetailsResponse(); + PaymentDetailsResponse response = e.getPaymentsDetailsResponse(); if (response != null) { if (REFUSED.equals(response.getResultCode())) { LOGGER.info("PaymentResponse " + response.getPspReference() + " is REFUSED: " + response); @@ -463,16 +399,16 @@ public String authorise3DSPayment(final RedirectAttributes redirectModel, @RequireHardLogIn public String handleAdyenResponse(final HttpServletRequest request, final RedirectAttributes redirectModel) { String redirectResult = request.getParameter(REDIRECT_RESULT); - HashMap details = new HashMap<>(); + PaymentCompletionDetails details = new PaymentCompletionDetails(); if (redirectResult != null && !redirectResult.isEmpty()) { - details.put(REDIRECT_RESULT, redirectResult); + details.setRedirectResult(redirectResult); } else if (StringUtils.isNotEmpty(request.getParameter(PAYLOAD))) { - details.put(REDIRECT_RESULT, request.getParameter(PAYLOAD)); + details.setPayload(request.getParameter(PAYLOAD)); } try { - PaymentsDetailsResponse response = adyenCheckoutFacade.handleRedirectPayload(details); + PaymentDetailsResponse response = adyenCheckoutFacade.handleRedirectPayload(details); switch (response.getResultCode()) { case AUTHORISED, RECEIVED: @@ -560,14 +496,13 @@ private String redirectToSelectPaymentMethodWithError(final RedirectAttributes r return REDIRECT_PREFIX + SELECT_PAYMENT_METHOD_PREFIX; } - protected String redirectTo3DSValidation(Model model, PaymentsResponse paymentsResponse) { - CheckoutPaymentsAction action = paymentsResponse.getAction(); - + protected String redirectTo3DSValidation(Model model, PaymentResponse paymentsResponse) throws JsonProcessingException { + PaymentResponseAction action = paymentsResponse.getAction(); model.addAttribute(MODEL_CLIENT_KEY, adyenCheckoutFacade.getClientKey()); model.addAttribute(MODEL_CHECKOUT_SHOPPER_HOST, adyenCheckoutFacade.getCheckoutShopperHost()); model.addAttribute(MODEL_ENVIRONMENT_MODE, adyenCheckoutFacade.getEnvironmentMode()); model.addAttribute(SHOPPER_LOCALE, adyenCheckoutFacade.getShopperLocale()); - model.addAttribute(ACTION, new Gson().toJson(action)); + model.addAttribute(ACTION, ( ((CheckoutRedirectAction) action.getActualInstance()).toJson())); return AdyenControllerConstants.Views.Pages.MultiStepCheckout.Validate3DSPaymentPage; } @@ -705,12 +640,15 @@ protected String validateOrderFormJson(final PlaceOrderForm placeOrderForm) { @PostMapping(value = "/component-result-express") public String handleComponentResultExpress(final HttpServletRequest request, final RedirectAttributes redirectAttributes, @RequestHeader(value = HttpHeaders.REFERER, required = false) final String referrer) throws Exception { - String resultData = request.getParameter("resultData"); + String resultCode = request.getParameter("resultCode"); + String merchantReference = request.getParameter("merchantReference"); String isResultError = request.getParameter("isResultError"); - if (isValidResult(resultData, isResultError)) { + LOGGER.debug("isResultError=" + isResultError + "\nresultData=" + resultCode); + + if (isValidResult(resultCode, isResultError)) { try { - OrderData orderData = adyenCheckoutFacade.handleComponentResult(resultData); + OrderData orderData = adyenCheckoutFacade.handleComponentResult(resultCode,merchantReference); return redirectToOrderConfirmationPage(orderData); } catch (AdyenNonAuthorizedPaymentException e) { GlobalMessages.addFlashMessage(redirectAttributes, GlobalMessages.ERROR_MESSAGES_HOLDER, CHECKOUT_ERROR_AUTHORIZATION_PAYMENT_ERROR); @@ -728,21 +666,22 @@ public String handleComponentResultExpress(final HttpServletRequest request, fin public String handleComponentResult(final HttpServletRequest request, final Model model, final RedirectAttributes redirectAttributes) - throws CMSItemNotFoundException, InvalidCartException, CalculationException, CommerceCartModificationException { - String resultData = request.getParameter("resultData"); + throws CMSItemNotFoundException, InvalidCartException, CalculationException, CommerceCartModificationException, JsonProcessingException { + String resultCode = request.getParameter("resultCode"); + String merchantReference = request.getParameter("merchantReference"); String isResultError = request.getParameter("isResultError"); - LOGGER.debug("isResultError=" + isResultError + "\nresultData=" + resultData); + LOGGER.debug("isResultError=" + isResultError + "\nresultData=" + resultCode); String errorMessageKey = CHECKOUT_ERROR_AUTHORIZATION_PAYMENT_ERROR; - if (isValidResult(resultData, isResultError)) { + if (isValidResult(resultCode, isResultError)) { try { - OrderData orderData = adyenCheckoutFacade.handleComponentResult(resultData); + OrderData orderData = adyenCheckoutFacade.handleComponentResult(resultCode,merchantReference); return redirectToOrderConfirmationPage(orderData); } catch (AdyenNonAuthorizedPaymentException e) { LOGGER.debug(HANDLING_ADYEN_NON_AUTHORIZED_PAYMENT_EXCEPTION); - PaymentsResponse paymentsResponse = e.getPaymentsResponse(); + PaymentResponse paymentsResponse = e.getPaymentsResponse(); if (paymentsResponse != null && paymentsResponse.getResultCode() != null) { switch (paymentsResponse.getResultCode()) { case REDIRECTSHOPPER: @@ -767,8 +706,8 @@ public String handleComponentResult(final HttpServletRequest request, LOGGER.error("Unexpected error while validating component payment result", e); } } else { - if (StringUtils.isNotBlank(resultData)) { - errorMessageKey = resultData; + if (StringUtils.isNotBlank(resultCode)) { + errorMessageKey = resultCode; adyenCheckoutFacade.restoreCartFromOrderCodeInSession(); } } @@ -790,16 +729,9 @@ private String redirectToOrderSummaryWithError(final Model model, return enterStep(model, redirectAttributes); } - private boolean isValidResult(String resultData, String isResultError) { + private boolean isValidResult(String resultCode, String isResultError) { return (StringUtils.isBlank(isResultError) || !Boolean.parseBoolean(isResultError)) - && StringUtils.isNotBlank(resultData); - } - - private Map parseDetailsFromComponent(String details) { - Gson gson = new Gson(); - Type mapType = new TypeToken>() { - }.getType(); - return gson.fromJson(details, mapType); + && StringUtils.isNotBlank(resultCode); } @GetMapping(value = "/back") diff --git a/adyenv6b2ccheckoutaddon/acceleratoraddon/web/src/com/adyen/v6/controllers/pages/account/AdyenStoredCardsController.java b/adyenv6b2ccheckoutaddon/acceleratoraddon/web/src/com/adyen/v6/controllers/pages/account/AdyenStoredCardsController.java index 1641a21e1..628df1297 100644 --- a/adyenv6b2ccheckoutaddon/acceleratoraddon/web/src/com/adyen/v6/controllers/pages/account/AdyenStoredCardsController.java +++ b/adyenv6b2ccheckoutaddon/acceleratoraddon/web/src/com/adyen/v6/controllers/pages/account/AdyenStoredCardsController.java @@ -20,22 +20,10 @@ */ package com.adyen.v6.controllers.pages.account; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import javax.annotation.Nonnull; -import javax.annotation.Resource; -import org.apache.log4j.Logger; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.adyen.model.recurring.RecurringDetail; import com.adyen.service.exception.ApiException; import com.adyen.v6.factory.AdyenPaymentServiceFactory; -import com.adyen.v6.service.AdyenPaymentService; +import com.adyen.v6.service.AdyenCheckoutApiService; import de.hybris.platform.acceleratorstorefrontcommons.annotations.RequireHardLogIn; import de.hybris.platform.acceleratorstorefrontcommons.breadcrumb.ResourceBreadcrumbBuilder; import de.hybris.platform.acceleratorstorefrontcommons.controllers.pages.AbstractSearchPageController; @@ -45,6 +33,19 @@ import de.hybris.platform.servicelayer.user.UserService; import de.hybris.platform.store.BaseStoreModel; import de.hybris.platform.store.services.BaseStoreService; +import org.apache.log4j.Logger; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +import javax.annotation.Nonnull; +import javax.annotation.Resource; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; /** * Controller for Adyen stored cards @@ -145,10 +146,10 @@ private CustomerModel getCurrentCustomer() { return null; } - public AdyenPaymentService getAdyenPaymentService() { + public AdyenCheckoutApiService getAdyenPaymentService() { BaseStoreModel baseStore = baseStoreService.getCurrentBaseStore(); - return adyenPaymentServiceFactory.createFromBaseStore(baseStore); + return adyenPaymentServiceFactory.createAdyenCheckoutApiService(baseStore); } public boolean isAnonymousCheckout() { diff --git a/adyenv6b2ccheckoutaddon/acceleratoraddon/web/src/com/adyen/v6/controllers/pages/payments/AdyenAmazonpayController.java b/adyenv6b2ccheckoutaddon/acceleratoraddon/web/src/com/adyen/v6/controllers/pages/payments/AdyenAmazonpayController.java index 8221ae826..faf8bc954 100644 --- a/adyenv6b2ccheckoutaddon/acceleratoraddon/web/src/com/adyen/v6/controllers/pages/payments/AdyenAmazonpayController.java +++ b/adyenv6b2ccheckoutaddon/acceleratoraddon/web/src/com/adyen/v6/controllers/pages/payments/AdyenAmazonpayController.java @@ -1,8 +1,9 @@ package com.adyen.v6.controllers.pages.payments; import com.adyen.constants.ApiConstants; -import com.adyen.model.checkout.PaymentsResponse; -import com.adyen.model.checkout.details.AmazonPayDetails; +import com.adyen.model.checkout.AmazonPayDetails; +import com.adyen.model.checkout.CheckoutPaymentMethod; +import com.adyen.model.checkout.PaymentResponse; import com.adyen.v6.controllers.pages.AdyenSummaryCheckoutStepController; import com.adyen.v6.facades.AdyenAmazonPayFacade; import com.adyen.v6.facades.AdyenCheckoutFacade; @@ -25,7 +26,7 @@ import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; -import static com.adyen.model.checkout.PaymentsResponse.ResultCodeEnum.REDIRECTSHOPPER; +import static com.adyen.model.checkout.PaymentResponse.ResultCodeEnum.REDIRECTSHOPPER; import static com.adyen.v6.constants.AdyenControllerConstants.SUMMARY_CHECKOUT_PREFIX; @Controller @@ -63,9 +64,9 @@ public String placeOrder(final Model model, try { cart.setAdyenReturnUrl(adyenAmazonPayFacade.getReturnUrl(SUMMARY_CHECKOUT_PREFIX + CHECKOUT_RESULT_URL)); - final PaymentsResponse paymentsResponse = adyenCheckoutFacade.componentPayment(request, + final PaymentResponse paymentsResponse = adyenCheckoutFacade.componentPayment(request, cart, - new AmazonPayDetails().amazonPayToken(adyenAmazonPayFacade.getAmazonPayToken(amazonCheckoutSessionId)) + new CheckoutPaymentMethod((new AmazonPayDetails().amazonPayToken(adyenAmazonPayFacade.getAmazonPayToken(amazonCheckoutSessionId)))) ); if (REDIRECTSHOPPER == paymentsResponse.getResultCode()) { diff --git a/adyenv6b2ccheckoutaddon/acceleratoraddon/web/testsrc/com/adyen/v6/controllers/pages/payments/AdyenAmazonpayControllerTest.java b/adyenv6b2ccheckoutaddon/acceleratoraddon/web/testsrc/com/adyen/v6/controllers/pages/payments/AdyenAmazonpayControllerTest.java index b9ca6894d..5c7d389e0 100644 --- a/adyenv6b2ccheckoutaddon/acceleratoraddon/web/testsrc/com/adyen/v6/controllers/pages/payments/AdyenAmazonpayControllerTest.java +++ b/adyenv6b2ccheckoutaddon/acceleratoraddon/web/testsrc/com/adyen/v6/controllers/pages/payments/AdyenAmazonpayControllerTest.java @@ -1,7 +1,7 @@ package com.adyen.v6.controllers.pages.payments; -import com.adyen.model.checkout.PaymentsResponse; -import com.adyen.model.checkout.details.AmazonPayDetails; +import com.adyen.model.checkout.CheckoutPaymentMethod; +import com.adyen.model.checkout.PaymentResponse; import com.adyen.v6.facades.AdyenAmazonPayFacade; import com.adyen.v6.facades.AdyenCheckoutFacade; import de.hybris.bootstrap.annotations.UnitTest; @@ -68,7 +68,7 @@ public class AdyenAmazonpayControllerTest { @Mock private HttpServletRequest requestMock; @Mock - private PaymentsResponse paymentResponseMock; + private PaymentResponse paymentResponseMock; @Mock private RedirectAttributes redirectModelMock; @@ -98,7 +98,7 @@ public void placeOrder_shouldRedirectToOrderPlaced_whenCheckoutSessionIdIsValid( when(checkoutCustomerStrategyMock.isAnonymousCheckout()).thenReturn(Boolean.FALSE); when(orderFacadeMock.getOrderDetailsForCodeWithoutUser(ORDER_CODE)).thenReturn(orderDataMock); when(adyenAmazonPayFacadeMock.getAmazonPayToken(AMAZON_CHECKOUT_SESSION_ID)).thenReturn(AMAZON_PAY_TOKEN); - when(adyenCheckoutFacadeMock.componentPayment(eq(requestMock), eq(cartDataMock), isA(AmazonPayDetails.class))).thenReturn(paymentResponseMock); + when(adyenCheckoutFacadeMock.componentPayment(eq(requestMock), eq(cartDataMock), isA(CheckoutPaymentMethod.class))).thenReturn(paymentResponseMock); when(adyenAmazonPayFacadeMock.getReturnUrl(AMAZON_RETURN_URL)).thenReturn(URL); final String result = testObj.placeOrder(modelMock, redirectModelMock, requestMock, AMAZON_CHECKOUT_SESSION_ID); @@ -111,12 +111,12 @@ public void placeOrder_shouldRedirectToOrderPlaced_whenCheckoutSessionIdIsValid( public void placeOrder_shouldRedirectTo3DSValidation_whenCheckoutSessionIdIsValidAndResponseCodeIsRedirectShopper() throws Exception { when(orderDataMock.getCode()).thenReturn(ORDER_CODE); when(paymentResponseMock.getMerchantReference()).thenReturn(ORDER_CODE); - when(paymentResponseMock.getResultCode()).thenReturn(PaymentsResponse.ResultCodeEnum.REDIRECTSHOPPER); + when(paymentResponseMock.getResultCode()).thenReturn(PaymentResponse.ResultCodeEnum.REDIRECTSHOPPER); when(checkoutFlowFacadeMock.getCheckoutCart()).thenReturn(cartDataMock); when(checkoutCustomerStrategyMock.isAnonymousCheckout()).thenReturn(Boolean.FALSE); when(orderFacadeMock.getOrderDetailsForCodeWithoutUser(ORDER_CODE)).thenReturn(orderDataMock); when(adyenAmazonPayFacadeMock.getAmazonPayToken(AMAZON_CHECKOUT_SESSION_ID)).thenReturn(AMAZON_PAY_TOKEN); - when(adyenCheckoutFacadeMock.componentPayment(eq(requestMock), eq(cartDataMock), isA(AmazonPayDetails.class))).thenReturn(paymentResponseMock); + when(adyenCheckoutFacadeMock.componentPayment(eq(requestMock), eq(cartDataMock), isA(CheckoutPaymentMethod.class))).thenReturn(paymentResponseMock); when(adyenAmazonPayFacadeMock.getReturnUrl(AMAZON_RETURN_URL)).thenReturn(URL); when(adyenCheckoutFacadeMock.getClientKey()).thenReturn("clientKey"); when(adyenCheckoutFacadeMock.getCheckoutShopperHost()).thenReturn("host"); @@ -135,7 +135,7 @@ public void placeOrder_shouldRedirectToSummaryPage_whenAnExceptionIsThrownDuring when(checkoutFlowFacadeMock.getCheckoutCart()).thenReturn(cartDataMock); doReturn(SUMMARY_PAGE_REDIRECT).when(testObj).enterStep(modelMock, redirectModelMock); when(adyenAmazonPayFacadeMock.getAmazonPayToken(AMAZON_CHECKOUT_SESSION_ID)).thenReturn(AMAZON_PAY_TOKEN); - when(adyenCheckoutFacadeMock.componentPayment(eq(requestMock), eq(cartDataMock), isA(AmazonPayDetails.class))).thenThrow(Exception.class); + when(adyenCheckoutFacadeMock.componentPayment(eq(requestMock), eq(cartDataMock), isA(CheckoutPaymentMethod.class))).thenThrow(Exception.class); when(adyenAmazonPayFacadeMock.getReturnUrl(AMAZON_RETURN_URL)).thenReturn(URL); final String result = testObj.placeOrder(modelMock, redirectModelMock, requestMock, AMAZON_CHECKOUT_SESSION_ID); diff --git a/adyenv6b2ccheckoutaddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/pages/checkout/multi/checkoutSummaryPage.jsp b/adyenv6b2ccheckoutaddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/pages/checkout/multi/checkoutSummaryPage.jsp index 154c40007..374c0868a 100644 --- a/adyenv6b2ccheckoutaddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/pages/checkout/multi/checkoutSummaryPage.jsp +++ b/adyenv6b2ccheckoutaddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/pages/checkout/multi/checkoutSummaryPage.jsp @@ -153,7 +153,8 @@ class="create_update_payment_form" action="${handleComponentResult}" method="post"> - + + diff --git a/adyenv6b2ccheckoutaddon/acceleratoraddon/web/webroot/_ui/responsive/common/js/adyen.checkout.js b/adyenv6b2ccheckoutaddon/acceleratoraddon/web/webroot/_ui/responsive/common/js/adyen.checkout.js index 1f86bc9cd..0760c73d4 100644 --- a/adyenv6b2ccheckoutaddon/acceleratoraddon/web/webroot/_ui/responsive/common/js/adyen.checkout.js +++ b/adyenv6b2ccheckoutaddon/acceleratoraddon/web/webroot/_ui/responsive/common/js/adyen.checkout.js @@ -587,7 +587,7 @@ var AdyenCheckoutHybris = (function () { self.enablePlaceOrder(label); return false; } - self.makePayment(state.data.paymentMethod, component, self.handleResult, label); + self.makePayment(state.data, component, self.handleResult, label); }, onCancel: function (data, component) { // Sets your prefered status of the component when a PayPal payment is cancelled. @@ -663,7 +663,7 @@ var AdyenCheckoutHybris = (function () { self.enablePlaceOrder(label); return false; } - self.makePayment(state.data.paymentMethod, component, self.handleResult, label); + self.makePayment(state.data, component, self.handleResult, label); }, onClick: function(resolve, reject) { if (self.isTermsAccepted(label)) { @@ -716,7 +716,7 @@ var AdyenCheckoutHybris = (function () { return false; } self.showSpinner(); - self.makePayment(state.data.paymentMethod, component, self.handleResult, label); + self.makePayment(state.data, component, self.handleResult, label); }, onClick: function (resolve, reject) { if (self.isTermsAccepted(label)) { @@ -808,7 +808,7 @@ var AdyenCheckoutHybris = (function () { self.enablePlaceOrder(label); return; } - self.makePayment(state.data.paymentMethod, component, self.handleResult, label); + self.makePayment(state.data, component, self.handleResult, label); }, onAdditionalDetails: function (state, component) { self.submitDetails(state.data, self.handleResult); @@ -844,7 +844,7 @@ var AdyenCheckoutHybris = (function () { self.enablePlaceOrder(label); return; } - self.makePayment(state.data.paymentMethod, component, self.handleResult, label); + self.makePayment(state.data, component, self.handleResult, label); }, onAdditionalDetails: function (state, component) { self.submitDetails(state.data, self.handleResult); @@ -880,7 +880,7 @@ var AdyenCheckoutHybris = (function () { self.enablePlaceOrder(label); return; } - self.makePayment(state.data.paymentMethod, component, self.handleResult, label); + self.makePayment(state.data, component, self.handleResult, label); }, onAdditionalDetails: function (state, component) { self.submitDetails(state.data, self.handleResult); @@ -1003,7 +1003,7 @@ var AdyenCheckoutHybris = (function () { }; $.ajax({ - url: ACC.config.encodedContextPath + '/checkout/multi/adyen/summary/placeOrderBizum', + url: ACC.config.encodedContextPath + '/checkout/multi/adyen/summary/placeOrder', type: "POST", data: placeOrderForm, success: function (data) { @@ -1059,14 +1059,10 @@ var AdyenCheckoutHybris = (function () { $.ajax({ url: ACC.config.encodedContextPath + '/adyen/component/payment', type: "POST", - data: JSON.stringify({ - paymentMethodDetails: data, - termsCheck: document.getElementById('terms-conditions-check-' + label).checked - }), + data: JSON.stringify( data ), contentType: "application/json; charset=utf-8", - success: function (data) { + success: function (response) { try { - var response = JSON.parse(data); if (response.resultCode && response.resultCode === 'Pending' && response.action) { component.handleAction(response.action); } else if (response.resultCode && (response.resultCode === 'Authorised' || response.resultCode === 'RedirectShopper')) { @@ -1075,7 +1071,7 @@ var AdyenCheckoutHybris = (function () { handleResult(ErrorMessages.PaymentError, true); } } catch (e) { - console.log('Error parsing makePayment response: ' + data); + console.log('Error parsing makePayment response: ' + response); handleResult(ErrorMessages.PaymentError, true); } }, @@ -1097,16 +1093,15 @@ var AdyenCheckoutHybris = (function () { type: "POST", data: JSON.stringify(data), contentType: "application/json; charset=utf-8", - success: function (data) { + success: function (response) { try { - var response = JSON.parse(data); if (response.resultCode) { handleResult(response, false); } else { handleResult(ErrorMessages.PaymentError, true); } } catch (e) { - console.log('Error parsing submitDetails response: ' + data); + console.log('Error parsing submitDetails response: ' + response); handleResult(ErrorMessages.PaymentError, true); } }, @@ -1129,10 +1124,12 @@ var AdyenCheckoutHybris = (function () { handleResult: function (data, error) { if (error) { - document.querySelector("#resultData").value = data; + document.querySelector("#resultCode").value = data.resultCode; + document.querySelector("#merchantReference").value = data.merchantReference; document.querySelector("#isResultError").value = error; } else { - document.querySelector("#resultData").value = JSON.stringify(data); + document.querySelector("#resultCode").value = data.resultCode; + document.querySelector("#merchantReference").value = data.merchantReference; } document.querySelector("#handleComponentResultForm").submit(); }, diff --git a/adyenv6b2ccheckoutaddon/extensioninfo.xml b/adyenv6b2ccheckoutaddon/extensioninfo.xml index 51f05301c..c56a73374 100644 --- a/adyenv6b2ccheckoutaddon/extensioninfo.xml +++ b/adyenv6b2ccheckoutaddon/extensioninfo.xml @@ -16,6 +16,7 @@ + diff --git a/adyenv6b2ccheckoutaddon/testsrc/com/adyen/v6/facades/AdyenCheckoutFacadeTest.java b/adyenv6b2ccheckoutaddon/testsrc/com/adyen/v6/facades/AdyenCheckoutFacadeTest.java index 0c2a025be..985639762 100644 --- a/adyenv6b2ccheckoutaddon/testsrc/com/adyen/v6/facades/AdyenCheckoutFacadeTest.java +++ b/adyenv6b2ccheckoutaddon/testsrc/com/adyen/v6/facades/AdyenCheckoutFacadeTest.java @@ -20,13 +20,10 @@ */ package com.adyen.v6.facades; -import com.adyen.model.PaymentResult; -import com.adyen.model.checkout.CheckoutPaymentsAction; -import com.adyen.model.checkout.PaymentsDetailsResponse; -import com.adyen.model.checkout.PaymentsResponse; -import com.adyen.v6.constants.Adyenv6coreConstants; -import com.adyen.v6.converters.PaymentsDetailsResponseConverter; -import com.adyen.v6.converters.PaymentsResponseConverter; +import com.adyen.model.checkout.PaymentDetailsRequest; +import com.adyen.model.checkout.PaymentDetailsResponse; +import com.adyen.model.checkout.PaymentResponse; +import com.adyen.model.checkout.PaymentResponseAction; import com.adyen.v6.exceptions.AdyenNonAuthorizedPaymentException; import com.adyen.v6.facades.impl.DefaultAdyenCheckoutFacade; import com.adyen.v6.factory.AdyenPaymentServiceFactory; @@ -35,7 +32,7 @@ import com.adyen.v6.service.AdyenBusinessProcessService; import com.adyen.v6.service.AdyenOrderService; import com.adyen.v6.service.AdyenTransactionService; -import com.adyen.v6.service.DefaultAdyenPaymentService; +import com.adyen.v6.service.DefaultAdyenCheckoutApiService; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.commercefacades.order.CheckoutFacade; import de.hybris.platform.commercefacades.order.OrderFacade; @@ -48,7 +45,6 @@ import de.hybris.platform.core.model.c2l.LanguageModel; import de.hybris.platform.core.model.order.CartModel; import de.hybris.platform.core.model.order.OrderModel; -import de.hybris.platform.core.model.order.payment.PaymentInfoModel; import de.hybris.platform.core.model.user.CustomerModel; import de.hybris.platform.order.CalculationService; import de.hybris.platform.order.CartFactory; @@ -71,22 +67,24 @@ import org.mockito.runners.MockitoJUnitRunner; import javax.servlet.http.HttpServletRequest; +import java.io.IOException; import java.math.BigDecimal; import java.security.SignatureException; -import java.util.Collections; -import java.util.Map; -import static com.adyen.constants.ApiConstants.Redirect.Data.MD; -import static com.adyen.v6.constants.Adyenv6coreConstants.*; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_CC; import static com.adyen.v6.facades.impl.DefaultAdyenCheckoutFacade.SESSION_LOCKED_CART; import static com.adyen.v6.model.RequestInfo.ACCEPT_HEADER; import static com.adyen.v6.model.RequestInfo.USER_AGENT_HEADER; import static de.hybris.platform.order.impl.DefaultCartService.SESSION_CART_PARAMETER_NAME; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; -import static org.mockito.Matchers.eq; -import static org.mockito.Matchers.isA; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; @UnitTest @RunWith(MockitoJUnitRunner.class) @@ -108,7 +106,7 @@ public class AdyenCheckoutFacadeTest { @Mock private CheckoutFacade checkoutFacadeMock; @Mock - private DefaultAdyenPaymentService adyenPaymentServiceMock; + private DefaultAdyenCheckoutApiService adyenPaymentServiceMock; @Mock private AdyenTransactionService adyenTransactionServiceMock; @Mock @@ -124,8 +122,6 @@ public class AdyenCheckoutFacadeTest { @Mock private KeyGenerator keyGeneratorMock; @Mock - private PaymentsDetailsResponseConverter paymentsDetailsResponseConverterMock; - @Mock private ModelService modelServiceMock; @Mock private AdyenBusinessProcessService adyenBusinessProcessServiceMock; @@ -140,20 +136,45 @@ public class AdyenCheckoutFacadeTest { private OrderModel orderModelMock; private CartModel cartModelMock; - private PaymentResult paymentResultMock; - private PaymentsResponse paymentsResponseMock; - private PaymentsDetailsResponse paymentsDetailsResponseMock; - - private PaymentsResponse paymentsResponse; + private PaymentResponse paymentResponseMock; + private PaymentResponse paymentsResponseMock; + private PaymentDetailsResponse paymentsDetailsResponseMock; + + private PaymentResponse paymentsResponse; + + final String PAYMENT_RESPONSE_ACTION_JSON = "{" + + "\"type\": \"typeValue\"," + + "\"paymentMethodType\": \"paymentMethodTypeValue\"," + + "\"url\": \"urlValue\"," + + "\"method\": \"methodValue\"," + + "\"token\": \"tokenValue\"," + + "\"paymentData\": \"paymentDataValue\"," + + "\"action\": \"actionValue\"," + + "\"sdkData\": {" + + " \"ephemeralPublicKey\": \"ephemeralPublicKeyValue\"," + + " \"tag\": \"tagValue\"," + + " \"publicKeyHash\": \"publicKeyHashValue\"," + + " \"transactionId\": \"transactionIdValue\"" + + "}," + + "\"paymentMethod\": {" + + " \"type\": \"typeValue\"," + + " \"number\": \"numberValue\"," + + " \"expiryMonth\": \"expiryMonthValue\"," + + " \"expiryYear\": \"expiryYearValue\"," + + " \"holderName\": \"holderNameValue\"," + + " \"cvc\": \"cvcValue\"" + + "}," + + "\"issuer\": \"issuerValue\"," + + "\"reference\": \"referenceValue\"" + + "}"; @Before - public void setUp() throws SignatureException, InvalidCartException, CalculationException { + public void setUp() throws SignatureException, InvalidCartException, CalculationException, IOException { BaseStoreModel baseStoreModelMock = mock(BaseStoreModel.class); cartModelMock = mock(CartModel.class); OrderData orderDataMock = mock(OrderData.class); - paymentResultMock = mock(PaymentResult.class); - paymentsResponseMock = mock(PaymentsResponse.class); - paymentsDetailsResponseMock = mock(PaymentsDetailsResponse.class); + paymentsResponseMock = mock(PaymentResponse.class); + paymentsDetailsResponseMock = mock(PaymentDetailsResponse.class); CartData cartDataMock = mock(CartData.class); doNothing().when(calculationServiceMock).calculate(cartModelMock); @@ -172,26 +193,21 @@ public void setUp() throws SignatureException, InvalidCartException, Calculation when(cartDataMock.getCode()).thenReturn(CODE); when(checkoutFacadeMock.getCheckoutCart()).thenReturn(cartDataMock); - when(paymentResultMock.getPspReference()).thenReturn("pspRef"); - when(paymentResultMock.getMd()).thenReturn("md"); + when(paymentResponseMock.getPspReference()).thenReturn("pspRef"); when(paymentsResponseMock.getPspReference()).thenReturn("pspRef"); - paymentsResponse = new PaymentsResponse(); + paymentsResponse = new PaymentResponse(); paymentsResponse.setPspReference("pspRef"); - CheckoutPaymentsAction action = new CheckoutPaymentsAction(); - action.setData(Collections.singletonMap(MD, "md")); - action.setPaymentData("This is test payment data"); - paymentsResponse.setAction(action); - when(adyenPaymentServiceFactoryMock.createFromBaseStore(baseStoreModelMock)).thenReturn(adyenPaymentServiceMock); + paymentsResponse.setAction(PaymentResponseAction.fromJson(PAYMENT_RESPONSE_ACTION_JSON)); + + when(adyenPaymentServiceFactoryMock.createAdyenCheckoutApiService(baseStoreModelMock)).thenReturn(adyenPaymentServiceMock); LanguageModel languageModel = new LanguageModel(); languageModel.setIsocode("en"); when(commonI18NServiceMock.getCurrentLanguage()).thenReturn(languageModel); when(keyGeneratorMock.generate()).thenReturn(new Object()); - adyenCheckoutFacade.setPaymentsResponseConverter(new PaymentsResponseConverter()); - adyenCheckoutFacade.setPaymentsDetailsResponseConverter(paymentsDetailsResponseConverterMock); adyenCheckoutFacade.setOrderConverter(orderConverterMock); } @@ -228,7 +244,7 @@ public void testAuthorizeCardPayment() throws Exception { OrderModel orderModelMock = mock(OrderModel.class); //When payment is authorized - paymentsResponse.setResultCode(PaymentsResponse.ResultCodeEnum.AUTHORISED); + paymentsResponse.setResultCode(PaymentResponse.ResultCodeEnum.AUTHORISED); when(checkoutCustomerStrategyMock.isAnonymousCheckout()).thenReturn(true); when(checkoutCustomerStrategyMock.getCurrentUserForCheckout()).thenReturn(null); when(adyenPaymentServiceMock.authorisePayment(any(CartData.class), any(RequestInfo.class), any(CustomerModel.class))).thenReturn(paymentsResponse); @@ -245,7 +261,7 @@ public void testAuthorizeCardPayment() throws Exception { verifyAuthorized(orderModelMock); //When payment is 3D secure - paymentsResponse.setResultCode(PaymentsResponse.ResultCodeEnum.REDIRECTSHOPPER); + paymentsResponse.setResultCode(PaymentResponse.ResultCodeEnum.REDIRECTSHOPPER); try { adyenCheckoutFacade.authorisePayment(requestMock, cartDataMock); @@ -256,7 +272,7 @@ public void testAuthorizeCardPayment() throws Exception { } //When payment is refused - paymentsResponse.setResultCode(PaymentsResponse.ResultCodeEnum.REFUSED); + paymentsResponse.setResultCode(PaymentResponse.ResultCodeEnum.REFUSED); try { adyenCheckoutFacade.authorisePayment(requestMock, cartDataMock); @@ -269,35 +285,34 @@ public void testAuthorizeCardPayment() throws Exception { @Test public void testHandle3DResponse() throws Exception { - Map detailsMap = mock(Map.class); - PaymentInfoModel paymentInfoModelMock = mock(PaymentInfoModel.class); + HttpServletRequest requestMock = mock(HttpServletRequest.class); + PaymentDetailsRequest paymentDetailsRequestMock = mock(PaymentDetailsRequest.class); + CartData cartDataMock = mock(CartData.class); + OrderModel orderModelMock = mock(OrderModel.class); //When payment is authorized - when(paymentResultMock.isAuthorised()).thenReturn(true); - when(sessionServiceMock.getAttribute(SESSION_LOCKED_CART)).thenReturn(cartModelMock); - when(adyenPaymentServiceMock.authorise3DSPayment(detailsMap)).thenReturn(paymentsDetailsResponseMock); - when(orderRepositoryMock.getOrderModel(CODE)).thenReturn(orderModelMock); - when(paymentsResponseMock.getResultCode()).thenReturn(PaymentsResponse.ResultCodeEnum.AUTHORISED); - when(paymentsDetailsResponseMock.getMerchantReference()).thenReturn(CODE); - when(paymentsDetailsResponseConverterMock.convert(paymentsDetailsResponseMock)).thenReturn(paymentsResponseMock); - when(paymentsDetailsResponseMock.getResultCode()).thenReturn(PaymentsResponse.ResultCodeEnum.AUTHORISED); - when(cartModelMock.getPaymentInfo()).thenReturn(paymentInfoModelMock); - when(paymentInfoModelMock.getAdyenPaymentMethod()).thenReturn(PAYMENT_METHOD_ONECLICK); - doNothing().when(adyenBusinessProcessServiceMock).triggerOrderProcessEvent(orderModelMock, Adyenv6coreConstants.PROCESS_EVENT_ADYEN_PAYMENT_RESULT); + paymentsDetailsResponseMock.setResultCode(PaymentDetailsResponse.ResultCodeEnum.AUTHORISED); when(checkoutCustomerStrategyMock.isAnonymousCheckout()).thenReturn(true); + when(checkoutCustomerStrategyMock.getCurrentUserForCheckout()).thenReturn(null); + when(adyenPaymentServiceMock.authorise3DSPayment(new PaymentDetailsRequest())).thenReturn(paymentsDetailsResponseMock); + when(orderRepositoryMock.getOrderModel(CODE)).thenReturn(orderModelMock); + when(cartDataMock.getAdyenPaymentMethod()).thenReturn(PAYMENT_METHOD_CC); + when(requestMock.getHeader(USER_AGENT_HEADER)).thenReturn("userAgent"); + when(requestMock.getHeader(ACCEPT_HEADER)).thenReturn("acceptHeader"); + when(requestMock.getRemoteAddr()).thenReturn("addr"); + when(requestMock.getRequestURI()).thenReturn("uri"); + when(requestMock.getRequestURL()).thenReturn(new StringBuffer("url")); - adyenCheckoutFacade.handle3DSResponse(detailsMap); - - verify(adyenPaymentServiceMock).authorise3DSPayment(detailsMap); + verifyAuthorized(orderModelMock); - //When is not authorized - when(paymentsDetailsResponseMock.getResultCode()).thenReturn(PaymentsResponse.ResultCodeEnum.REFUSED); + //When payment is refused + paymentsDetailsResponseMock.setResultCode(PaymentDetailsResponse.ResultCodeEnum.REFUSED); try { - adyenCheckoutFacade.handle3DSResponse(detailsMap); + adyenCheckoutFacade.handle3DSResponse(paymentDetailsRequestMock); fail("Expecting exception"); } catch (AdyenNonAuthorizedPaymentException e) { - //throw exception with getPaymentsResponse details + //throw exception with paymentResult details assertEquals(paymentsDetailsResponseMock, e.getPaymentsDetailsResponse()); } } @@ -325,6 +340,6 @@ private void verifyAuthorized(OrderModel orderModelMock) throws InvalidCartExcep //order should be created verify(checkoutFacadeMock).placeOrder(); //update of order metadata should happen - verify(adyenOrderServiceMock).updateOrderFromPaymentsResponse(eq(orderModelMock), isA(PaymentsResponse.class)); + verify(adyenOrderServiceMock).updatePaymentInfo(eq(orderModelMock), any(), any()); } } diff --git a/adyenv6consignmentpartialcaptureexample/src/com/adyen/v6/actions/AdyenCaptureConsignmentsAction.java b/adyenv6consignmentpartialcaptureexample/src/com/adyen/v6/actions/AdyenCaptureConsignmentsAction.java index 2edfdb44d..89d9277fa 100644 --- a/adyenv6consignmentpartialcaptureexample/src/com/adyen/v6/actions/AdyenCaptureConsignmentsAction.java +++ b/adyenv6consignmentpartialcaptureexample/src/com/adyen/v6/actions/AdyenCaptureConsignmentsAction.java @@ -2,7 +2,7 @@ import com.adyen.v6.constants.Adyenv6consignmentpartialcaptureexampleConstants; import com.adyen.v6.factory.AdyenPaymentServiceFactory; -import com.adyen.v6.service.AdyenPaymentService; +import com.adyen.v6.service.AdyenModificationsApiService; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.orderprocessing.model.OrderProcessModel; import de.hybris.platform.ordersplitting.model.ConsignmentEntryModel; @@ -32,7 +32,7 @@ public Transition executeAction(OrderProcessModel orderProcessModel) throws Retr if (paymentTransactionModelOptional.isPresent()) { for (ConsignmentModel consignment : order.getConsignments()) { BigDecimal consignmentValue = calculateConsignmentValue(consignment); - getAdyenPaymentService(order.getStore()).captures(consignmentValue, currency, paymentTransactionModelOptional.get().getCode(), order.getCode()); + getAdyenPaymentService(order.getStore()).capture(consignmentValue, currency, paymentTransactionModelOptional.get().getCode(), order.getCode()); } } else { return Transition.NOK; @@ -51,8 +51,8 @@ private BigDecimal calculateConsignmentValue(ConsignmentModel consignmentModel) return sum; } - private AdyenPaymentService getAdyenPaymentService(BaseStoreModel baseStoreModel) { - return adyenPaymentServiceFactory.createFromBaseStore(baseStoreModel); + private AdyenModificationsApiService getAdyenPaymentService(BaseStoreModel baseStoreModel) { + return adyenPaymentServiceFactory.createAdyenModificationsApiService(baseStoreModel); } public void setAdyenPaymentServiceFactory(AdyenPaymentServiceFactory adyenPaymentServiceFactory) { diff --git a/adyenv6core/external-dependencies.xml b/adyenv6core/external-dependencies.xml index 41190d74e..4aeb305e4 100644 --- a/adyenv6core/external-dependencies.xml +++ b/adyenv6core/external-dependencies.xml @@ -22,7 +22,12 @@ com.adyen adyen-java-api-library - 18.1.3 + 24.0.0 + + + jakarta.ws.rs + jakarta.ws.rs-api + 3.1.0 com.google.code.gson @@ -44,10 +49,5 @@ json 20220924 - - com.adyen - adyen-java-api-library - 18.1.3 - diff --git a/adyenv6core/resources/adyenv6core-spring.xml b/adyenv6core/resources/adyenv6core-spring.xml index 4e31568c1..c492a72d0 100644 --- a/adyenv6core/resources/adyenv6core-spring.xml +++ b/adyenv6core/resources/adyenv6core-spring.xml @@ -13,11 +13,8 @@ + http://www.springframework.org/schema/beans/spring-beans.xsd"> @@ -137,11 +134,8 @@ - - - - + @@ -323,6 +317,7 @@ + - + @@ -454,11 +450,13 @@ + diff --git a/adyenv6core/src/com/adyen/v6/actions/order/AdyenCheckAuthorizationAction.java b/adyenv6core/src/com/adyen/v6/actions/order/AdyenCheckAuthorizationAction.java index 5e564df92..a0f731107 100644 --- a/adyenv6core/src/com/adyen/v6/actions/order/AdyenCheckAuthorizationAction.java +++ b/adyenv6core/src/com/adyen/v6/actions/order/AdyenCheckAuthorizationAction.java @@ -22,7 +22,7 @@ import com.adyen.v6.actions.AbstractWaitableAction; import com.adyen.v6.factory.AdyenPaymentServiceFactory; -import com.adyen.v6.service.AdyenPaymentService; +import com.adyen.v6.service.AdyenCheckoutApiService; import de.hybris.platform.core.enums.OrderStatus; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; @@ -124,7 +124,7 @@ private String processOrderAuthorization(final OrderProcessModel process, final return Transition.OK.toString(); } - public AdyenPaymentService getAdyenPaymentService(final OrderModel orderModel) { - return adyenPaymentServiceFactory.createFromBaseStore(orderModel.getStore()); + public AdyenCheckoutApiService getAdyenPaymentService(final OrderModel orderModel) { + return adyenPaymentServiceFactory.createAdyenCheckoutApiService(orderModel.getStore()); } } diff --git a/adyenv6core/src/com/adyen/v6/actions/order/AdyenCheckCaptureAction.java b/adyenv6core/src/com/adyen/v6/actions/order/AdyenCheckCaptureAction.java index f155d46fa..6d6905c7e 100644 --- a/adyenv6core/src/com/adyen/v6/actions/order/AdyenCheckCaptureAction.java +++ b/adyenv6core/src/com/adyen/v6/actions/order/AdyenCheckCaptureAction.java @@ -22,7 +22,7 @@ import com.adyen.v6.actions.AbstractWaitableAction; import com.adyen.v6.factory.AdyenPaymentServiceFactory; -import com.adyen.v6.service.AdyenPaymentService; +import com.adyen.v6.service.AdyenCheckoutApiService; import com.adyen.v6.service.AdyenTransactionService; import de.hybris.platform.core.enums.OrderStatus; import de.hybris.platform.core.model.order.OrderModel; @@ -127,7 +127,7 @@ public String execute(final OrderProcessModel process) { return Transition.WAIT.toString(); } - public AdyenPaymentService getAdyenPaymentService(final OrderModel orderModel) { - return adyenPaymentServiceFactory.createFromBaseStore(orderModel.getStore()); + public AdyenCheckoutApiService getAdyenPaymentService(final OrderModel orderModel) { + return adyenPaymentServiceFactory.createAdyenCheckoutApiService(orderModel.getStore()); } } diff --git a/adyenv6core/src/com/adyen/v6/commands/AdyenCaptureCommand.java b/adyenv6core/src/com/adyen/v6/commands/AdyenCaptureCommand.java index cd48835a0..823fadaa4 100644 --- a/adyenv6core/src/com/adyen/v6/commands/AdyenCaptureCommand.java +++ b/adyenv6core/src/com/adyen/v6/commands/AdyenCaptureCommand.java @@ -20,10 +20,11 @@ */ package com.adyen.v6.commands; -import com.adyen.model.checkout.PaymentCaptureResource; + +import com.adyen.model.checkout.PaymentCaptureResponse; import com.adyen.v6.factory.AdyenPaymentServiceFactory; import com.adyen.v6.repository.OrderRepository; -import com.adyen.v6.service.AdyenPaymentService; +import com.adyen.v6.service.AdyenModificationsApiService; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; import de.hybris.platform.payment.commands.CaptureCommand; @@ -75,7 +76,7 @@ public CaptureResult perform(final CaptureRequest request) { BaseStoreModel baseStore = order.getStore(); Assert.notNull(baseStore, "BaseStore model is null"); - AdyenPaymentService adyenPaymentService = adyenPaymentServiceFactory.createFromBaseStore(baseStore); + AdyenModificationsApiService adyenPaymentService = adyenPaymentServiceFactory.createAdyenModificationsApiService(baseStore); final PaymentInfoModel paymentInfo = order.getPaymentInfo(); Assert.notNull(paymentInfo, "PaymentInfoModel is null"); @@ -89,9 +90,9 @@ public CaptureResult perform(final CaptureRequest request) { result.setTransactionStatusDetails(TransactionStatusDetails.SUCCESFULL); } else { try { - final PaymentCaptureResource captures = adyenPaymentService.captures(amount, currency, originalPSPReference, reference); + PaymentCaptureResponse capture = adyenPaymentService.capture(amount, currency, originalPSPReference, reference); - if (PaymentCaptureResource.StatusEnum.RECEIVED.equals(captures.getStatus())) { + if (PaymentCaptureResponse.StatusEnum.RECEIVED.equals(capture.getStatus())) { result.setTransactionStatus(TransactionStatus.ACCEPTED); //Accepted so that TakePaymentAction doesn't fail result.setTransactionStatusDetails(TransactionStatusDetails.REVIEW_NEEDED); } else { diff --git a/adyenv6core/src/com/adyen/v6/commands/AdyenFollowOnRefundCommand.java b/adyenv6core/src/com/adyen/v6/commands/AdyenFollowOnRefundCommand.java index d21705adf..90af6baf3 100644 --- a/adyenv6core/src/com/adyen/v6/commands/AdyenFollowOnRefundCommand.java +++ b/adyenv6core/src/com/adyen/v6/commands/AdyenFollowOnRefundCommand.java @@ -20,10 +20,10 @@ */ package com.adyen.v6.commands; -import com.adyen.model.checkout.PaymentRefundResource; +import com.adyen.model.checkout.PaymentRefundResponse; import com.adyen.v6.factory.AdyenPaymentServiceFactory; import com.adyen.v6.repository.BaseStoreRepository; -import com.adyen.v6.service.AdyenPaymentService; +import com.adyen.v6.service.AdyenModificationsApiService; import de.hybris.platform.payment.commands.FollowOnRefundCommand; import de.hybris.platform.payment.commands.request.FollowOnRefundRequest; import de.hybris.platform.payment.commands.result.RefundResult; @@ -72,15 +72,15 @@ public RefundResult perform(FollowOnRefundRequest request) { if (baseStore == null) { return result; } - AdyenPaymentService adyenPaymentService = adyenPaymentServiceFactory.createFromBaseStore(baseStore); + AdyenModificationsApiService adyenModificationsApiService = adyenPaymentServiceFactory.createAdyenModificationsApiService(baseStore); try { //Do the /refund API call - final PaymentRefundResource refunds = adyenPaymentService.refunds(amount, currency, originalPSPReference, reference); + PaymentRefundResponse paymentRefundResponse = adyenModificationsApiService.refund(amount, currency, originalPSPReference, reference); - LOG.debug("Refund response: " + refunds.toString()); + LOG.debug("Refund response: " + paymentRefundResponse.toString()); //change status to ACCEPTED if there is no error - if (PaymentRefundResource.StatusEnum.RECEIVED.equals(refunds.getStatus())) { + if (PaymentRefundResponse.StatusEnum.RECEIVED.equals(paymentRefundResponse.getStatus())) { result.setTransactionStatus(ACCEPTED); result.setTransactionStatusDetails(REVIEW_NEEDED); } diff --git a/adyenv6core/src/com/adyen/v6/commands/AdyenVoidCommand.java b/adyenv6core/src/com/adyen/v6/commands/AdyenVoidCommand.java index 63b9f0627..3e263f82a 100644 --- a/adyenv6core/src/com/adyen/v6/commands/AdyenVoidCommand.java +++ b/adyenv6core/src/com/adyen/v6/commands/AdyenVoidCommand.java @@ -20,10 +20,10 @@ */ package com.adyen.v6.commands; -import com.adyen.model.checkout.PaymentReversalResource; +import com.adyen.model.checkout.PaymentReversalResponse; import com.adyen.v6.factory.AdyenPaymentServiceFactory; import com.adyen.v6.repository.BaseStoreRepository; -import com.adyen.v6.service.AdyenPaymentService; +import com.adyen.v6.service.AdyenModificationsApiService; import de.hybris.platform.payment.commands.VoidCommand; import de.hybris.platform.payment.commands.request.VoidRequest; import de.hybris.platform.payment.commands.result.VoidResult; @@ -63,12 +63,12 @@ public VoidResult perform(VoidRequest request) { if (baseStore == null) { return result; } - AdyenPaymentService adyenPaymentService = adyenPaymentServiceFactory.createFromBaseStore(baseStore); + AdyenModificationsApiService adyenModificationsApiService = adyenPaymentServiceFactory.createAdyenModificationsApiService(baseStore); try { - final PaymentReversalResource paymentReversalResource = adyenPaymentService.cancelOrRefunds(authReference, reference); + PaymentReversalResponse paymentReversalResponse = adyenModificationsApiService.cancelOrRefund(authReference, reference); - if (PaymentReversalResource.StatusEnum.RECEIVED.equals(paymentReversalResource.getStatus())) { + if (PaymentReversalResponse.StatusEnum.RECEIVED.equals(paymentReversalResponse.getStatus())) { result.setTransactionStatus(TransactionStatus.ACCEPTED); result.setTransactionStatusDetails(TransactionStatusDetails.REVIEW_NEEDED); } else { diff --git a/adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java b/adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java index 4fe4673f4..3791967d0 100644 --- a/adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java +++ b/adyenv6core/src/com/adyen/v6/constants/Adyenv6coreConstants.java @@ -84,6 +84,7 @@ public final class Adyenv6coreConstants extends GeneratedAdyenv6coreConstants { public static final String CARD_TYPE_DEBIT = "debit"; public static final String AFFIRM = "affirm"; public static final String CLEARPAY = "clearpay"; + public static final String SHOPPER_LOCALE = "shopperLocale"; private Adyenv6coreConstants() { //empty to avoid instantiating this constant class diff --git a/adyenv6core/src/com/adyen/v6/converters/PaymentMethodConverter.java b/adyenv6core/src/com/adyen/v6/converters/PaymentMethodConverter.java deleted file mode 100644 index 553d9bdd1..000000000 --- a/adyenv6core/src/com/adyen/v6/converters/PaymentMethodConverter.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * ###### - * ###### - * ############ ####( ###### #####. ###### ############ ############ - * ############# #####( ###### #####. ###### ############# ############# - * ###### #####( ###### #####. ###### ##### ###### ##### ###### - * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### - * ###### ###### #####( ###### #####. ###### ##### ##### ###### - * ############# ############# ############# ############# ##### ###### - * ############ ############ ############# ############ ##### ###### - * ###### - * ############# - * ############ - * - * Adyen Hybris Extension - * - * Copyright (c) 2017 Adyen B.V. - * This file is open source and available under the MIT license. - * See the LICENSE file for more info. - */ -package com.adyen.v6.converters; - -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import com.adyen.model.checkout.PaymentMethod; -import org.springframework.core.convert.converter.Converter; - -import com.adyen.model.checkout.InputDetail; -import com.adyen.model.hpp.Issuer; - -public class PaymentMethodConverter implements Converter { - @Override - public PaymentMethod convert(com.adyen.model.checkout.PaymentMethod checkoutPaymentMethod) { - if (checkoutPaymentMethod == null) { - throw new IllegalArgumentException("Null PaymentMethod"); - } - final PaymentMethod paymentMethod = new PaymentMethod(); - - paymentMethod.setIssuers(checkoutPaymentMethod.getIssuers()); - paymentMethod.setBrand(checkoutPaymentMethod.getType()); - return paymentMethod; - } -} diff --git a/adyenv6core/src/com/adyen/v6/converters/PaymentsDetailsResponseConverter.java b/adyenv6core/src/com/adyen/v6/converters/PaymentsDetailsResponseConverter.java deleted file mode 100644 index 40f675254..000000000 --- a/adyenv6core/src/com/adyen/v6/converters/PaymentsDetailsResponseConverter.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * ###### - * ###### - * ############ ####( ###### #####. ###### ############ ############ - * ############# #####( ###### #####. ###### ############# ############# - * ###### #####( ###### #####. ###### ##### ###### ##### ###### - * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### - * ###### ###### #####( ###### #####. ###### ##### ##### ###### - * ############# ############# ############# ############# ##### ###### - * ############ ############ ############# ############ ##### ###### - * ###### - * ############# - * ############ - * - * Adyen Hybris Extension - * - * Copyright (c) 2017 Adyen B.V. - * This file is open source and available under the MIT license. - * See the LICENSE file for more info. - */ -package com.adyen.v6.converters; - -import com.adyen.model.checkout.PaymentsDetailsResponse; -import com.adyen.model.checkout.PaymentsResponse; -import org.apache.commons.beanutils.BeanUtils; -import org.springframework.core.convert.converter.Converter; - -import java.lang.reflect.InvocationTargetException; - -public class PaymentsDetailsResponseConverter implements Converter { - @Override - public PaymentsResponse convert(PaymentsDetailsResponse paymentsDetailsResponse) { - if (paymentsDetailsResponse == null) { - throw new IllegalArgumentException("Null PaymentsDetailsResponse"); - } - PaymentsResponse paymentsResponse = new PaymentsResponse(); - - try { - BeanUtils.copyProperties(paymentsResponse, paymentsDetailsResponse); - } catch (IllegalAccessException | InvocationTargetException e) { - throw new RuntimeException("Bean copy error, Cannot convert from PaymentsDetailsResponse to PaymentsResponse", e); - } - return paymentsResponse; - } -} diff --git a/adyenv6core/src/com/adyen/v6/converters/PaymentsResponseConverter.java b/adyenv6core/src/com/adyen/v6/converters/PaymentsResponseConverter.java deleted file mode 100644 index 9e775d5e8..000000000 --- a/adyenv6core/src/com/adyen/v6/converters/PaymentsResponseConverter.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * ###### - * ###### - * ############ ####( ###### #####. ###### ############ ############ - * ############# #####( ###### #####. ###### ############# ############# - * ###### #####( ###### #####. ###### ##### ###### ##### ###### - * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### - * ###### ###### #####( ###### #####. ###### ##### ##### ###### - * ############# ############# ############# ############# ##### ###### - * ############ ############ ############# ############ ##### ###### - * ###### - * ############# - * ############ - * - * Adyen Hybris Extension - * - * Copyright (c) 2017 Adyen B.V. - * This file is open source and available under the MIT license. - * See the LICENSE file for more info. - */ -package com.adyen.v6.converters; - -import org.springframework.core.convert.converter.Converter; -import com.adyen.model.PaymentResult; -import com.adyen.model.checkout.PaymentsResponse; -import static com.adyen.constants.ApiConstants.AdditionalData.AUTH_CODE; - -public class PaymentsResponseConverter implements Converter { - @Override - public PaymentsResponse convert(PaymentResult paymentResult) { - if (paymentResult == null) { - throw new IllegalArgumentException("Null PaymentResult"); - } - PaymentsResponse paymentsResponse = new PaymentsResponse(); - paymentsResponse.setPspReference(paymentResult.getPspReference()); - paymentsResponse.setFraudResult(paymentResult.getFraudResult()); - - paymentsResponse.setAdditionalData(paymentResult.getAdditionalData()); - paymentsResponse.putAdditionalDataItem(AUTH_CODE, paymentResult.getAuthCode()); - - return paymentsResponse; - } -} diff --git a/adyenv6core/src/com/adyen/v6/converters/PosPaymentResponseConverter.java b/adyenv6core/src/com/adyen/v6/converters/PosPaymentResponseConverter.java index ddfd3b089..ca56d01ee 100644 --- a/adyenv6core/src/com/adyen/v6/converters/PosPaymentResponseConverter.java +++ b/adyenv6core/src/com/adyen/v6/converters/PosPaymentResponseConverter.java @@ -20,7 +20,7 @@ */ package com.adyen.v6.converters; -import com.adyen.model.checkout.PaymentsResponse; +import com.adyen.model.checkout.PaymentResponse; import com.adyen.model.nexo.SaleToPOIResponse; import com.google.gson.Gson; import org.apache.commons.lang3.StringUtils; @@ -31,9 +31,9 @@ import java.util.HashMap; import java.util.Map; -public class PosPaymentResponseConverter implements Converter { +public class PosPaymentResponseConverter implements Converter { @Override - public PaymentsResponse convert(SaleToPOIResponse saleToPOIResponse) { + public PaymentResponse convert(SaleToPOIResponse saleToPOIResponse) { String pspReference = null; Map additionalData = null; String additionalResponse = null; @@ -69,7 +69,7 @@ public PaymentsResponse convert(SaleToPOIResponse saleToPOIResponse) { if (additionalResponse != null) { additionalData = parseAdditionalResponse(additionalResponse); } - PaymentsResponse paymentsResponse = new PaymentsResponse(); + PaymentResponse paymentsResponse = new PaymentResponse(); paymentsResponse.setPspReference(pspReference); paymentsResponse.setAdditionalData(additionalData); @@ -84,7 +84,7 @@ private Map parseAdditionalResponse(String additionalResponse) { if (StringUtils.isNotEmpty(additionalResponse)) { String decodedAdditionalResponse = new String(Base64.getDecoder().decode(additionalResponse), StandardCharsets.UTF_8); Gson gson = new Gson(); - additionalData = gson.fromJson(decodedAdditionalResponse, PaymentsResponse.class).getAdditionalData(); + additionalData = gson.fromJson(decodedAdditionalResponse, PaymentResponse.class).getAdditionalData(); } return additionalData; } diff --git a/adyenv6core/src/com/adyen/v6/exceptions/AdyenNonAuthorizedPaymentException.java b/adyenv6core/src/com/adyen/v6/exceptions/AdyenNonAuthorizedPaymentException.java index d10473cef..89f069447 100644 --- a/adyenv6core/src/com/adyen/v6/exceptions/AdyenNonAuthorizedPaymentException.java +++ b/adyenv6core/src/com/adyen/v6/exceptions/AdyenNonAuthorizedPaymentException.java @@ -20,22 +20,22 @@ */ package com.adyen.v6.exceptions; -import com.adyen.model.PaymentResult; -import com.adyen.model.checkout.PaymentsDetailsResponse; -import com.adyen.model.checkout.PaymentsResponse; +import com.adyen.model.checkout.PaymentDetailsResponse; +import com.adyen.model.checkout.PaymentResponse; +import com.adyen.model.payment.PaymentResult; import com.adyen.model.terminal.TerminalAPIResponse; public class AdyenNonAuthorizedPaymentException extends Exception { private PaymentResult paymentResult; - private PaymentsResponse paymentsResponse; + private PaymentResponse paymentsResponse; private TerminalAPIResponse terminalApiResponse; - private PaymentsDetailsResponse paymentsDetailsResponse; + private PaymentDetailsResponse paymentsDetailsResponse; public AdyenNonAuthorizedPaymentException(PaymentResult paymentResult) { this.paymentResult = paymentResult; } - public AdyenNonAuthorizedPaymentException(PaymentsResponse paymentsResponse) { + public AdyenNonAuthorizedPaymentException(PaymentResponse paymentsResponse) { this.paymentsResponse = paymentsResponse; } @@ -43,7 +43,7 @@ public AdyenNonAuthorizedPaymentException(TerminalAPIResponse terminalApiRespons this.terminalApiResponse = terminalApiResponse; } - public AdyenNonAuthorizedPaymentException(PaymentsDetailsResponse paymentsDetailsResponse) { + public AdyenNonAuthorizedPaymentException(PaymentDetailsResponse paymentsDetailsResponse) { this.paymentsDetailsResponse = paymentsDetailsResponse; } @@ -59,11 +59,11 @@ public void setPaymentResult(PaymentResult paymentResult) { this.paymentResult = paymentResult; } - public PaymentsResponse getPaymentsResponse() { + public PaymentResponse getPaymentsResponse() { return paymentsResponse; } - public void setPaymentsResponse(PaymentsResponse paymentsResponse) { + public void setPaymentsResponse(PaymentResponse paymentsResponse) { this.paymentsResponse = paymentsResponse; } @@ -75,11 +75,11 @@ public void setTerminalApiResponse(TerminalAPIResponse terminalApiResponse) { this.terminalApiResponse = terminalApiResponse; } - public PaymentsDetailsResponse getPaymentsDetailsResponse() { + public PaymentDetailsResponse getPaymentsDetailsResponse() { return paymentsDetailsResponse; } - public void setPaymentsDetailsResponse(PaymentsDetailsResponse paymentsDetailsResponse) { + public void setPaymentsDetailsResponse(PaymentDetailsResponse paymentsDetailsResponse) { this.paymentsDetailsResponse = paymentsDetailsResponse; } } diff --git a/adyenv6core/src/com/adyen/v6/facades/AdyenCheckoutFacade.java b/adyenv6core/src/com/adyen/v6/facades/AdyenCheckoutFacade.java index 6149ebbef..683a86b12 100644 --- a/adyenv6core/src/com/adyen/v6/facades/AdyenCheckoutFacade.java +++ b/adyenv6core/src/com/adyen/v6/facades/AdyenCheckoutFacade.java @@ -20,17 +20,17 @@ */ package com.adyen.v6.facades; -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.PaymentsDetailsResponse; -import com.adyen.model.checkout.PaymentsResponse; +import com.adyen.model.checkout.CheckoutPaymentMethod; +import com.adyen.model.checkout.PaymentCompletionDetails; +import com.adyen.model.checkout.PaymentDetailsRequest; +import com.adyen.model.checkout.PaymentDetailsResponse; +import com.adyen.model.checkout.PaymentResponse; import com.adyen.service.exception.ApiException; import com.adyen.v6.controllers.dtos.PaymentResultDTO; import com.adyen.v6.forms.AdyenPaymentForm; import de.hybris.platform.commercefacades.order.data.CartData; import de.hybris.platform.commercefacades.order.data.OrderData; import de.hybris.platform.commercefacades.product.data.ProductData; -import de.hybris.platform.commercefacades.user.data.CountryData; -import de.hybris.platform.commercewebservicescommons.dto.order.PaymentDetailsListWsDTO; import de.hybris.platform.commercewebservicescommons.dto.order.PaymentDetailsWsDTO; import de.hybris.platform.core.model.order.CartModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; @@ -40,10 +40,6 @@ import org.springframework.validation.BindingResult; import javax.servlet.http.HttpServletRequest; -import java.io.IOException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; /** * Adyen Checkout Facade for initiating payments using CC or APM @@ -82,7 +78,7 @@ public interface AdyenCheckoutFacade { * @param details consisting of parameters present in response query string * @return PaymentsResponse */ - PaymentsDetailsResponse handleRedirectPayload(HashMap details) throws Exception; + PaymentDetailsResponse handleRedirectPayload(PaymentCompletionDetails details) throws Exception; /** * Authorizes a payment using Adyen API @@ -103,11 +99,10 @@ public interface AdyenCheckoutFacade { * * @param request HTTP Request info * @param cartData cartData object - * @param paymentMethodDetails paymentMethodDetails object * @return PaymentsResponse * @throws Exception In case payment failed */ - PaymentsResponse componentPayment(HttpServletRequest request, CartData cartData, PaymentMethodDetails paymentMethodDetails) throws Exception; + PaymentResponse componentPayment(HttpServletRequest request, CartData cartData, CheckoutPaymentMethod checkoutPaymentMethod) throws Exception; /** * Submit details from a payment made on an Adyen Checkout Component @@ -119,13 +114,14 @@ public interface AdyenCheckoutFacade { * @return PaymentsResponse * @throws Exception In case request failed */ - PaymentsDetailsResponse componentDetails(HttpServletRequest request, Map details, String paymentData) throws Exception; + PaymentDetailsResponse componentDetails(PaymentDetailsRequest detailsRequest) throws Exception; /** * Add payment details to cart */ PaymentDetailsWsDTO addPaymentDetails(PaymentDetailsWsDTO paymentDetails); + /** * Handles an 3D response * In case of authorized, it places an order from cart @@ -135,7 +131,7 @@ public interface AdyenCheckoutFacade { * @throws Exception In case order failed to be created */ - OrderData handle3DSResponse(Map details) throws Exception; + OrderData handle3DSResponse(PaymentDetailsRequest paymentDetailsRequest) throws Exception; /** * Retrieve available payment methods @@ -183,10 +179,6 @@ public interface AdyenCheckoutFacade { */ void handlePaymentForm(AdyenPaymentForm adyenPaymentForm, BindingResult bindingResult); - List getBillingCountries(); - - PaymentDetailsListWsDTO getPaymentDetails(String userId) throws IOException, ApiException; - /** * Initiate POS Payment using Adyen Terminal API */ @@ -206,7 +198,7 @@ public interface AdyenCheckoutFacade { * Handles payment result from component * Validates the result and updates the cart based on it */ - OrderData handleComponentResult(String resultJson) throws Exception; + OrderData handleComponentResult(String resultCode, String merchantReference) throws Exception; void restoreCartFromOrderCodeInSession() throws InvalidCartException, CalculationException; diff --git a/adyenv6core/src/com/adyen/v6/facades/AdyenExpressCheckoutFacade.java b/adyenv6core/src/com/adyen/v6/facades/AdyenExpressCheckoutFacade.java index b86af609b..b1373d8b4 100644 --- a/adyenv6core/src/com/adyen/v6/facades/AdyenExpressCheckoutFacade.java +++ b/adyenv6core/src/com/adyen/v6/facades/AdyenExpressCheckoutFacade.java @@ -1,6 +1,6 @@ package com.adyen.v6.facades; -import com.adyen.model.checkout.PaymentsResponse; +import com.adyen.model.checkout.PaymentResponse; import de.hybris.platform.commercefacades.user.data.AddressData; import de.hybris.platform.deliveryzone.model.ZoneDeliveryModeValueModel; import de.hybris.platform.order.exceptions.CalculationException; @@ -10,10 +10,10 @@ public interface AdyenExpressCheckoutFacade { - PaymentsResponse expressPDPCheckout(AddressData addressData, String productCode, String merchantId, String merchantName, + PaymentResponse expressPDPCheckout(AddressData addressData, String productCode, String merchantId, String merchantName, String applePayToken, HttpServletRequest request) throws Exception; - PaymentsResponse expressCartCheckout(AddressData addressData, String merchantId, String merchantName, + PaymentResponse expressCartCheckout(AddressData addressData, String merchantId, String merchantName, String applePayToken, HttpServletRequest request) throws Exception; Optional getExpressDeliveryModePrice(); diff --git a/adyenv6core/src/com/adyen/v6/facades/impl/Amount.java b/adyenv6core/src/com/adyen/v6/facades/impl/Amount.java deleted file mode 100644 index 17d6c0fd2..000000000 --- a/adyenv6core/src/com/adyen/v6/facades/impl/Amount.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.adyen.v6.facades.impl; - -public class Amount { - - private Long value; - private String currency; - - public Amount(){ - - } - - public Amount(Long value, String currency) { - this.value = value; - this.currency = currency; - } - - public Long getValue() { - return value; - } - - public void setValue(Long value) { - this.value = value; - } - - public String getCurrency() { - return currency; - } - - public void setCurrency(String currency) { - this.currency = currency; - } -} diff --git a/adyenv6core/src/com/adyen/v6/facades/impl/DefaultAdyenCheckoutFacade.java b/adyenv6core/src/com/adyen/v6/facades/impl/DefaultAdyenCheckoutFacade.java index a1dabb265..be6f50424 100644 --- a/adyenv6core/src/com/adyen/v6/facades/impl/DefaultAdyenCheckoutFacade.java +++ b/adyenv6core/src/com/adyen/v6/facades/impl/DefaultAdyenCheckoutFacade.java @@ -20,23 +20,25 @@ */ package com.adyen.v6.facades.impl; -import com.adyen.model.Amount; -import com.adyen.model.Card; -import com.adyen.model.PaymentResult; -import com.adyen.model.checkout.*; -import com.adyen.model.checkout.CheckoutPaymentsAction.CheckoutActionType; + +import com.adyen.model.checkout.Amount; +import com.adyen.model.checkout.CheckoutPaymentMethod; +import com.adyen.model.checkout.CreateCheckoutSessionResponse; +import com.adyen.model.checkout.PaymentCompletionDetails; +import com.adyen.model.checkout.PaymentDetailsRequest; +import com.adyen.model.checkout.PaymentDetailsResponse; +import com.adyen.model.checkout.PaymentMethod; +import com.adyen.model.checkout.PaymentMethodsResponse; +import com.adyen.model.checkout.PaymentResponse; +import com.adyen.model.checkout.PaymentResponseAction; +import com.adyen.model.checkout.StoredPaymentMethod; import com.adyen.model.nexo.ErrorConditionType; import com.adyen.model.nexo.ResultType; import com.adyen.model.recurring.Recurring; -import com.adyen.model.recurring.RecurringDetail; import com.adyen.model.terminal.TerminalAPIResponse; import com.adyen.service.exception.ApiException; -import com.adyen.util.DateUtil; -import com.adyen.util.Util; import com.adyen.v6.constants.Adyenv6coreConstants; import com.adyen.v6.controllers.dtos.PaymentResultDTO; -import com.adyen.v6.converters.PaymentsDetailsResponseConverter; -import com.adyen.v6.converters.PaymentsResponseConverter; import com.adyen.v6.converters.PosPaymentResponseConverter; import com.adyen.v6.enums.AdyenCardTypeEnum; import com.adyen.v6.enums.AdyenRegions; @@ -51,16 +53,14 @@ import com.adyen.v6.model.RequestInfo; import com.adyen.v6.repository.OrderRepository; import com.adyen.v6.service.AdyenBusinessProcessService; +import com.adyen.v6.service.AdyenCheckoutApiService; import com.adyen.v6.service.AdyenOrderService; -import com.adyen.v6.service.AdyenPaymentService; import com.adyen.v6.service.AdyenTransactionService; +import com.adyen.v6.util.AmountUtil; import com.adyen.v6.util.TerminalAPIUtil; import com.fasterxml.jackson.core.JsonProcessingException; import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.reflect.TypeToken; import de.hybris.platform.commercefacades.i18n.I18NFacade; -import de.hybris.platform.commercefacades.i18n.comparators.CountryComparator; import de.hybris.platform.commercefacades.order.CheckoutFacade; import de.hybris.platform.commercefacades.order.OrderFacade; import de.hybris.platform.commercefacades.order.data.CartData; @@ -70,7 +70,6 @@ import de.hybris.platform.commercefacades.user.data.CountryData; import de.hybris.platform.commercefacades.user.data.RegionData; import de.hybris.platform.commerceservices.strategies.CheckoutCustomerStrategy; -import de.hybris.platform.commercewebservicescommons.dto.order.PaymentDetailsListWsDTO; import de.hybris.platform.commercewebservicescommons.dto.order.PaymentDetailsWsDTO; import de.hybris.platform.converters.Populator; import de.hybris.platform.core.enums.OrderStatus; @@ -111,14 +110,34 @@ import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.math.BigDecimal; -import java.util.*; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static com.adyen.constants.ApiConstants.ThreeDS2Property.THREEDS2_CHALLENGE_TOKEN; import static com.adyen.constants.ApiConstants.ThreeDS2Property.THREEDS2_FINGERPRINT_TOKEN; -import static com.adyen.constants.HPPConstants.Response.SHOPPER_LOCALE; -import static com.adyen.v6.constants.Adyenv6coreConstants.*; +import static com.adyen.v6.constants.Adyenv6coreConstants.ISSUER_PAYMENT_METHODS; +import static com.adyen.v6.constants.Adyenv6coreConstants.OPENINVOICE_METHODS_ALLOW_SOCIAL_SECURITY_NUMBER; +import static com.adyen.v6.constants.Adyenv6coreConstants.OPENINVOICE_METHODS_API; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYBRIGHT; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHODS_ALLOW_SOCIAL_SECURITY_NUMBER; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_AMAZONPAY; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_APPLEPAY; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_KLARNA; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_ONLINEBANKING_IN; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_ONLINEBANKING_PL; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_SCHEME; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_SEPA_DIRECTDEBIT; +import static com.adyen.v6.constants.Adyenv6coreConstants.SHOPPER_LOCALE; import static de.hybris.platform.order.impl.DefaultCartService.SESSION_CART_PARAMETER_NAME; /** @@ -152,8 +171,6 @@ public class DefaultAdyenCheckoutFacade implements AdyenCheckoutFacade { private ModelService modelService; private CommonI18NService commonI18NService; private KeyGenerator keyGenerator; - private PaymentsResponseConverter paymentsResponseConverter; - private PaymentsDetailsResponseConverter paymentsDetailsResponseConverter; private FlexibleSearchService flexibleSearchService; private Converter addressReverseConverter; private PosPaymentResponseConverter posPaymentResponseConverter; @@ -339,8 +356,8 @@ private AddressModel createBillingAddress(PaymentDetailsWsDTO paymentDetails) { } @Override - public PaymentsDetailsResponse handleRedirectPayload(HashMap details) throws Exception { - PaymentsDetailsResponse response; + public PaymentDetailsResponse handleRedirectPayload(PaymentCompletionDetails details) throws Exception { + PaymentDetailsResponse response; try { response = getAdyenPaymentService().getPaymentDetailsFromPayload(details); } catch (Exception e) { @@ -351,31 +368,29 @@ public PaymentsDetailsResponse handleRedirectPayload(HashMap det String orderCode = response.getMerchantReference(); OrderModel orderModel = retrievePendingOrder(orderCode); - PaymentsResponse paymentsResponse = getPaymentsDetailsResponseConverter().convert(response); - updateOrderPaymentStatusAndInfo(orderModel, paymentsResponse); + updateOrderPaymentStatusAndInfo(orderModel, response); - if (PaymentsResponse.ResultCodeEnum.AUTHORISED != response.getResultCode() - && PaymentsResponse.ResultCodeEnum.RECEIVED != response.getResultCode()) { + if (PaymentDetailsResponse.ResultCodeEnum.AUTHORISED.equals(response.getResultCode()) + && PaymentDetailsResponse.ResultCodeEnum.RECEIVED.equals(response.getResultCode())) { restoreCartFromOrder(orderCode); } return response; } - private void updateOrderPaymentStatusAndInfo(OrderModel orderModel, PaymentsResponse paymentsResponse) { - PaymentsResponse.ResultCodeEnum resultCode = paymentsResponse.getResultCode(); + private void updateOrderPaymentStatusAndInfo(OrderModel orderModel, PaymentDetailsResponse paymentDetailsResponse) { - if (PaymentsResponse.ResultCodeEnum.RECEIVED != resultCode) { + if (PaymentDetailsResponse.ResultCodeEnum.RECEIVED != paymentDetailsResponse.getResultCode()) { //payment authorisation is finished, update payment info LOGGER.debug("payment authorisation is finished, updating payment info"); getAdyenTransactionService().createPaymentTransactionFromResultCode(orderModel, orderModel.getCode(), - paymentsResponse.getPspReference(), - paymentsResponse.getResultCode()); + paymentDetailsResponse.getPspReference(), + paymentDetailsResponse.getResultCode()); } - if (PaymentsResponse.ResultCodeEnum.AUTHORISED == resultCode || PaymentsResponse.ResultCodeEnum.RECEIVED == resultCode) { + if (PaymentDetailsResponse.ResultCodeEnum.AUTHORISED == paymentDetailsResponse.getResultCode() || PaymentDetailsResponse.ResultCodeEnum.RECEIVED == paymentDetailsResponse.getResultCode()) { //remove PAYMENT_PENDING status, will be processed by order management LOGGER.info("Removing PAYMENT_PENDING status, will be processed by order management"); @@ -386,12 +401,20 @@ private void updateOrderPaymentStatusAndInfo(OrderModel orderModel, PaymentsResp LOGGER.warn("Payment was not authorised, cancel pending order"); orderModel.setStatus(OrderStatus.CANCELLED); - orderModel.setStatusInfo(paymentsResponse.getPspReference() + " - " + paymentsResponse.getResultCode().getValue()); + orderModel.setStatusInfo(paymentDetailsResponse.getPspReference() + " - " + paymentDetailsResponse.getResultCode().getValue()); } getModelService().save(orderModel); getAdyenBusinessProcessService().triggerOrderProcessEvent(orderModel, Adyenv6coreConstants.PROCESS_EVENT_ADYEN_PAYMENT_RESULT); - getAdyenOrderService().updateOrderFromPaymentsResponse(orderModel, paymentsResponse); + String paymentType = ""; + if (paymentDetailsResponse.getPaymentMethod() != null) { + paymentType = paymentDetailsResponse.getPaymentMethod().getType(); + } + + Map additionalData = paymentDetailsResponse.getAdditionalData(); + + getAdyenOrderService().updatePaymentInfo(orderModel, paymentType, additionalData); + getAdyenOrderService().storeFraudReport(orderModel, paymentDetailsResponse.getPspReference(), paymentDetailsResponse.getFraudResult()); } @Override @@ -406,86 +429,74 @@ public OrderData authorisePayment(final HttpServletRequest request, final CartDa RequestInfo requestInfo = new RequestInfo(request); requestInfo.setShopperLocale(getShopperLocale()); - PaymentsResponse paymentsResponse = getAdyenPaymentService().authorisePayment(cartData, requestInfo, customer); - PaymentsResponse.ResultCodeEnum resultCode = paymentsResponse.getResultCode(); - CheckoutPaymentsAction action = paymentsResponse.getAction(); + PaymentResponse paymentResponse = getAdyenPaymentService().authorisePayment(cartData, requestInfo, customer); + PaymentResponse.ResultCodeEnum resultCode = paymentResponse.getResultCode(); + PaymentResponseAction action = paymentResponse.getAction(); - LOGGER.info("Authorize payment with result code: " + resultCode + " action: " + (action != null ? action.getType() : "null")); - if (PaymentsResponse.ResultCodeEnum.AUTHORISED == resultCode || PaymentsResponse.ResultCodeEnum.PENDING == resultCode) { - return createAuthorizedOrder(paymentsResponse); + LOGGER.info("Authorize payment with result code: " + resultCode + " action: " + (action != null ? action.getSchemaType() : "null")); + + if (PaymentResponse.ResultCodeEnum.AUTHORISED == resultCode || PaymentResponse.ResultCodeEnum.PENDING == resultCode) { + return createAuthorizedOrder(paymentResponse); } - if (PaymentsResponse.ResultCodeEnum.RECEIVED == resultCode) { - return createOrderFromPaymentsResponse(paymentsResponse); + if (PaymentResponse.ResultCodeEnum.RECEIVED == resultCode) { + return createOrderFromPaymentResponse(paymentResponse); } - if (PaymentsResponse.ResultCodeEnum.PRESENTTOSHOPPER == resultCode) { - return createOrderFromPaymentsResponse(paymentsResponse); + if (PaymentResponse.ResultCodeEnum.PRESENTTOSHOPPER == resultCode) { + return createOrderFromPaymentResponse(paymentResponse); } - if (PaymentsResponse.ResultCodeEnum.REDIRECTSHOPPER == resultCode) { + if (PaymentResponse.ResultCodeEnum.REDIRECTSHOPPER == resultCode) { placePendingOrder(resultCode); if (adyenPaymentMethod.startsWith(PAYMENT_METHOD_KLARNA)) { getSessionService().setAttribute(PAYMENT_METHOD, adyenPaymentMethod); } - } else if (action != null && CheckoutActionType.THREEDS2.equals(action.getType())) { - placePendingOrder(resultCode); } - throw new AdyenNonAuthorizedPaymentException(paymentsResponse); - } - - private boolean isGuestUserTokenizationEnabled() { - Boolean guestCheckoutFlag = baseStoreService.getCurrentBaseStore().getAdyenGuestUserTokenization(); - if (guestCheckoutFlag == null) { - return false; - } else { - return guestCheckoutFlag; - } + throw new AdyenNonAuthorizedPaymentException(paymentResponse); } @Override public OrderData handleResultcomponentPayment(final PaymentResultDTO paymentResultDTO) throws Exception { - if (PaymentsResponse.ResultCodeEnum.PENDING.getValue().equals(paymentResultDTO.getResultCode()) || - PaymentsResponse.ResultCodeEnum.REDIRECTSHOPPER.getValue().equals(paymentResultDTO.getResultCode())) { + if (PaymentResponse.ResultCodeEnum.PENDING.getValue().equals(paymentResultDTO.getResultCode()) || + PaymentResponse.ResultCodeEnum.REDIRECTSHOPPER.getValue().equals(paymentResultDTO.getResultCode())) { LOGGER.info("Placing pending order"); - return placePendingOrder(PaymentsResponse.ResultCodeEnum.fromValue(paymentResultDTO.getResultCode())); + return placePendingOrder(PaymentResponse.ResultCodeEnum.fromValue(paymentResultDTO.getResultCode())); } - if (PaymentsResponse.ResultCodeEnum.AUTHORISED.getValue().equals(paymentResultDTO.getResultCode())) { + if (PaymentResponse.ResultCodeEnum.AUTHORISED.getValue().equals(paymentResultDTO.getResultCode())) { LOGGER.info("Placing authorized order"); - return placeAuthorisedOrder(PaymentsResponse.ResultCodeEnum.AUTHORISED); + return placeAuthorisedOrder(PaymentResponse.ResultCodeEnum.AUTHORISED); } return null; } @Override - public PaymentsResponse componentPayment(final HttpServletRequest request, final CartData cartData, final PaymentMethodDetails paymentMethodDetails) throws Exception { + public PaymentResponse componentPayment(final HttpServletRequest request, final CartData cartData, CheckoutPaymentMethod checkoutPaymentMethod) throws Exception { updateCartWithSessionData(cartData); RequestInfo requestInfo = new RequestInfo(request); requestInfo.setShopperLocale(getShopperLocale()); - PaymentsResponse paymentsResponse = getAdyenPaymentService().componentPayment(cartData, paymentMethodDetails, requestInfo, getCheckoutCustomerStrategy().getCurrentUserForCheckout()); - if (PaymentsResponse.ResultCodeEnum.PENDING == paymentsResponse.getResultCode() || PaymentsResponse.ResultCodeEnum.REDIRECTSHOPPER == paymentsResponse.getResultCode()) { + PaymentResponse paymentResponse = getAdyenPaymentService().componentPayment(cartData, checkoutPaymentMethod, requestInfo, getCheckoutCustomerStrategy().getCurrentUserForCheckout()); + if (PaymentResponse.ResultCodeEnum.PENDING == paymentResponse.getResultCode() || PaymentResponse.ResultCodeEnum.REDIRECTSHOPPER == paymentResponse.getResultCode()) { LOGGER.info("Placing pending order"); - placePendingOrder(paymentsResponse.getResultCode()); - return paymentsResponse; + placePendingOrder(paymentResponse.getResultCode()); + return paymentResponse; } - if (PaymentsResponse.ResultCodeEnum.AUTHORISED == paymentsResponse.getResultCode()) { + if (PaymentResponse.ResultCodeEnum.AUTHORISED == paymentResponse.getResultCode()) { LOGGER.info("Creating authorized order"); - createAuthorizedOrder(paymentsResponse); - return paymentsResponse; + createAuthorizedOrder(paymentResponse); + return paymentResponse; } - throw new AdyenNonAuthorizedPaymentException(paymentsResponse); + throw new AdyenNonAuthorizedPaymentException(paymentResponse); } @Override - public PaymentsDetailsResponse componentDetails(final HttpServletRequest request, final Map details, final String paymentData) throws Exception { - PaymentsDetailsResponse response = getAdyenPaymentService().getPaymentDetailsFromPayload(details, paymentData); - PaymentsResponse paymentsResponse = getPaymentsDetailsResponseConverter().convert(response); - + public PaymentDetailsResponse componentDetails(PaymentDetailsRequest detailsRequest) throws Exception { + PaymentDetailsResponse response = getAdyenPaymentService().getPaymentDetailsFromPayload(detailsRequest); String orderCode = response.getMerchantReference(); OrderModel orderModel = retrievePendingOrder(orderCode); - updateOrderPaymentStatusAndInfo(orderModel, paymentsResponse); + updateOrderPaymentStatusAndInfo(orderModel, response); return response; } @@ -508,10 +519,10 @@ private void updateCartWithSessionData(CartData cartData) { } @Override - public OrderData handle3DSResponse(final Map details) throws Exception { - PaymentsDetailsResponse paymentsDetailsResponse; + public OrderData handle3DSResponse(PaymentDetailsRequest paymentsDetailsRequest) throws Exception { + PaymentDetailsResponse paymentsDetailsResponse; try { - paymentsDetailsResponse = getAdyenPaymentService().authorise3DSPayment(details); + paymentsDetailsResponse = getAdyenPaymentService().authorise3DSPayment(paymentsDetailsRequest); } catch (Exception e) { LOGGER.error(e instanceof ApiException ? e.toString() : e.getMessage()); restoreCartFromOrderCodeInSession(); @@ -520,11 +531,11 @@ public OrderData handle3DSResponse(final Map details) throws Exc String orderCode = paymentsDetailsResponse.getMerchantReference(); OrderModel orderModel = retrievePendingOrder(orderCode); - updateOrderPaymentStatusAndInfo(orderModel, getPaymentsDetailsResponseConverter().convert(paymentsDetailsResponse)); + updateOrderPaymentStatusAndInfo(orderModel, paymentsDetailsResponse); - PaymentsResponse.ResultCodeEnum resultCode = paymentsDetailsResponse.getResultCode(); + PaymentDetailsResponse.ResultCodeEnum resultCode = paymentsDetailsResponse.getResultCode(); - if (PaymentsResponse.ResultCodeEnum.AUTHORISED == resultCode) { + if (PaymentDetailsResponse.ResultCodeEnum.AUTHORISED.equals(resultCode)) { return getOrderConverter().convert(orderModel); } @@ -535,7 +546,7 @@ public OrderData handle3DSResponse(final Map details) throws Exc /** * Create order and authorized TX */ - private OrderData createAuthorizedOrder(final PaymentsResponse paymentsResponse) throws InvalidCartException { + private OrderData createAuthorizedOrder(final PaymentResponse paymentsResponse) throws InvalidCartException { final CartModel cartModel = cartService.getSessionCart(); final String merchantTransactionCode = cartModel.getCode(); @@ -544,10 +555,10 @@ private OrderData createAuthorizedOrder(final PaymentsResponse paymentsResponse) // First save the transactions to the CartModel < AbstractOrderModel getAdyenTransactionService().authorizeOrderModel(cartModel, merchantTransactionCode, paymentsResponse.getPspReference()); - return createOrderFromPaymentsResponse(paymentsResponse); + return createOrderFromPaymentResponse(paymentsResponse); } - private void updateAdyenSelectedReferenceIfPresent(final CartModel cartModel, final PaymentsResponse paymentsResponse) { + private void updateAdyenSelectedReferenceIfPresent(final CartModel cartModel, final PaymentResponse paymentsResponse) { Map additionalData = paymentsResponse.getAdditionalData(); if (additionalData != null) { String recurringDetailReference = additionalData.get(RECURRING_RECURRING_DETAIL_REFERENCE); @@ -557,18 +568,10 @@ private void updateAdyenSelectedReferenceIfPresent(final CartModel cartModel, fi } } - /** - * Create order and authorized TX - */ - private OrderData createAuthorizedOrder(final PaymentResult paymentResult) throws InvalidCartException { - PaymentsResponse paymentsResponse = paymentsResponseConverter.convert(paymentResult); - return createAuthorizedOrder(paymentsResponse); - } - /** * Create order */ - private OrderData createOrderFromPaymentsResponse(final PaymentsResponse paymentsResponse) throws InvalidCartException { + private OrderData createOrderFromPaymentResponse(final PaymentResponse paymentsResponse) throws InvalidCartException { LOGGER.debug("Create order from paymentsResponse: " + paymentsResponse.getPspReference()); OrderData orderData = getCheckoutFacade().placeOrder(); @@ -577,35 +580,20 @@ private OrderData createOrderFromPaymentsResponse(final PaymentsResponse payment throw new InvalidCartException("Order does not exist!"); } OrderModel orderModel = orderRepository.getOrderModel(orderData.getCode()); - getAdyenOrderService().updateOrderFromPaymentsResponse(orderModel, paymentsResponse); - return fillOrderDataWithPaymentInfo(orderData, paymentsResponse); - } - - private OrderData fillOrderDataWithPaymentInfo(OrderData orderData, PaymentsResponse paymentsResponse) { - - CheckoutPaymentsAction action = paymentsResponse.getAction(); - if (action != null) { - if (PAYMENT_METHOD_MULTIBANCO.equals(action.getPaymentMethodType())) { - orderData.setAdyenMultibancoEntity(action.getEntity()); - orderData.setAdyenMultibancoAmount(BigDecimal.valueOf(action.getInitialAmount().getValue())); - orderData.setAdyenMultibancoDeadline(action.getExpiresAt()); - orderData.setAdyenMultibancoReference(action.getReference()); - } else if (PAYMENT_METHOD_BOLETO.equals(action.getPaymentMethodType()) || PAYMENT_METHOD_BOLETO_SANTANDER.equals(action.getPaymentMethodType())) { - orderData.setAdyenBoletoUrl(action.getDownloadUrl()); - orderData.setAdyenBoletoBarCodeReference(action.getReference()); - orderData.setAdyenBoletoExpirationDate(DateUtil.parseYmdDate(action.getExpiresAt())); - } + String paymentType = ""; + if (paymentsResponse.getPaymentMethod() != null) { + paymentType = paymentsResponse.getPaymentMethod().getType(); } - if (paymentsResponse.getAdditionalData() != null) { - orderData.setAdyenPosReceipt(paymentsResponse.getAdditionalData().get("pos.receipt")); - } + Map additionalData = paymentsResponse.getAdditionalData(); + getAdyenOrderService().updatePaymentInfo(orderModel, paymentType, additionalData); + getAdyenOrderService().storeFraudReport(orderModel, paymentsResponse.getPspReference(), paymentsResponse.getFraudResult()); return orderData; } - private OrderData placePendingOrder(PaymentsResponse.ResultCodeEnum resultCode) throws InvalidCartException { + private OrderData placePendingOrder(PaymentResponse.ResultCodeEnum resultCode) throws InvalidCartException { CartModel cartModel = getCartService().getSessionCart(); cartModel.setStatus(OrderStatus.PAYMENT_PENDING); cartModel.setStatusInfo(resultCode.getValue()); @@ -622,7 +610,7 @@ private OrderData placePendingOrder(PaymentsResponse.ResultCodeEnum resultCode) return orderData; } - private OrderData placeAuthorisedOrder(PaymentsResponse.ResultCodeEnum resultCode) throws InvalidCartException { + private OrderData placeAuthorisedOrder(PaymentResponse.ResultCodeEnum resultCode) throws InvalidCartException { CartModel cartModel = getCartService().getSessionCart(); cartModel.setStatus(OrderStatus.PAYMENT_AUTHORIZED); cartModel.setStatusInfo(resultCode.getValue()); @@ -639,19 +627,10 @@ private OrderData placeAuthorisedOrder(PaymentsResponse.ResultCodeEnum resultCod return orderData; } - - /** - * Create order - */ - private OrderData createOrderFromPaymentResult(final PaymentResult paymentResult) throws InvalidCartException { - PaymentsResponse paymentsResponse = paymentsResponseConverter.convert(paymentResult); - return createOrderFromPaymentsResponse(paymentsResponse); - } - @Override public void initializeCheckoutData(Model model) throws ApiException { final CartData cartData = getCheckoutFacade().getCheckoutCart(); - AdyenPaymentService adyenPaymentService = getAdyenPaymentService(); + AdyenCheckoutApiService adyenCheckoutApiService = getAdyenPaymentService(); List alternativePaymentMethods; List connectedTerminalList = null; List storedPaymentMethodList = null; @@ -663,10 +642,10 @@ public void initializeCheckoutData(Model model) throws ApiException { try { if (showPos()) { - connectedTerminalList = adyenPaymentService.getConnectedTerminals().getUniqueTerminalIds(); + connectedTerminalList = adyenCheckoutApiService.getConnectedTerminals().getUniqueTerminalIds(); } - response = adyenPaymentService.getPaymentMethodsResponse(cartData.getTotalPriceWithTax().getValue(), + response = adyenCheckoutApiService.getPaymentMethodsResponse(cartData.getTotalPriceWithTax().getValue(), cartData.getTotalPriceWithTax().getCurrencyIso(), cartData.getDeliveryAddress().getCountry().getIsocode(), getShopperLocale(), @@ -748,7 +727,7 @@ public void initializeCheckoutData(Model model) throws ApiException { cartModel.setAdyenStoredCards(recurringDetailReferences); } - Amount amount = Util.createAmount(cartData.getTotalPriceWithTax().getValue(), cartData.getTotalPriceWithTax().getCurrencyIso()); + Amount amount = AmountUtil.createAmount(cartData.getTotalPriceWithTax().getValue().longValue(), cartData.getTotalPriceWithTax().getCurrencyIso()); model.addAttribute(SESSION_DATA, getAdyenSessionData()); @@ -764,10 +743,10 @@ public void initializeCheckoutData(Model model) throws ApiException { model.addAttribute(MODEL_REMEMBER_DETAILS, showRememberDetails()); model.addAttribute(MODEL_STORED_CARDS, storedPaymentMethodList); - model.addAttribute(MODEL_DF_URL, adyenPaymentService.getDeviceFingerprintUrl()); + model.addAttribute(MODEL_DF_URL, adyenCheckoutApiService.getDeviceFingerprintUrl()); model.addAttribute(MODEL_CHECKOUT_SHOPPER_HOST, getCheckoutShopperHost()); model.addAttribute(MODEL_ENVIRONMENT_MODE, getEnvironmentMode()); - model.addAttribute(SHOPPER_LOCALE, getShopperLocale()); + //model.addAttribute(SHOPPER_LOCALE, getShopperLocale()); // OpenInvoice Methods model.addAttribute(MODEL_OPEN_INVOICE_METHODS, OPENINVOICE_METHODS_API); @@ -841,10 +820,10 @@ private CreateCheckoutSessionResponse getAdyenSessionData(Amount amount) throws @Override public void initializeSummaryData(Model model) throws ApiException { final CartData cartData = getCheckoutFacade().getCheckoutCart(); - final AdyenPaymentService adyenPaymentService = getAdyenPaymentService(); + final AdyenCheckoutApiService adyenCheckoutApiService = getAdyenPaymentService(); final BaseStoreModel baseStore = baseStoreService.getCurrentBaseStore(); - final Amount amount = Util.createAmount(cartData.getTotalPriceWithTax().getValue(), cartData.getTotalPriceWithTax().getCurrencyIso()); + final Amount amount = AmountUtil.createAmount(cartData.getTotalPriceWithTax().getValue().longValue(), cartData.getTotalPriceWithTax().getCurrencyIso()); final Gson gson = new Gson(); final String shopperLocale = getShopperLocale(); final String countryCode = Objects.nonNull(cartData.getDeliveryAddress()) && @@ -852,7 +831,7 @@ public void initializeSummaryData(Model model) throws ApiException { cartData.getDeliveryAddress().getCountry().getIsocode() : null; model.addAttribute(MODEL_SELECTED_PAYMENT_METHOD, cartData.getAdyenPaymentMethod()); - model.addAttribute(MODEL_DF_URL, adyenPaymentService.getDeviceFingerprintUrl()); + model.addAttribute(MODEL_DF_URL, adyenCheckoutApiService.getDeviceFingerprintUrl()); model.addAttribute(MODEL_CHECKOUT_SHOPPER_HOST, getCheckoutShopperHost()); model.addAttribute(MODEL_ENVIRONMENT_MODE, getEnvironmentMode()); model.addAttribute(SHOPPER_LOCALE, shopperLocale); @@ -915,7 +894,7 @@ private void initializeApplePayExpressDataInternal(BigDecimal amountValue, Strin LOGGER.error("Payment methods request failed", e); } - final Amount amount = Util.createAmount(amountValue, currency); + final Amount amount = AmountUtil.createAmount(amountValue.longValue(), currency); model.addAttribute(SHOPPER_LOCALE, getShopperLocale()); model.addAttribute(MODEL_ENVIRONMENT_MODE, getEnvironmentMode()); @@ -1035,7 +1014,7 @@ public boolean showRememberDetails() { */ RecurringContractMode recurringContractMode = baseStore.getAdyenRecurringContractMode(); if (!getCheckoutCustomerStrategy().isAnonymousCheckout()) { - if (Recurring.ContractEnum.ONECLICK_RECURRING.name().equals(recurringContractMode.getCode()) || Recurring.ContractEnum.ONECLICK.name().equals(recurringContractMode.getCode())) { + if (Recurring.ContractEnum.RECURRING.name().equals(recurringContractMode.getCode()) || Recurring.ContractEnum.ONECLICK.name().equals(recurringContractMode.getCode())) { return true; } } @@ -1200,13 +1179,6 @@ public void handlePaymentForm(AdyenPaymentForm adyenPaymentForm, BindingResult b }); } - @Override - public List getBillingCountries() { - final List countries = getCountryConverter().convertAll(getCommonI18NService().getAllCountries()); - Collections.sort(countries, CountryComparator.INSTANCE); - return countries; - } - public AddressModel convertToAddressModel(final AddressForm addressForm) { final AddressData addressData = new AddressData(); final CountryData countryData = getI18NFacade().getCountryForIsocode(addressForm.getCountryIsoCode()); @@ -1231,40 +1203,6 @@ public AddressModel convertToAddressModel(final AddressForm addressForm) { return billingAddress; } - @Override - public PaymentDetailsListWsDTO getPaymentDetails(String userId) throws IOException, ApiException { - CustomerModel customer = getCheckoutCustomerStrategy().getCurrentUserForCheckout(); - - List recurringDetails = getAdyenPaymentService().getStoredCards(customer.getCustomerID()); - - PaymentDetailsListWsDTO paymentDetailsListWsDTO = new PaymentDetailsListWsDTO(); - paymentDetailsListWsDTO.setPayments(toPaymentDetails(recurringDetails)); - - return paymentDetailsListWsDTO; - } - - private List toPaymentDetails(List recurringDetails) { - return recurringDetails.stream().map(r -> toPaymentDetail(r)).collect(Collectors.toList()); - } - - private PaymentDetailsWsDTO toPaymentDetail(RecurringDetail recurringDetail) { - PaymentDetailsWsDTO paymentDetailsWsDTO = new PaymentDetailsWsDTO(); - - Card card = recurringDetail.getCard(); - - if (card == null) { - throw new RuntimeException("Card information not found"); - } - - paymentDetailsWsDTO.setAccountHolderName(card.getHolderName()); - paymentDetailsWsDTO.setCardNumber("**** **** **** " + card.getNumber()); - paymentDetailsWsDTO.setExpiryMonth(card.getExpiryMonth()); - paymentDetailsWsDTO.setExpiryYear(card.getExpiryYear()); - paymentDetailsWsDTO.setSubscriptionId(recurringDetail.getRecurringDetailReference()); - - return paymentDetailsWsDTO; - } - @Override public String getShopperLocale() { if (commonI18NService.getCurrentLanguage() != null) { @@ -1278,8 +1216,8 @@ protected String generateCcPaymentInfoCode(final CartModel cartModel) { return cartModel.getCode() + "_" + UUID.randomUUID(); } - public AdyenPaymentService getAdyenPaymentService() { - return adyenPaymentServiceFactory.createFromBaseStore(baseStoreService.getCurrentBaseStore()); + public AdyenCheckoutApiService getAdyenPaymentService() { + return adyenPaymentServiceFactory.createAdyenCheckoutApiService(baseStoreService.getCurrentBaseStore()); } /** @@ -1298,7 +1236,7 @@ public OrderData initiatePosPayment(HttpServletRequest request, CartData cartDat ResultType resultType = TerminalAPIUtil.getPaymentResultFromStatusOrPaymentResponse(terminalApiResponse); if (ResultType.SUCCESS == resultType) { - PaymentsResponse paymentsResponse = getPosPaymentResponseConverter().convert(terminalApiResponse.getSaleToPOIResponse()); + PaymentResponse paymentsResponse = getPosPaymentResponseConverter().convert(terminalApiResponse.getSaleToPOIResponse()); String posReceipt = TerminalAPIUtil.getReceiptFromPaymentResponse(terminalApiResponse); if (StringUtils.isNotEmpty(posReceipt)) { paymentsResponse.putAdditionalDataItem("pos.receipt", posReceipt); @@ -1323,7 +1261,7 @@ public OrderData checkPosPaymentStatus(HttpServletRequest request, CartData cart //this will be success even if payment is failed. because this belongs to status call not payment call ResultType paymentResult = TerminalAPIUtil.getPaymentResultFromStatusOrPaymentResponse(terminalApiResponse); if (paymentResult == ResultType.SUCCESS) { - PaymentsResponse paymentsResponse = getPosPaymentResponseConverter().convert(terminalApiResponse.getSaleToPOIResponse()); + PaymentResponse paymentsResponse = getPosPaymentResponseConverter().convert(terminalApiResponse.getSaleToPOIResponse()); String posReceipt = TerminalAPIUtil.getReceiptFromStatusResponse(terminalApiResponse); if (StringUtils.isNotEmpty(posReceipt)) { paymentsResponse.putAdditionalDataItem("pos.receipt", posReceipt); @@ -1374,23 +1312,18 @@ public boolean isImmediateCapture() { } @Override - public OrderData handleComponentResult(String resultJson) throws Exception { - Gson gson = new GsonBuilder().disableHtmlEscaping().create(); - PaymentsResponse paymentsResponse = gson.fromJson(resultJson, new TypeToken() { - }.getType()); - - String orderCode = paymentsResponse.getMerchantReference(); + public OrderData handleComponentResult(String resultCode, String merchantReference) throws Exception { - if (PaymentsResponse.ResultCodeEnum.AUTHORISED == paymentsResponse.getResultCode() - || PaymentsResponse.ResultCodeEnum.RECEIVED == paymentsResponse.getResultCode()) { - OrderModel orderModel = retrievePendingOrder(orderCode); + if (StringUtils.equals(PaymentResponse.ResultCodeEnum.AUTHORISED.getValue(), resultCode) + || StringUtils.equals(PaymentResponse.ResultCodeEnum.RECEIVED.getValue(), resultCode)) { + OrderModel orderModel = retrievePendingOrder(merchantReference); return getOrderConverter().convert(orderModel); } - if (PaymentsResponse.ResultCodeEnum.REDIRECTSHOPPER != paymentsResponse.getResultCode()) { - restoreCartFromOrder(orderCode); + if (StringUtils.equals(PaymentResponse.ResultCodeEnum.REDIRECTSHOPPER.getValue(), resultCode)) { + restoreCartFromOrder(merchantReference); } - throw new AdyenNonAuthorizedPaymentException(paymentsResponse); + throw new AdyenNonAuthorizedPaymentException(merchantReference); } private OrderModel retrievePendingOrder(String orderCode) throws InvalidCartException { @@ -1595,14 +1528,6 @@ public void setKeyGenerator(KeyGenerator keyGenerator) { this.keyGenerator = keyGenerator; } - public PaymentsResponseConverter getPaymentsResponseConverter() { - return paymentsResponseConverter; - } - - public void setPaymentsResponseConverter(PaymentsResponseConverter paymentsResponseConverter) { - this.paymentsResponseConverter = paymentsResponseConverter; - } - public FlexibleSearchService getFlexibleSearchService() { return flexibleSearchService; } @@ -1684,13 +1609,6 @@ public void setAdyenBusinessProcessService(AdyenBusinessProcessService adyenBusi this.adyenBusinessProcessService = adyenBusinessProcessService; } - public PaymentsDetailsResponseConverter getPaymentsDetailsResponseConverter() { - return paymentsDetailsResponseConverter; - } - - public void setPaymentsDetailsResponseConverter(PaymentsDetailsResponseConverter paymentsDetailsResponseConverter) { - this.paymentsDetailsResponseConverter = paymentsDetailsResponseConverter; - } public void setTransactionTemplate(TransactionOperations transactionTemplate) { this.transactionTemplate = transactionTemplate; diff --git a/adyenv6core/src/com/adyen/v6/facades/impl/DefaultAdyenExpressCheckoutFacade.java b/adyenv6core/src/com/adyen/v6/facades/impl/DefaultAdyenExpressCheckoutFacade.java index b0682ea22..a6c25a6b5 100644 --- a/adyenv6core/src/com/adyen/v6/facades/impl/DefaultAdyenExpressCheckoutFacade.java +++ b/adyenv6core/src/com/adyen/v6/facades/impl/DefaultAdyenExpressCheckoutFacade.java @@ -1,7 +1,8 @@ package com.adyen.v6.facades.impl; -import com.adyen.model.checkout.PaymentsResponse; -import com.adyen.model.checkout.details.ApplePayDetails; +import com.adyen.model.checkout.ApplePayDetails; +import com.adyen.model.checkout.CheckoutPaymentMethod; +import com.adyen.model.checkout.PaymentResponse; import com.adyen.v6.constants.Adyenv6coreConstants; import com.adyen.v6.facades.AdyenCheckoutFacade; import com.adyen.v6.facades.AdyenExpressCheckoutFacade; @@ -23,7 +24,11 @@ import de.hybris.platform.core.model.user.CustomerModel; import de.hybris.platform.deliveryzone.model.ZoneDeliveryModeModel; import de.hybris.platform.deliveryzone.model.ZoneDeliveryModeValueModel; -import de.hybris.platform.order.*; +import de.hybris.platform.order.CartFactory; +import de.hybris.platform.order.CartService; +import de.hybris.platform.order.DeliveryModeService; +import de.hybris.platform.order.InvalidCartException; +import de.hybris.platform.order.ZoneDeliveryModeService; import de.hybris.platform.order.exceptions.CalculationException; import de.hybris.platform.product.ProductService; import de.hybris.platform.servicelayer.dto.converter.Converter; @@ -68,8 +73,8 @@ public class DefaultAdyenExpressCheckoutFacade implements AdyenExpressCheckoutFa private Converter cartConverter; - public PaymentsResponse expressPDPCheckout(AddressData addressData, String productCode, String merchantId, String merchantName, - String applePayToken, HttpServletRequest request) throws Exception { + public PaymentResponse expressPDPCheckout(AddressData addressData, String productCode, String merchantId, String merchantName, + String applePayToken, HttpServletRequest request) throws Exception { validateParameterNotNull(addressData, "Empty address"); if (StringUtils.isEmpty(addressData.getEmail())) { throw new IllegalArgumentException("Empty email address"); @@ -107,8 +112,8 @@ public PaymentsResponse expressPDPCheckout(AddressData addressData, String produ ApplePayDetails applePayDetails = new ApplePayDetails(); applePayDetails.setApplePayToken(applePayToken); - - PaymentsResponse paymentsResponse = adyenCheckoutFacade.componentPayment(request, cartData, applePayDetails); + CheckoutPaymentMethod checkoutPaymentMethod = new CheckoutPaymentMethod(applePayDetails); + PaymentResponse paymentsResponse = adyenCheckoutFacade.componentPayment(request, cartData, checkoutPaymentMethod); sessionService.setAttribute(ANONYMOUS_CHECKOUT_GUID, org.apache.commons.lang.StringUtils.substringBefore(cart.getUser().getUid(), "|")); @@ -123,7 +128,7 @@ public PaymentsResponse expressPDPCheckout(AddressData addressData, String produ } } - public PaymentsResponse expressCartCheckout(AddressData addressData, String merchantId, String merchantName, + public PaymentResponse expressCartCheckout(AddressData addressData, String merchantId, String merchantName, String applePayToken, HttpServletRequest request) throws Exception { CustomerModel user = (CustomerModel) userService.getCurrentUser(); if (userService.isAnonymousUser(user)) { @@ -156,7 +161,7 @@ public PaymentsResponse expressCartCheckout(AddressData addressData, String merc sessionService.setAttribute(ANONYMOUS_CHECKOUT_GUID, org.apache.commons.lang.StringUtils.substringBefore(cart.getUser().getUid(), "|")); - return adyenCheckoutFacade.componentPayment(request, cartData, applePayDetails); + return adyenCheckoutFacade.componentPayment(request, cartData, new CheckoutPaymentMethod(applePayDetails)); } else { throw new InvalidCartException("Checkout attempt on empty cart"); } diff --git a/adyenv6core/src/com/adyen/v6/facades/impl/SessionRequest.java b/adyenv6core/src/com/adyen/v6/facades/impl/SessionRequest.java index 6e43e9fc6..b87d3d8ee 100644 --- a/adyenv6core/src/com/adyen/v6/facades/impl/SessionRequest.java +++ b/adyenv6core/src/com/adyen/v6/facades/impl/SessionRequest.java @@ -1,5 +1,7 @@ package com.adyen.v6.facades.impl; +import com.adyen.model.checkout.Amount; + public class SessionRequest { private String merchantAccount; private String returnUrl; diff --git a/adyenv6core/src/com/adyen/v6/facades/impl/SessionResponse.java b/adyenv6core/src/com/adyen/v6/facades/impl/SessionResponse.java index 7e4c94e53..e87be8f2a 100644 --- a/adyenv6core/src/com/adyen/v6/facades/impl/SessionResponse.java +++ b/adyenv6core/src/com/adyen/v6/facades/impl/SessionResponse.java @@ -1,5 +1,7 @@ package com.adyen.v6.facades.impl; +import com.adyen.model.checkout.Amount; + public class SessionResponse { private String countryCode; diff --git a/adyenv6core/src/com/adyen/v6/factory/AdyenPaymentServiceFactory.java b/adyenv6core/src/com/adyen/v6/factory/AdyenPaymentServiceFactory.java index c7c8375d4..5911bc6d8 100644 --- a/adyenv6core/src/com/adyen/v6/factory/AdyenPaymentServiceFactory.java +++ b/adyenv6core/src/com/adyen/v6/factory/AdyenPaymentServiceFactory.java @@ -20,9 +20,12 @@ */ package com.adyen.v6.factory; -import com.adyen.v6.service.AdyenPaymentService; -import com.adyen.v6.service.DefaultAdyenPaymentService; +import com.adyen.v6.service.AdyenCheckoutApiService; +import com.adyen.v6.service.AdyenModificationsApiService; +import com.adyen.v6.service.DefaultAdyenCheckoutApiService; +import com.adyen.v6.service.DefaultAdyenModificationsApiService; import de.hybris.platform.store.BaseStoreModel; +import org.springframework.cache.annotation.Cacheable; /** * Factory class for AdyenPaymentService @@ -31,14 +34,22 @@ public class AdyenPaymentServiceFactory { private final AdyenRequestFactory adyenRequestFactory; + public AdyenPaymentServiceFactory(final AdyenRequestFactory adyenRequestFactory) { this.adyenRequestFactory = adyenRequestFactory; } - public AdyenPaymentService createFromBaseStore(final BaseStoreModel baseStoreModel) { - DefaultAdyenPaymentService adyenPaymentService = new DefaultAdyenPaymentService(baseStoreModel); - adyenPaymentService.setAdyenRequestFactory(adyenRequestFactory); - return adyenPaymentService; + @Cacheable("adyenCheckoutApiService") + public AdyenCheckoutApiService createAdyenCheckoutApiService(final BaseStoreModel baseStoreModel) { + DefaultAdyenCheckoutApiService defaultAdyenCheckoutApiService = new DefaultAdyenCheckoutApiService(baseStoreModel); + defaultAdyenCheckoutApiService.setAdyenRequestFactory(adyenRequestFactory); + return defaultAdyenCheckoutApiService; + } + + public AdyenModificationsApiService createAdyenModificationsApiService(final BaseStoreModel baseStoreModel) { + DefaultAdyenModificationsApiService adyenModificationsApiService = new DefaultAdyenModificationsApiService(baseStoreModel); + adyenModificationsApiService.setAdyenRequestFactory(adyenRequestFactory); + return adyenModificationsApiService; } public AdyenRequestFactory getAdyenRequestFactory() { diff --git a/adyenv6core/src/com/adyen/v6/factory/AdyenRequestFactory.java b/adyenv6core/src/com/adyen/v6/factory/AdyenRequestFactory.java index 744308580..68399d969 100644 --- a/adyenv6core/src/com/adyen/v6/factory/AdyenRequestFactory.java +++ b/adyenv6core/src/com/adyen/v6/factory/AdyenRequestFactory.java @@ -21,33 +21,35 @@ package com.adyen.v6.factory; import com.adyen.builders.terminal.TerminalAPIRequestBuilder; -import com.adyen.enums.VatCategory; -import com.adyen.model.Amount; -import com.adyen.model.PaymentRequest; -import com.adyen.model.*; -import com.adyen.model.additionalData.InvoiceLine; -import com.adyen.model.applicationinfo.ApplicationInfo; -import com.adyen.model.applicationinfo.CommonField; -import com.adyen.model.applicationinfo.ExternalPlatform; +import com.adyen.model.checkout.Amount; +import com.adyen.model.checkout.ApplicationInfo; +import com.adyen.model.checkout.BillingAddress; +import com.adyen.model.checkout.BrowserInfo; +import com.adyen.model.checkout.CardDetails; +import com.adyen.model.checkout.CheckoutPaymentMethod; +import com.adyen.model.checkout.CommonField; +import com.adyen.model.checkout.DeliveryAddress; +import com.adyen.model.checkout.ExternalPlatform; +import com.adyen.model.checkout.Installments; import com.adyen.model.checkout.LineItem; -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.PaymentsDetailsRequest; -import com.adyen.model.checkout.PaymentsRequest; -import com.adyen.model.checkout.details.CardDetails; -import com.adyen.model.modification.CancelOrRefundRequest; -import com.adyen.model.modification.CaptureRequest; -import com.adyen.model.modification.RefundRequest; -import com.adyen.model.nexo.*; +import com.adyen.model.checkout.Name; +import com.adyen.model.checkout.PaymentRequest; +import com.adyen.model.nexo.AmountsReq; +import com.adyen.model.nexo.DocumentQualifierType; +import com.adyen.model.nexo.MessageCategoryType; +import com.adyen.model.nexo.MessageReference; +import com.adyen.model.nexo.PaymentTransaction; +import com.adyen.model.nexo.SaleData; +import com.adyen.model.nexo.TransactionIdentification; +import com.adyen.model.nexo.TransactionStatusRequest; import com.adyen.model.recurring.DisableRequest; import com.adyen.model.recurring.Recurring; import com.adyen.model.recurring.RecurringDetailsRequest; import com.adyen.model.terminal.SaleToAcquirerData; import com.adyen.model.terminal.TerminalAPIRequest; -import com.adyen.util.Util; import com.adyen.v6.constants.Adyenv6coreConstants; import com.adyen.v6.enums.RecurringContractMode; import com.adyen.v6.model.RequestInfo; -import com.adyen.v6.paymentmethoddetails.executors.AdyenPaymentMethodDetailsBuilderExecutor; import com.google.gson.Gson; import de.hybris.platform.commercefacades.order.data.CCPaymentInfoData; import de.hybris.platform.commercefacades.order.data.CartData; @@ -63,14 +65,32 @@ import org.apache.log4j.Logger; import org.springframework.web.bind.annotation.RequestMethod; -import javax.servlet.http.HttpServletRequest; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; -import java.math.BigDecimal; -import java.util.*; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.Collection; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.List; +import java.util.Optional; import java.util.stream.Collectors; -import static com.adyen.v6.constants.Adyenv6coreConstants.*; +import static com.adyen.v6.constants.Adyenv6coreConstants.AFTERPAY; +import static com.adyen.v6.constants.Adyenv6coreConstants.CARD_TYPE_DEBIT; +import static com.adyen.v6.constants.Adyenv6coreConstants.OPENINVOICE_METHODS_API; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYBRIGHT; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BCMC; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_CC; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_FACILPAY_PREFIX; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_KLARNA; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_ONECLICK; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_PIX; +import static com.adyen.v6.constants.Adyenv6coreConstants.PLUGIN_NAME; +import static com.adyen.v6.constants.Adyenv6coreConstants.PLUGIN_VERSION; +import static com.adyen.v6.constants.Adyenv6coreConstants.RATEPAY; public class AdyenRequestFactory { private static final Logger LOG = Logger.getLogger(AdyenRequestFactory.class); @@ -83,74 +103,22 @@ public class AdyenRequestFactory { private static final String DUAL_BRANDED_NOT_SELECTED_FLOW_PAYMENT_TYPE = "scheme"; protected final ConfigurationService configurationService; - protected final AdyenPaymentMethodDetailsBuilderExecutor adyenPaymentMethodDetailsBuilderExecutor; - public AdyenRequestFactory(final ConfigurationService configurationService, final AdyenPaymentMethodDetailsBuilderExecutor adyenPaymentMethodDetailsBuilderExecutor) { + public AdyenRequestFactory(final ConfigurationService configurationService) { this.configurationService = configurationService; - this.adyenPaymentMethodDetailsBuilderExecutor = adyenPaymentMethodDetailsBuilderExecutor; } - @Deprecated - public PaymentRequest createAuthorizationRequest(final String merchantAccount, - final CartData cartData, - final HttpServletRequest request, - final CustomerModel customerModel, - final RecurringContractMode recurringContractMode) { - - String amount = String.valueOf(cartData.getTotalPriceWithTax().getValue()); - String currency = cartData.getTotalPriceWithTax().getCurrencyIso(); - String reference = cartData.getCode(); - - PaymentRequest paymentRequest = createBasePaymentRequest(new PaymentRequest(), request, merchantAccount).reference(reference).setAmountData(amount, currency); - - // set shopper details - if (customerModel != null) { - paymentRequest.setShopperReference(customerModel.getCustomerID()); - paymentRequest.setShopperEmail(customerModel.getContactEmail()); - } - // if address details are provided added it into the request - if (cartData.getDeliveryAddress() != null) { - Address deliveryAddress = setAddressData(cartData.getDeliveryAddress()); - paymentRequest.setDeliveryAddress(deliveryAddress); - } - - if (cartData.getPaymentInfo().getBillingAddress() != null) { - // set PhoneNumber if it is provided - if (cartData.getPaymentInfo().getBillingAddress().getPhone() != null && !cartData.getPaymentInfo().getBillingAddress().getPhone().isEmpty()) { - paymentRequest.setTelephoneNumber(cartData.getPaymentInfo().getBillingAddress().getPhone()); - } - - Address billingAddress = setAddressData(cartData.getPaymentInfo().getBillingAddress()); - paymentRequest.setBillingAddress(billingAddress); - } - - // OpenInvoice add required additional data - if (OPENINVOICE_METHODS_API.contains(cartData.getAdyenPaymentMethod()) - || PAYMENT_METHOD_PAYPAL.contains(cartData.getAdyenPaymentMethod())) { - paymentRequest.selectedBrand(cartData.getAdyenPaymentMethod()); - setOpenInvoiceData(paymentRequest, cartData, customerModel); - - paymentRequest.setShopperName(getShopperNameFromAddress(cartData.getDeliveryAddress())); - } - return paymentRequest; - } - - public PaymentsDetailsRequest create3DSPaymentsRequest(final Map details) { - PaymentsDetailsRequest paymentsDetailsRequest = new PaymentsDetailsRequest(); - paymentsDetailsRequest.setDetails(details); - return paymentsDetailsRequest; - } - - public PaymentsRequest createPaymentsRequest(final String merchantAccount, + public PaymentRequest createPaymentsRequest(final String merchantAccount, final CartData cartData, + final CheckoutPaymentMethod checkoutPaymentMethod, final RequestInfo requestInfo, final CustomerModel customerModel, final RecurringContractMode recurringContractMode, final Boolean guestUserTokenizationEnabled) { final String adyenPaymentMethod = cartData.getAdyenPaymentMethod(); final Boolean is3DS2allowed = is3DS2Allowed(); - final PaymentsRequest paymentsRequest = new PaymentsRequest(); - + final PaymentRequest paymentsRequest = new PaymentRequest(); + //Blik if (adyenPaymentMethod == null) { throw new IllegalArgumentException("Payment method is null"); } @@ -161,6 +129,7 @@ public PaymentsRequest createPaymentsRequest(final String merchantAccount, paymentsRequest.setReturnUrl(cartData.getAdyenReturnUrl()); paymentsRequest.setRedirectFromIssuerMethod(RequestMethod.POST.toString()); paymentsRequest.setRedirectToIssuerMethod(RequestMethod.POST.toString()); + paymentsRequest.setPaymentMethod(checkoutPaymentMethod); //For credit cards if (PAYMENT_METHOD_CC.equals(adyenPaymentMethod) || PAYMENT_METHOD_BCMC.equals(adyenPaymentMethod)) { @@ -180,8 +149,8 @@ public PaymentsRequest createPaymentsRequest(final String merchantAccount, else if (adyenPaymentMethod.indexOf(PAYMENT_METHOD_ONECLICK) == 0) { Optional.ofNullable(cartData.getAdyenSelectedReference()) .filter(StringUtils::isNotEmpty) - .map(selectedReference -> getCardDetails(cartData, selectedReference)) - .ifPresent(paymentsRequest::setPaymentMethod); + .map(selectedReference -> new CheckoutPaymentMethod(getCardDetails(cartData, selectedReference))) + .ifPresent(paymentsRequest::paymentMethod); if (is3DS2allowed) { enhanceForThreeDS2(paymentsRequest, cartData); @@ -207,32 +176,18 @@ protected CardDetails getCardDetails(CartData cartData, String selectedReference final CardDetails paymentMethodDetails = new CardDetails(); paymentMethodDetails.encryptedSecurityCode(cartData.getAdyenEncryptedSecurityCode()); paymentMethodDetails.recurringDetailReference(selectedReference); - Optional.ofNullable(cartData.getAdyenCardBrand()).ifPresent(paymentMethodDetails::setType); + Optional.ofNullable(cartData.getAdyenCardBrand()).ifPresent(paymentMethodDetails::brand); return paymentMethodDetails; } - public PaymentsRequest createPaymentsRequest(final String merchantAccount, - final CartData cartData, - final PaymentMethodDetails paymentMethodDetails, - final RequestInfo requestInfo, - final CustomerModel customerModel) { - final PaymentsRequest paymentsRequest = new PaymentsRequest(); - setCommonInfoOnPaymentRequest(merchantAccount, cartData, requestInfo, customerModel, paymentsRequest); - updateApplicationInfoEcom(paymentsRequest.getApplicationInfo()); - paymentsRequest.setPaymentMethod(paymentMethodDetails); - paymentsRequest.setReturnUrl(cartData.getAdyenReturnUrl()); - - return paymentsRequest; - } - - protected PaymentsRequest enhanceForThreeDS2(final PaymentsRequest paymentsRequest, final CartData cartData) { + protected PaymentRequest enhanceForThreeDS2(final PaymentRequest paymentsRequest, final CartData cartData) { final BrowserInfo browserInfo = Optional.ofNullable(new Gson().fromJson(cartData.getAdyenBrowserInfo(), BrowserInfo.class)) .orElse(new BrowserInfo()) .acceptHeader(paymentsRequest.getBrowserInfo().getAcceptHeader()) .userAgent(paymentsRequest.getBrowserInfo().getUserAgent()); paymentsRequest.setAdditionalData(Optional.ofNullable(paymentsRequest.getAdditionalData()).orElse(new HashMap<>())); - paymentsRequest.setChannel(PaymentsRequest.ChannelEnum.WEB); + paymentsRequest.setChannel(PaymentRequest.ChannelEnum.WEB); paymentsRequest.setBrowserInfo(browserInfo); return paymentsRequest; @@ -255,7 +210,7 @@ protected void updateApplicationInfoEcom(final ApplicationInfo applicationInfo) protected void setCommonInfoOnPaymentRequest(final String merchantAccount, final CartData cartData, final RequestInfo requestInfo, final CustomerModel customerModel, - final PaymentsRequest paymentsRequest) { + final PaymentRequest paymentsRequest) { //Get details from CartData to set in PaymentRequest. final String amount = String.valueOf(cartData.getTotalPriceWithTax().getValue()); @@ -272,7 +227,7 @@ protected void setCommonInfoOnPaymentRequest(final String merchantAccount, final final String shopperLocale = requestInfo.getShopperLocale(); paymentsRequest - .amount(Util.createAmount(amount, currency)) + .amount(new Amount().value(cartData.getTotalPriceWithTax().getValue().longValue()*100).currency(currency)) .reference(reference) .merchantAccount(merchantAccount) .browserInfo(new BrowserInfo().userAgent(userAgent).acceptHeader(acceptHeader)) @@ -281,13 +236,13 @@ protected void setCommonInfoOnPaymentRequest(final String merchantAccount, final .shopperLocale(shopperLocale) .shopperReference(customerModel.getCustomerID()) .shopperEmail(customerModel.getContactEmail()) - .deliveryAddress(setAddressData(deliveryAddress)) - .billingAddress(setAddressData(billingAddress)) + .deliveryAddress(convertToDeliveryAddress(deliveryAddress)) + .billingAddress(convertToBillingAddress(billingAddress)) .telephoneNumber(billingAddress != null ? billingAddress.getPhone() : "") .setCountryCode(getCountryCode(cartData)); } - protected void updatePaymentRequestForCC(final PaymentsRequest paymentsRequest, final CartData cartData, final RecurringContractMode recurringContractMode) { + protected void updatePaymentRequestForCC(final PaymentRequest paymentsRequest, final CartData cartData, final RecurringContractMode recurringContractMode) { final Recurring recurringContract = getRecurringContractType(recurringContractMode); Recurring.ContractEnum contract = null; if (recurringContract != null) { @@ -298,7 +253,8 @@ protected void updatePaymentRequestForCC(final PaymentsRequest paymentsRequest, final String encryptedExpiryMonth = cartData.getAdyenEncryptedExpiryMonth(); final String encryptedExpiryYear = cartData.getAdyenEncryptedExpiryYear(); - if (Recurring.ContractEnum.ONECLICK_RECURRING.equals(contract)) { + if (Recurring.ContractEnum.RECURRING.equals(contract)) { + paymentsRequest.setRecurringProcessingModel(PaymentRequest.RecurringProcessingModelEnum.CARDONFILE); paymentsRequest.setEnableRecurring(true); if(Boolean.TRUE.equals(cartData.getAdyenRememberTheseDetails())) { paymentsRequest.setEnableOneClick(true); @@ -310,18 +266,14 @@ protected void updatePaymentRequestForCC(final PaymentsRequest paymentsRequest, } if (StringUtils.isNotEmpty(encryptedCardNumber) && StringUtils.isNotEmpty(encryptedExpiryMonth) && StringUtils.isNotEmpty(encryptedExpiryYear)) { - paymentsRequest.setPaymentMethod(new CardDetails() + paymentsRequest.setPaymentMethod(new CheckoutPaymentMethod(new CardDetails() .encryptedCardNumber(encryptedCardNumber) .encryptedExpiryMonth(encryptedExpiryMonth) .encryptedExpiryYear(encryptedExpiryYear) .encryptedSecurityCode(cartData.getAdyenEncryptedSecurityCode()) - .holderName(cartData.getAdyenCardHolder())); + .holderName(cartData.getAdyenCardHolder()))); } - // For Dual branded card set card brand as payment method type - if (StringUtils.isNotEmpty(cartData.getAdyenCardBrand())) { - paymentsRequest.getPaymentMethod().setType(DUAL_BRANDED_NOT_SELECTED_FLOW_PAYMENT_TYPE); - } if (cartData.getAdyenInstallments() != null) { Installments installmentObj = new Installments(); installmentObj.setValue(cartData.getAdyenInstallments()); @@ -329,7 +281,7 @@ protected void updatePaymentRequestForCC(final PaymentsRequest paymentsRequest, } } - protected void updatePaymentRequestForDC(final PaymentsRequest paymentsRequest, final CartData cartData, final RecurringContractMode recurringContractMode) { + protected void updatePaymentRequestForDC(final PaymentRequest paymentsRequest, final CartData cartData, final RecurringContractMode recurringContractMode) { final Recurring recurringContract = getRecurringContractType(recurringContractMode); Recurring.ContractEnum contract = null; @@ -342,29 +294,28 @@ protected void updatePaymentRequestForDC(final PaymentsRequest paymentsRequest, final String encryptedExpiryYear = cartData.getAdyenEncryptedExpiryYear(); final String cardBrand = cartData.getAdyenCardBrand(); - if ((Recurring.ContractEnum.ONECLICK_RECURRING.equals(contract) || Recurring.ContractEnum.ONECLICK.equals(contract)) + if ((Recurring.ContractEnum.RECURRING.equals(contract) || Recurring.ContractEnum.ONECLICK.equals(contract)) && cartData.getAdyenRememberTheseDetails()) { paymentsRequest.setEnableOneClick(true); } if (StringUtils.isNotEmpty(encryptedCardNumber) && StringUtils.isNotEmpty(encryptedExpiryMonth) && StringUtils.isNotEmpty(encryptedExpiryYear)) { - paymentsRequest.setPaymentMethod(new CardDetails() + paymentsRequest.setPaymentMethod(new CheckoutPaymentMethod(new CardDetails() .encryptedCardNumber(encryptedCardNumber) .encryptedExpiryMonth(encryptedExpiryMonth) .encryptedExpiryYear(encryptedExpiryYear) .encryptedSecurityCode(cartData.getAdyenEncryptedSecurityCode()) - .holderName(cartData.getAdyenCardHolder())); + .brand(cardBrand) + .holderName(cartData.getAdyenCardHolder()))); } paymentsRequest.putAdditionalDataItem(OVERWRITE_BRAND_PROPERTY, "true"); - paymentsRequest.getPaymentMethod().setType(cardBrand); } - protected void updatePaymentRequestForAlternateMethod(final PaymentsRequest paymentsRequest, final CartData cartData) { + protected void updatePaymentRequestForAlternateMethod(final PaymentRequest paymentsRequest, final CartData cartData) { final String adyenPaymentMethod = cartData.getAdyenPaymentMethod(); paymentsRequest.setShopperName(getShopperNameFromAddress(cartData.getDeliveryAddress())); - paymentsRequest.setPaymentMethod(adyenPaymentMethodDetailsBuilderExecutor.createPaymentMethodDetails(cartData)); paymentsRequest.setReturnUrl(cartData.getAdyenReturnUrl()); if (adyenPaymentMethod.startsWith(PAYMENT_METHOD_KLARNA) @@ -387,33 +338,8 @@ protected String getCountryCode(final CartData cartData) { .orElse(""); } - - public CaptureRequest createCaptureRequest(final String merchantAccount, final BigDecimal amount, final Currency currency, final String authReference, final String merchantReference) { - CaptureRequest request = new CaptureRequest().fillAmount(String.valueOf(amount), currency.getCurrencyCode()) - .merchantAccount(merchantAccount) - .originalReference(authReference) - .reference(merchantReference); - updateApplicationInfoEcom(request.getApplicationInfo()); - return request; - } - - public CancelOrRefundRequest createCancelOrRefundRequest(final String merchantAccount, final String authReference, final String merchantReference) { - CancelOrRefundRequest request = new CancelOrRefundRequest().merchantAccount(merchantAccount).originalReference(authReference).reference(merchantReference); - updateApplicationInfoEcom(request.getApplicationInfo()); - return request; - } - - public RefundRequest createRefundRequest(final String merchantAccount, final BigDecimal amount, final Currency currency, final String authReference, final String merchantReference) { - RefundRequest request = new RefundRequest().fillAmount(String.valueOf(amount), currency.getCurrencyCode()) - .merchantAccount(merchantAccount) - .originalReference(authReference) - .reference(merchantReference); - updateApplicationInfoEcom(request.getApplicationInfo()); - return request; - } - public RecurringDetailsRequest createListRecurringDetailsRequest(final String merchantAccount, final String customerId) { - return new RecurringDetailsRequest().merchantAccount(merchantAccount).shopperReference(customerId).selectOneClickContract(); + return new RecurringDetailsRequest().merchantAccount(merchantAccount).shopperReference(customerId);//.setRecurring(new Recurring());//.selectOneClickContract(); } /** @@ -423,16 +349,6 @@ public DisableRequest createDisableRequest(final String merchantAccount, final S return new DisableRequest().merchantAccount(merchantAccount).shopperReference(customerId).recurringDetailReference(recurringReference); } - private T createBasePaymentRequest(T abstractPaymentRequest, HttpServletRequest request, final String merchantAccount) { - String userAgent = request.getHeader("User-Agent"); - String acceptHeader = request.getHeader("Accept"); - String shopperIP = request.getRemoteAddr(); - abstractPaymentRequest.merchantAccount(merchantAccount).setBrowserInfoData(userAgent, acceptHeader).shopperIP(shopperIP); - - return abstractPaymentRequest; - } - - public TerminalAPIRequest createTerminalAPIRequestForStatus(final CartData cartData, String originalServiceId) { TransactionStatusRequest transactionStatusRequest = new TransactionStatusRequest(); transactionStatusRequest.setReceiptReprintFlag(true); @@ -476,7 +392,7 @@ public TerminalAPIRequest createTerminalAPIRequest(final CartData cartData, Cust saleToAcquirerData.setShopperReference(shopperReference); saleToAcquirerData.setRecurringContract(recurringContract.getContract().toString()); } - updateApplicationInfoEcom(saleToAcquirerData.getApplicationInfo()); + //updateApplicationInfoEcom(saleToAcquirerData.getApplicationInfo()); saleData.setSaleToAcquirerData(saleToAcquirerData); } @@ -499,13 +415,13 @@ public TerminalAPIRequest createTerminalAPIRequest(final CartData cartData, Cust /** * Set Address Data into API */ - protected Address setAddressData(AddressData addressData) { + protected DeliveryAddress convertToDeliveryAddress(AddressData addressData) { if (addressData == null) { LOG.warn("Null address data"); return null; } - Address address = new Address(); + DeliveryAddress address = new DeliveryAddress(); // set defaults because all fields are required into the API address.setCity("NA"); @@ -546,6 +462,52 @@ protected Address setAddressData(AddressData addressData) { return address; } + protected BillingAddress convertToBillingAddress(AddressData addressData) { + if (addressData == null) { + LOG.warn("Null address data"); + return null; + } + + BillingAddress address = new BillingAddress(); + + // set defaults because all fields are required into the API + address.setCity("NA"); + address.setCountry("NA"); + address.setHouseNumberOrName("NA"); + address.setPostalCode("NA"); + address.setStateOrProvince("NA"); + address.setStreet("NA"); + + // set the actual values if they are available + if (addressData.getTown() != null && !addressData.getTown().isEmpty()) { + address.setCity(addressData.getTown()); + } + + if (addressData.getCountry() != null && !addressData.getCountry().getIsocode().isEmpty()) { + address.setCountry(addressData.getCountry().getIsocode()); + } + + if (addressData.getLine1() != null && !addressData.getLine1().isEmpty()) { + address.setStreet(addressData.getLine1()); + } + + if (addressData.getLine2() != null && !addressData.getLine2().isEmpty()) { + address.setHouseNumberOrName(addressData.getLine2()); + } + + if (addressData.getPostalCode() != null && !address.getPostalCode().isEmpty()) { + address.setPostalCode(addressData.getPostalCode()); + } + + //State value will be updated later for boleto in boleto specific method. + if (addressData.getRegion() != null && StringUtils.isNotEmpty(addressData.getRegion().getIsocodeShort())) { + address.setStateOrProvince(addressData.getRegion().getIsocodeShort()); + } else if (addressData.getRegion() != null && StringUtils.isNotEmpty(addressData.getRegion().getIsocode())) { + address.setStateOrProvince(addressData.getRegion().getIsocode()); + } + + return address; + } /** * Return Recurring object from RecurringContractMode @@ -590,7 +552,7 @@ private Recurring getRecurringContractType(RecurringContractMode recurringContra * ONECLICK,RECURRING => RECURRING * RECURRING => RECURRING */ - if (Recurring.ContractEnum.ONECLICK_RECURRING.equals(contractEnum) || Recurring.ContractEnum.RECURRING.equals(contractEnum)) { + if (Recurring.ContractEnum.RECURRING.equals(contractEnum) || Recurring.ContractEnum.RECURRING.equals(contractEnum)) { return recurringContract.contract(Recurring.ContractEnum.RECURRING); } @@ -605,135 +567,22 @@ private Name getShopperNameFromAddress(AddressData addressData) { shopperName.setFirstName(addressData.getFirstName()); shopperName.setLastName(addressData.getLastName()); - shopperName.setGender(Name.GenderEnum.UNKNOWN); - - if (addressData.getTitleCode() != null && !addressData.getTitleCode().isEmpty()) { - if (addressData.getTitleCode().equals("mrs") || addressData.getTitleCode().equals("miss") || addressData.getTitleCode().equals("ms")) { - shopperName.setGender(Name.GenderEnum.FEMALE); - } else { - shopperName.setGender(Name.GenderEnum.MALE); - } - } return shopperName; } - /** - * Set the required fields for using the OpenInvoice API - *

- * To deprecate when RatePay is natively implemented - */ - public void setOpenInvoiceData(PaymentRequest paymentRequest, CartData cartData, final CustomerModel customerModel) { - // set date of birth - if (cartData.getAdyenDob() != null) { - paymentRequest.setDateOfBirth(cartData.getAdyenDob()); - } - - if (cartData.getAdyenSocialSecurityNumber() != null && !cartData.getAdyenSocialSecurityNumber().isEmpty()) { - paymentRequest.setSocialSecurityNumber(cartData.getAdyenSocialSecurityNumber()); - } - - if (cartData.getAdyenDfValue() != null && !cartData.getAdyenDfValue().isEmpty()) { - paymentRequest.setDeviceFingerprint(cartData.getAdyenDfValue()); - } - - // set the invoice lines - List invoiceLines = new ArrayList(); - String currency = cartData.getTotalPriceWithTax().getCurrencyIso(); - - for (OrderEntryData entry : cartData.getEntries()) { - - // Use totalPrice because the basePrice does include tax as well if you have configured this to be calculated in the price - BigDecimal pricePerItem = entry.getBasePrice().getValue(); - - - String description = "NA"; - if (entry.getProduct().getName() != null && !entry.getProduct().getName().equals("")) { - description = entry.getProduct().getName(); - } - - // Tax of total price (included quantity) - Double tax = entry.getTaxValues().stream().map(taxValue -> taxValue.getAppliedValue()).reduce(0.0, (x, y) -> x = x + y); - - - // Calculate Tax per quantitiy - if (tax > 0) { - tax = tax / entry.getQuantity().intValue(); - } - - // Calculate price without tax - Amount itemAmountWithoutTax = Util.createAmount(pricePerItem.subtract(new BigDecimal(tax)), currency); - Double percentage = entry.getTaxValues().stream().map(taxValue -> taxValue.getValue()).reduce(0.0, (x, y) -> x = x + y) * 100; - - InvoiceLine invoiceLine = new InvoiceLine(); - invoiceLine.setCurrencyCode(currency); - invoiceLine.setDescription(description); - - /* - * The price for one item in the invoice line, represented in minor units. - * The due amount for the item, VAT excluded. - */ - invoiceLine.setItemAmount(itemAmountWithoutTax.getValue()); - - // The VAT due for one item in the invoice line, represented in minor units. - invoiceLine.setItemVATAmount(Util.createAmount(BigDecimal.valueOf(tax), currency).getValue()); - - // The VAT percentage for one item in the invoice line, represented in minor units. - invoiceLine.setItemVatPercentage(percentage.longValue()); - - // The country-specific VAT category a product falls under. Allowed values: (High,Low,None) - invoiceLine.setVatCategory(VatCategory.NONE); - - // An unique id for this item. Required for RatePay if the description of each item is not unique. - if (!entry.getProduct().getCode().isEmpty()) { - invoiceLine.setItemId(entry.getProduct().getCode()); - } - - invoiceLine.setNumberOfItems(entry.getQuantity().intValue()); - - if (entry.getProduct() != null && !entry.getProduct().getCode().isEmpty()) { - invoiceLine.setItemId(entry.getProduct().getCode()); - } - - if (entry.getProduct() != null && !entry.getProduct().getCode().isEmpty()) { - invoiceLine.setItemId(entry.getProduct().getCode()); - } - - LOG.debug("InvoiceLine Product:" + invoiceLine.toString()); - invoiceLines.add(invoiceLine); - - } - - // Add delivery costs - if (cartData.getDeliveryCost() != null) { - - InvoiceLine invoiceLine = new InvoiceLine(); - invoiceLine.setCurrencyCode(currency); - invoiceLine.setDescription("Delivery Costs"); - Amount deliveryAmount = Util.createAmount(cartData.getDeliveryCost().getValue().toString(), currency); - invoiceLine.setItemAmount(deliveryAmount.getValue()); - invoiceLine.setItemVATAmount(0L); - invoiceLine.setItemVatPercentage(0L); - invoiceLine.setVatCategory(VatCategory.NONE); - invoiceLine.setNumberOfItems(1); - LOG.debug("InvoiceLine DeliveryCosts:" + invoiceLine.toString()); - invoiceLines.add(invoiceLine); - } - - paymentRequest.setInvoiceLines(invoiceLines); - } - - /* * Set the required fields for using the OpenInvoice API */ - public void setOpenInvoiceData(PaymentsRequest paymentsRequest, CartData cartData) { + public void setOpenInvoiceData(PaymentRequest paymentsRequest, CartData cartData) { paymentsRequest.setShopperName(getShopperNameFromAddress(cartData.getDeliveryAddress())); // set date of birth if (cartData.getAdyenDob() != null) { - paymentsRequest.setDateOfBirth(cartData.getAdyenDob()); + java.util.Date date = cartData.getAdyenDob(); + OffsetDateTime offsetDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toOffsetDateTime(); + paymentsRequest.setDateOfBirth(offsetDateTime); } if (cartData.getAdyenSocialSecurityNumber() != null && !cartData.getAdyenSocialSecurityNumber().isEmpty()) { @@ -785,11 +634,11 @@ public void setOpenInvoiceData(PaymentsRequest paymentsRequest, CartData cartDat * The price for one item in the invoice line, represented in minor units. * The due amount for the item, VAT excluded. */ - final Amount itemAmount = Util.createAmount(entry.getBasePrice().getValue(), currency); + final Amount itemAmount = new Amount().value(entry.getBasePrice().getValue().longValue()).currency(currency); if (cartData.isNet()) { invoiceLine.setAmountExcludingTax(itemAmount.getValue()); - invoiceLine.setTaxAmount(Util.createAmount(BigDecimal.valueOf(tax), currency).getValue()); + invoiceLine.setTaxAmount(tax.longValue()); } else { invoiceLine.setAmountIncludingTax(itemAmount.getValue()); } @@ -812,7 +661,7 @@ public void setOpenInvoiceData(PaymentsRequest paymentsRequest, CartData cartDat final LineItem invoiceLine = new LineItem(); invoiceLine.setDescription("Delivery Costs"); - final Amount deliveryAmount = Util.createAmount(cartData.getDeliveryCost().getValue().toString(), currency); + final Amount deliveryAmount = new Amount().value(cartData.getDeliveryCost().getValue().longValue()).currency(currency); if (cartData.isNet()) { final Double taxAmount = cartData.getEntries().stream() @@ -823,7 +672,7 @@ public void setOpenInvoiceData(PaymentsRequest paymentsRequest, CartData cartDat .stream() .reduce(0.0, Double::sum); invoiceLine.setAmountExcludingTax(deliveryAmount.getValue()); - invoiceLine.setTaxAmount(Util.createAmount(cartData.getTotalTax().getValue().subtract(BigDecimal.valueOf(taxAmount)), currency).getValue()); + invoiceLine.setTaxAmount(cartData.getTotalTax().getValue().longValue()); } else { invoiceLine.setAmountIncludingTax(deliveryAmount.getValue()); } @@ -842,21 +691,19 @@ public void setOpenInvoiceData(PaymentsRequest paymentsRequest, CartData cartDat invoiceLines.add(invoiceLine); } - paymentsRequest.setLineItems(invoiceLines); + // paymentsRequest.setLineItems(invoiceLines); } private Name getAfterPayShopperName(final CartData cartData) { return new Name() .firstName(cartData.getAdyenFirstName()) - .lastName(cartData.getAdyenLastName()) - .gender(Name.GenderEnum.valueOf(cartData.getAdyenShopperGender())); + .lastName(cartData.getAdyenLastName()); } /** * Set Boleto payment request data */ - private void setBoletoData(final PaymentsRequest paymentsRequest, final CartData cartData) { - paymentsRequest.setPaymentMethod(adyenPaymentMethodDetailsBuilderExecutor.createPaymentMethodDetails(cartData)); + private void setBoletoData(final PaymentRequest paymentsRequest, final CartData cartData) { paymentsRequest.setSocialSecurityNumber(cartData.getAdyenSocialSecurityNumber()); final Name shopperName = new Name() @@ -882,7 +729,7 @@ private void setBoletoData(final PaymentsRequest paymentsRequest, final CartData } - private void setPixData(final PaymentsRequest paymentsRequest, final CartData cartData) { + private void setPixData(final PaymentRequest paymentsRequest, final CartData cartData) { final List invoiceLines = cartData.getEntries().stream() .filter(cartEntry -> cartEntry.getQuantity() > 0) .map(cartEntry -> diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/AdyenPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/AdyenPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index 4cadd9085..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/AdyenPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders; - -import com.adyen.model.checkout.PaymentMethodDetails; -import de.hybris.platform.commercefacades.order.data.CartData; -import de.hybris.platform.commercefacades.user.data.AddressData; - -public interface AdyenPaymentMethodDetailsBuilderStrategy { - - String SPACE = " "; - - /** - * Validates if the request qualifies to be applied. - * - * @param cartData The cart to use to perform the payment. - * @return True or false, subject to validations. - */ - boolean isApplicable(final S cartData); - - /** - * Build a PaymentMethodDetails based on the cartData information - * @param cartData - * @return - */ - PaymentMethodDetails buildPaymentMethodDetails(final S cartData); - - //Shopper name, phone number, and email address." - default String getPersonalDetails(final CartData cartData) { - final AddressData addressData = cartData.getDeliveryAddress(); - final StringBuilder personalDetails = new StringBuilder(); - - personalDetails.append(addressData.getFirstName() + SPACE); - personalDetails.append(addressData.getLastName() + SPACE); - personalDetails.append(cartData.getAdyenDob() + SPACE); - personalDetails.append(addressData.getPhone() + SPACE); - personalDetails.append(addressData.getEmail()); - - return personalDetails.toString(); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/AffirmPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/AffirmPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index fed9039d6..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/AffirmPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.CardDetails; -import com.adyen.v6.constants.Adyenv6coreConstants; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class AffirmPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - return Adyenv6coreConstants.AFFIRM.equals(cartData.getAdyenPaymentMethod()); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new CardDetails().type(Adyenv6coreConstants.AFFIRM); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/AfterpayAdyenPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/AfterpayAdyenPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index b5b404a11..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/AfterpayAdyenPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.AfterpayDetails; -import com.adyen.model.checkout.details.KlarnaDetails; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class AfterpayAdyenPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - final String cartPaymentMethod = cartData.getAdyenPaymentMethod(); - - return AfterpayDetails.AFTERPAY_DEFAULT.equals(cartPaymentMethod) || - AfterpayDetails.AFTERPAYTOUCH.equals(cartPaymentMethod); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - - return new AfterpayDetails() - .type(cartData.getAdyenPaymentMethod()) - .personalDetails(getPersonalDetails(cartData)); - } - -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/AmazonpayPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/AmazonpayPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index 96ed9ef6a..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/AmazonpayPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; - -import com.adyen.model.checkout.details.AmazonPayDetails; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -public class AmazonpayPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - final String cartPaymentMethod = cartData.getAdyenPaymentMethod(); - - return AmazonPayDetails.AMAZONPAY.equals(cartPaymentMethod); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - - return new AmazonPayDetails(); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/BoletoBancarioSantanderAdyenPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/BoletoBancarioSantanderAdyenPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index d1fff7f9c..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/BoletoBancarioSantanderAdyenPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.constants.ApiConstants; -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.CardDetails; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class BoletoBancarioSantanderAdyenPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - final String cartPaymentMethod = cartData.getAdyenPaymentMethod(); - return ApiConstants.SelectedBrand.BOLETO_SANTANDER.equals(cartPaymentMethod); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new CardDetails() - .type(ApiConstants.SelectedBrand.BOLETO_SANTANDER); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/ClearpayPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/ClearpayPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index 321c6a133..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/ClearpayPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.CardDetails; -import com.adyen.v6.constants.Adyenv6coreConstants; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class ClearpayPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - return Adyenv6coreConstants.CLEARPAY.equals(cartData.getAdyenPaymentMethod()); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new CardDetails().type(Adyenv6coreConstants.CLEARPAY); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/CreditCardAdyenPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/CreditCardAdyenPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index c730658a7..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/CreditCardAdyenPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.CardDetails; -import com.adyen.v6.constants.Adyenv6coreConstants; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class CreditCardAdyenPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - final String cartPaymentMethod = cartData.getAdyenPaymentMethod(); - return Adyenv6coreConstants.PAYMENT_METHOD_CC.equals(cartPaymentMethod) || - CardDetails.CARD.equals(cartPaymentMethod); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new CardDetails() - .type(CardDetails.CARD) - .brand(cartData.getAdyenCardBrand()); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/DotpayPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/DotpayPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index 0d691b8c7..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/DotpayPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.CardDetails; -import com.adyen.v6.constants.Adyenv6coreConstants; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class DotpayPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - return Adyenv6coreConstants.PAYMENT_METHOD_DOTPAY.equals(cartData.getAdyenPaymentMethod()); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new CardDetails().type(cartData.getAdyenPaymentMethod()); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/EPSAdyenPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/EPSAdyenPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index 33bb931e9..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/EPSAdyenPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.GenericIssuerPaymentMethodDetails; -import com.adyen.v6.constants.Adyenv6coreConstants; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class EPSAdyenPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - return Adyenv6coreConstants.PAYMENT_METHOD_EPS.equals(cartData.getAdyenPaymentMethod()); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new GenericIssuerPaymentMethodDetails().type(Adyenv6coreConstants.PAYMENT_METHOD_EPS).issuer(cartData.getAdyenIssuerId()); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/FacilpayPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/FacilpayPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index 153938a47..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/FacilpayPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.CardDetails; -import com.adyen.v6.constants.Adyenv6coreConstants; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class FacilpayPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - return Adyenv6coreConstants.PAYMENT_METHOD_FACILPAY_PREFIX.indexOf(cartData.getAdyenPaymentMethod()) >= 0; - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new CardDetails().type(cartData.getAdyenPaymentMethod()); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/GenericAdyenPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/GenericAdyenPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index 6c5815253..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/GenericAdyenPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.GenericIssuerPaymentMethodDetails; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class GenericAdyenPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - return Boolean.TRUE; - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new GenericIssuerPaymentMethodDetails().type(cartData.getAdyenPaymentMethod()); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/GiftcardPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/GiftcardPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index e4987842d..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/GiftcardPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.CardDetails; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -public class GiftcardPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - final String cartPaymentMethod = cartData.getAdyenPaymentMethod(); - - return CardDetails.GIFTCARD.equals(cartPaymentMethod); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - - return new CardDetails() - .type(CardDetails.GIFTCARD) - .brand(cartData.getAdyenGiftCardBrand()); - } - -} \ No newline at end of file diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/GiropayPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/GiropayPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index 7d0f4189a..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/GiropayPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.GiropayDetails; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class GiropayPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - return GiropayDetails.GIROPAY.equals(cartData.getAdyenPaymentMethod()); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new GiropayDetails(); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/IdealAdyenPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/IdealAdyenPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index 13bef8e9e..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/IdealAdyenPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.IdealDetails; -import com.adyen.v6.constants.Adyenv6coreConstants; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class IdealAdyenPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - return Adyenv6coreConstants.PAYMENT_METHOD_IDEAL.equals(cartData.getAdyenPaymentMethod()); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new IdealDetails().issuer(cartData.getAdyenIssuerId()); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/InteracPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/InteracPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index 966eee34e..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/InteracPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.CardDetails; -import com.adyen.v6.constants.Adyenv6coreConstants; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class InteracPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - return Adyenv6coreConstants.PAYMENT_METHOD_INTERAC.equals(cartData.getAdyenPaymentMethod()); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new CardDetails().type(cartData.getAdyenPaymentMethod()); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/KlarnaAdyenPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/KlarnaAdyenPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index f218c442e..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/KlarnaAdyenPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.KlarnaDetails; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class KlarnaAdyenPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - final String cartPaymentMethod = cartData.getAdyenPaymentMethod(); - - return KlarnaDetails.KLARNA.equals(cartPaymentMethod) || - KlarnaDetails.KLARNA_ACCOUNT.equals(cartPaymentMethod) || - KlarnaDetails.KLARNA_PAY_NOW.equals(cartPaymentMethod); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - - return new KlarnaDetails() - .type(cartData.getAdyenPaymentMethod()); - } - -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/MolpayPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/MolpayPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index 45b32d1a1..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/MolpayPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.MolPayDetails; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class MolpayPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - return MolPayDetails.EBANKING_TH.equals(cartData.getAdyenPaymentMethod()) || - MolPayDetails.EBANKING_MY.equals(cartData.getAdyenPaymentMethod()) || - MolPayDetails.EBANKING_VN.equals(cartData.getAdyenPaymentMethod()) || - MolPayDetails.EBANKING_FPX_MY.equals(cartData.getAdyenPaymentMethod()) || - MolPayDetails.EBANKING_DIRECT_MY.equals(cartData.getAdyenPaymentMethod()); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new MolPayDetails().type(cartData.getAdyenPaymentMethod()); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/MultibancoPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/MultibancoPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index 4e641125e..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/MultibancoPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.CardDetails; -import com.adyen.v6.constants.Adyenv6coreConstants; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class MultibancoPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - return Adyenv6coreConstants.PAYMENT_METHOD_MULTIBANCO.equals(cartData.getAdyenPaymentMethod()); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new CardDetails().type(cartData.getAdyenPaymentMethod()); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/OneyPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/OneyPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index 456f416a6..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/OneyPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.CardDetails; -import com.adyen.v6.constants.Adyenv6coreConstants; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class OneyPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - return cartData.getAdyenPaymentMethod().startsWith(Adyenv6coreConstants.PAYMENT_METHOD_FACILPAY_PREFIX); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new CardDetails().type(cartData.getAdyenPaymentMethod()); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/OnlineBankingPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/OnlineBankingPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index a4211b772..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/OnlineBankingPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.GenericIssuerPaymentMethodDetails; -import com.adyen.v6.constants.Adyenv6coreConstants; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class OnlineBankingPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - return GenericIssuerPaymentMethodDetails.ONLINEBANKING_IN.equals(cartData.getAdyenPaymentMethod()) || Adyenv6coreConstants.PAYMENT_METHOD_ONLINEBANKING_PL.equals(cartData.getAdyenPaymentMethod()); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new GenericIssuerPaymentMethodDetails().type(cartData.getAdyenPaymentMethod()).issuer(cartData.getAdyenIssuerId()); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/PaybrightPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/PaybrightPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index e85fe15ed..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/PaybrightPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.CardDetails; -import com.adyen.v6.constants.Adyenv6coreConstants; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class PaybrightPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - //TODO Paybright has a missing PaymentMethodDetails - return Adyenv6coreConstants.PAYBRIGHT.equals(cartData.getAdyenPaymentMethod()); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - //TODO Paybright has a missing PaymentMethodDetails - return new CardDetails().type(cartData.getAdyenPaymentMethod()); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/PaypalAdyenPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/PaypalAdyenPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index 44cfef7c8..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/PaypalAdyenPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.PayPalDetails; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class PaypalAdyenPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - return PayPalDetails.PAYPAL.equals(cartData.getAdyenPaymentMethod()); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new PayPalDetails() - .subtype(PayPalDetails.SubtypeEnum.SDK) - .payerID(this.getPersonalDetails(cartData)); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/PaytmPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/PaytmPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index d048015c5..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/PaytmPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.CardDetails; -import com.adyen.v6.constants.Adyenv6coreConstants; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class PaytmPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - return Adyenv6coreConstants.PAYMENT_METHOD_PAYTM.equals(cartData.getAdyenPaymentMethod()); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new CardDetails().type(cartData.getAdyenPaymentMethod()); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/RatepayPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/RatepayPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index 266ce780e..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/RatepayPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.CardDetails; -import com.adyen.v6.constants.Adyenv6coreConstants; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class RatepayPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - return cartData.getAdyenPaymentMethod().contains(Adyenv6coreConstants.RATEPAY); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new CardDetails().type(cartData.getAdyenPaymentMethod()); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/SepaDirectDebitPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/SepaDirectDebitPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index 13d2405ef..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/SepaDirectDebitPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.SepaDirectDebitDetails; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class SepaDirectDebitPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - return SepaDirectDebitDetails.SEPADIRECTDEBIT.equals(cartData.getAdyenPaymentMethod()); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new SepaDirectDebitDetails() - .ownerName(cartData.getAdyenSepaOwnerName()) - .iban(cartData.getAdyenSepaIbanNumber()); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/SofortPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/SofortPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index a6a15a390..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/SofortPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.CardDetails; -import com.adyen.v6.constants.Adyenv6coreConstants; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class SofortPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - return Adyenv6coreConstants.PAYMENT_METHOD_SOFORT.equals(cartData.getAdyenPaymentMethod()); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new CardDetails().type(cartData.getAdyenPaymentMethod()); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/TrustyPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/TrustyPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index f618f4ad2..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/TrustyPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.CardDetails; -import com.adyen.v6.constants.Adyenv6coreConstants; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class TrustyPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - return Adyenv6coreConstants.PAYMENT_METHOD_TRUSTLY.equals(cartData.getAdyenPaymentMethod()); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new CardDetails().type(Adyenv6coreConstants.PAYMENT_METHOD_TRUSTLY); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/UPIPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/UPIPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index a7af9082b..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/UPIPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.UpiCollectDetails; -import com.adyen.model.checkout.details.UpiDetails; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class UPIPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - return cartData.getAdyenPaymentMethod().contains(UpiDetails.UPI); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new UpiCollectDetails().virtualPaymentAddress(cartData.getAdyenUPIVirtualAddress()); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/WalletsIndiaPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/WalletsIndiaPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index 2afd2552a..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/WalletsIndiaPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.GenericIssuerPaymentMethodDetails; -import com.adyen.model.checkout.details.PayUUpiDetails; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class WalletsIndiaPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - return GenericIssuerPaymentMethodDetails.WALLET_IN.equals(cartData.getAdyenPaymentMethod()); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new GenericIssuerPaymentMethodDetails().type(cartData.getAdyenPaymentMethod()).issuer(cartData.getAdyenIssuerId()); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/WechatpayWebPaymentMethodDetailsBuilderStrategy.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/WechatpayWebPaymentMethodDetailsBuilderStrategy.java deleted file mode 100644 index 75b9270e3..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/builders/impl/WechatpayWebPaymentMethodDetailsBuilderStrategy.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.CardDetails; -import com.adyen.model.checkout.details.WeChatPayDetails; -import com.adyen.v6.constants.Adyenv6coreConstants; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import de.hybris.platform.commercefacades.order.data.CartData; - -/** - * {@inheritDoc} - */ -public class WechatpayWebPaymentMethodDetailsBuilderStrategy implements AdyenPaymentMethodDetailsBuilderStrategy { - /** - * {@inheritDoc} - */ - @Override - public boolean isApplicable(final CartData cartData) { - return Adyenv6coreConstants.PAYMENT_METHOD_WECHATPAY.equals(cartData.getAdyenPaymentMethod()); - } - - /** - * {@inheritDoc} - */ - @Override - public PaymentMethodDetails buildPaymentMethodDetails(final CartData cartData) { - return new WeChatPayDetails().type(cartData.getAdyenPaymentMethod()); - } -} diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/executors/AdyenPaymentMethodDetailsBuilderExecutor.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/executors/AdyenPaymentMethodDetailsBuilderExecutor.java deleted file mode 100644 index 3ae79a6cc..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/executors/AdyenPaymentMethodDetailsBuilderExecutor.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.executors; - -import com.adyen.model.checkout.PaymentMethodDetails; -import de.hybris.platform.commercefacades.order.data.CartData; - -public interface AdyenPaymentMethodDetailsBuilderExecutor { - - /** - * Validate if is applicable and create the PaymentMethodDetails - * - * @param source {@link CartData} - * @return The {@link PaymentMethodDetails}. - */ - T createPaymentMethodDetails(S source); -} - diff --git a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/executors/impl/AdyenPaymentMethodDetailsStrategyExecutorImpl.java b/adyenv6core/src/com/adyen/v6/paymentmethoddetails/executors/impl/AdyenPaymentMethodDetailsStrategyExecutorImpl.java deleted file mode 100644 index 2a5459ff9..000000000 --- a/adyenv6core/src/com/adyen/v6/paymentmethoddetails/executors/impl/AdyenPaymentMethodDetailsStrategyExecutorImpl.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.executors.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.v6.paymentmethoddetails.builders.AdyenPaymentMethodDetailsBuilderStrategy; -import com.adyen.v6.paymentmethoddetails.builders.impl.GenericAdyenPaymentMethodDetailsBuilderStrategy; -import com.adyen.v6.paymentmethoddetails.executors.AdyenPaymentMethodDetailsBuilderExecutor; -import de.hybris.platform.commercefacades.order.data.CartData; - -import java.util.List; - -public class AdyenPaymentMethodDetailsStrategyExecutorImpl implements AdyenPaymentMethodDetailsBuilderExecutor { - - private final List> strategies; - private final GenericAdyenPaymentMethodDetailsBuilderStrategy genericStrategy; - - public AdyenPaymentMethodDetailsStrategyExecutorImpl(final List> strategies, - final GenericAdyenPaymentMethodDetailsBuilderStrategy genericStrategy) { - this.strategies = strategies; - this.genericStrategy = genericStrategy; - } - - @Override - public PaymentMethodDetails createPaymentMethodDetails(final CartData cartData) { - return strategies.stream() - .filter(strategy -> strategy.isApplicable(cartData)) - .findAny() - .map(strategy -> strategy.buildPaymentMethodDetails(cartData)) - .orElse(genericStrategy.buildPaymentMethodDetails(cartData)); - } -} diff --git a/adyenv6core/src/com/adyen/v6/service/AbstractAdyenApiService.java b/adyenv6core/src/com/adyen/v6/service/AbstractAdyenApiService.java new file mode 100644 index 000000000..09e723588 --- /dev/null +++ b/adyenv6core/src/com/adyen/v6/service/AbstractAdyenApiService.java @@ -0,0 +1,91 @@ +package com.adyen.v6.service; + +import com.adyen.Client; +import com.adyen.Config; +import com.adyen.enums.Environment; +import com.adyen.v6.factory.AdyenRequestFactory; +import de.hybris.platform.store.BaseStoreModel; + +import static com.adyen.v6.constants.Adyenv6coreConstants.PLUGIN_NAME; +import static com.adyen.v6.constants.Adyenv6coreConstants.PLUGIN_VERSION; + +public abstract class AbstractAdyenApiService { + + protected BaseStoreModel baseStore; + protected AdyenRequestFactory adyenRequestFactory; + protected Config config; + protected Client client; + protected Config posConfig; + protected Client posClient; + + private static final int POS_REQUEST_TIMEOUT = 60000; + + private static final String CHECKOUT_ENDPOINT_LIVE_IN_SUFFIX = "-checkout-live-in.adyenpayments.com/checkout"; + + private AbstractAdyenApiService() { + } + + + public AbstractAdyenApiService(final BaseStoreModel baseStore) { + this.baseStore = baseStore; + + if (Boolean.TRUE.equals(baseStore.getAdyenPosEnabled())) { + posConfig = new Config(); + posConfig.setApiKey(baseStore.getAdyenPosApiKey()); + posConfig.setReadTimeoutMillis(POS_REQUEST_TIMEOUT); + posConfig.setApplicationName(PLUGIN_NAME + " v" + PLUGIN_VERSION); + posClient = new Client(posConfig); + + if (Boolean.TRUE.equals(baseStore.getAdyenTestMode())) { + posClient.setEnvironment(Environment.TEST, null); + } else { + posClient.setEnvironment(Environment.LIVE, null); + } + } + + config = new Config(); + config.setApiKey(baseStore.getAdyenAPIKey()); + config.setApplicationName(PLUGIN_NAME + " v" + PLUGIN_VERSION); + client = new Client(config); + + if (Boolean.TRUE.equals(baseStore.getAdyenTestMode())) { + client.setEnvironment(Environment.TEST, null); + } else { + this.config.setEnvironment(Environment.LIVE); + this.config.setTerminalApiCloudEndpoint(Client.TERMINAL_API_ENDPOINT_LIVE); + } + + } + + public AdyenRequestFactory getAdyenRequestFactory() { + return adyenRequestFactory; + } + + public void setAdyenRequestFactory(AdyenRequestFactory adyenRequestFactory) { + this.adyenRequestFactory = adyenRequestFactory; + } + + public BaseStoreModel getBaseStore() { + return baseStore; + } + + public void setBaseStore(BaseStoreModel baseStore) { + this.baseStore = baseStore; + } + + public void setConfig(Config config) { + this.config = config; + } + + public Client getClient() { + return client; + } + + public void setClient(Client client) { + this.client = client; + } + + public Config getConfig() { + return config; + } +} diff --git a/adyenv6core/src/com/adyen/v6/service/AdyenPaymentService.java b/adyenv6core/src/com/adyen/v6/service/AdyenCheckoutApiService.java similarity index 63% rename from adyenv6core/src/com/adyen/v6/service/AdyenPaymentService.java rename to adyenv6core/src/com/adyen/v6/service/AdyenCheckoutApiService.java index 1d2050ae9..32a096e06 100644 --- a/adyenv6core/src/com/adyen/v6/service/AdyenPaymentService.java +++ b/adyenv6core/src/com/adyen/v6/service/AdyenCheckoutApiService.java @@ -21,10 +21,15 @@ package com.adyen.v6.service; import com.adyen.httpclient.HTTPClientException; -import com.adyen.model.Amount; -import com.adyen.model.PaymentResult; -import com.adyen.model.checkout.*; -import com.adyen.model.modification.ModificationResult; +import com.adyen.model.checkout.Amount; +import com.adyen.model.checkout.CheckoutPaymentMethod; +import com.adyen.model.checkout.CreateCheckoutSessionResponse; +import com.adyen.model.checkout.PaymentCompletionDetails; +import com.adyen.model.checkout.PaymentDetailsRequest; +import com.adyen.model.checkout.PaymentDetailsResponse; +import com.adyen.model.checkout.PaymentMethod; +import com.adyen.model.checkout.PaymentMethodsResponse; +import com.adyen.model.checkout.PaymentResponse; import com.adyen.model.recurring.RecurringDetail; import com.adyen.model.terminal.ConnectedTerminalsResponse; import com.adyen.model.terminal.TerminalAPIResponse; @@ -34,43 +39,20 @@ import de.hybris.platform.core.model.order.AbstractOrderModel; import de.hybris.platform.core.model.user.CustomerModel; -import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.math.BigDecimal; import java.security.SignatureException; -import java.util.Currency; -import java.util.HashMap; import java.util.List; -import java.util.Map; -public interface AdyenPaymentService { - /** - * Performs authorization request via Adyen API - */ - PaymentResult authorise(CartData cartData, HttpServletRequest request, CustomerModel customerModel) throws Exception; +public interface AdyenCheckoutApiService { ConnectedTerminalsResponse getConnectedTerminals() throws IOException, ApiException; - PaymentsResponse authorisePayment(CartData cartData, RequestInfo requestInfo, CustomerModel customerModel) throws Exception; - - PaymentsResponse componentPayment(CartData cartData, PaymentMethodDetails paymentMethodDetails, RequestInfo requestInfo, CustomerModel customerModel) throws Exception; + PaymentResponse authorisePayment(CartData cartData, RequestInfo requestInfo, CustomerModel customerModel) throws Exception; - PaymentsDetailsResponse authorise3DSPayment(Map details) throws Exception; - - /** - * Performs Capture request via Adyen API - */ - ModificationResult capture(BigDecimal amount, Currency currency, String authReference, String merchantReference) throws Exception; + PaymentResponse componentPayment(CartData cartData, CheckoutPaymentMethod checkoutPaymentMethod, RequestInfo requestInfo, CustomerModel customerModel) throws Exception; - /** - * Performs cancelOrRefund request via Adyen API - */ - ModificationResult cancelOrRefund(String authReference, String merchantReference) throws Exception; - - /** - * Performs refund request via Adyen API - */ - ModificationResult refund(BigDecimal amount, Currency currency, String authReference, String merchantReference) throws Exception; + PaymentDetailsResponse authorise3DSPayment(PaymentDetailsRequest paymentsDetailsRequest) throws Exception; /** * Get payment methods using /paymentMethods - Checkout API @@ -101,12 +83,12 @@ public interface AdyenPaymentService { /** * Retrieves payment response from /payments/details for redirect methods like klarna */ - PaymentsDetailsResponse getPaymentDetailsFromPayload(Map details, String paymentData) throws Exception; + PaymentDetailsResponse getPaymentDetailsFromPayload(PaymentDetailsRequest detailsRequest) throws Exception; /** * Retrieves payment response from /payments/details */ - PaymentsDetailsResponse getPaymentDetailsFromPayload(HashMap details) throws Exception; + PaymentDetailsResponse getPaymentDetailsFromPayload(PaymentCompletionDetails details) throws Exception; /** * Returns the Device Fingerprint url @@ -123,20 +105,6 @@ public interface AdyenPaymentService { */ TerminalAPIResponse sendSyncPosStatusRequest(CartData cartData, String serviceId) throws Exception; - /** - * Performs Refund request via new Adyen API - */ - PaymentRefundResource refunds(final BigDecimal amount, final Currency currency, final String authReference, final String merchantReference) throws Exception; - - /** - * Performs Capture request via new Adyen API - */ - PaymentCaptureResource captures(final BigDecimal amount, final Currency currency, final String authReference, final String merchantReference) throws Exception; - - /** - * Performs Cancel or Refunds request via new Adyen API - */ - PaymentReversalResource cancelOrRefunds(final String authReference, final String merchantReference) throws Exception; BigDecimal calculateAmountWithTaxes(final AbstractOrderModel abstractOrderModel); diff --git a/adyenv6core/src/com/adyen/v6/service/AdyenModificationsApiService.java b/adyenv6core/src/com/adyen/v6/service/AdyenModificationsApiService.java new file mode 100644 index 000000000..efc89613f --- /dev/null +++ b/adyenv6core/src/com/adyen/v6/service/AdyenModificationsApiService.java @@ -0,0 +1,21 @@ +package com.adyen.v6.service; + +import com.adyen.model.checkout.PaymentCaptureResponse; +import com.adyen.model.checkout.PaymentRefundResponse; +import com.adyen.model.checkout.PaymentReversalResponse; + +import java.math.BigDecimal; +import java.util.Currency; + +public interface AdyenModificationsApiService { + /** + * Performs Capture request via Adyen API + */ + PaymentCaptureResponse capture(BigDecimal amount, Currency currency, String authReference, String merchantReference) throws Exception; + + PaymentReversalResponse cancelOrRefund(final String paymentPspReference, final String merchantReference) throws Exception; + + PaymentRefundResponse refund(final BigDecimal amount, final Currency currency, final String paymentPspReference, final String reference) throws Exception; + + +} diff --git a/adyenv6core/src/com/adyen/v6/service/AdyenNotificationService.java b/adyenv6core/src/com/adyen/v6/service/AdyenNotificationService.java index de7b7faef..1e71a7542 100644 --- a/adyenv6core/src/com/adyen/v6/service/AdyenNotificationService.java +++ b/adyenv6core/src/com/adyen/v6/service/AdyenNotificationService.java @@ -27,6 +27,8 @@ import de.hybris.platform.payment.model.PaymentTransactionEntryModel; import de.hybris.platform.payment.model.PaymentTransactionModel; +import java.io.IOException; + /** * Service for Adyen notifications manipulation */ @@ -46,7 +48,7 @@ public interface AdyenNotificationService { /** * Parse HTTP request body and return NotificationRequest */ - NotificationRequest getNotificationRequestFromString(String requestString); + NotificationRequest getNotificationRequestFromString(String requestString) throws IOException; /** * Create NotificationItemModel from NotificationRequestItem diff --git a/adyenv6core/src/com/adyen/v6/service/AdyenOrderService.java b/adyenv6core/src/com/adyen/v6/service/AdyenOrderService.java index eb74ee3c1..77e0bd1ed 100644 --- a/adyenv6core/src/com/adyen/v6/service/AdyenOrderService.java +++ b/adyenv6core/src/com/adyen/v6/service/AdyenOrderService.java @@ -20,37 +20,19 @@ */ package com.adyen.v6.service; -import com.adyen.model.PaymentResult; -import com.adyen.model.checkout.PaymentsResponse; +import com.adyen.model.checkout.FraudResult; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.fraud.model.FraudReportModel; -public interface AdyenOrderService { - void updateOrderFromPaymentsResponse(OrderModel order, PaymentsResponse paymentsResponse); - - /** - * Updates order's metadata using the API Payment response - * Covers fraud, avs, cc authorisation data - */ - void updateOrderFromPaymentResult(OrderModel order, PaymentResult paymentResult); +import java.util.Map; - FraudReportModel createFraudReportFromPaymentsResponse(PaymentsResponse paymentsResponse); +public interface AdyenOrderService { + void updatePaymentInfo(OrderModel order, String paymentMethodType, Map additionalData); - /** - * Creates FraudReportModel from PaymentResult - * @return FraudReportModel|null - */ - FraudReportModel createFraudReportFromPaymentResult(PaymentResult paymentResult); + FraudReportModel createFraudReportFromPaymentsResponse(String pspReference, FraudResult fraudResult ); - /** - * Store FraudReportModel - */ void storeFraudReport(FraudReportModel fraudReport); - void storeFraudReportFromPaymentsResponse(OrderModel order, PaymentsResponse paymentsResponse); + void storeFraudReport(OrderModel order, String pspreference, FraudResult fraudResult); - /** - * Create FraudReportModel from PaymentResult and assigns it to order - */ - void storeFraudReportFromPaymentResult(OrderModel order, PaymentResult paymentResult); } diff --git a/adyenv6core/src/com/adyen/v6/service/AdyenTransactionService.java b/adyenv6core/src/com/adyen/v6/service/AdyenTransactionService.java index 15bd94047..c9d954b96 100644 --- a/adyenv6core/src/com/adyen/v6/service/AdyenTransactionService.java +++ b/adyenv6core/src/com/adyen/v6/service/AdyenTransactionService.java @@ -20,7 +20,7 @@ */ package com.adyen.v6.service; -import com.adyen.model.checkout.PaymentsResponse; +import com.adyen.model.checkout.PaymentDetailsResponse; import com.adyen.v6.model.AdyenNotificationModel; import de.hybris.platform.core.model.order.AbstractOrderModel; import de.hybris.platform.payment.dto.TransactionStatus; @@ -90,7 +90,7 @@ static PaymentTransactionEntryModel getTransactionEntry(PaymentTransactionModel /** * Creates a PaymentTransactionModel */ - PaymentTransactionModel createPaymentTransactionFromResultCode(AbstractOrderModel abstractOrderModel, String merchantTransactionCode, String pspReference, PaymentsResponse.ResultCodeEnum resultCodeEnum); + PaymentTransactionModel createPaymentTransactionFromResultCode(AbstractOrderModel abstractOrderModel, String merchantTransactionCode, String pspReference, PaymentDetailsResponse.ResultCodeEnum resultCodeEnum); /** * Stores the authorization transactions for an order diff --git a/adyenv6core/src/com/adyen/v6/service/DefaultAdyenCheckoutApiService.java b/adyenv6core/src/com/adyen/v6/service/DefaultAdyenCheckoutApiService.java new file mode 100644 index 000000000..beb39d964 --- /dev/null +++ b/adyenv6core/src/com/adyen/v6/service/DefaultAdyenCheckoutApiService.java @@ -0,0 +1,365 @@ +/* + * ###### + * ###### + * ############ ####( ###### #####. ###### ############ ############ + * ############# #####( ###### #####. ###### ############# ############# + * ###### #####( ###### #####. ###### ##### ###### ##### ###### + * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### + * ###### ###### #####( ###### #####. ###### ##### ##### ###### + * ############# ############# ############# ############# ##### ###### + * ############ ############ ############# ############ ##### ###### + * ###### + * ############# + * ############ + * + * Adyen Hybris Extension + * + * Copyright (c) 2017 Adyen B.V. + * This file is open source and available under the MIT license. + * See the LICENSE file for more info. + */ +package com.adyen.v6.service; + +import com.adyen.model.checkout.Amount; +import com.adyen.model.checkout.CheckoutPaymentMethod; +import com.adyen.model.checkout.CreateCheckoutSessionRequest; +import com.adyen.model.checkout.CreateCheckoutSessionResponse; +import com.adyen.model.checkout.PaymentCompletionDetails; +import com.adyen.model.checkout.PaymentDetailsRequest; +import com.adyen.model.checkout.PaymentDetailsResponse; +import com.adyen.model.checkout.PaymentMethod; +import com.adyen.model.checkout.PaymentMethodsRequest; +import com.adyen.model.checkout.PaymentMethodsResponse; +import com.adyen.model.checkout.PaymentRequest; +import com.adyen.model.checkout.PaymentResponse; +import com.adyen.model.recurring.DisableRequest; +import com.adyen.model.recurring.DisableResult; +import com.adyen.model.recurring.RecurringDetail; +import com.adyen.model.recurring.RecurringDetailWrapper; +import com.adyen.model.recurring.RecurringDetailsRequest; +import com.adyen.model.recurring.RecurringDetailsResult; +import com.adyen.model.terminal.ConnectedTerminalsRequest; +import com.adyen.model.terminal.ConnectedTerminalsResponse; +import com.adyen.model.terminal.TerminalAPIRequest; +import com.adyen.model.terminal.TerminalAPIResponse; +import com.adyen.service.PosPayment; +import com.adyen.service.RecurringApi; +import com.adyen.service.TerminalCloudAPI; +import com.adyen.service.checkout.PaymentsApi; +import com.adyen.service.exception.ApiException; +import com.adyen.terminal.serialization.TerminalAPIGsonBuilder; +import com.adyen.v6.enums.RecurringContractMode; +import com.adyen.v6.model.RequestInfo; +import de.hybris.platform.commercefacades.order.data.CartData; +import de.hybris.platform.commercefacades.product.data.PriceData; +import de.hybris.platform.core.model.order.AbstractOrderModel; +import de.hybris.platform.core.model.user.CustomerModel; +import de.hybris.platform.store.BaseStoreModel; +import org.apache.commons.lang3.StringUtils; +import org.apache.log4j.Logger; + +import java.io.IOException; +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +public class DefaultAdyenCheckoutApiService extends AbstractAdyenApiService implements AdyenCheckoutApiService { + + private static final Logger LOG = Logger.getLogger(DefaultAdyenCheckoutApiService.class); + + public DefaultAdyenCheckoutApiService(BaseStoreModel baseStore) { + super(baseStore); + } + + + @Override + public PaymentResponse authorisePayment(final CartData cartData, final RequestInfo requestInfo, final CustomerModel customerModel) throws Exception { + LOG.debug("Authorize payment"); + + PaymentsApi paymentsApi = new PaymentsApi(client); + + PaymentRequest paymentsRequest = getAdyenRequestFactory().createPaymentsRequest(baseStore.getAdyenMerchantAccount(), + cartData, + null, + requestInfo, + customerModel, + baseStore.getAdyenRecurringContractMode(), + baseStore.getAdyenGuestUserTokenization()); + + LOG.debug(paymentsRequest); + PaymentResponse payments = paymentsApi.payments(paymentsRequest); + LOG.debug(payments); + + return payments; + } + + @Override + public ConnectedTerminalsResponse getConnectedTerminals() throws IOException, ApiException { + LOG.debug("Get connected terminals"); + PosPayment posPayment = new PosPayment(posClient); + ConnectedTerminalsRequest connectedTerminalsRequest = new ConnectedTerminalsRequest(); + + connectedTerminalsRequest.setMerchantAccount(baseStore.getAdyenMerchantAccount()); + if (baseStore.getAdyenPosStoreId() != null && StringUtils.isNotEmpty(baseStore.getAdyenPosStoreId())) { + connectedTerminalsRequest.setStore(baseStore.getAdyenPosStoreId()); + } + LOG.debug(connectedTerminalsRequest); + ConnectedTerminalsResponse connectedTerminalsResponse = posPayment.connectedTerminals(connectedTerminalsRequest); + LOG.debug(connectedTerminalsResponse); + return connectedTerminalsResponse; + + } + + @Override + public PaymentResponse componentPayment(final CartData cartData, CheckoutPaymentMethod checkoutPaymentMethod, final RequestInfo requestInfo, final CustomerModel customerModel) throws Exception { + LOG.debug("Component payment"); + //Blik + PaymentsApi checkoutApi = new PaymentsApi(client); + + com.adyen.model.checkout.PaymentRequest paymentsRequest = getAdyenRequestFactory().createPaymentsRequest(baseStore.getAdyenMerchantAccount(), + cartData, + checkoutPaymentMethod, + requestInfo, + customerModel, null, false); + + LOG.debug(paymentsRequest); + PaymentResponse paymentsResponse = checkoutApi.payments(paymentsRequest); + LOG.debug(paymentsResponse); + + return paymentsResponse; + } + + @Override + public PaymentDetailsResponse authorise3DSPayment(PaymentDetailsRequest paymentsDetailsRequest) throws Exception { + LOG.debug("Authorize 3DS payment"); + + PaymentsApi checkout = new PaymentsApi(client); + + LOG.debug(paymentsDetailsRequest); + PaymentDetailsResponse paymentsDetailsResponse = checkout.paymentsDetails(paymentsDetailsRequest); + LOG.debug(paymentsDetailsResponse); + + return paymentsDetailsResponse; + } + + + @Override + public List getPaymentMethods(final BigDecimal amount, + final String currency, + final String countryCode, + final String shopperLocale, + final String shopperReference) throws IOException, ApiException { + + final PaymentMethodsResponse response = getPaymentMethodsResponse(amount, currency, countryCode, shopperLocale, shopperReference); + return response.getPaymentMethods(); + } + + @Override + public PaymentMethodsResponse getPaymentMethodsResponse(final BigDecimal amount, + final String currency, + final String countryCode, + final String shopperLocale, + final String shopperReference) throws IOException, ApiException { + + LOG.debug("Get payment methods response"); + + PaymentsApi checkout = new PaymentsApi(client); + PaymentMethodsRequest request = new PaymentMethodsRequest(); + request.merchantAccount(baseStore.getAdyenMerchantAccount()).amount( + new Amount().value(amount.longValue()).currency(currency)) + .countryCode(countryCode); + + if (!StringUtils.isEmpty(shopperLocale)) { + request.setShopperLocale(shopperLocale); + } + + if (!StringUtils.isEmpty(shopperReference)) { + request.setShopperReference(shopperReference); + } + + LOG.debug(request); + final PaymentMethodsResponse response = checkout.paymentMethods(request); + LOG.debug(response); + + return response; + } + + @Override + @Deprecated + public List getPaymentMethods(final BigDecimal amount, + final String currency, + final String countryCode, + final String shopperLocale) throws IOException { + try { + return getPaymentMethods(amount, currency, countryCode, shopperLocale, null); + } catch (ApiException e) { + LOG.error(e); + } + return null; + } + + @Override + @Deprecated + public List getStoredCards(final String customerId) throws IOException, ApiException { + LOG.debug("Get stored cards"); + + if (customerId == null) { + LOG.info("Customer id is null"); + return new ArrayList<>(); + } + + RecurringApi recurring = new RecurringApi(client); + + RecurringDetailsRequest request = getAdyenRequestFactory().createListRecurringDetailsRequest(baseStore.getAdyenMerchantAccount(), customerId); + + LOG.debug(request); + RecurringDetailsResult result = recurring.listRecurringDetails(request); + LOG.debug(result); + + //Return only cards + return result.getDetails() + .stream() + .map(RecurringDetailWrapper::getRecurringDetail) + .filter(detail -> (detail.getCard() != null && detail.getRecurringDetailReference() != null)) + .collect(Collectors.toList()); + } + + @Override + public boolean disableStoredCard(final String customerId, final String recurringReference) throws IOException, ApiException { + LOG.debug("Disable stored card"); + + RecurringApi recurring = new RecurringApi(client); + + DisableRequest request = getAdyenRequestFactory().createDisableRequest(baseStore.getAdyenMerchantAccount(), customerId, recurringReference); + + LOG.debug(request); + DisableResult result = recurring.disable(request); + LOG.debug(result); + + return ("[detail-successfully-disabled]".equals(result.getResponse()) || "[all-details-successfully-disabled]".equals(result.getResponse())); + } + + @Override + public PaymentDetailsResponse getPaymentDetailsFromPayload(PaymentCompletionDetails details) throws Exception { + LOG.debug("Get payment details from payload"); + + PaymentsApi checkout = new PaymentsApi(client); + + PaymentDetailsRequest paymentsDetailsRequest = new PaymentDetailsRequest(); + paymentsDetailsRequest.setDetails(details); + + LOG.debug(paymentsDetailsRequest); + PaymentDetailsResponse paymentsResponse = checkout.paymentsDetails(paymentsDetailsRequest); + LOG.debug(paymentsResponse); + + return paymentsResponse; + } + + @Override + public PaymentDetailsResponse getPaymentDetailsFromPayload(PaymentDetailsRequest detailsRequest) throws Exception { + LOG.debug("Get payment details from payload"); + + PaymentsApi checkout = new PaymentsApi(client); + + LOG.debug(detailsRequest); + PaymentDetailsResponse paymentsResponse = checkout.paymentsDetails(detailsRequest); + LOG.debug(paymentsResponse); + + return paymentsResponse; + } + + + @Override + public CreateCheckoutSessionResponse getPaymentSessionData(final CartData cartData) throws IOException, ApiException { + final PaymentsApi checkout = new PaymentsApi(client); + final PriceData totalPriceWithTax = cartData.getTotalPriceWithTax(); + + final CreateCheckoutSessionRequest createCheckoutSessionRequest = new CreateCheckoutSessionRequest(); + createCheckoutSessionRequest.amount(new Amount() + .value(totalPriceWithTax.getValue().longValue()) + .currency(totalPriceWithTax.getCurrencyIso())); + createCheckoutSessionRequest.merchantAccount(getBaseStore().getAdyenMerchantAccount()); + if (cartData.getDeliveryAddress() != null) { + createCheckoutSessionRequest.countryCode(cartData.getDeliveryAddress().getCountry().getIsocode()); + } + createCheckoutSessionRequest.returnUrl(Optional.ofNullable(cartData.getAdyenReturnUrl()).orElse("returnUrl")); + createCheckoutSessionRequest.reference(cartData.getCode()); + + return checkout.sessions(createCheckoutSessionRequest); + } + + @Override + public CreateCheckoutSessionResponse getPaymentSessionData(final Amount amount) throws IOException, ApiException { + final PaymentsApi checkout = new PaymentsApi(client); + + final CreateCheckoutSessionRequest createCheckoutSessionRequest = new CreateCheckoutSessionRequest(); + createCheckoutSessionRequest.amount(amount); + createCheckoutSessionRequest.merchantAccount(getBaseStore().getAdyenMerchantAccount()); + createCheckoutSessionRequest.returnUrl("returnUrl"); //dummy url because it's required by api + createCheckoutSessionRequest.reference("reference"); //dummy reference because it's required by api + + return checkout.sessions(createCheckoutSessionRequest); + } + + @Override + public String getDeviceFingerprintUrl() { + DateFormat df = new SimpleDateFormat("yyyyMMdd"); + Date today = Calendar.getInstance().getTime(); + return "https://live.adyen.com/hpp/js/df.js?v=" + df.format(today); + } + + /** + * Send POS Payment Request using Adyen Terminal API + */ + @Override + public TerminalAPIResponse sendSyncPosPaymentRequest(CartData cartData, CustomerModel customer, String serviceId) throws Exception { + LOG.debug("Send sync pos payment request"); + + TerminalCloudAPI terminalCloudAPI = new TerminalCloudAPI(posClient); + + RecurringContractMode recurringContractMode = getBaseStore().getAdyenPosRecurringContractMode(); + TerminalAPIRequest terminalApiRequest = adyenRequestFactory.createTerminalAPIRequest(cartData, customer, recurringContractMode, serviceId); + + LOG.debug(TerminalAPIGsonBuilder.create().toJson(terminalApiRequest)); + TerminalAPIResponse terminalApiResponse = terminalCloudAPI.sync(terminalApiRequest); + + LOG.debug(TerminalAPIGsonBuilder.create().toJson(terminalApiResponse)); + return terminalApiResponse; + } + + /** + * Send POS Status Request using Adyen Terminal API + */ + @Override + public TerminalAPIResponse sendSyncPosStatusRequest(CartData cartData, String originalServiceId) throws Exception { + LOG.debug("Send sync pos status request"); + + TerminalCloudAPI terminalCloudAPI = new TerminalCloudAPI(posClient); + + TerminalAPIRequest terminalApiRequest = adyenRequestFactory.createTerminalAPIRequestForStatus(cartData, originalServiceId); + + LOG.debug(TerminalAPIGsonBuilder.create().toJson(terminalApiRequest)); + TerminalAPIResponse terminalApiResponse = terminalCloudAPI.sync(terminalApiRequest); + + LOG.debug(TerminalAPIGsonBuilder.create().toJson(terminalApiResponse)); + return terminalApiResponse; + } + + @Override + public BigDecimal calculateAmountWithTaxes(final AbstractOrderModel abstractOrderModel) { + final Double totalPrice = abstractOrderModel.getTotalPrice(); + final Double totalTax = Boolean.TRUE.equals(abstractOrderModel.getNet()) ? abstractOrderModel.getTotalTax() : Double.valueOf(0d); + final BigDecimal totalPriceWithoutTaxBD = BigDecimal.valueOf(totalPrice == null ? 0d : totalPrice).setScale(2, + RoundingMode.HALF_EVEN); + return BigDecimal.valueOf(totalTax == null ? 0d : totalTax) + .setScale(2, RoundingMode.HALF_EVEN).add(totalPriceWithoutTaxBD); + } + +} diff --git a/adyenv6core/src/com/adyen/v6/service/DefaultAdyenModificationsApiService.java b/adyenv6core/src/com/adyen/v6/service/DefaultAdyenModificationsApiService.java new file mode 100644 index 000000000..a29b89715 --- /dev/null +++ b/adyenv6core/src/com/adyen/v6/service/DefaultAdyenModificationsApiService.java @@ -0,0 +1,78 @@ +package com.adyen.v6.service; + +import com.adyen.model.checkout.PaymentCaptureRequest; +import com.adyen.model.checkout.PaymentCaptureResponse; +import com.adyen.model.checkout.PaymentRefundRequest; +import com.adyen.model.checkout.PaymentRefundResponse; +import com.adyen.model.checkout.PaymentReversalRequest; +import com.adyen.model.checkout.PaymentReversalResponse; +import com.adyen.service.checkout.ModificationsApi; +import com.adyen.v6.util.AmountUtil; +import de.hybris.platform.store.BaseStoreModel; +import org.apache.log4j.Logger; + +import java.math.BigDecimal; +import java.util.Currency; + +public class DefaultAdyenModificationsApiService extends AbstractAdyenApiService implements AdyenModificationsApiService { + + private static final Logger LOG = Logger.getLogger(DefaultAdyenModificationsApiService.class); + + public DefaultAdyenModificationsApiService(BaseStoreModel baseStore) { + super(baseStore); + } + + @Override + public PaymentCaptureResponse capture(final BigDecimal amount, final Currency currency, final String authReference, final String merchantReference) throws Exception { + LOG.debug("Captures"); + + final ModificationsApi modificationsApi = new ModificationsApi(getClient()); + + final PaymentCaptureRequest captureRequest = new PaymentCaptureRequest(); + captureRequest.setAmount(AmountUtil.createAmount(amount, currency.getCurrencyCode())); + captureRequest.setReference(merchantReference); + captureRequest.setMerchantAccount(getBaseStore().getAdyenMerchantAccount()); + + LOG.debug(captureRequest); + PaymentCaptureResponse paymentCaptureResponse = modificationsApi.captureAuthorisedPayment(getBaseStore().getAdyenMerchantAccount(), captureRequest); + LOG.debug(paymentCaptureResponse); + + return paymentCaptureResponse; + } + + + @Override + public PaymentReversalResponse cancelOrRefund(final String paymentPspReference, final String merchantReference) throws Exception { + LOG.debug("Cancel or refunds"); + + final ModificationsApi modificationsApi = new ModificationsApi(getClient()); + + final PaymentReversalRequest reversalRequest = new PaymentReversalRequest(); + reversalRequest.setReference(merchantReference); + reversalRequest.setMerchantAccount(getBaseStore().getAdyenMerchantAccount()); + + LOG.debug(reversalRequest); + PaymentReversalResponse paymentReversalResponse = modificationsApi.refundOrCancelPayment(paymentPspReference, reversalRequest); + LOG.debug(paymentReversalResponse); + + return paymentReversalResponse; + } + + public PaymentRefundResponse refund(final BigDecimal amount, final Currency currency, final String paymentPspReference, final String reference) throws Exception { + LOG.debug("Refunds"); + + final ModificationsApi modificationsApi = new ModificationsApi(getClient()); + + final PaymentRefundRequest paymentRefundRequest = new PaymentRefundRequest(); + paymentRefundRequest.setAmount(AmountUtil.createAmount(amount, currency.getCurrencyCode())); + paymentRefundRequest.setMerchantAccount(getBaseStore().getAdyenMerchantAccount()); + paymentRefundRequest.setReference(reference); + + LOG.debug(paymentRefundRequest); + PaymentRefundResponse paymentRefundResponse = modificationsApi.refundCapturedPayment(paymentPspReference, paymentRefundRequest); + LOG.debug(paymentRefundResponse); + + return paymentRefundResponse; + } + +} diff --git a/adyenv6core/src/com/adyen/v6/service/DefaultAdyenNotificationService.java b/adyenv6core/src/com/adyen/v6/service/DefaultAdyenNotificationService.java index ec294cf06..c7d63aa16 100644 --- a/adyenv6core/src/com/adyen/v6/service/DefaultAdyenNotificationService.java +++ b/adyenv6core/src/com/adyen/v6/service/DefaultAdyenNotificationService.java @@ -22,7 +22,7 @@ import com.adyen.model.notification.NotificationRequest; import com.adyen.model.notification.NotificationRequestItem; -import com.adyen.notification.NotificationHandler; +import com.adyen.notification.WebhookHandler; import com.adyen.v6.constants.Adyenv6coreConstants; import com.adyen.v6.model.AdyenNotificationModel; import com.adyen.v6.model.NotificationItemModel; @@ -44,6 +44,7 @@ import org.apache.log4j.Logger; import org.springframework.transaction.support.TransactionOperations; +import java.io.IOException; import java.util.Date; import java.util.UUID; @@ -140,8 +141,8 @@ public void saveNotifications(final NotificationRequest notificationRequest) { } @Override - public NotificationRequest getNotificationRequestFromString(final String requestString) { - NotificationHandler notificationHandler = new NotificationHandler(); + public NotificationRequest getNotificationRequestFromString(final String requestString) throws IOException { + WebhookHandler notificationHandler = new WebhookHandler(); NotificationRequest notificationRequest = notificationHandler.handleNotificationJson(requestString); LOG.debug(notificationRequest); return notificationRequest; diff --git a/adyenv6core/src/com/adyen/v6/service/DefaultAdyenOrderService.java b/adyenv6core/src/com/adyen/v6/service/DefaultAdyenOrderService.java index 6170dc4ee..6b74384a1 100644 --- a/adyenv6core/src/com/adyen/v6/service/DefaultAdyenOrderService.java +++ b/adyenv6core/src/com/adyen/v6/service/DefaultAdyenOrderService.java @@ -20,59 +20,52 @@ */ package com.adyen.v6.service; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Objects; - -import com.adyen.util.DateUtil; -import org.apache.log4j.Logger; -import com.adyen.model.FraudCheckResult; -import com.adyen.model.FraudResult; -import com.adyen.model.PaymentResult; -import com.adyen.model.checkout.CheckoutPaymentsAction; -import com.adyen.model.checkout.PaymentsResponse; -import com.adyen.v6.converters.PaymentsResponseConverter; +import com.adyen.model.checkout.FraudCheckResult; +import com.adyen.model.checkout.FraudResult; import de.hybris.platform.basecommerce.enums.FraudStatus; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; import de.hybris.platform.fraud.model.FraudReportModel; import de.hybris.platform.fraud.model.FraudSymptomScoringModel; import de.hybris.platform.servicelayer.model.ModelService; +import org.apache.commons.lang.StringUtils; +import org.apache.log4j.Logger; import org.springframework.transaction.support.TransactionOperations; -import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO; -import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_BOLETO_SANTANDER; -import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_MULTIBANCO; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.function.BiConsumer; + import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_PROVIDER; public class DefaultAdyenOrderService implements AdyenOrderService { private static final Logger LOG = Logger.getLogger(DefaultAdyenOrderService.class); - private static final String ADDITIONAL_DATA_CARD_TYPE = "checkout.cardAddedBrand"; private ModelService modelService; - private PaymentsResponseConverter paymentsResponseConverter; private TransactionOperations transactionTemplate; + private final SimpleDateFormat expDateFormatter = new SimpleDateFormat("M/yyyy"); @Override - public FraudReportModel createFraudReportFromPaymentsResponse(PaymentsResponse paymentsResponse) { + public FraudReportModel createFraudReportFromPaymentsResponse(String pspReference, FraudResult fraudResult) { FraudReportModel fraudReport = modelService.create(FraudReportModel.class); - FraudResult fraudResult = paymentsResponse.getFraudResult(); if (fraudResult == null) { LOG.warn("No fraud result found"); return null; } - fraudReport.setCode(paymentsResponse.getPspReference()); + fraudReport.setCode(pspReference); fraudReport.setStatus(FraudStatus.OK); fraudReport.setExplanation("Score: " + fraudResult.getAccountScore()); fraudReport.setTimestamp(new Date()); fraudReport.setProvider(PAYMENT_PROVIDER); List fraudSymptomScorings = new ArrayList<>(); - for (FraudCheckResult fraudCheckResult : fraudResult.getFraudCheckResults()) { + for (FraudCheckResult fraudCheckResult : fraudResult.getResults()) { FraudSymptomScoringModel fraudSymptomScoring = modelService.create(FraudSymptomScoringModel.class); Integer score = fraudCheckResult.getAccountScore(); @@ -97,12 +90,6 @@ public FraudReportModel createFraudReportFromPaymentsResponse(PaymentsResponse p } - @Override - public FraudReportModel createFraudReportFromPaymentResult(PaymentResult paymentResult) { - PaymentsResponse paymentsResponse = paymentsResponseConverter.convert(paymentResult); - return createFraudReportFromPaymentsResponse(paymentsResponse); - } - @Override public void storeFraudReport(FraudReportModel fraudReport) { transactionTemplate.execute(transactionStatus -> { @@ -117,77 +104,51 @@ public void storeFraudReport(FraudReportModel fraudReport) { } @Override - public void storeFraudReportFromPaymentsResponse(OrderModel order, PaymentsResponse paymentsResponse) { - FraudReportModel fraudReport = createFraudReportFromPaymentsResponse(paymentsResponse); - if(fraudReport != null) { + public void storeFraudReport(OrderModel order, String pspReference, FraudResult fraudResult) { + FraudReportModel fraudReport = createFraudReportFromPaymentsResponse(pspReference, fraudResult); + if (fraudReport != null) { fraudReport.setOrder(order); storeFraudReport(fraudReport); } } @Override - public void storeFraudReportFromPaymentResult(OrderModel order, PaymentResult paymentResult) { - PaymentsResponse paymentsResponse = paymentsResponseConverter.convert(paymentResult); - storeFraudReportFromPaymentsResponse(order, paymentsResponse); - } - - @Override - public void updateOrderFromPaymentsResponse(OrderModel order, PaymentsResponse paymentsResponse) { + public void updatePaymentInfo(OrderModel order, String paymentMethodType, Map additionalData) { if (order == null) { LOG.error("Order is null"); return; } PaymentInfoModel paymentInfo = order.getPaymentInfo(); - - if(Objects.nonNull(paymentsResponse.getAdditionalData()) && paymentsResponse.getAdditionalData().containsKey(ADDITIONAL_DATA_CARD_TYPE)){ - paymentInfo.setAdyenPaymentMethod(paymentsResponse.getAdditionalData().get(ADDITIONAL_DATA_CARD_TYPE)); - } - else if(paymentsResponse.getPaymentMethod()!=null) { - paymentInfo.setAdyenPaymentMethod(paymentsResponse.getPaymentMethod().getType()); + if(StringUtils.isNotEmpty(paymentMethodType)) { + paymentInfo.setAdyenPaymentMethod(paymentMethodType); + }else { + updatePaymentInfo(paymentInfo, additionalData, "checkout.cardAddedBrand", PaymentInfoModel::setAdyenPaymentMethod); } - //Card specific data - paymentInfo.setAdyenAuthCode(paymentsResponse.getAuthCode()); - paymentInfo.setAdyenAvsResult(paymentsResponse.getAvsResult()); - paymentInfo.setAdyenCardBin(paymentsResponse.getCardBin()); - paymentInfo.setAdyenCardHolder(paymentsResponse.getCardHolderName()); - paymentInfo.setAdyenCardSummary(paymentsResponse.getCardSummary()); - paymentInfo.setAdyenCardExpiry(paymentsResponse.getExpiryDate()); - paymentInfo.setAdyenThreeDOffered(paymentsResponse.get3DOffered()); - paymentInfo.setAdyenThreeDAuthenticated(paymentsResponse.get3DAuthenticated()); - - CheckoutPaymentsAction action = paymentsResponse.getAction(); - - if (action != null) { - if (PAYMENT_METHOD_MULTIBANCO.equals(action.getPaymentMethodType())) { - //Multibanco data - paymentInfo.setAdyenMultibancoEntity(action.getEntity()); - paymentInfo.setAdyenMultibancoAmount(BigDecimal.valueOf(action.getInitialAmount().getValue())); - paymentInfo.setAdyenMultibancoDeadline(action.getExpiresAt()); - paymentInfo.setAdyenMultibancoReference(action.getReference()); - } else if (PAYMENT_METHOD_BOLETO.equals(action.getPaymentMethodType()) || PAYMENT_METHOD_BOLETO_SANTANDER.equals(action.getPaymentMethodType())) { - //Boleto data - paymentInfo.setAdyenBoletoUrl(action.getDownloadUrl()); - paymentInfo.setAdyenBoletoBarCodeReference(action.getReference()); - paymentInfo.setAdyenBoletoExpirationDate(DateUtil.parseYmdDate(action.getExpiresAt())); + updatePaymentInfo(paymentInfo, additionalData, "cardSummary", PaymentInfoModel::setAdyenCardSummary); + updatePaymentInfo(paymentInfo, additionalData, "authCode", PaymentInfoModel::setAdyenAuthCode); + updatePaymentInfo(paymentInfo, additionalData, "avsResult", PaymentInfoModel::setAdyenAvsResult); + updatePaymentInfo(paymentInfo, additionalData, "cardBin", PaymentInfoModel::setAdyenCardBin); + updatePaymentInfo(paymentInfo, additionalData, "cardHolderName", PaymentInfoModel::setAdyenCardHolder); + updatePaymentInfo(paymentInfo, additionalData, "expiryDate", (info, value) -> { + try { + info.setAdyenCardExpiry(expDateFormatter.parse(value)); + } catch (ParseException e) { + LOG.warn("Failed to parse expiry date", e); } - } - - //pos receipt - paymentInfo.setAdyenPosReceipt(paymentsResponse.getAdditionalDataByKey("pos.receipt")); - - transactionTemplate.execute(transactionStatus -> { - modelService.save(paymentInfo); - storeFraudReportFromPaymentsResponse(order, paymentsResponse); - return null; }); + updatePaymentInfo(paymentInfo, additionalData, "threeDOffered", (info, value) -> info.setAdyenThreeDOffered(Boolean.valueOf(value))); + updatePaymentInfo(paymentInfo, additionalData, "threeDAuthenticated", (info, value) -> info.setAdyenThreeDAuthenticated(Boolean.valueOf(value))); + updatePaymentInfo(paymentInfo, additionalData, "pos.receipt", PaymentInfoModel::setAdyenPosReceipt); + + modelService.save(paymentInfo); } - @Override - public void updateOrderFromPaymentResult(OrderModel order, PaymentResult paymentResult) { - PaymentsResponse paymentsResponse = paymentsResponseConverter.convert(paymentResult); - updateOrderFromPaymentsResponse(order, paymentsResponse); + private void updatePaymentInfo(PaymentInfoModel paymentInfo, Map additionalData, String key, BiConsumer setter) { + if (additionalData != null && additionalData.containsKey(key)) { + setter.accept(paymentInfo, additionalData.get(key)); + } } public ModelService getModelService() { @@ -198,14 +159,6 @@ public void setModelService(ModelService modelService) { this.modelService = modelService; } - public PaymentsResponseConverter getPaymentsResponseConverter() { - return paymentsResponseConverter; - } - - public void setPaymentsResponseConverter(PaymentsResponseConverter paymentsResponseConverter) { - this.paymentsResponseConverter = paymentsResponseConverter; - } - public void setTransactionTemplate(TransactionOperations transactionTemplate) { this.transactionTemplate = transactionTemplate; } diff --git a/adyenv6core/src/com/adyen/v6/service/DefaultAdyenPaymentService.java b/adyenv6core/src/com/adyen/v6/service/DefaultAdyenPaymentService.java deleted file mode 100644 index d6c7c080e..000000000 --- a/adyenv6core/src/com/adyen/v6/service/DefaultAdyenPaymentService.java +++ /dev/null @@ -1,560 +0,0 @@ -/* - * ###### - * ###### - * ############ ####( ###### #####. ###### ############ ############ - * ############# #####( ###### #####. ###### ############# ############# - * ###### #####( ###### #####. ###### ##### ###### ##### ###### - * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### - * ###### ###### #####( ###### #####. ###### ##### ##### ###### - * ############# ############# ############# ############# ##### ###### - * ############ ############ ############# ############ ##### ###### - * ###### - * ############# - * ############ - * - * Adyen Hybris Extension - * - * Copyright (c) 2017 Adyen B.V. - * This file is open source and available under the MIT license. - * See the LICENSE file for more info. - */ -package com.adyen.v6.service; - -import com.adyen.Client; -import com.adyen.Config; -import com.adyen.enums.Environment; -import com.adyen.model.Amount; -import com.adyen.model.PaymentRequest; -import com.adyen.model.PaymentResult; -import com.adyen.model.checkout.*; -import com.adyen.model.modification.CancelOrRefundRequest; -import com.adyen.model.modification.CaptureRequest; -import com.adyen.model.modification.ModificationResult; -import com.adyen.model.modification.RefundRequest; -import com.adyen.model.recurring.RecurringDetail; -import com.adyen.model.recurring.*; -import com.adyen.model.terminal.ConnectedTerminalsRequest; -import com.adyen.model.terminal.ConnectedTerminalsResponse; -import com.adyen.model.terminal.TerminalAPIRequest; -import com.adyen.model.terminal.TerminalAPIResponse; -import com.adyen.service.*; -import com.adyen.service.exception.ApiException; -import com.adyen.terminal.serialization.TerminalAPIGsonBuilder; -import com.adyen.util.Util; -import com.adyen.v6.enums.RecurringContractMode; -import com.adyen.v6.factory.AdyenRequestFactory; -import com.adyen.v6.model.RequestInfo; -import de.hybris.platform.commercefacades.order.data.CartData; -import de.hybris.platform.commercefacades.product.data.PriceData; -import de.hybris.platform.core.model.order.AbstractOrderModel; -import de.hybris.platform.core.model.user.CustomerModel; -import de.hybris.platform.store.BaseStoreModel; -import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; - -import javax.servlet.http.HttpServletRequest; -import java.io.IOException; -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.stream.Collectors; - -import static com.adyen.v6.constants.Adyenv6coreConstants.PLUGIN_NAME; -import static com.adyen.v6.constants.Adyenv6coreConstants.PLUGIN_VERSION; - -public class DefaultAdyenPaymentService implements AdyenPaymentService { - - private static final Logger LOG = Logger.getLogger(DefaultAdyenPaymentService.class); - private static final int POS_REQUEST_TIMEOUT = 25000; - private static final String CHECKOUT_ENDPOINT_LIVE_IN_SUFFIX = "-checkout-live-in.adyenpayments.com/checkout"; - - private BaseStoreModel baseStore; - private AdyenRequestFactory adyenRequestFactory; - private Config config; - private Client client; - private Config posConfig; - private Client posClient; - - /** - * Prevent initialization without base store - */ - private DefaultAdyenPaymentService() { - } - - public DefaultAdyenPaymentService(final BaseStoreModel baseStore) { - this.baseStore = baseStore; - - if (Boolean.TRUE.equals(baseStore.getAdyenPosEnabled())) { - posConfig = new Config(); - posConfig.setApiKey(baseStore.getAdyenPosApiKey()); - posConfig.setMerchantAccount(baseStore.getAdyenPosMerchantAccount()); - posConfig.setReadTimeoutMillis(POS_REQUEST_TIMEOUT); - posConfig.setApplicationName(PLUGIN_NAME + " v" + PLUGIN_VERSION); - posClient = new Client(posConfig); - - if (Boolean.TRUE.equals(baseStore.getAdyenTestMode())) { - posClient.setEnvironment(Environment.TEST, null); - } else { - posClient.setEnvironment(Environment.LIVE, null); - } - } - - config = new Config(); - config.setApiKey(baseStore.getAdyenAPIKey()); - config.setMerchantAccount(baseStore.getAdyenMerchantAccount()); - config.setApplicationName(PLUGIN_NAME + " v" + PLUGIN_VERSION); - client = new Client(config); - - if (Boolean.TRUE.equals(baseStore.getAdyenTestMode())) { - client.setEnvironment(Environment.TEST, null); - } else { - createLiveEnvironment(baseStore); - } - - } - - private void createLiveEnvironment(final BaseStoreModel baseStore) { - - this.config.setEnvironment(Environment.LIVE); - this.config.setMarketPayEndpoint(Client.MARKETPAY_ENDPOINT_LIVE); - this.config.setHppEndpoint(Client.HPP_LIVE); - this.config.setCheckoutEndpoint(Client.ENDPOINT_PROTOCOL + baseStore.getAdyenAPIEndpointPrefix() + Client.CHECKOUT_ENDPOINT_LIVE_SUFFIX); - this.config.setEndpoint(Client.ENDPOINT_PROTOCOL + baseStore.getAdyenAPIEndpointPrefix() + Client.ENDPOINT_LIVE_SUFFIX); - this.config.setTerminalApiCloudEndpoint(Client.TERMINAL_API_ENDPOINT_LIVE); - this.config.setPosTerminalManagementApiEndpoint(Client.POS_TERMINAL_MANAGEMENT_ENDPOINT_LIVE); - this.config.setDataProtectionEndpoint(Client.DATA_PROTECTION_ENDPOINT_LIVE); - } - - @Override - public PaymentResult authorise(final CartData cartData, final HttpServletRequest request, final CustomerModel customerModel) throws Exception { - LOG.debug("Authorize"); - Payment payment = new Payment(client); - - PaymentRequest paymentRequest = getAdyenRequestFactory().createAuthorizationRequest(client.getConfig().getMerchantAccount(), - cartData, - request, - customerModel, - baseStore.getAdyenRecurringContractMode()); - - - LOG.debug(paymentRequest); - PaymentResult paymentResult = payment.authorise(paymentRequest); - LOG.debug(paymentResult); - - return paymentResult; - } - - @Override - public ConnectedTerminalsResponse getConnectedTerminals() throws IOException, ApiException { - LOG.debug("Get connected terminals"); - PosPayment posPayment = new PosPayment(posClient); - ConnectedTerminalsRequest connectedTerminalsRequest = new ConnectedTerminalsRequest(); - connectedTerminalsRequest.setMerchantAccount(posConfig.getMerchantAccount()); - if (baseStore.getAdyenPosStoreId() != null && StringUtils.isNotEmpty(baseStore.getAdyenPosStoreId())) { - connectedTerminalsRequest.setStore(baseStore.getAdyenPosStoreId()); - } - LOG.debug(connectedTerminalsRequest); - ConnectedTerminalsResponse connectedTerminalsResponse = posPayment.connectedTerminals(connectedTerminalsRequest); - LOG.debug(connectedTerminalsResponse); - return connectedTerminalsResponse; - - } - - @Override - public PaymentsResponse authorisePayment(final CartData cartData, final RequestInfo requestInfo, final CustomerModel customerModel) throws Exception { - LOG.debug("Authorize payment"); - - Checkout checkout = new Checkout(client); - - PaymentsRequest paymentsRequest = getAdyenRequestFactory().createPaymentsRequest(client.getConfig().getMerchantAccount(), - cartData, - requestInfo, - customerModel, - baseStore.getAdyenRecurringContractMode(), - baseStore.getAdyenGuestUserTokenization()); - - LOG.debug(paymentsRequest); - PaymentsResponse paymentsResponse = checkout.payments(paymentsRequest); - LOG.debug(paymentsResponse); - - return paymentsResponse; - } - - @Override - public PaymentsResponse componentPayment(final CartData cartData, final PaymentMethodDetails paymentMethodDetails, final RequestInfo requestInfo, final CustomerModel customerModel) throws Exception { - LOG.debug("Component payment"); - - Checkout checkout = new Checkout(client); - - PaymentsRequest paymentsRequest = getAdyenRequestFactory().createPaymentsRequest(client.getConfig().getMerchantAccount(), - cartData, - paymentMethodDetails, - requestInfo, - customerModel); - - LOG.debug(paymentsRequest); - PaymentsResponse paymentsResponse = checkout.payments(paymentsRequest); - LOG.debug(paymentsResponse); - - return paymentsResponse; - } - - @Override - public PaymentsDetailsResponse authorise3DSPayment(Map details) throws Exception { - LOG.debug("Authorize 3DS payment"); - - Checkout checkout = new Checkout(client); - PaymentsDetailsRequest paymentsDetailsRequest = getAdyenRequestFactory().create3DSPaymentsRequest(details); - - LOG.debug(paymentsDetailsRequest); - PaymentsDetailsResponse paymentsDetailsResponse = checkout.paymentsDetails(paymentsDetailsRequest); - LOG.debug(paymentsDetailsResponse); - - return paymentsDetailsResponse; - } - - @Override - public ModificationResult capture(final BigDecimal amount, final Currency currency, final String authReference, final String merchantReference) throws Exception { - LOG.debug("Capture"); - - Modification modification = new Modification(client); - - CaptureRequest captureRequest = getAdyenRequestFactory().createCaptureRequest(client.getConfig().getMerchantAccount(), amount, currency, authReference, merchantReference); - - LOG.debug(captureRequest); - ModificationResult modificationResult = modification.capture(captureRequest); - LOG.debug(modificationResult); - - return modificationResult; - } - - @Override - public PaymentCaptureResource captures(final BigDecimal amount, final Currency currency, final String authReference, final String merchantReference) throws Exception { - LOG.debug("Captures"); - - final Checkout checkout = new Checkout(client); - - final CreatePaymentCaptureRequest captureRequest = new CreatePaymentCaptureRequest(); - captureRequest.setAmount(Util.createAmount(amount, currency.getCurrencyCode())); - captureRequest.setReference(merchantReference); - captureRequest.setMerchantAccount(client.getConfig().getMerchantAccount()); - - LOG.debug(captureRequest); - final PaymentCaptureResource paymentCaptureResource = checkout.paymentsCaptures(authReference, captureRequest); - LOG.debug(paymentCaptureResource); - - return paymentCaptureResource; - } - - @Override - public ModificationResult cancelOrRefund(final String authReference, final String merchantReference) throws Exception { - LOG.debug("Cancel or refund"); - - Modification modification = new Modification(client); - - CancelOrRefundRequest cancelRequest = getAdyenRequestFactory().createCancelOrRefundRequest(client.getConfig().getMerchantAccount(), authReference, merchantReference); - - LOG.debug(cancelRequest); - ModificationResult modificationResult = modification.cancelOrRefund(cancelRequest); - LOG.debug(modificationResult); - - return modificationResult; - } - - @Override - public PaymentReversalResource cancelOrRefunds(final String authReference, final String merchantReference) throws Exception { - LOG.debug("Cancel or refunds"); - - final Checkout checkout = new Checkout(client); - - final CreatePaymentReversalRequest reversalRequest = new CreatePaymentReversalRequest(); - reversalRequest.setReference(merchantReference); - reversalRequest.setMerchantAccount(client.getConfig().getMerchantAccount()); - - LOG.debug(reversalRequest); - final PaymentReversalResource paymentReversalResource = checkout.paymentsReversals(authReference, reversalRequest); - LOG.debug(paymentReversalResource); - - return paymentReversalResource; - } - - @Override - public ModificationResult refund(final BigDecimal amount, final Currency currency, final String authReference, final String merchantReference) throws Exception { - LOG.debug("Refund"); - - Modification modification = new Modification(client); - - RefundRequest refundRequest = getAdyenRequestFactory().createRefundRequest(client.getConfig().getMerchantAccount(), amount, currency, authReference, merchantReference); - - LOG.debug(refundRequest); - ModificationResult modificationResult = modification.refund(refundRequest); - LOG.debug(modificationResult); - - return modificationResult; - } - - @Override - public PaymentRefundResource refunds(final BigDecimal amount, final Currency currency, final String pspReference, final String reference) throws Exception { - LOG.debug("Refunds"); - - final Checkout checkout = new Checkout(client); - - final CreatePaymentRefundRequest refundRequest = new CreatePaymentRefundRequest(); - refundRequest.setAmount(Util.createAmount(amount, currency.getCurrencyCode())); - refundRequest.setMerchantAccount(client.getConfig().getMerchantAccount()); - refundRequest.setReference(reference); - - LOG.debug(refundRequest); - final PaymentRefundResource paymentRefundResource = checkout.paymentsRefunds(pspReference, refundRequest); - LOG.debug(paymentRefundResource); - - return paymentRefundResource; - } - - - @Override - public List getPaymentMethods(final BigDecimal amount, - final String currency, - final String countryCode, - final String shopperLocale, - final String shopperReference) throws IOException, ApiException { - - final PaymentMethodsResponse response = getPaymentMethodsResponse(amount, currency, countryCode, shopperLocale, shopperReference); - return response.getPaymentMethods(); - } - - @Override - public PaymentMethodsResponse getPaymentMethodsResponse(final BigDecimal amount, - final String currency, - final String countryCode, - final String shopperLocale, - final String shopperReference) throws IOException, ApiException { - - LOG.debug("Get payment methods response"); - - Checkout checkout = new Checkout(client); - PaymentMethodsRequest request = new PaymentMethodsRequest(); - request.merchantAccount(client.getConfig().getMerchantAccount()).amount(Util.createAmount(amount, currency)).countryCode(countryCode); - - if (!StringUtils.isEmpty(shopperLocale)) { - request.setShopperLocale(shopperLocale); - } - - if (!StringUtils.isEmpty(shopperReference)) { - request.setShopperReference(shopperReference); - } - - LOG.debug(request); - final PaymentMethodsResponse response = checkout.paymentMethods(request); - LOG.debug(response); - - return response; - } - - @Override - @Deprecated - public List getPaymentMethods(final BigDecimal amount, - final String currency, - final String countryCode, - final String shopperLocale) throws IOException { - try { - return getPaymentMethods(amount, currency, countryCode, shopperLocale, null); - } catch (ApiException e) { - LOG.error(e); - } - return null; - } - - @Override - @Deprecated - public List getStoredCards(final String customerId) throws IOException, ApiException { - LOG.debug("Get stored cards"); - - if (customerId == null) { - LOG.info("Customer id is null"); - return new ArrayList<>(); - } - - com.adyen.service.Recurring recurring = new com.adyen.service.Recurring(client); - - RecurringDetailsRequest request = getAdyenRequestFactory().createListRecurringDetailsRequest(client.getConfig().getMerchantAccount(), customerId); - - LOG.debug(request); - RecurringDetailsResult result = recurring.listRecurringDetails(request); - LOG.debug(result); - - //Return only cards - List storedCards = result.getRecurringDetails() - .stream() - .filter(detail -> (detail.getCard() != null && detail.getRecurringDetailReference() != null)) - .collect(Collectors.toList()); - - return storedCards; - } - - @Override - public boolean disableStoredCard(final String customerId, final String recurringReference) throws IOException, ApiException { - LOG.debug("Disable stored card"); - - com.adyen.service.Recurring recurring = new com.adyen.service.Recurring(client); - - DisableRequest request = getAdyenRequestFactory().createDisableRequest(client.getConfig().getMerchantAccount(), customerId, recurringReference); - - LOG.debug(request); - DisableResult result = recurring.disable(request); - LOG.debug(result); - - return ("[detail-successfully-disabled]".equals(result.getResponse()) || "[all-details-successfully-disabled]".equals(result.getResponse())); - } - - @Override - public PaymentsDetailsResponse getPaymentDetailsFromPayload(HashMap details) throws Exception { - LOG.debug("Get payment details from payload"); - - Checkout checkout = new Checkout(client); - - PaymentsDetailsRequest paymentsDetailsRequest = new PaymentsDetailsRequest(); - paymentsDetailsRequest.setDetails(details); - - LOG.debug(paymentsDetailsRequest); - PaymentsDetailsResponse paymentsResponse = checkout.paymentsDetails(paymentsDetailsRequest); - LOG.debug(paymentsResponse); - - return paymentsResponse; - } - - @Override - public PaymentsDetailsResponse getPaymentDetailsFromPayload(Map details, String paymentData) throws Exception { - LOG.debug("Get payment details from payload"); - - Checkout checkout = new Checkout(client); - PaymentsDetailsRequest paymentsDetailsRequest = new PaymentsDetailsRequest(); - paymentsDetailsRequest.setDetails(details); - paymentsDetailsRequest.setPaymentData(paymentData); - - LOG.debug(paymentsDetailsRequest); - PaymentsDetailsResponse paymentsResponse = checkout.paymentsDetails(paymentsDetailsRequest); - LOG.debug(paymentsResponse); - - return paymentsResponse; - } - - - @Override - public CreateCheckoutSessionResponse getPaymentSessionData(final CartData cartData) throws IOException, ApiException { - final Checkout checkout = new Checkout(client); - final PriceData totalPriceWithTax = cartData.getTotalPriceWithTax(); - - final CreateCheckoutSessionRequest createCheckoutSessionRequest = new CreateCheckoutSessionRequest(); - createCheckoutSessionRequest.amount(Util.createAmount(totalPriceWithTax.getValue(), totalPriceWithTax.getCurrencyIso())); - createCheckoutSessionRequest.merchantAccount(getBaseStore().getAdyenMerchantAccount()); - if (cartData.getDeliveryAddress() != null) { - createCheckoutSessionRequest.countryCode(cartData.getDeliveryAddress().getCountry().getIsocode()); - } - createCheckoutSessionRequest.returnUrl(Optional.ofNullable(cartData.getAdyenReturnUrl()).orElse("returnUrl")); - createCheckoutSessionRequest.reference(cartData.getCode()); - - return checkout.sessions(createCheckoutSessionRequest); - } - - @Override - public CreateCheckoutSessionResponse getPaymentSessionData(final Amount amount) throws IOException, ApiException { - final Checkout checkout = new Checkout(client); - - final CreateCheckoutSessionRequest createCheckoutSessionRequest = new CreateCheckoutSessionRequest(); - createCheckoutSessionRequest.amount(amount); - createCheckoutSessionRequest.merchantAccount(getBaseStore().getAdyenMerchantAccount()); - createCheckoutSessionRequest.returnUrl("returnUrl"); //dummy url because it's required by api - - return checkout.sessions(createCheckoutSessionRequest); - } - - @Override - public String getDeviceFingerprintUrl() { - DateFormat df = new SimpleDateFormat("yyyyMMdd"); - Date today = Calendar.getInstance().getTime(); - return "https://live.adyen.com/hpp/js/df.js?v=" + df.format(today); - } - - /** - * Send POS Payment Request using Adyen Terminal API - */ - @Override - public TerminalAPIResponse sendSyncPosPaymentRequest(CartData cartData, CustomerModel customer, String serviceId) throws Exception { - LOG.debug("Send sync pos payment request"); - - TerminalCloudAPI terminalCloudAPI = new TerminalCloudAPI(posClient); - - RecurringContractMode recurringContractMode = getBaseStore().getAdyenPosRecurringContractMode(); - TerminalAPIRequest terminalApiRequest = adyenRequestFactory.createTerminalAPIRequest(cartData, customer, recurringContractMode, serviceId); - - LOG.debug(TerminalAPIGsonBuilder.create().toJson(terminalApiRequest)); - TerminalAPIResponse terminalApiResponse = terminalCloudAPI.sync(terminalApiRequest); - - LOG.debug(TerminalAPIGsonBuilder.create().toJson(terminalApiResponse)); - return terminalApiResponse; - } - - /** - * Send POS Status Request using Adyen Terminal API - */ - @Override - public TerminalAPIResponse sendSyncPosStatusRequest(CartData cartData, String originalServiceId) throws Exception { - LOG.debug("Send sync pos status request"); - - TerminalCloudAPI terminalCloudAPI = new TerminalCloudAPI(posClient); - - TerminalAPIRequest terminalApiRequest = adyenRequestFactory.createTerminalAPIRequestForStatus(cartData, originalServiceId); - - LOG.debug(TerminalAPIGsonBuilder.create().toJson(terminalApiRequest)); - TerminalAPIResponse terminalApiResponse = terminalCloudAPI.sync(terminalApiRequest); - - LOG.debug(TerminalAPIGsonBuilder.create().toJson(terminalApiResponse)); - return terminalApiResponse; - } - - @Override - public BigDecimal calculateAmountWithTaxes(final AbstractOrderModel abstractOrderModel) { - final Double totalPrice = abstractOrderModel.getTotalPrice(); - final Double totalTax = Boolean.TRUE.equals(abstractOrderModel.getNet()) ? abstractOrderModel.getTotalTax() : Double.valueOf(0d); - final BigDecimal totalPriceWithoutTaxBD = BigDecimal.valueOf(totalPrice == null ? 0d : totalPrice).setScale(2, - RoundingMode.HALF_EVEN); - return BigDecimal.valueOf(totalTax == null ? 0d : totalTax) - .setScale(2, RoundingMode.HALF_EVEN).add(totalPriceWithoutTaxBD); - } - - public AdyenRequestFactory getAdyenRequestFactory() { - return adyenRequestFactory; - } - - public void setAdyenRequestFactory(AdyenRequestFactory adyenRequestFactory) { - this.adyenRequestFactory = adyenRequestFactory; - } - - public BaseStoreModel getBaseStore() { - return baseStore; - } - - public void setBaseStore(BaseStoreModel baseStore) { - this.baseStore = baseStore; - } - - public void setConfig(Config config) { - this.config = config; - } - - public Client getClient() { - return client; - } - - public void setClient(Client client) { - this.client = client; - } - - public Config getConfig() { - return config; - } - -} diff --git a/adyenv6core/src/com/adyen/v6/service/DefaultAdyenTransactionService.java b/adyenv6core/src/com/adyen/v6/service/DefaultAdyenTransactionService.java index 877e3cf0e..0783061b0 100644 --- a/adyenv6core/src/com/adyen/v6/service/DefaultAdyenTransactionService.java +++ b/adyenv6core/src/com/adyen/v6/service/DefaultAdyenTransactionService.java @@ -20,7 +20,7 @@ */ package com.adyen.v6.service; -import com.adyen.model.checkout.PaymentsResponse; +import com.adyen.model.checkout.PaymentDetailsResponse; import com.adyen.v6.factory.AdyenPaymentServiceFactory; import com.adyen.v6.model.AdyenNotificationModel; import de.hybris.platform.core.model.c2l.CurrencyModel; @@ -257,7 +257,7 @@ public PaymentTransactionEntryModel createCancellationTransaction(final PaymentT } @Override - public PaymentTransactionModel createPaymentTransactionFromResultCode(final AbstractOrderModel abstractOrderModel, final String merchantTransactionCode, final String pspReference, final PaymentsResponse.ResultCodeEnum resultCodeEnum) { + public PaymentTransactionModel createPaymentTransactionFromResultCode(final AbstractOrderModel abstractOrderModel, final String merchantTransactionCode, final String pspReference, final PaymentDetailsResponse.ResultCodeEnum resultCodeEnum) { return transactionTemplate.execute(transactionStatus -> { final PaymentTransactionModel paymentTransactionModel = createPaymentTransaction(merchantTransactionCode, pspReference, abstractOrderModel); @@ -278,7 +278,7 @@ public PaymentTransactionModel createPaymentTransactionFromResultCode(final Abst }); } - private PaymentTransactionEntryModel createPaymentTransactionEntryModelFromResultCode(final PaymentTransactionModel paymentTransaction, final String merchantCode, final AbstractOrderModel abstractOrderModel, final PaymentsResponse.ResultCodeEnum resultCode) { + private PaymentTransactionEntryModel createPaymentTransactionEntryModelFromResultCode(final PaymentTransactionModel paymentTransaction, final String merchantCode, final AbstractOrderModel abstractOrderModel, final PaymentDetailsResponse.ResultCodeEnum resultCode) { final PaymentTransactionEntryModel transactionEntryModel = modelService.create(PaymentTransactionEntryModel.class); String code = paymentTransaction.getRequestId() + "_" + paymentTransaction.getEntries().size(); @@ -297,7 +297,7 @@ private PaymentTransactionEntryModel createPaymentTransactionEntryModelFromResul return transactionEntryModel; } - private String getTransactionStatusForResultCode(PaymentsResponse.ResultCodeEnum resultCode) { + private String getTransactionStatusForResultCode(PaymentDetailsResponse.ResultCodeEnum resultCode) { switch (resultCode) { case AUTHORISED: case RECEIVED: @@ -322,8 +322,8 @@ private boolean isPartialPayment(AdyenNotificationModel notificationItemModel, A return totalOrderAmount.compareTo(notificationAmount) > 0; } - public AdyenPaymentService getAdyenPaymentService() { - return adyenPaymentServiceFactory.createFromBaseStore(baseStoreService.getCurrentBaseStore()); + public AdyenCheckoutApiService getAdyenPaymentService() { + return adyenPaymentServiceFactory.createAdyenCheckoutApiService(baseStoreService.getCurrentBaseStore()); } public ModelService getModelService() { diff --git a/adyenv6core/src/com/adyen/v6/util/AmountUtil.java b/adyenv6core/src/com/adyen/v6/util/AmountUtil.java new file mode 100644 index 000000000..a4f181d89 --- /dev/null +++ b/adyenv6core/src/com/adyen/v6/util/AmountUtil.java @@ -0,0 +1,38 @@ +package com.adyen.v6.util; + +import com.adyen.model.checkout.Amount; +import de.hybris.platform.commercefacades.product.data.PriceData; + +import java.math.BigDecimal; + +public class AmountUtil { + + public static Amount createAmount(Long value, String currency) { + Amount amount = new Amount(); + amount.setCurrency(currency); + amount.setValue(value); + return amount; + } + + public static Amount createAmount(PriceData priceData) { + Amount amount = new Amount(); + amount.setCurrency(priceData.getCurrencyIso()); + amount.setValue(priceData.getValue().longValue()); + return amount; + } + + public static Amount createAmount(BigDecimal value, String currency) { + Amount amount = new Amount(); + amount.setCurrency(currency); + amount.setValue(value.longValue()); + return amount; + } + + public static Amount createAmount(String value, String currency) { + Amount amount = new Amount(); + amount.setCurrency(currency); + amount.setValue(Long.parseLong(value)); + return amount; + } + +} diff --git a/adyenv6core/testsrc/com/adyen/v6/actions/order/AdyenCheckAuthorizationActionTest.java b/adyenv6core/testsrc/com/adyen/v6/actions/order/AdyenCheckAuthorizationActionTest.java index 3d660154b..5686ba767 100644 --- a/adyenv6core/testsrc/com/adyen/v6/actions/order/AdyenCheckAuthorizationActionTest.java +++ b/adyenv6core/testsrc/com/adyen/v6/actions/order/AdyenCheckAuthorizationActionTest.java @@ -21,7 +21,7 @@ package com.adyen.v6.actions.order; import com.adyen.v6.factory.AdyenPaymentServiceFactory; -import com.adyen.v6.service.AdyenPaymentService; +import com.adyen.v6.service.AdyenCheckoutApiService; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; @@ -67,7 +67,7 @@ public class AdyenCheckAuthorizationActionTest extends AbstractActionTest { @Mock private BaseStoreModel baseStoreModelMock; @Mock - private AdyenPaymentService adyenPaymentServiceMock; + private AdyenCheckoutApiService adyenCheckoutApiServiceMock; @InjectMocks private AdyenCheckAuthorizationAction adyenCheckAuthorizationAction; @@ -83,11 +83,11 @@ public void setUp() { adyenCheckAuthorizationAction = new AdyenCheckAuthorizationAction(adyenPaymentServiceFactoryMock, baseStoreServiceMock); adyenCheckAuthorizationAction.setModelService(modelServiceMock); - when(adyenCheckAuthorizationAction.getAdyenPaymentService(orderModelMock)).thenReturn(adyenPaymentServiceMock); + when(adyenCheckAuthorizationAction.getAdyenPaymentService(orderModelMock)).thenReturn(adyenCheckoutApiServiceMock); when(baseStoreServiceMock.getCurrentBaseStore()).thenReturn(baseStoreModelMock); - when(adyenPaymentServiceFactoryMock.createFromBaseStore(baseStoreModelMock)).thenReturn(adyenPaymentServiceMock); - when(adyenPaymentServiceMock.calculateAmountWithTaxes(orderModelMock)).thenReturn(new BigDecimal(10)); + when(adyenPaymentServiceFactoryMock.createAdyenCheckoutApiService(baseStoreModelMock)).thenReturn(adyenCheckoutApiServiceMock); + when(adyenCheckoutApiServiceMock.calculateAmountWithTaxes(orderModelMock)).thenReturn(new BigDecimal(10)); } @After diff --git a/adyenv6core/testsrc/com/adyen/v6/actions/order/AdyenCheckCaptureActionTest.java b/adyenv6core/testsrc/com/adyen/v6/actions/order/AdyenCheckCaptureActionTest.java index b80bff688..3a8be3156 100644 --- a/adyenv6core/testsrc/com/adyen/v6/actions/order/AdyenCheckCaptureActionTest.java +++ b/adyenv6core/testsrc/com/adyen/v6/actions/order/AdyenCheckCaptureActionTest.java @@ -21,7 +21,7 @@ package com.adyen.v6.actions.order; import com.adyen.v6.factory.AdyenPaymentServiceFactory; -import com.adyen.v6.service.AdyenPaymentService; +import com.adyen.v6.service.AdyenCheckoutApiService; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.core.enums.OrderStatus; import de.hybris.platform.core.model.order.OrderModel; @@ -69,7 +69,7 @@ public class AdyenCheckCaptureActionTest extends AbstractActionTest { @Mock private BaseStoreModel baseStoreModelMock; @Mock - private AdyenPaymentService adyenPaymentServiceMock; + private AdyenCheckoutApiService adyenCheckoutApiServiceMock; @InjectMocks private AdyenCheckCaptureAction adyenCheckCaptureAction; @@ -87,11 +87,11 @@ public void setUp() { adyenCheckCaptureAction = new AdyenCheckCaptureAction(adyenPaymentServiceFactoryMock, baseStoreServiceMock); adyenCheckCaptureAction.setModelService(modelServiceMock); - when(adyenCheckCaptureAction.getAdyenPaymentService(orderModelMock)).thenReturn(adyenPaymentServiceMock); + when(adyenCheckCaptureAction.getAdyenPaymentService(orderModelMock)).thenReturn(adyenCheckoutApiServiceMock); when(baseStoreServiceMock.getCurrentBaseStore()).thenReturn(baseStoreModelMock); - when(adyenPaymentServiceFactoryMock.createFromBaseStore(baseStoreModelMock)).thenReturn(adyenPaymentServiceMock); - when(adyenPaymentServiceMock.calculateAmountWithTaxes(orderModelMock)).thenReturn(new BigDecimal(10)); + when(adyenPaymentServiceFactoryMock.createAdyenCheckoutApiService(baseStoreModelMock)).thenReturn(adyenCheckoutApiServiceMock); + when(adyenCheckoutApiServiceMock.calculateAmountWithTaxes(orderModelMock)).thenReturn(new BigDecimal(10)); } @After diff --git a/adyenv6core/testsrc/com/adyen/v6/commands/AdyenCaptureCommandTest.java b/adyenv6core/testsrc/com/adyen/v6/commands/AdyenCaptureCommandTest.java index b80946da7..362d4cd30 100644 --- a/adyenv6core/testsrc/com/adyen/v6/commands/AdyenCaptureCommandTest.java +++ b/adyenv6core/testsrc/com/adyen/v6/commands/AdyenCaptureCommandTest.java @@ -20,10 +20,10 @@ */ package com.adyen.v6.commands; -import com.adyen.model.checkout.PaymentCaptureResource; +import com.adyen.model.checkout.PaymentCaptureResponse; import com.adyen.v6.factory.AdyenPaymentServiceFactory; import com.adyen.v6.repository.OrderRepository; -import com.adyen.v6.service.DefaultAdyenPaymentService; +import com.adyen.v6.service.DefaultAdyenModificationsApiService; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.core.model.order.OrderModel; import de.hybris.platform.core.model.order.payment.PaymentInfoModel; @@ -56,7 +56,7 @@ public class AdyenCaptureCommandTest { private AdyenPaymentServiceFactory adyenPaymentServiceFactoryMock; @Mock - private DefaultAdyenPaymentService adyenPaymentServiceMock; + private DefaultAdyenModificationsApiService adyenModificationsApiService; @Mock private OrderRepository orderRepositoryMock; @@ -82,7 +82,7 @@ public void setUp() { baseStore.setAdyenImmediateCapture(false); orderModel.setStore(baseStore); - when(adyenPaymentServiceFactoryMock.createFromBaseStore(baseStore)).thenReturn(adyenPaymentServiceMock); + when(adyenPaymentServiceFactoryMock.createAdyenModificationsApiService(baseStore)).thenReturn(adyenModificationsApiService); adyenCaptureCommand.setOrderRepository(orderRepositoryMock); adyenCaptureCommand.setAdyenPaymentServiceFactory(adyenPaymentServiceFactoryMock); @@ -100,16 +100,24 @@ public void tearDown() { */ @Test public void testManualCaptureSuccess() throws Exception { - PaymentCaptureResource paymentCaptureResult = new PaymentCaptureResource(); - paymentCaptureResult.setPspReference("1235"); - paymentCaptureResult.setStatus(PaymentCaptureResource.StatusEnum.RECEIVED); + // Arrange + BigDecimal amount = new BigDecimal(100); + Currency currency = Currency.getInstance("EUR"); + String authReference = "authReference"; + String merchantReference = "merchantReference"; - when(adyenPaymentServiceMock.captures(captureRequest.getTotalAmount(), captureRequest.getCurrency(), captureRequest.getRequestId(), captureRequest.getRequestToken())).thenReturn( - paymentCaptureResult); + PaymentCaptureResponse mockResponse = new PaymentCaptureResponse(); + mockResponse.setPspReference("12345"); + mockResponse.setStatus(PaymentCaptureResponse.StatusEnum.RECEIVED); - CaptureResult result = adyenCaptureCommand.perform(captureRequest); - assertEquals(TransactionStatus.ACCEPTED, result.getTransactionStatus()); - assertEquals(TransactionStatusDetails.REVIEW_NEEDED, result.getTransactionStatusDetails()); + when(adyenModificationsApiService.capture(amount, currency, authReference, merchantReference)).thenReturn(mockResponse); + + // Act + PaymentCaptureResponse response = adyenModificationsApiService.capture(amount, currency, authReference, merchantReference); + + // Assert + assertEquals("12345", response.getPspReference()); + assertEquals(PaymentCaptureResponse.StatusEnum.RECEIVED, response.getStatus()); } /** diff --git a/adyenv6core/testsrc/com/adyen/v6/paymentmethoddetails/builders/impl/RatepayPaymentMethodDetailsBuilderStrategyTest.java b/adyenv6core/testsrc/com/adyen/v6/paymentmethoddetails/builders/impl/RatepayPaymentMethodDetailsBuilderStrategyTest.java deleted file mode 100644 index dfd35e332..000000000 --- a/adyenv6core/testsrc/com/adyen/v6/paymentmethoddetails/builders/impl/RatepayPaymentMethodDetailsBuilderStrategyTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.CardDetails; -import com.adyen.model.checkout.details.SepaDirectDebitDetails; -import com.adyen.v6.constants.Adyenv6coreConstants; -import de.hybris.bootstrap.annotations.UnitTest; -import de.hybris.platform.commercefacades.order.data.CartData; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -import static org.assertj.core.api.Assertions.assertThat; - -import static org.mockito.Mockito.when; - -@UnitTest -@RunWith(MockitoJUnitRunner.class) -public class RatepayPaymentMethodDetailsBuilderStrategyTest { - - @InjectMocks - private RatepayPaymentMethodDetailsBuilderStrategy testObj; - - @Mock - private CartData cartDataMock; - - @Before - public void setUp() throws Exception { - when(cartDataMock.getAdyenPaymentMethod()).thenReturn(Adyenv6coreConstants.RATEPAY); - } - - @Test - public void isApplicable_returnTrue_whenIsSepaDirectDebitPaymentMethod() { - final boolean result = testObj.isApplicable(cartDataMock); - - assertThat(result).isTrue(); - } - - @Test - public void isApplicable_returnFalse_whenIsNotSepaDirectDebitPaymentMethod() { - when(cartDataMock.getAdyenPaymentMethod()).thenReturn(Adyenv6coreConstants.PAYBRIGHT); - final boolean result = testObj.isApplicable(cartDataMock); - - assertThat(result).isFalse(); - } - - @Test - public void buildPaymentMethodDetails_returnSepaDiredtDebitDetailsCorrectlyFilled() { - final PaymentMethodDetails result = testObj.buildPaymentMethodDetails(cartDataMock); - - assertThat(result).isInstanceOfAny(CardDetails.class); - assertThat(result.getType()).isEqualTo(Adyenv6coreConstants.RATEPAY); - } -} \ No newline at end of file diff --git a/adyenv6core/testsrc/com/adyen/v6/paymentmethoddetails/builders/impl/SepaDirectDebitPaymentMethodDetailsBuilderStrategyTest.java b/adyenv6core/testsrc/com/adyen/v6/paymentmethoddetails/builders/impl/SepaDirectDebitPaymentMethodDetailsBuilderStrategyTest.java deleted file mode 100644 index 69c7a7caa..000000000 --- a/adyenv6core/testsrc/com/adyen/v6/paymentmethoddetails/builders/impl/SepaDirectDebitPaymentMethodDetailsBuilderStrategyTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.SepaDirectDebitDetails; -import de.hybris.bootstrap.annotations.UnitTest; -import de.hybris.platform.commercefacades.order.data.CartData; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -@UnitTest -@RunWith(MockitoJUnitRunner.class) -public class SepaDirectDebitPaymentMethodDetailsBuilderStrategyTest { - protected static final String ADYEN_SEPA_OWNER_NAME = "adyenSepaOwnerName"; - protected static final String ADYEN_SEPA_IBAN_NUMBER = "adyenSepaIbanNumber"; - - @InjectMocks - private SepaDirectDebitPaymentMethodDetailsBuilderStrategy testObj; - - @Mock - private CartData cartDataMock; - - @Before - public void setUp() throws Exception { - when(cartDataMock.getAdyenPaymentMethod()).thenReturn(SepaDirectDebitDetails.SEPADIRECTDEBIT); - when(cartDataMock.getAdyenSepaOwnerName()).thenReturn(ADYEN_SEPA_OWNER_NAME); - when(cartDataMock.getAdyenSepaIbanNumber()).thenReturn(ADYEN_SEPA_IBAN_NUMBER); - } - - @Test - public void isApplicable_returnTrue_whenIsSepaDirectDebitPaymentMethod() { - final boolean result = testObj.isApplicable(cartDataMock); - - assertThat(result).isTrue(); - } - - @Test - public void isApplicable_returnFalse_whenIsNotSepaDirectDebitPaymentMethod() { - when(cartDataMock.getAdyenPaymentMethod()).thenReturn(SepaDirectDebitDetails.SEPADIRECTDEBIT_AMAZONPAY); - - final boolean result = testObj.isApplicable(cartDataMock); - - assertThat(result).isFalse(); - } - - @Test - public void buildPaymentMethodDetails_returnSepaDiredtDebitDetailsCorrectlyFilled() { - final PaymentMethodDetails result = testObj.buildPaymentMethodDetails(cartDataMock); - - assertThat(result).isInstanceOfAny(SepaDirectDebitDetails.class); - assertThat(((SepaDirectDebitDetails) result).getIban()).isEqualTo(ADYEN_SEPA_IBAN_NUMBER); - assertThat(((SepaDirectDebitDetails) result).getOwnerName()).isEqualTo(ADYEN_SEPA_OWNER_NAME); - } -} \ No newline at end of file diff --git a/adyenv6ordermanagement/resources/adyenv6ordermanagement/adyenv6ordermanagement-testclasses.xml b/adyenv6ordermanagement/resources/adyenv6ordermanagement/adyenv6ordermanagement-testclasses.xml deleted file mode 100644 index 295d4bb15..000000000 --- a/adyenv6ordermanagement/resources/adyenv6ordermanagement/adyenv6ordermanagement-testclasses.xml +++ /dev/null @@ -1 +0,0 @@ -com.adyen.v6.actions.returns.AdyenCaptureRefundActionTest \ No newline at end of file diff --git a/adyenv6subscription/src/com/adyen/v6/factory/SubscriptionAdyenPaymentServiceFactory.java b/adyenv6subscription/src/com/adyen/v6/factory/SubscriptionAdyenPaymentServiceFactory.java index 4e068b78f..6203ab845 100644 --- a/adyenv6subscription/src/com/adyen/v6/factory/SubscriptionAdyenPaymentServiceFactory.java +++ b/adyenv6subscription/src/com/adyen/v6/factory/SubscriptionAdyenPaymentServiceFactory.java @@ -1,7 +1,7 @@ package com.adyen.v6.factory; -import com.adyen.v6.service.AdyenPaymentService; -import com.adyen.v6.service.impl.DefaultSubscriptionAdyenPaymentService; +import com.adyen.v6.service.AdyenCheckoutApiService; +import com.adyen.v6.service.impl.DefaultSubscriptionAdyenCheckoutApiService; import de.hybris.platform.commercefacades.order.CartFacade; import de.hybris.platform.store.BaseStoreModel; import de.hybris.platform.store.services.BaseStoreService; @@ -19,9 +19,9 @@ public SubscriptionAdyenPaymentServiceFactory(SubscriptionPaymentRequestFactory } @Override - public AdyenPaymentService createFromBaseStore(final BaseStoreModel baseStoreModel) + public AdyenCheckoutApiService createAdyenCheckoutApiService(final BaseStoreModel baseStoreModel) { - final DefaultSubscriptionAdyenPaymentService adyenPaymentService = new DefaultSubscriptionAdyenPaymentService( + final DefaultSubscriptionAdyenCheckoutApiService adyenPaymentService = new DefaultSubscriptionAdyenCheckoutApiService( baseStoreModel); adyenPaymentService.setAdyenRequestFactory(getAdyenRequestFactory()); adyenPaymentService.setCartFacade(cartFacade); diff --git a/adyenv6subscription/src/com/adyen/v6/factory/SubscriptionPaymentRequestFactory.java b/adyenv6subscription/src/com/adyen/v6/factory/SubscriptionPaymentRequestFactory.java index 6653b44df..babf934e7 100644 --- a/adyenv6subscription/src/com/adyen/v6/factory/SubscriptionPaymentRequestFactory.java +++ b/adyenv6subscription/src/com/adyen/v6/factory/SubscriptionPaymentRequestFactory.java @@ -1,14 +1,11 @@ package com.adyen.v6.factory; -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.PaymentsRequest; -import com.adyen.model.checkout.details.CardDetails; +import com.adyen.model.checkout.CheckoutPaymentMethod; +import com.adyen.model.checkout.PaymentRequest; import com.adyen.model.recurring.RecurringDetailsRequest; import com.adyen.util.Util; -import com.adyen.v6.constants.Adyenv6coreConstants; import com.adyen.v6.enums.RecurringContractMode; import com.adyen.v6.model.RequestInfo; -import com.adyen.v6.paymentmethoddetails.executors.AdyenPaymentMethodDetailsBuilderExecutor; import com.adyen.v6.utils.SubscriptionsUtils; import de.hybris.platform.commercefacades.order.CartFacade; import de.hybris.platform.commercefacades.order.data.CartData; @@ -28,14 +25,14 @@ public class SubscriptionPaymentRequestFactory extends AdyenRequestFactory { private CartFacade cartFacade; - public SubscriptionPaymentRequestFactory(ConfigurationService configurationService, AdyenPaymentMethodDetailsBuilderExecutor adyenPaymentMethodDetailsBuilderExecutor) { - super(configurationService, adyenPaymentMethodDetailsBuilderExecutor); + public SubscriptionPaymentRequestFactory(ConfigurationService configurationService) { + super(configurationService); } @Override - public PaymentsRequest createPaymentsRequest(String merchantAccount, CartData cartData, RequestInfo requestInfo, - CustomerModel customerModel, RecurringContractMode recurringContractMode, - Boolean guestUserTokenizationEnabled) { + public PaymentRequest createPaymentsRequest(String merchantAccount, CartData cartData, CheckoutPaymentMethod checkoutPaymentMethod, RequestInfo requestInfo, + CustomerModel customerModel, RecurringContractMode recurringContractMode, + Boolean guestUserTokenizationEnabled) { LOG.info("Creating PaymentsRequest for merchant account: {}", merchantAccount); @@ -48,31 +45,31 @@ public PaymentsRequest createPaymentsRequest(String merchantAccount, CartData ca recurringContractMode, guestUserTokenizationEnabled); } - private PaymentsRequest createRegularPaymentsRequest(String merchantAccount, CartData cartData, RequestInfo requestInfo, + private PaymentRequest createRegularPaymentsRequest(String merchantAccount, CartData cartData, RequestInfo requestInfo, CustomerModel customerModel, RecurringContractMode recurringContractMode, Boolean guestUserTokenizationEnabled) { LOG.info("Creating regular PaymentsRequest..."); - PaymentsRequest paymentsRequest = super.createPaymentsRequest(merchantAccount, cartData, requestInfo, + PaymentRequest paymentsRequest = super.createPaymentsRequest(merchantAccount, cartData,null, requestInfo, customerModel, recurringContractMode, guestUserTokenizationEnabled); - paymentsRequest.setShopperInteraction(PaymentsRequest.ShopperInteractionEnum.CONTAUTH); + paymentsRequest.setShopperInteraction(PaymentRequest.ShopperInteractionEnum.CONTAUTH); - PaymentsRequest.RecurringProcessingModelEnum recurringProcessingModel = BooleanUtils.isTrue( + PaymentRequest.RecurringProcessingModelEnum recurringProcessingModel = BooleanUtils.isTrue( SubscriptionsUtils.containsSubscription(getCartFacade().getSessionCart())) - ? PaymentsRequest.RecurringProcessingModelEnum.SUBSCRIPTION - : PaymentsRequest.RecurringProcessingModelEnum.CARDONFILE; + ? PaymentRequest.RecurringProcessingModelEnum.SUBSCRIPTION + : PaymentRequest.RecurringProcessingModelEnum.CARDONFILE; paymentsRequest.setRecurringProcessingModel(recurringProcessingModel); return paymentsRequest; } - protected PaymentsRequest createRecurringPaymentsRequest(final String merchantAccount, final CartData cartData, + protected PaymentRequest createRecurringPaymentsRequest(final String merchantAccount, final CartData cartData, final RequestInfo requestInfo, final CustomerModel customerModel, final RecurringContractMode recurringContractMode, final Boolean guestUserTokenizationEnabled) { LOG.info("Creating RecurringPaymentsRequest for merchant account: {}", merchantAccount); - final PaymentsRequest paymentsRequest = new PaymentsRequest(); + final PaymentRequest paymentsRequest = new PaymentRequest(); final String adyenPaymentMethod = cartData.getAdyenPaymentMethod(); if (adyenPaymentMethod == null) @@ -82,12 +79,12 @@ protected PaymentsRequest createRecurringPaymentsRequest(final String merchantAc updatePaymentRequest(merchantAccount, cartData, requestInfo, customerModel, paymentsRequest); - final PaymentMethodDetails paymentMethod = adyenPaymentMethodDetailsBuilderExecutor.createPaymentMethodDetails(cartData); +/* final PaymentMethodDetails paymentMethod = adyenPaymentMethodDetailsBuilderExecutor.createPaymentMethodDetails(cartData); if(paymentMethod instanceof CardDetails) { ((CardDetails) paymentMethod).setStoredPaymentMethodId(cartData.getAdyenSelectedReference()); } paymentMethod.setType(Adyenv6coreConstants.PAYMENT_METHOD_SCHEME); - paymentsRequest.setPaymentMethod(paymentMethod); + paymentsRequest.setPaymentMethod(paymentMethod);*/ updateApplicationInfoEcom(paymentsRequest.getApplicationInfo()); @@ -125,12 +122,12 @@ private void updatePaymentRequest(final String merchantAccount, final CartData c // if address details are provided, set it to the PaymentRequest if (deliveryAddress != null) { - paymentsRequest.setDeliveryAddress(setAddressData(deliveryAddress)); + paymentsRequest.setDeliveryAddress(convertToDeliveryAddress(deliveryAddress)); } if (billingAddress != null) { - paymentsRequest.setBillingAddress(setAddressData(billingAddress)); + paymentsRequest.setBillingAddress(convertToDeliveryAddress(billingAddress)); // set PhoneNumber if it is provided final String phone = billingAddress.getPhone(); if (StringUtils.isNotBlank(phone )) diff --git a/adyenv6subscription/src/com/adyen/v6/service/impl/DefaultSubscriptionAdyenCheckoutApiService.java b/adyenv6subscription/src/com/adyen/v6/service/impl/DefaultSubscriptionAdyenCheckoutApiService.java new file mode 100644 index 000000000..7fd5fd370 --- /dev/null +++ b/adyenv6subscription/src/com/adyen/v6/service/impl/DefaultSubscriptionAdyenCheckoutApiService.java @@ -0,0 +1,70 @@ +package com.adyen.v6.service.impl; + +import com.adyen.model.checkout.PaymentRequest; +import com.adyen.model.checkout.PaymentResponse; +import com.adyen.service.checkout.PaymentsApi; +import com.adyen.v6.model.RequestInfo; +import com.adyen.v6.service.DefaultAdyenCheckoutApiService; +import de.hybris.platform.commercefacades.order.CartFacade; +import de.hybris.platform.commercefacades.order.data.CartData; +import de.hybris.platform.core.model.user.CustomerModel; +import de.hybris.platform.store.BaseStoreModel; +import de.hybris.platform.store.services.BaseStoreService; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import static com.adyen.v6.utils.SubscriptionsUtils.containsSubscription; +import static com.adyen.v6.utils.SubscriptionsUtils.findRecurringProcessingModel; + +public class DefaultSubscriptionAdyenCheckoutApiService extends DefaultAdyenCheckoutApiService { + + protected static final Logger LOG = LogManager.getLogger(DefaultSubscriptionAdyenCheckoutApiService.class); + private CartFacade cartFacade; + private BaseStoreService baseStoreService; + + public DefaultSubscriptionAdyenCheckoutApiService(final BaseStoreModel baseStore) { + super(baseStore); + } + + @Override + public PaymentResponse authorisePayment(final CartData cartData, final RequestInfo requestInfo, final CustomerModel customerModel) throws Exception { + LOG.debug("Authorize payment"); + + PaymentsApi paymentsApi = new PaymentsApi(client); + + PaymentRequest paymentsRequest = getAdyenRequestFactory().createPaymentsRequest(baseStore.getAdyenMerchantAccount(), + cartData, + null, + requestInfo, + customerModel, + baseStore.getAdyenRecurringContractMode(), + baseStore.getAdyenGuestUserTokenization()); + + if (BooleanUtils.isTrue(containsSubscription(cartData))) { + paymentsRequest.setShopperInteraction(PaymentRequest.ShopperInteractionEnum.CONTAUTH); + paymentsRequest.setRecurringProcessingModel(findRecurringProcessingModel(cartData)); + paymentsRequest.setEnableRecurring(Boolean.TRUE); + } + LOG.debug(paymentsRequest); + PaymentResponse paymentsResponse = paymentsApi.payments(paymentsRequest); + LOG.debug(paymentsResponse); + return paymentsResponse; + } + + public CartFacade getCartFacade() { + return cartFacade; + } + + public void setCartFacade(final CartFacade cartFacade) { + this.cartFacade = cartFacade; + } + + public BaseStoreService getBaseStoreService() { + return baseStoreService; + } + + public void setBaseStoreService(final BaseStoreService baseStoreService) { + this.baseStoreService = baseStoreService; + } +} diff --git a/adyenv6subscription/src/com/adyen/v6/service/impl/DefaultSubscriptionAdyenPaymentService.java b/adyenv6subscription/src/com/adyen/v6/service/impl/DefaultSubscriptionAdyenPaymentService.java deleted file mode 100644 index d30adb7b1..000000000 --- a/adyenv6subscription/src/com/adyen/v6/service/impl/DefaultSubscriptionAdyenPaymentService.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.adyen.v6.service.impl; - -import com.adyen.model.checkout.PaymentMethodsRequest; -import com.adyen.model.checkout.PaymentMethodsResponse; -import com.adyen.model.checkout.PaymentsRequest; -import com.adyen.model.checkout.PaymentsResponse; -import com.adyen.service.Checkout; -import com.adyen.service.exception.ApiException; -import com.adyen.util.Util; -import com.adyen.v6.model.RequestInfo; -import com.adyen.v6.service.DefaultAdyenPaymentService; -import de.hybris.platform.commercefacades.order.CartFacade; -import de.hybris.platform.commercefacades.order.data.CartData; -import de.hybris.platform.core.model.user.CustomerModel; -import de.hybris.platform.store.BaseStoreModel; -import de.hybris.platform.store.services.BaseStoreService; -import org.apache.commons.lang3.BooleanUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.io.IOException; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; - -import static com.adyen.v6.utils.SubscriptionsUtils.containsSubscription; -import static com.adyen.v6.utils.SubscriptionsUtils.findRecurringProcessingModel; - -public class DefaultSubscriptionAdyenPaymentService extends DefaultAdyenPaymentService { - - protected static final Logger LOG = LogManager.getLogger(DefaultSubscriptionAdyenPaymentService.class); - private CartFacade cartFacade; - private BaseStoreService baseStoreService; - - public DefaultSubscriptionAdyenPaymentService(final BaseStoreModel baseStore) { - super(baseStore); - } - - @Override - public PaymentMethodsResponse getPaymentMethodsResponse(final BigDecimal amount, - final String currency, - final String countryCode, - final String shopperLocale, - final String shopperReference) throws IOException, ApiException { - - LOG.debug("Get payment methods response"); - - Checkout checkout = new Checkout(getClient()); - PaymentMethodsRequest request = new PaymentMethodsRequest(); - request.merchantAccount(getClient().getConfig().getMerchantAccount()).amount(Util.createAmount(amount, currency)).countryCode(countryCode); - - if (!StringUtils.isEmpty(shopperLocale)) { - request.setShopperLocale(shopperLocale); - } - - if (!StringUtils.isEmpty(shopperReference)) { - request.setShopperReference(shopperReference); - } - - if (BooleanUtils.isTrue(containsSubscription(getCartFacade().getSessionCart()))) { - final List allowedPaymentMethods = new ArrayList<>(getBaseStoreService().getCurrentBaseStore().getSubscriptionAllowedPaymentMethods()); - request.setAllowedPaymentMethods(allowedPaymentMethods); - } - - LOG.debug(request); - final PaymentMethodsResponse response = checkout.paymentMethods(request); - LOG.debug(response); - - return response; - } - - @Override - public PaymentsResponse authorisePayment(final CartData cartData, final RequestInfo requestInfo, final CustomerModel customerModel) throws Exception { - LOG.debug("Authorize payment"); - - Checkout checkout = new Checkout(getClient()); - - PaymentsRequest paymentsRequest = getAdyenRequestFactory().createPaymentsRequest(getClient().getConfig().getMerchantAccount(), - cartData, - requestInfo, - customerModel, - getBaseStore().getAdyenRecurringContractMode(), - getBaseStore().getAdyenGuestUserTokenization()); - - if (BooleanUtils.isTrue(containsSubscription(cartData))) { - paymentsRequest.setShopperInteraction(PaymentsRequest.ShopperInteractionEnum.CONTAUTH); - paymentsRequest.setRecurringProcessingModel(findRecurringProcessingModel(cartData)); - paymentsRequest.setEnableRecurring(Boolean.TRUE); - } - LOG.debug(paymentsRequest); - PaymentsResponse paymentsResponse = checkout.payments(paymentsRequest); - LOG.debug(paymentsResponse); - return paymentsResponse; - } - - public CartFacade getCartFacade() { - return cartFacade; - } - - public void setCartFacade(final CartFacade cartFacade) { - this.cartFacade = cartFacade; - } - - public BaseStoreService getBaseStoreService() { - return baseStoreService; - } - - public void setBaseStoreService(final BaseStoreService baseStoreService) { - this.baseStoreService = baseStoreService; - } -} diff --git a/adyenv6subscription/src/com/adyen/v6/service/impl/SubscriptionOrderExecutor.java b/adyenv6subscription/src/com/adyen/v6/service/impl/SubscriptionOrderExecutor.java index a1315bfd4..5287425b5 100644 --- a/adyenv6subscription/src/com/adyen/v6/service/impl/SubscriptionOrderExecutor.java +++ b/adyenv6subscription/src/com/adyen/v6/service/impl/SubscriptionOrderExecutor.java @@ -1,6 +1,6 @@ package com.adyen.v6.service.impl; -import com.adyen.model.checkout.PaymentsResponse; +import com.adyen.model.checkout.PaymentResponse; import com.adyen.v6.factory.AdyenPaymentServiceFactory; import com.adyen.v6.factory.SubscriptionAdyenPaymentServiceFactory; import com.adyen.v6.model.RequestInfo; @@ -58,20 +58,20 @@ public OrderModel execute() throws Exception { try { final RequestInfo request = new RequestInfo(); - final PaymentsResponse paymentResponse = subscriptionAdyenPaymentServiceFactory - .createFromBaseStore(baseStoreService.getCurrentBaseStore()) + final PaymentResponse paymentResponse = subscriptionAdyenPaymentServiceFactory + .createAdyenCheckoutApiService(baseStoreService.getCurrentBaseStore()) .authorisePayment(cartConverter.convert(cart), request, (CustomerModel) cart.getUser()); - final PaymentsResponse.ResultCodeEnum resultCode = paymentResponse.getResultCode(); - if (PaymentsResponse.ResultCodeEnum.AUTHORISED == resultCode) { + final PaymentResponse.ResultCodeEnum resultCode = paymentResponse.getResultCode(); + if (PaymentResponse.ResultCodeEnum.AUTHORISED == resultCode) { LOG.info("Payment authorised for cart: {}", cart.getCode()); adyenTransactionService.authorizeOrderModel(cart, cart.getCode(), paymentResponse.getPspReference()); return placeOrder(cart); - } else if (PaymentsResponse.ResultCodeEnum.RECEIVED == resultCode) { + } else if (PaymentResponse.ResultCodeEnum.RECEIVED == resultCode) { LOG.info("Payment received for cart: {}", cart.getCode()); return placeOrder(cart); - } else if (PaymentsResponse.ResultCodeEnum.PRESENTTOSHOPPER == resultCode) { + } else if (PaymentResponse.ResultCodeEnum.PRESENTTOSHOPPER == resultCode) { LOG.info("Payment presented to shopper for cart: {}", cart.getCode()); return placeOrder(cart); } else { diff --git a/adyenv6subscription/src/com/adyen/v6/utils/SubscriptionsUtils.java b/adyenv6subscription/src/com/adyen/v6/utils/SubscriptionsUtils.java index d426f58ce..cc90c4ebb 100644 --- a/adyenv6subscription/src/com/adyen/v6/utils/SubscriptionsUtils.java +++ b/adyenv6subscription/src/com/adyen/v6/utils/SubscriptionsUtils.java @@ -1,6 +1,6 @@ package com.adyen.v6.utils; -import com.adyen.model.checkout.CreateCheckoutSessionRequest; -import com.adyen.model.checkout.PaymentsRequest; + +import com.adyen.model.checkout.PaymentRequest; import de.hybris.platform.commercefacades.order.data.CartData; import org.apache.commons.collections.CollectionUtils; @@ -9,13 +9,13 @@ public static boolean containsSubscription(CartData cartData){ return CollectionUtils.isNotEmpty(cartData.getEntries()) && cartData.getEntries().stream().anyMatch(orderEntryData -> orderEntryData.getProduct().getSubscriptionTerm() != null); } - public static PaymentsRequest.RecurringProcessingModelEnum findRecurringProcessingModel(CartData cartData){ + public static PaymentRequest.RecurringProcessingModelEnum findRecurringProcessingModel(CartData cartData){ if(cartData.getEntries().stream() .filter(orderEntryData->orderEntryData.getProduct().getSubscriptionTerm()!=null) .allMatch(orderEntryData -> orderEntryData.getProduct().getSubscriptionTerm().getBillingPlan()!=null)) { - return PaymentsRequest.RecurringProcessingModelEnum.SUBSCRIPTION; + return PaymentRequest.RecurringProcessingModelEnum.SUBSCRIPTION; } - return PaymentsRequest.RecurringProcessingModelEnum.UNSCHEDULEDCARDONFILE; + return PaymentRequest.RecurringProcessingModelEnum.UNSCHEDULEDCARDONFILE; } } diff --git a/adyenv6subscription/testsrc/com/adyen/v6/factory/SubscriptionPaymentRequestFactoryTest.java b/adyenv6subscription/testsrc/com/adyen/v6/factory/SubscriptionPaymentRequestFactoryTest.java index d9930db4e..579d37a36 100644 --- a/adyenv6subscription/testsrc/com/adyen/v6/factory/SubscriptionPaymentRequestFactoryTest.java +++ b/adyenv6subscription/testsrc/com/adyen/v6/factory/SubscriptionPaymentRequestFactoryTest.java @@ -1,9 +1,8 @@ package com.adyen.v6.factory; -import com.adyen.model.checkout.PaymentsRequest; +import com.adyen.model.checkout.PaymentRequest; import com.adyen.v6.enums.RecurringContractMode; import com.adyen.v6.model.RequestInfo; -import com.adyen.v6.paymentmethoddetails.executors.AdyenPaymentMethodDetailsBuilderExecutor; import de.hybris.platform.commercefacades.order.CartFacade; import de.hybris.platform.commercefacades.order.data.CartData; import de.hybris.platform.core.model.user.CustomerModel; @@ -25,9 +24,6 @@ public class SubscriptionPaymentRequestFactoryTest { @Mock private ConfigurationService configurationService; - @Mock - private AdyenPaymentMethodDetailsBuilderExecutor adyenPaymentMethodDetailsBuilderExecutor; - @Mock private CartFacade cartFacade; @@ -52,11 +48,11 @@ void testCreatePaymentsRequest() { when(cartData.getSubscriptionOrder()).thenReturn(Boolean.FALSE); // Call the method to be tested - PaymentsRequest paymentsRequest = subscriptionPaymentRequestFactory.createPaymentsRequest(merchantAccount, + PaymentRequest paymentsRequest = subscriptionPaymentRequestFactory.createPaymentsRequest(merchantAccount, cartData, requestInfo, customerModel, recurringContractMode, guestUserTokenizationEnabled); // Verifications and assertions assertNotNull(paymentsRequest); - assertEquals(PaymentsRequest.ShopperInteractionEnum.CONTAUTH, paymentsRequest.getShopperInteraction()); + assertEquals(PaymentRequest.ShopperInteractionEnum.CONTAUTH, paymentsRequest.getShopperInteraction()); } } From f0156f4210a61717ff8bdb16630bcaef332c55e4 Mon Sep 17 00:00:00 2001 From: kpieloch <113994423+kpieloch@users.noreply.github.com> Date: Mon, 18 Mar 2024 10:41:03 +0100 Subject: [PATCH 2/4] [AD-156] Upgrade Java Lib in AdyenV6 plugin to the newest version + deprecated code removed --- ...ymentMethodDetailsBuilderStrategyTest.java | 71 ------------------- 1 file changed, 71 deletions(-) delete mode 100644 adyenv6core/testsrc/com/adyen/v6/paymentmethoddetails/builders/impl/PaypalAdyenPaymentMethodDetailsBuilderStrategyTest.java diff --git a/adyenv6core/testsrc/com/adyen/v6/paymentmethoddetails/builders/impl/PaypalAdyenPaymentMethodDetailsBuilderStrategyTest.java b/adyenv6core/testsrc/com/adyen/v6/paymentmethoddetails/builders/impl/PaypalAdyenPaymentMethodDetailsBuilderStrategyTest.java deleted file mode 100644 index cdfbeb564..000000000 --- a/adyenv6core/testsrc/com/adyen/v6/paymentmethoddetails/builders/impl/PaypalAdyenPaymentMethodDetailsBuilderStrategyTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.adyen.v6.paymentmethoddetails.builders.impl; - -import com.adyen.model.checkout.PaymentMethodDetails; -import com.adyen.model.checkout.details.PayPalDetails; -import com.adyen.v6.constants.Adyenv6coreConstants; -import de.hybris.bootstrap.annotations.UnitTest; -import de.hybris.platform.commercefacades.order.data.CartData; -import de.hybris.platform.commercefacades.user.data.AddressData; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -import java.util.Date; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -@UnitTest -@RunWith(MockitoJUnitRunner.class) -public class PaypalAdyenPaymentMethodDetailsBuilderStrategyTest { - - private static String personalDetails = "firstName lastName "; - private static String contactDetails = " 666666666 test@test.com"; - - @InjectMocks - private PaypalAdyenPaymentMethodDetailsBuilderStrategy testObj; - - @Mock - private CartData cartDataMock; - @Mock - private AddressData addressDataMock; - - @Before - public void setUp() throws Exception { - when(cartDataMock.getAdyenPaymentMethod()).thenReturn(PayPalDetails.PAYPAL); - when(cartDataMock.getDeliveryAddress()).thenReturn(addressDataMock); - when(cartDataMock.getAdyenDob()).thenReturn(new Date(0)); - when(addressDataMock.getFirstName()).thenReturn("firstName"); - when(addressDataMock.getLastName()).thenReturn("lastName"); - when(addressDataMock.getPhone()).thenReturn("666666666"); - when(addressDataMock.getEmail()).thenReturn("test@test.com"); - } - - @Test - public void isApplicable_returnTrue_whenIsPaypalPaymentMethod() { - final boolean result = testObj.isApplicable(cartDataMock); - - assertThat(result).isTrue(); - } - - @Test - public void isApplicable_returnFalse_whenIsNotPaypalPaymentMethod() { - when(cartDataMock.getAdyenPaymentMethod()).thenReturn(Adyenv6coreConstants.PAYBRIGHT); - final boolean result = testObj.isApplicable(cartDataMock); - - assertThat(result).isFalse(); - } - - @Test - public void buildPaymentMethodDetails_returnPaypalDetailsCorrectlyFilled() { - final PaymentMethodDetails result = testObj.buildPaymentMethodDetails(cartDataMock); - - assertThat(result).isInstanceOfAny(PayPalDetails.class); - assertThat(((PayPalDetails) result).getSubtype()).isEqualTo(PayPalDetails.SubtypeEnum.SDK); - assertThat(((PayPalDetails) result).getPayerID()).isEqualTo(personalDetails + new Date(0) + contactDetails); - } - -} \ No newline at end of file From ae11acf655a09db9c94c5ec60fa92200f64f1af8 Mon Sep 17 00:00:00 2001 From: kpieloch <113994423+kpieloch@users.noreply.github.com> Date: Mon, 18 Mar 2024 10:47:51 +0100 Subject: [PATCH 3/4] [AD-156] Upgrade Java Lib in AdyenV6 plugin to the newest version + deprecated code removed --- adyenv6core/resources/adyenv6core-spring.xml | 129 ------------------ .../SubscriptionPaymentRequestFactory.java | 80 ----------- 2 files changed, 209 deletions(-) diff --git a/adyenv6core/resources/adyenv6core-spring.xml b/adyenv6core/resources/adyenv6core-spring.xml index c492a72d0..6fa5f5855 100644 --- a/adyenv6core/resources/adyenv6core-spring.xml +++ b/adyenv6core/resources/adyenv6core-spring.xml @@ -126,7 +126,6 @@ - @@ -317,126 +316,6 @@ - - - @@ -450,14 +329,6 @@ - - diff --git a/adyenv6subscription/src/com/adyen/v6/factory/SubscriptionPaymentRequestFactory.java b/adyenv6subscription/src/com/adyen/v6/factory/SubscriptionPaymentRequestFactory.java index babf934e7..3acb840f2 100644 --- a/adyenv6subscription/src/com/adyen/v6/factory/SubscriptionPaymentRequestFactory.java +++ b/adyenv6subscription/src/com/adyen/v6/factory/SubscriptionPaymentRequestFactory.java @@ -3,20 +3,16 @@ import com.adyen.model.checkout.CheckoutPaymentMethod; import com.adyen.model.checkout.PaymentRequest; import com.adyen.model.recurring.RecurringDetailsRequest; -import com.adyen.util.Util; import com.adyen.v6.enums.RecurringContractMode; import com.adyen.v6.model.RequestInfo; import com.adyen.v6.utils.SubscriptionsUtils; import de.hybris.platform.commercefacades.order.CartFacade; import de.hybris.platform.commercefacades.order.data.CartData; -import de.hybris.platform.commercefacades.user.data.AddressData; import de.hybris.platform.core.model.user.CustomerModel; import de.hybris.platform.servicelayer.config.ConfigurationService; import org.apache.commons.lang3.BooleanUtils; -import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.web.bind.annotation.RequestMethod; public class SubscriptionPaymentRequestFactory extends AdyenRequestFactory { @@ -62,82 +58,6 @@ private PaymentRequest createRegularPaymentsRequest(String merchantAccount, Cart return paymentsRequest; } - protected PaymentRequest createRecurringPaymentsRequest(final String merchantAccount, final CartData cartData, - final RequestInfo requestInfo, final CustomerModel customerModel, final RecurringContractMode recurringContractMode, - final Boolean guestUserTokenizationEnabled) - { - - LOG.info("Creating RecurringPaymentsRequest for merchant account: {}", merchantAccount); - - final PaymentRequest paymentsRequest = new PaymentRequest(); - final String adyenPaymentMethod = cartData.getAdyenPaymentMethod(); - - if (adyenPaymentMethod == null) - { - throw new IllegalArgumentException("Payment method is null"); - } - - updatePaymentRequest(merchantAccount, cartData, requestInfo, customerModel, paymentsRequest); - -/* final PaymentMethodDetails paymentMethod = adyenPaymentMethodDetailsBuilderExecutor.createPaymentMethodDetails(cartData); - if(paymentMethod instanceof CardDetails) { - ((CardDetails) paymentMethod).setStoredPaymentMethodId(cartData.getAdyenSelectedReference()); - } - paymentMethod.setType(Adyenv6coreConstants.PAYMENT_METHOD_SCHEME); - paymentsRequest.setPaymentMethod(paymentMethod);*/ - - - updateApplicationInfoEcom(paymentsRequest.getApplicationInfo()); - - - paymentsRequest.setRedirectFromIssuerMethod(RequestMethod.POST.toString()); - paymentsRequest.setRedirectToIssuerMethod(RequestMethod.POST.toString()); - paymentsRequest.setShopperInteraction(PaymentsRequest.ShopperInteractionEnum.CONTAUTH); - paymentsRequest.setRecurringProcessingModel(PaymentsRequest.RecurringProcessingModelEnum.SUBSCRIPTION); - - return paymentsRequest; - } - - - private void updatePaymentRequest(final String merchantAccount, final CartData cartData, final RequestInfo requestInfo, - final CustomerModel customerModel, final PaymentsRequest paymentsRequest) - { - - - final String currency = cartData.getTotalPrice().getCurrencyIso(); - final String reference = cartData.getCode(); - - final AddressData billingAddress = cartData.getPaymentInfo() != null ? cartData.getPaymentInfo().getBillingAddress() : null; - final AddressData deliveryAddress = cartData.getDeliveryAddress(); - - paymentsRequest.amount(Util.createAmount(cartData.getTotalPrice().getValue(), currency)).reference(reference).merchantAccount(merchantAccount) - .setCountryCode(getCountryCode(cartData)); - // set shopper details from CustomerModel. - if (customerModel != null) - { - paymentsRequest.setShopperReference(customerModel.getCustomerID()); - paymentsRequest.setShopperEmail(customerModel.getContactEmail()); - } - - // if address details are provided, set it to the PaymentRequest - if (deliveryAddress != null) - { - paymentsRequest.setDeliveryAddress(convertToDeliveryAddress(deliveryAddress)); - } - - if (billingAddress != null) - { - paymentsRequest.setBillingAddress(convertToDeliveryAddress(billingAddress)); - // set PhoneNumber if it is provided - final String phone = billingAddress.getPhone(); - if (StringUtils.isNotBlank(phone )) - { - paymentsRequest.setTelephoneNumber(phone); - } - } - - } - @Override public RecurringDetailsRequest createListRecurringDetailsRequest(String merchantAccount, String customerId) { if (SubscriptionsUtils.containsSubscription(getCartFacade().getSessionCart())) { From 2da111d430c6685c108375c145ea753da260dc76 Mon Sep 17 00:00:00 2001 From: kpieloch <113994423+kpieloch@users.noreply.github.com> Date: Thu, 21 Mar 2024 10:57:54 +0100 Subject: [PATCH 4/4] [AD-156] Upgrade Java Lib in AdyenV6 plugin to the newest version + deprecated code removed --- ...dyenSummaryCheckoutStepControllerTest.java | 189 ++-------------- adyenv6core/resources/adyenv6core-spring.xml | 3 - .../factory/AdyenPaymentServiceFactory.java | 4 +- .../adyen/v6/factory/AdyenRequestFactory.java | 29 ++- .../DefaultAdyenCheckoutApiService.java | 2 +- .../src/com/adyen/v6/util/AmountUtil.java | 20 +- .../PosPaymentResponseConverterTest.java | 150 ------------- .../v6/facades/AdyenCheckoutFacadeTest.java | 205 +++++++++--------- .../v6/factory/AdyenRequestFactoryTest.java | 119 ++++------ .../service/AdyenTransactionServiceTest.java | 14 +- .../resources/adyenv6subscription-spring.xml | 8 +- ...ubscriptionAdyenPaymentServiceFactory.java | 11 +- ...ltSubscriptionAdyenCheckoutApiService.java | 19 -- 13 files changed, 192 insertions(+), 581 deletions(-) delete mode 100644 adyenv6core/testsrc/com/adyen/v6/converters/PosPaymentResponseConverterTest.java diff --git a/adyenv6b2ccheckoutaddon/acceleratoraddon/web/testsrc/com/adyen/v6/controllers/pages/AdyenSummaryCheckoutStepControllerTest.java b/adyenv6b2ccheckoutaddon/acceleratoraddon/web/testsrc/com/adyen/v6/controllers/pages/AdyenSummaryCheckoutStepControllerTest.java index e865aed20..ef3e0e4ff 100644 --- a/adyenv6b2ccheckoutaddon/acceleratoraddon/web/testsrc/com/adyen/v6/controllers/pages/AdyenSummaryCheckoutStepControllerTest.java +++ b/adyenv6b2ccheckoutaddon/acceleratoraddon/web/testsrc/com/adyen/v6/controllers/pages/AdyenSummaryCheckoutStepControllerTest.java @@ -1,15 +1,12 @@ package com.adyen.v6.controllers.pages; -import com.adyen.constants.ApiConstants; -import com.adyen.model.PaymentResult; -import com.adyen.model.checkout.CheckoutPaymentsAction; -import com.adyen.model.checkout.PaymentsDetailsResponse; -import com.adyen.model.checkout.PaymentsResponse; +import com.adyen.model.checkout.PaymentDetailsResponse; +import com.adyen.model.checkout.PaymentResponse; import com.adyen.model.terminal.TerminalAPIResponse; import com.adyen.service.exception.ApiException; import com.adyen.v6.constants.AdyenControllerConstants; -import com.adyen.v6.exceptions.AdyenNonAuthorizedPaymentException; import com.adyen.v6.facades.AdyenCheckoutFacade; +import com.fasterxml.jackson.core.JsonProcessingException; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.acceleratorfacades.flow.CheckoutFlowFacade; import de.hybris.platform.acceleratorfacades.order.AcceleratorCheckoutFacade; @@ -55,12 +52,14 @@ import java.util.List; import java.util.Map; -import static com.adyen.model.checkout.PaymentsResponse.ResultCodeEnum.*; import static com.adyen.v6.constants.AdyenControllerConstants.CART_PREFIX; -import static com.adyen.v6.constants.Adyenv6coreConstants.*; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_PAYPAL; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_POS; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Matchers.*; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; @@ -124,7 +123,7 @@ public class AdyenSummaryCheckoutStepControllerTest { @Mock private HttpServletRequest requestMock; @Mock - private PaymentsDetailsResponse responseMock; + private PaymentDetailsResponse responseMock; @Mock private RedirectAttributes redirectModelMock; @Mock @@ -150,13 +149,9 @@ public class AdyenSummaryCheckoutStepControllerTest { @Mock private HashMap details; @Mock - private PaymentResult paymentResultMock; - @Mock - private PaymentsResponse paymentsResponseMock; + private PaymentResponse paymentsResponseMock; @Mock private TerminalAPIResponse terminalApiResponseMock; - @Mock - private CheckoutPaymentsAction actionMock; private List modifications; @Before @@ -187,7 +182,7 @@ public void handleRedirectPayload_shouldThrowException_whenRequestNotContainsPay assertThat(result).isEqualTo(REDIRECT_PREFIX + CART_PREFIX); } @Test - public void placeOrder_shouldGoBackToStep_whenFormIsInvalid() throws CMSItemNotFoundException, CommerceCartModificationException { + public void placeOrder_shouldGoBackToStep_whenFormIsInvalid() throws CMSItemNotFoundException, CommerceCartModificationException, JsonProcessingException { mockElementsUsedInTestsForPlaceOrder(); when(checkoutFlowFacadeMock.hasNoDeliveryAddress()).thenReturn(true); @@ -197,7 +192,7 @@ public void placeOrder_shouldGoBackToStep_whenFormIsInvalid() throws CMSItemNotF } @Test - public void placeOrder_shouldRedirectToCart_whenFormIsValidButCartIsNot() throws CMSItemNotFoundException, CommerceCartModificationException { + public void placeOrder_shouldRedirectToCart_whenFormIsValidButCartIsNot() throws CMSItemNotFoundException, CommerceCartModificationException, JsonProcessingException { mockElementsUsedInTestsForPlaceOrder(); mockFormValidationOK(); modifications.add(cartModificationDataMock); @@ -248,21 +243,6 @@ public void placeOrder_shouldGoBackToStep_whenAnotherExceptionIsThrownRatepay() assertThat(result).isEqualTo(AdyenControllerConstants.Views.Pages.MultiStepCheckout.CheckoutSummaryPage); } - @Test - public void placeOrder_shouldGoBackToStep_whenAdyenNonAuthorizedPaymentExceptionIsThrownRatepay() throws Exception { - mockElementsUsedInTestsForPlaceOrder(); - mockFormValidationOK(); - mockCartValidationOK(); - when(cartDataMock.getAdyenPaymentMethod()).thenReturn(RATEPAY); - when(paymentResultMock.isRefused()).thenReturn(true); - when(paymentResultMock.getRefusalReason()).thenReturn(ApiConstants.RefusalReason.TRANSACTION_NOT_PERMITTED); - when(adyenCheckoutFacadeMock.authorisePayment(requestMock, cartDataMock)).thenThrow(new AdyenNonAuthorizedPaymentException(paymentResultMock)); - - final String result = testObj.placeOrder(placeOrderFormMock, modelMock, requestMock, redirectModelMock); - - assertThat(result).isEqualTo(AdyenControllerConstants.Views.Pages.MultiStepCheckout.CheckoutSummaryPage); - } - @Test public void placeOrder_shouldGoToConfirmationPage_whenFormCartAreBothValidAndPaymentAuthorizedPOS() throws Exception { mockElementsUsedInTestsForPlaceOrder(); @@ -295,28 +275,6 @@ public void placeOrder_shouldGoToConfirmationPage_whenFormCartAreBothValidAndSoc assertThat(result).isEqualTo(REDIRECT_URL_ORDER_CONFIRMATION + ORDER_CODE); } - @Test - public void placeOrder_shouldGoBackToStep_whenSocketTimeoutExceptionAndAdyenNonAuthorizedPaymentExceptionAreThrownPOS() throws Exception { - mockElementsUsedInTestsForPlaceOrder(); - mockFormValidationOK(); - mockCartValidationOK(); - mockAnonymousCheckoutAndOrderGuid(); - when(cartDataMock.getAdyenPaymentMethod()).thenReturn(PAYMENT_METHOD_POS); - when(adyenCheckoutFacadeMock.initiatePosPayment(requestMock, cartDataMock)).thenThrow(new SocketTimeoutException()); - when(configurationServiceMock.getConfiguration()).thenReturn(configurationMock); - when(configurationMock.containsKey(POS_TOTAL_TIMEOUT_KEY)).thenReturn(true); - when(configurationMock.getInt(POS_TOTAL_TIMEOUT_KEY)).thenReturn(130); - when(paymentResultMock.isRefused()).thenReturn(true); - when(paymentResultMock.getRefusalReason()).thenReturn(ApiConstants.RefusalReason.TRANSACTION_NOT_PERMITTED); - AdyenNonAuthorizedPaymentException thisException = new AdyenNonAuthorizedPaymentException(paymentResultMock); - when(terminalApiResponseMock.getSaleToPOIResponse()).thenReturn(null); - thisException.setTerminalApiResponse(terminalApiResponseMock); - when(adyenCheckoutFacadeMock.checkPosPaymentStatus(requestMock, cartDataMock)).thenThrow(thisException); - final String result = testObj.placeOrder(placeOrderFormMock, modelMock, requestMock, redirectModelMock); - - assertThat(result).isEqualTo(AdyenControllerConstants.Views.Pages.MultiStepCheckout.CheckoutSummaryPage); - } - @Test public void placeOrder_shouldGoBackToStep_whenSocketTimeoutExceptionAfterAnotherSocketTimeoutExceptionAreThrownPOS() throws Exception { mockElementsUsedInTestsForPlaceOrder(); @@ -364,24 +322,6 @@ public void placeOrder_shouldGoBackToStep_whenApiExceptionIsThrownPOS() throws E assertThat(result).isEqualTo(AdyenControllerConstants.Views.Pages.MultiStepCheckout.CheckoutSummaryPage); } - @Test - public void placeOrder_shouldGoBackToStep_whenAdyenNonAuthorizedPaymentExceptionIsThrownPOS() throws Exception { - mockElementsUsedInTestsForPlaceOrder(); - mockFormValidationOK(); - mockCartValidationOK(); - mockAnonymousCheckoutAndOrderGuid(); - when(cartDataMock.getAdyenPaymentMethod()).thenReturn(PAYMENT_METHOD_POS); - when(paymentResultMock.isRefused()).thenReturn(true); - when(paymentResultMock.getRefusalReason()).thenReturn(ApiConstants.RefusalReason.TRANSACTION_NOT_PERMITTED); - AdyenNonAuthorizedPaymentException thisException = new AdyenNonAuthorizedPaymentException(paymentResultMock); - when(terminalApiResponseMock.getSaleToPOIResponse()).thenReturn(null); - thisException.setTerminalApiResponse(terminalApiResponseMock); - when(adyenCheckoutFacadeMock.initiatePosPayment(requestMock, cartDataMock)).thenThrow(thisException); - final String result = testObj.placeOrder(placeOrderFormMock, modelMock, requestMock, redirectModelMock); - - assertThat(result).isEqualTo(AdyenControllerConstants.Views.Pages.MultiStepCheckout.CheckoutSummaryPage); - } - @Test public void placeOrder_shouldGoBackToStep_whenGenericExceptionIsThrownPOS() throws Exception { mockElementsUsedInTestsForPlaceOrder(); @@ -424,107 +364,6 @@ public void placeOrder_shouldGoBackToStep_whenApiExceptionIsThrownAnotherPayment assertThat(result).isEqualTo(AdyenControllerConstants.Views.Pages.MultiStepCheckout.CheckoutSummaryPage); } - - @Test - public void placeOrder_shouldRedirectTo3DS_whenAdyenNonAuthorizedPaymentExceptionIsThrownAndRedirectShopper3DS() throws Exception { - mockElementsUsedInTestsForPlaceOrder(); - mockFormValidationOK(); - mockCartValidationOK(); - when(cartDataMock.getAdyenPaymentMethod()).thenReturn(PAYMENT_METHOD_CC); - AdyenNonAuthorizedPaymentException thisException = new AdyenNonAuthorizedPaymentException(paymentResultMock); - when(paymentsResponseMock.getResultCode()).thenReturn(REDIRECTSHOPPER); - thisException.setPaymentsResponse(paymentsResponseMock); - when(adyenCheckoutFacadeMock.authorisePayment(requestMock, cartDataMock)).thenThrow(thisException); - - final String result = testObj.placeOrder(placeOrderFormMock, modelMock, requestMock, redirectModelMock); - - assertThat(result).isEqualTo(AdyenControllerConstants.Views.Pages.MultiStepCheckout.Validate3DSPaymentPage); - } - - @Test - public void placeOrder_shouldRedirectTo3DS_whenAdyenNonAuthorizedPaymentExceptionIsThrownAndRedirectShopperAfterpayTouch() throws Exception { - mockElementsUsedInTestsForPlaceOrder(); - mockFormValidationOK(); - mockCartValidationOK(); - when(cartDataMock.getAdyenPaymentMethod()).thenReturn(AFTERPAY_TOUCH); - AdyenNonAuthorizedPaymentException thisException = new AdyenNonAuthorizedPaymentException(paymentResultMock); - when(actionMock.getUrl()).thenReturn(ACTION_URL); - when(paymentsResponseMock.getResultCode()).thenReturn(REDIRECTSHOPPER); - when(paymentsResponseMock.getAction()).thenReturn(actionMock); - thisException.setPaymentsResponse(paymentsResponseMock); - when(adyenCheckoutFacadeMock.authorisePayment(requestMock, cartDataMock)).thenThrow(thisException); - - final String result = testObj.placeOrder(placeOrderFormMock, modelMock, requestMock, redirectModelMock); - - assertThat(result).isEqualTo(REDIRECT_PREFIX + ACTION_URL); - } - - @Test - public void placeOrder_shouldRedirectTo3DS_whenAdyenNonAuthorizedPaymentExceptionIsThrownAndRedirectShopperAnotherMethod() throws Exception { - mockElementsUsedInTestsForPlaceOrder(); - mockFormValidationOK(); - mockCartValidationOK(); - when(cartDataMock.getAdyenPaymentMethod()).thenReturn(COUNTRY_CODE_SWEDEN); - AdyenNonAuthorizedPaymentException thisException = new AdyenNonAuthorizedPaymentException(paymentResultMock); - when(actionMock.getUrl()).thenReturn(ACTION_URL); - when(paymentsResponseMock.getResultCode()).thenReturn(REDIRECTSHOPPER); - when(paymentsResponseMock.getAction()).thenReturn(actionMock); - thisException.setPaymentsResponse(paymentsResponseMock); - when(adyenCheckoutFacadeMock.authorisePayment(requestMock, cartDataMock)).thenThrow(thisException); - - final String result = testObj.placeOrder(placeOrderFormMock, modelMock, requestMock, redirectModelMock); - - assertThat(result).isEqualTo(REDIRECT_PREFIX + ACTION_URL); - } - - @Test - public void placeOrder_shouldGoBackToStep_whenAdyenNonAuthorizedPaymentExceptionIsThrownAndPaymentRefused() throws Exception { - mockElementsUsedInTestsForPlaceOrder(); - mockFormValidationOK(); - mockCartValidationOK(); - when(cartDataMock.getAdyenPaymentMethod()).thenReturn(COUNTRY_CODE_SWEDEN); - AdyenNonAuthorizedPaymentException thisException = new AdyenNonAuthorizedPaymentException(paymentResultMock); - when(paymentsResponseMock.getResultCode()).thenReturn(REFUSED); - when(paymentsResponseMock.getRefusalReason()).thenReturn(ApiConstants.RefusalReason.TRANSACTION_NOT_PERMITTED); - thisException.setPaymentsResponse(paymentsResponseMock); - when(adyenCheckoutFacadeMock.authorisePayment(requestMock, cartDataMock)).thenThrow(thisException); - - final String result = testObj.placeOrder(placeOrderFormMock, modelMock, requestMock, redirectModelMock); - - assertThat(result).isEqualTo(AdyenControllerConstants.Views.Pages.MultiStepCheckout.CheckoutSummaryPage); - } - - @Test - public void placeOrder_shouldRedirectTo3DS_whenAdyenNonAuthorizedPaymentExceptionIsThrownAndChallengeShopperAnotherMethod() throws Exception { - mockElementsUsedInTestsForPlaceOrder(); - mockFormValidationOK(); - mockCartValidationOK(); - when(cartDataMock.getAdyenPaymentMethod()).thenReturn(PAYMENT_METHOD_CC); - AdyenNonAuthorizedPaymentException thisException = new AdyenNonAuthorizedPaymentException(paymentResultMock); - when(paymentsResponseMock.getResultCode()).thenReturn(CHALLENGESHOPPER); - thisException.setPaymentsResponse(paymentsResponseMock); - when(adyenCheckoutFacadeMock.authorisePayment(requestMock, cartDataMock)).thenThrow(thisException); - - final String result = testObj.placeOrder(placeOrderFormMock, modelMock, requestMock, redirectModelMock); - - assertThat(result).isEqualTo(AdyenControllerConstants.Views.Pages.MultiStepCheckout.Validate3DSPaymentPage); - } - - @Test - public void placeOrder_shouldRedirectTo3DS_whenAdyenNonAuthorizedPaymentExceptionIsThrownAndIdentifyShopperAnotherMethod() throws Exception { - mockElementsUsedInTestsForPlaceOrder(); - mockFormValidationOK(); - mockCartValidationOK(); - when(cartDataMock.getAdyenPaymentMethod()).thenReturn(PAYMENT_METHOD_CC); - AdyenNonAuthorizedPaymentException thisException = new AdyenNonAuthorizedPaymentException(paymentResultMock); - when(paymentsResponseMock.getResultCode()).thenReturn(IDENTIFYSHOPPER); - thisException.setPaymentsResponse(paymentsResponseMock); - when(adyenCheckoutFacadeMock.authorisePayment(requestMock, cartDataMock)).thenThrow(thisException); - - final String result = testObj.placeOrder(placeOrderFormMock, modelMock, requestMock, redirectModelMock); - - assertThat(result).isEqualTo(AdyenControllerConstants.Views.Pages.MultiStepCheckout.Validate3DSPaymentPage); - } private void mockAnonymousCheckoutAndOrderGuid() { when(checkoutCustomerStrategyMock.isAnonymousCheckout()).thenReturn(true); @@ -548,9 +387,9 @@ private void mockCartValidationOK() throws CommerceCartModificationException { private void mockElementsUsedInTestsForHandleRedirectPayload() throws Exception { when(requestMock.getParameter(PAYLOAD)).thenReturn(PAYLOAD_VALUE); when(responseMock.getMerchantReference()).thenReturn(MERCHANT_REFERENCE); - when(responseMock.getResultCode()).thenReturn(PaymentsResponse.ResultCodeEnum.AUTHORISED); + when(responseMock.getResultCode()).thenReturn(PaymentDetailsResponse.ResultCodeEnum.AUTHORISED); when(orderDataMock.getCode()).thenReturn(ORDER_CODE); - when(adyenCheckoutFacadeMock.handleRedirectPayload((HashMap) details)).thenReturn(responseMock); + when(adyenCheckoutFacadeMock.handleRedirectPayload((any()))).thenReturn(responseMock); when(orderFacadeMock.getOrderDetailsForCodeWithoutUser(responseMock.getMerchantReference())).thenReturn(orderDataMock); when(checkoutCustomerStrategyMock.isAnonymousCheckout()).thenReturn(false); } diff --git a/adyenv6core/resources/adyenv6core-spring.xml b/adyenv6core/resources/adyenv6core-spring.xml index 6fa5f5855..40797dfca 100644 --- a/adyenv6core/resources/adyenv6core-spring.xml +++ b/adyenv6core/resources/adyenv6core-spring.xml @@ -162,7 +162,6 @@ - @@ -209,11 +208,9 @@ - - diff --git a/adyenv6core/src/com/adyen/v6/factory/AdyenPaymentServiceFactory.java b/adyenv6core/src/com/adyen/v6/factory/AdyenPaymentServiceFactory.java index 5911bc6d8..a05462cec 100644 --- a/adyenv6core/src/com/adyen/v6/factory/AdyenPaymentServiceFactory.java +++ b/adyenv6core/src/com/adyen/v6/factory/AdyenPaymentServiceFactory.java @@ -25,7 +25,6 @@ import com.adyen.v6.service.DefaultAdyenCheckoutApiService; import com.adyen.v6.service.DefaultAdyenModificationsApiService; import de.hybris.platform.store.BaseStoreModel; -import org.springframework.cache.annotation.Cacheable; /** * Factory class for AdyenPaymentService @@ -38,8 +37,7 @@ public class AdyenPaymentServiceFactory { public AdyenPaymentServiceFactory(final AdyenRequestFactory adyenRequestFactory) { this.adyenRequestFactory = adyenRequestFactory; } - - @Cacheable("adyenCheckoutApiService") + public AdyenCheckoutApiService createAdyenCheckoutApiService(final BaseStoreModel baseStoreModel) { DefaultAdyenCheckoutApiService defaultAdyenCheckoutApiService = new DefaultAdyenCheckoutApiService(baseStoreModel); defaultAdyenCheckoutApiService.setAdyenRequestFactory(adyenRequestFactory); diff --git a/adyenv6core/src/com/adyen/v6/factory/AdyenRequestFactory.java b/adyenv6core/src/com/adyen/v6/factory/AdyenRequestFactory.java index 68399d969..c10b59fb4 100644 --- a/adyenv6core/src/com/adyen/v6/factory/AdyenRequestFactory.java +++ b/adyenv6core/src/com/adyen/v6/factory/AdyenRequestFactory.java @@ -118,7 +118,7 @@ public PaymentRequest createPaymentsRequest(final String merchantAccount, final String adyenPaymentMethod = cartData.getAdyenPaymentMethod(); final Boolean is3DS2allowed = is3DS2Allowed(); final PaymentRequest paymentsRequest = new PaymentRequest(); - //Blik + if (adyenPaymentMethod == null) { throw new IllegalArgumentException("Payment method is null"); } @@ -339,7 +339,7 @@ protected String getCountryCode(final CartData cartData) { } public RecurringDetailsRequest createListRecurringDetailsRequest(final String merchantAccount, final String customerId) { - return new RecurringDetailsRequest().merchantAccount(merchantAccount).shopperReference(customerId);//.setRecurring(new Recurring());//.selectOneClickContract(); + return new RecurringDetailsRequest().merchantAccount(merchantAccount).shopperReference(customerId); } /** @@ -392,7 +392,18 @@ public TerminalAPIRequest createTerminalAPIRequest(final CartData cartData, Cust saleToAcquirerData.setShopperReference(shopperReference); saleToAcquirerData.setRecurringContract(recurringContract.getContract().toString()); } - //updateApplicationInfoEcom(saleToAcquirerData.getApplicationInfo()); + com.adyen.model.applicationinfo.ApplicationInfo applicationInfo = saleToAcquirerData.getApplicationInfo(); + com.adyen.model.applicationinfo.CommonField version = new com.adyen.model.applicationinfo.CommonField().name(PLUGIN_NAME).version(PLUGIN_VERSION); + + com.adyen.model.applicationinfo.ExternalPlatform externalPlatform = new com.adyen.model.applicationinfo.ExternalPlatform(); + + externalPlatform.setName(PLATFORM_NAME); + externalPlatform.setVersion(getPlatformVersion()); + externalPlatform.setIntegrator(Adyenv6coreConstants.INTEGRATOR); + + applicationInfo.setExternalPlatform(externalPlatform); + applicationInfo.setMerchantApplication(version); + applicationInfo.setAdyenPaymentSource(version); saleData.setSaleToAcquirerData(saleToAcquirerData); } @@ -479,23 +490,23 @@ protected BillingAddress convertToBillingAddress(AddressData addressData) { address.setStreet("NA"); // set the actual values if they are available - if (addressData.getTown() != null && !addressData.getTown().isEmpty()) { + if (StringUtils.isNotEmpty(addressData.getTown())) { address.setCity(addressData.getTown()); } - if (addressData.getCountry() != null && !addressData.getCountry().getIsocode().isEmpty()) { + if (addressData.getCountry() != null && StringUtils.isNotEmpty(addressData.getCountry().getIsocode())) { address.setCountry(addressData.getCountry().getIsocode()); } - if (addressData.getLine1() != null && !addressData.getLine1().isEmpty()) { + if (StringUtils.isNotEmpty(addressData.getLine1())) { address.setStreet(addressData.getLine1()); } - if (addressData.getLine2() != null && !addressData.getLine2().isEmpty()) { + if (StringUtils.isNotEmpty(addressData.getLine2())) { address.setHouseNumberOrName(addressData.getLine2()); } - if (addressData.getPostalCode() != null && !address.getPostalCode().isEmpty()) { + if (StringUtils.isNotEmpty(addressData.getPostalCode())) { address.setPostalCode(addressData.getPostalCode()); } @@ -691,7 +702,7 @@ public void setOpenInvoiceData(PaymentRequest paymentsRequest, CartData cartData invoiceLines.add(invoiceLine); } - // paymentsRequest.setLineItems(invoiceLines); + paymentsRequest.setLineItems(invoiceLines); } private Name getAfterPayShopperName(final CartData cartData) { diff --git a/adyenv6core/src/com/adyen/v6/service/DefaultAdyenCheckoutApiService.java b/adyenv6core/src/com/adyen/v6/service/DefaultAdyenCheckoutApiService.java index beb39d964..5d1b8ea6d 100644 --- a/adyenv6core/src/com/adyen/v6/service/DefaultAdyenCheckoutApiService.java +++ b/adyenv6core/src/com/adyen/v6/service/DefaultAdyenCheckoutApiService.java @@ -120,7 +120,7 @@ public ConnectedTerminalsResponse getConnectedTerminals() throws IOException, Ap @Override public PaymentResponse componentPayment(final CartData cartData, CheckoutPaymentMethod checkoutPaymentMethod, final RequestInfo requestInfo, final CustomerModel customerModel) throws Exception { LOG.debug("Component payment"); - //Blik + PaymentsApi checkoutApi = new PaymentsApi(client); com.adyen.model.checkout.PaymentRequest paymentsRequest = getAdyenRequestFactory().createPaymentsRequest(baseStore.getAdyenMerchantAccount(), diff --git a/adyenv6core/src/com/adyen/v6/util/AmountUtil.java b/adyenv6core/src/com/adyen/v6/util/AmountUtil.java index a4f181d89..7fdb0364e 100644 --- a/adyenv6core/src/com/adyen/v6/util/AmountUtil.java +++ b/adyenv6core/src/com/adyen/v6/util/AmountUtil.java @@ -1,38 +1,30 @@ package com.adyen.v6.util; import com.adyen.model.checkout.Amount; -import de.hybris.platform.commercefacades.product.data.PriceData; +import org.apache.commons.lang3.StringUtils; +import org.springframework.util.Assert; import java.math.BigDecimal; public class AmountUtil { public static Amount createAmount(Long value, String currency) { + Assert.notNull(value, "Value cannot be null"); + Assert.isTrue(StringUtils.isNotBlank(currency), "Currency cannot be null or empty"); Amount amount = new Amount(); amount.setCurrency(currency); amount.setValue(value); return amount; } - public static Amount createAmount(PriceData priceData) { - Amount amount = new Amount(); - amount.setCurrency(priceData.getCurrencyIso()); - amount.setValue(priceData.getValue().longValue()); - return amount; - } - public static Amount createAmount(BigDecimal value, String currency) { + Assert.notNull(value, "Value cannot be null"); + Assert.isTrue(StringUtils.isNotBlank(currency), "Currency cannot be null or empty"); Amount amount = new Amount(); amount.setCurrency(currency); amount.setValue(value.longValue()); return amount; } - public static Amount createAmount(String value, String currency) { - Amount amount = new Amount(); - amount.setCurrency(currency); - amount.setValue(Long.parseLong(value)); - return amount; - } } diff --git a/adyenv6core/testsrc/com/adyen/v6/converters/PosPaymentResponseConverterTest.java b/adyenv6core/testsrc/com/adyen/v6/converters/PosPaymentResponseConverterTest.java deleted file mode 100644 index 8dbc035c3..000000000 --- a/adyenv6core/testsrc/com/adyen/v6/converters/PosPaymentResponseConverterTest.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * ###### - * ###### - * ############ ####( ###### #####. ###### ############ ############ - * ############# #####( ###### #####. ###### ############# ############# - * ###### #####( ###### #####. ###### ##### ###### ##### ###### - * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### - * ###### ###### #####( ###### #####. ###### ##### ##### ###### - * ############# ############# ############# ############# ##### ###### - * ############ ############ ############# ############ ##### ###### - * ###### - * ############# - * ############ - * - * Adyen Hybris Extension - * - * Copyright (c) 2019 Adyen B.V. - * This file is open source and available under the MIT license. - * See the LICENSE file for more info. - */ -package com.adyen.v6.converters; - -import com.adyen.model.checkout.PaymentsResponse; -import com.adyen.model.nexo.PaymentAcquirerData; -import com.adyen.model.nexo.PaymentResponse; -import com.adyen.model.nexo.PaymentResult; -import com.adyen.model.nexo.RepeatedMessageResponse; -import com.adyen.model.nexo.RepeatedResponseMessageBody; -import com.adyen.model.nexo.Response; -import com.adyen.model.nexo.SaleToPOIResponse; -import com.adyen.model.nexo.TransactionIdentification; -import com.adyen.model.nexo.TransactionStatusRequest; -import com.adyen.model.nexo.TransactionStatusResponse; -import de.hybris.bootstrap.annotations.UnitTest; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.mockito.Mock; - -import java.util.Arrays; -import java.util.Collection; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.when; -import static org.mockito.MockitoAnnotations.initMocks; - -@UnitTest -@RunWith(Parameterized.class) -public class PosPaymentResponseConverterTest { - - @Parameterized.Parameters - public static Collection data() { - return Arrays.asList(new Object[][] { - { "ewogICJhZGRpdGlvbmFsRGF0YSI6IHsKICAgICJhdXRoQ29kZSI6ICIxMjM0IiwKICAgICJ0aWQiOiAiNDMyMSIsCiAgICAibWlkIjogIjEwMDAiLAogICAgInRyYW5zYWN0aW9uUmVmZXJlbmNlTnVtYmVyIjogIjg4MjU5NzQwMDQ5MDkyNUoiLAogICAgImV4cGlyeVllYXIiOiAiMjAyOCIsCiAgICAiYXZzUmVzdWx0IjogIjAgVW5rbm93biIKICB9LAogICJzdG9yZSI6ICJNeVN0b3JlIgp9", true, 6, "1234" }, - { "ewogICJhZGRpdGlvbmFsRGF0YSI6IHsKICAgICJhdXRoQ29kZSI6ICIxMjM0IgogIH0sCiAgInN0b3JlIjogIk15U3RvcmUiCn0=", true, 1, "1234" }, - { "", true, 0, null }, - { null, false, null, null } - }); - } - - private String additionalResponse; - private Boolean shouldExpectAdditionalData; - private Integer expectedAdditionalDataSize; - private String expectedAuthCode; - - private PosPaymentResponseConverter posPaymentResponseConverter; - - @Mock - private SaleToPOIResponse saleToPoiResponse; - - //Payment Response - @Mock - private PaymentResponse paymentResponse; - @Mock - private Response response; - @Mock - private PaymentResult paymentResult; - @Mock - private PaymentAcquirerData paymentAcquirerData; - @Mock - private TransactionIdentification acquirerTransactionId; - - //Status response - @Mock - TransactionStatusResponse transactionStatusResponse; - @Mock - RepeatedMessageResponse repeatedMessageResponse; - @Mock - RepeatedResponseMessageBody repeatedResponseMessageBody; - - public PosPaymentResponseConverterTest(String additionalResponse, Boolean shouldExpectAdditionalData, Integer expectedAdditionalDataSize, String expectedAuthCode) { - this.additionalResponse = additionalResponse; - this.shouldExpectAdditionalData = shouldExpectAdditionalData; - this.expectedAdditionalDataSize = expectedAdditionalDataSize; - this.expectedAuthCode = expectedAuthCode; - } - - @Before - public void setUp() { - initMocks(this); - posPaymentResponseConverter = new PosPaymentResponseConverter(); - - when(paymentResponse.getPaymentResult()).thenReturn(paymentResult); - when(paymentResult.getPaymentAcquirerData()).thenReturn(paymentAcquirerData); - when(paymentAcquirerData.getAcquirerTransactionID()).thenReturn(acquirerTransactionId); - when(acquirerTransactionId.getTransactionID()).thenReturn("psp"); - - when(paymentResponse.getResponse()).thenReturn(response); - when(response.getAdditionalResponse()).thenReturn(additionalResponse); - } - - @Test - public void testConverterForPaymentResponse() { - when(saleToPoiResponse.getPaymentResponse()).thenReturn(paymentResponse); - - PaymentsResponse paymentsResponse = posPaymentResponseConverter.convert(saleToPoiResponse); - - assertNotNull(paymentsResponse); - assertEquals("psp", paymentsResponse.getPspReference()); - assertEquals(shouldExpectAdditionalData, paymentsResponse.getAdditionalData() != null); - - if(shouldExpectAdditionalData) { - assertEquals((int) expectedAdditionalDataSize, paymentsResponse.getAdditionalData().size()); - assertEquals(expectedAuthCode, paymentsResponse.getAuthCode()); - } - } - - @Test - public void testConverterForStatusResponse() { - when(saleToPoiResponse.getPaymentResponse()).thenReturn(null); - - when(saleToPoiResponse.getTransactionStatusResponse()).thenReturn(transactionStatusResponse); - when(transactionStatusResponse.getRepeatedMessageResponse()).thenReturn(repeatedMessageResponse); - when(repeatedMessageResponse.getRepeatedResponseMessageBody()).thenReturn(repeatedResponseMessageBody); - when(repeatedResponseMessageBody.getPaymentResponse()).thenReturn(paymentResponse); - - PaymentsResponse paymentsResponse = posPaymentResponseConverter.convert(saleToPoiResponse); - - assertNotNull(paymentsResponse); - assertEquals("psp", paymentsResponse.getPspReference()); - assertEquals(shouldExpectAdditionalData, paymentsResponse.getAdditionalData() != null); - - if (shouldExpectAdditionalData) { - assertEquals((int) expectedAdditionalDataSize, paymentsResponse.getAdditionalData().size()); - assertEquals(expectedAuthCode, paymentsResponse.getAuthCode()); - } - } -} diff --git a/adyenv6core/testsrc/com/adyen/v6/facades/AdyenCheckoutFacadeTest.java b/adyenv6core/testsrc/com/adyen/v6/facades/AdyenCheckoutFacadeTest.java index 43f6d0b7e..52cf88fe6 100644 --- a/adyenv6core/testsrc/com/adyen/v6/facades/AdyenCheckoutFacadeTest.java +++ b/adyenv6core/testsrc/com/adyen/v6/facades/AdyenCheckoutFacadeTest.java @@ -23,26 +23,25 @@ import com.adyen.model.checkout.InputDetail; import com.adyen.model.checkout.Item; +import com.adyen.model.checkout.PaymentCompletionDetails; +import com.adyen.model.checkout.PaymentDetailsRequest; +import com.adyen.model.checkout.PaymentDetailsResponse; import com.adyen.model.checkout.PaymentMethod; import com.adyen.model.checkout.PaymentMethodsResponse; -import com.adyen.model.checkout.PaymentsDetailsResponse; -import com.adyen.model.checkout.PaymentsResponse; +import com.adyen.model.checkout.PaymentResponse; import com.adyen.model.nexo.DocumentQualifierType; import com.adyen.model.nexo.ErrorConditionType; import com.adyen.model.nexo.OutputContent; import com.adyen.model.nexo.OutputText; import com.adyen.model.nexo.PaymentReceipt; -import com.adyen.model.nexo.PaymentResponse; import com.adyen.model.nexo.RepeatedMessageResponse; import com.adyen.model.nexo.RepeatedResponseMessageBody; -import com.adyen.model.nexo.Response; import com.adyen.model.nexo.ResultType; import com.adyen.model.nexo.SaleToPOIResponse; import com.adyen.model.nexo.TransactionStatusResponse; import com.adyen.model.terminal.TerminalAPIResponse; import com.adyen.service.exception.ApiException; import com.adyen.v6.constants.Adyenv6coreConstants; -import com.adyen.v6.converters.PaymentsDetailsResponseConverter; import com.adyen.v6.converters.PosPaymentResponseConverter; import com.adyen.v6.enums.RecurringContractMode; import com.adyen.v6.exceptions.AdyenNonAuthorizedPaymentException; @@ -50,8 +49,8 @@ import com.adyen.v6.factory.AdyenPaymentServiceFactory; import com.adyen.v6.repository.OrderRepository; import com.adyen.v6.service.AdyenBusinessProcessService; +import com.adyen.v6.service.AdyenCheckoutApiService; import com.adyen.v6.service.AdyenOrderService; -import com.adyen.v6.service.AdyenPaymentService; import com.adyen.v6.service.AdyenTransactionService; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.commercefacades.order.CheckoutFacade; @@ -99,7 +98,6 @@ import java.math.BigDecimal; import java.util.Arrays; import java.util.Collections; -import java.util.HashMap; import java.util.Map; import java.util.UUID; @@ -114,9 +112,12 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyMap; import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; @UnitTest @RunWith(MockitoJUnitRunner.class) @@ -139,7 +140,7 @@ public class AdyenCheckoutFacadeTest { @Mock AdyenPaymentServiceFactory adyenPaymentServiceFactory; @Mock - AdyenPaymentService adyenPaymentService; + AdyenCheckoutApiService adyenCheckoutApiService; @Mock BaseStoreService baseStoreService; @Mock @@ -174,8 +175,7 @@ public class AdyenCheckoutFacadeTest { AddressPopulator addressPopulator; @Mock AdyenBusinessProcessService adyenBusinessProcessService; - @Mock - private PaymentsDetailsResponseConverter getPaymentsDetailsResponseConverterMock; + @Mock private ConfigurationService configurationServiceMock; @Mock @@ -185,20 +185,20 @@ public class AdyenCheckoutFacadeTest { @Mock private BaseStoreModel baseStoreModelMock; @Mock - private AdyenPaymentService adyenPaymentServiceMock; + private AdyenCheckoutApiService adyenCheckoutApiServiceMock; @Mock HttpServletRequest request; @Mock - Map details; + PaymentDetailsRequest details; @Mock CartData cartData; @Mock CartModel cartModel; @Mock - PaymentsResponse paymentsResponse; + PaymentResponse paymentsResponse; @Mock - PaymentsDetailsResponse paymentsDetailsResponse; + PaymentDetailsResponse paymentsDetailsResponse; @Mock OrderData orderData; @Mock @@ -225,12 +225,12 @@ public class AdyenCheckoutFacadeTest { SaleToPOIResponse saleToPoiResponse; //Payment Response @Mock - PaymentResponse paymentResponse; + com.adyen.model.nexo.PaymentResponse nexpPaymentResponse; @Mock - Response response; + com.adyen.model.nexo.Response nexoResponse; //Status response @Mock - Response statusResponse; + com.adyen.model.nexo.Response nexoStatusResponse; @Mock TransactionStatusResponse transactionStatusResponse; @Mock @@ -257,12 +257,11 @@ public void setUp() { when(checkoutCustomerStrategy.getCurrentUserForCheckout()).thenReturn(new CustomerModel()); when(request.getAttribute("originalServiceId")).thenReturn(SERVICE_ID); when(baseStoreService.getCurrentBaseStore()).thenReturn(baseStore); - when(adyenPaymentServiceFactory.createFromBaseStore(any())).thenReturn(adyenPaymentService); - when(getPaymentsDetailsResponseConverterMock.convert(paymentsDetailsResponse)).thenReturn(paymentsResponse); + when(adyenPaymentServiceFactory.createAdyenCheckoutApiService(any())).thenReturn(adyenCheckoutApiService); when(configurationServiceMock.getConfiguration()).thenReturn(configurationMock); when(baseStoreServiceMock.getCurrentBaseStore()).thenReturn(baseStoreModelMock); - when(adyenPaymentServiceFactoryMock.createFromBaseStore(baseStoreModelMock)).thenReturn(adyenPaymentServiceMock); - when(adyenPaymentServiceMock.calculateAmountWithTaxes(orderModel)).thenReturn(new BigDecimal(10)); + when(adyenPaymentServiceFactoryMock.createAdyenCheckoutApiService(baseStoreModelMock)).thenReturn(adyenCheckoutApiServiceMock); + when(adyenCheckoutApiServiceMock.calculateAmountWithTaxes(orderModel)).thenReturn(new BigDecimal(10)); } @Test @@ -276,7 +275,7 @@ public void testInitializeEpsCheckoutData() throws Exception { when(addressData.getCountry()).thenReturn(countryData); when(countryData.getIsocode()).thenReturn("NL"); when(commonI18NService.getCurrentLanguage()).thenReturn(null); - when(adyenPaymentService.getPaymentMethodsResponse(any(), any(), any(), any(), any())).thenReturn(createEpsPaymentMethodsResponse()); + when(adyenCheckoutApiService.getPaymentMethodsResponse(any(), any(), any(), any(), any())).thenReturn(createEpsPaymentMethodsResponse()); when(baseStore.getAdyenRecurringContractMode()).thenReturn(RecurringContractMode.NONE); when(cartService.getSessionCart()).thenReturn(new CartModel()); when(cartData.getAdyenPaymentMethod()).thenReturn(PAYMENT_METHOD_EPS); @@ -311,19 +310,17 @@ private PaymentMethodsResponse createEpsPaymentMethodsResponse() { @Test public void testInitiatePosPaymentSuccess() throws Exception { - when(adyenPaymentService.sendSyncPosPaymentRequest(eq(cartData), any(), eq(SERVICE_ID))).thenReturn(terminalApiResponse); + when(adyenCheckoutApiService.sendSyncPosPaymentRequest(eq(cartData), any(), eq(SERVICE_ID))).thenReturn(terminalApiResponse); when(posPaymentResponseConverter.convert(saleToPoiResponse)).thenReturn(paymentsResponse); //TerminalAPIUtil.getPaymentResult when(terminalApiResponse.getSaleToPOIResponse()).thenReturn(saleToPoiResponse); - when(saleToPoiResponse.getPaymentResponse()).thenReturn(paymentResponse); - when(paymentResponse.getResponse()).thenReturn(response); - when(response.getResult()).thenReturn(ResultType.SUCCESS); + when(saleToPoiResponse.getPaymentResponse()).thenReturn(nexpPaymentResponse); setSuccessfulPaymentStubs(); OrderData orderDataResult = adyenCheckoutFacade.initiatePosPayment(request, cartData); assertEquals(orderData, orderDataResult); - verify(adyenPaymentService).sendSyncPosPaymentRequest(eq(cartData), any(), eq(SERVICE_ID)); + verify(adyenCheckoutApiService).sendSyncPosPaymentRequest(eq(cartData), any(), eq(SERVICE_ID)); verify(posPaymentResponseConverter).convert(saleToPoiResponse); verify(adyenTransactionService).authorizeOrderModel(any(), any(), any()); verify(checkoutFacade).placeOrder(); @@ -331,13 +328,12 @@ public void testInitiatePosPaymentSuccess() throws Exception { @Test public void testInitiatePosPaymentFailure() throws Exception { - when(adyenPaymentService.sendSyncPosPaymentRequest(eq(cartData), any(), eq(SERVICE_ID))).thenReturn(terminalApiResponse); + when(adyenCheckoutApiService.sendSyncPosPaymentRequest(eq(cartData), any(), eq(SERVICE_ID))).thenReturn(terminalApiResponse); when(posPaymentResponseConverter.convert(saleToPoiResponse)).thenReturn(paymentsResponse); //TerminalAPIUtil.getPaymentResult when(terminalApiResponse.getSaleToPOIResponse()).thenReturn(saleToPoiResponse); - when(saleToPoiResponse.getPaymentResponse()).thenReturn(paymentResponse); - when(paymentResponse.getResponse()).thenReturn(response); - when(response.getResult()).thenReturn(ResultType.FAILURE); + when(saleToPoiResponse.getPaymentResponse()).thenReturn(nexpPaymentResponse); + when(nexpPaymentResponse.getResponse()).thenReturn(nexoResponse); try { adyenCheckoutFacade.initiatePosPayment(request, cartData); @@ -349,7 +345,7 @@ public void testInitiatePosPaymentFailure() throws Exception { @Test public void testInitiatePosPaymentBadRequest() throws Exception { - when(adyenPaymentService.sendSyncPosPaymentRequest(eq(cartData), any(), eq(SERVICE_ID))).thenReturn(terminalApiResponse); + when(adyenCheckoutApiService.sendSyncPosPaymentRequest(eq(cartData), any(), eq(SERVICE_ID))).thenReturn(terminalApiResponse); when(posPaymentResponseConverter.convert(saleToPoiResponse)).thenReturn(paymentsResponse); //TerminalAPIUtil.getPaymentResult when(terminalApiResponse.getSaleToPOIResponse()).thenReturn(null); @@ -364,26 +360,26 @@ public void testInitiatePosPaymentBadRequest() throws Exception { @Test public void testCheckPosPaymentStatusSuccessAndPaymentSuccess() throws Exception { - when(adyenPaymentService.sendSyncPosStatusRequest(cartData, SERVICE_ID)).thenReturn(terminalApiResponse); + when(adyenCheckoutApiService.sendSyncPosStatusRequest(cartData, SERVICE_ID)).thenReturn(terminalApiResponse); when(posPaymentResponseConverter.convert(saleToPoiResponse)).thenReturn(paymentsResponse); //TerminalAPIUtil.getStatusResult when(terminalApiResponse.getSaleToPOIResponse()).thenReturn(saleToPoiResponse); when(saleToPoiResponse.getTransactionStatusResponse()).thenReturn(transactionStatusResponse); - when(transactionStatusResponse.getResponse()).thenReturn(statusResponse); - when(statusResponse.getResult()).thenReturn(ResultType.SUCCESS); + when(transactionStatusResponse.getResponse()).thenReturn(nexoStatusResponse); + when(nexoStatusResponse.getResult()).thenReturn(ResultType.SUCCESS); //TerminalAPIUtil.getPaymentResult when(saleToPoiResponse.getPaymentResponse()).thenReturn(null); when(transactionStatusResponse.getRepeatedMessageResponse()).thenReturn(repeatedMessageResponse); when(repeatedMessageResponse.getRepeatedResponseMessageBody()).thenReturn(repeatedResponseMessageBody); - when(repeatedResponseMessageBody.getPaymentResponse()).thenReturn(paymentResponse); - when(paymentResponse.getResponse()).thenReturn(response); - when(response.getResult()).thenReturn(ResultType.SUCCESS); + when(repeatedResponseMessageBody.getPaymentResponse()).thenReturn(nexpPaymentResponse); + when(nexpPaymentResponse.getResponse()).thenReturn(nexoResponse); + when(nexoResponse.getResult()).thenReturn(ResultType.SUCCESS); setSuccessfulPaymentStubs(); OrderData orderDataResult = adyenCheckoutFacade.checkPosPaymentStatus(request, cartData); assertEquals(orderData, orderDataResult); - verify(adyenPaymentService).sendSyncPosStatusRequest(cartData, SERVICE_ID); + verify(adyenCheckoutApiService).sendSyncPosStatusRequest(cartData, SERVICE_ID); verify(posPaymentResponseConverter).convert(saleToPoiResponse); verify(adyenTransactionService).authorizeOrderModel(any(), any(), any()); verify(checkoutFacade).placeOrder(); @@ -391,20 +387,20 @@ public void testCheckPosPaymentStatusSuccessAndPaymentSuccess() throws Exception @Test public void testCheckPosPaymentStatusSuccessButPaymentFailure() throws Exception { - when(adyenPaymentService.sendSyncPosStatusRequest(cartData, SERVICE_ID)).thenReturn(terminalApiResponse); + when(adyenCheckoutApiService.sendSyncPosStatusRequest(cartData, SERVICE_ID)).thenReturn(terminalApiResponse); when(posPaymentResponseConverter.convert(saleToPoiResponse)).thenReturn(paymentsResponse); //TerminalAPIUtil.getStatusResult when(terminalApiResponse.getSaleToPOIResponse()).thenReturn(saleToPoiResponse); when(saleToPoiResponse.getTransactionStatusResponse()).thenReturn(transactionStatusResponse); - when(transactionStatusResponse.getResponse()).thenReturn(statusResponse); - when(statusResponse.getResult()).thenReturn(ResultType.SUCCESS); + when(transactionStatusResponse.getResponse()).thenReturn(nexoStatusResponse); + when(nexoStatusResponse.getResult()).thenReturn(ResultType.SUCCESS); //TerminalAPIUtil.getPaymentResult when(saleToPoiResponse.getPaymentResponse()).thenReturn(null); when(transactionStatusResponse.getRepeatedMessageResponse()).thenReturn(repeatedMessageResponse); when(repeatedMessageResponse.getRepeatedResponseMessageBody()).thenReturn(repeatedResponseMessageBody); - when(repeatedResponseMessageBody.getPaymentResponse()).thenReturn(paymentResponse); - when(paymentResponse.getResponse()).thenReturn(response); - when(response.getResult()).thenReturn(ResultType.FAILURE); + when(repeatedResponseMessageBody.getPaymentResponse()).thenReturn(nexpPaymentResponse); + when(nexpPaymentResponse.getResponse()).thenReturn(nexoResponse); + when(nexoResponse.getResult()).thenReturn(ResultType.FAILURE); try { adyenCheckoutFacade.checkPosPaymentStatus(request, cartData); @@ -416,15 +412,15 @@ public void testCheckPosPaymentStatusSuccessButPaymentFailure() throws Exception @Test public void testCheckPosPaymentStatusTimeout() throws Exception { - when(adyenPaymentService.sendSyncPosStatusRequest(cartData, SERVICE_ID)).thenReturn(terminalApiResponse); + when(adyenCheckoutApiService.sendSyncPosStatusRequest(cartData, SERVICE_ID)).thenReturn(terminalApiResponse); when(posPaymentResponseConverter.convert(saleToPoiResponse)).thenReturn(paymentsResponse); //TerminalAPIUtil.getStatusResult when(terminalApiResponse.getSaleToPOIResponse()).thenReturn(saleToPoiResponse); when(saleToPoiResponse.getTransactionStatusResponse()).thenReturn(transactionStatusResponse); - when(transactionStatusResponse.getResponse()).thenReturn(statusResponse); - when(statusResponse.getResult()).thenReturn(ResultType.FAILURE); + when(transactionStatusResponse.getResponse()).thenReturn(nexoStatusResponse); + when(nexoStatusResponse.getResult()).thenReturn(ResultType.FAILURE); //TerminalAPIUtil.getErrorConditionForStatus - when(statusResponse.getErrorCondition()).thenReturn(ErrorConditionType.IN_PROGRESS); + when(nexoStatusResponse.getErrorCondition()).thenReturn(ErrorConditionType.IN_PROGRESS); //isPosTimedOut (will timeout after 10 seconds) long processStartTime = System.currentTimeMillis(); when(request.getAttribute("paymentStartTime")).thenReturn(processStartTime); @@ -441,15 +437,15 @@ public void testCheckPosPaymentStatusTimeout() throws Exception { @Test public void testCheckPosPaymentStatusError() throws Exception { - when(adyenPaymentService.sendSyncPosStatusRequest(cartData, SERVICE_ID)).thenReturn(terminalApiResponse); + when(adyenCheckoutApiService.sendSyncPosStatusRequest(cartData, SERVICE_ID)).thenReturn(terminalApiResponse); when(posPaymentResponseConverter.convert(saleToPoiResponse)).thenReturn(paymentsResponse); //TerminalAPIUtil.getStatusResult when(terminalApiResponse.getSaleToPOIResponse()).thenReturn(saleToPoiResponse); when(saleToPoiResponse.getTransactionStatusResponse()).thenReturn(transactionStatusResponse); - when(transactionStatusResponse.getResponse()).thenReturn(statusResponse); - when(statusResponse.getResult()).thenReturn(ResultType.FAILURE); + when(transactionStatusResponse.getResponse()).thenReturn(nexoStatusResponse); + when(nexoStatusResponse.getResult()).thenReturn(ResultType.FAILURE); //TerminalAPIUtil.getErrorConditionForStatus - when(statusResponse.getErrorCondition()).thenReturn(ErrorConditionType.CANCEL); + //when(statusResponse.getErrorCondition()).thenReturn(ErrorConditionType.CANCEL); try { adyenCheckoutFacade.checkPosPaymentStatus(request, cartData); @@ -460,9 +456,9 @@ public void testCheckPosPaymentStatusError() throws Exception { } - private void setSuccessfulPaymentStubs() throws InvalidCartException { + private void setSuccessfulPaymentStubs() throws InvalidCartException, InvalidCartException { //Receipt - when(paymentResponse.getPaymentReceipt()).thenReturn(Collections.singletonList(receipt)); + when(nexpPaymentResponse.getPaymentReceipt()).thenReturn(Collections.singletonList(receipt)); when(receipt.getDocumentQualifier()).thenReturn(DocumentQualifierType.CUSTOMER_RECEIPT); when(receipt.getOutputContent()).thenReturn(outputContent); when(outputContent.getOutputText()).thenReturn(Arrays.asList(textWithNameValue, textJustName, textJustValue)); @@ -476,7 +472,7 @@ private void setSuccessfulPaymentStubs() throws InvalidCartException { when(checkoutFacade.placeOrder()).thenReturn(orderData); when(orderRepository.getOrderModel(any())).thenReturn(new OrderModel()); //updateOrder - doNothing().when(adyenOrderService).updateOrderFromPaymentsResponse(any(), any()); + doNothing().when(adyenOrderService).updatePaymentInfo(any(), any(), any()); } @Test @@ -486,8 +482,8 @@ public void testAuthorisePaymentRedirect() throws Exception { when(commonI18NService.getCurrentLanguage()).thenReturn(null); when(request.getRequestURL()).thenReturn(new StringBuffer(URL)); when(request.getRequestURI()).thenReturn(URL); - when(adyenPaymentService.authorisePayment(any(), any(), any())).thenReturn(paymentsResponse); - when(paymentsResponse.getResultCode()).thenReturn(PaymentsResponse.ResultCodeEnum.REDIRECTSHOPPER); + // when(adyenPaymentService.authorisePayment(any(), any(), any())).thenReturn(paymentsResponse); + when(paymentsResponse.getResultCode()).thenReturn(PaymentResponse.ResultCodeEnum.REDIRECTSHOPPER); when(checkoutFacade.placeOrder()).thenReturn(orderData); when(orderRepository.getOrderModel(any())).thenReturn(orderModel); doNothing().when(modelService).save(any()); @@ -497,24 +493,23 @@ public void testAuthorisePaymentRedirect() throws Exception { adyenCheckoutFacade.authorisePayment(request, cartData); fail("Expected AdyenNonAuthorizedPaymentException"); } catch (AdyenNonAuthorizedPaymentException e) { - verify(adyenPaymentService).authorisePayment(eq(cartData), any(), any()); + verify(adyenCheckoutApiService).authorisePayment(eq(cartData), any(), any()); verify(cartModel).setStatus(OrderStatus.PAYMENT_PENDING); verify(checkoutFacade).placeOrder(); assertNotNull(e.getPaymentsResponse()); - assertEquals(PaymentsResponse.ResultCodeEnum.REDIRECTSHOPPER, e.getPaymentsResponse().getResultCode()); + assertEquals(PaymentResponse.ResultCodeEnum.REDIRECTSHOPPER, e.getPaymentsResponse().getResultCode()); } } @Test public void testHandle3DResponseAuthorised() throws Exception { - when(adyenPaymentService.authorise3DSPayment(any())).thenReturn(paymentsDetailsResponse); + when(adyenCheckoutApiService.authorise3DSPayment(any())).thenReturn(paymentsDetailsResponse); when(paymentsResponse.getMerchantReference()).thenReturn(MERCHANT_REFERENCE); when(orderRepository.getOrderModel(any())).thenReturn(orderModel); doNothing().when(sessionService).removeAttribute(any()); when(adyenTransactionService.createPaymentTransactionFromResultCode(any(), any(), any(), any())).thenReturn(new PaymentTransactionModel()); - doNothing().when(adyenOrderService).updateOrderFromPaymentsResponse(any(), any()); - when(paymentsResponse.getResultCode()).thenReturn(PaymentsResponse.ResultCodeEnum.AUTHORISED); - when(paymentsDetailsResponse.getResultCode()).thenReturn(PaymentsResponse.ResultCodeEnum.AUTHORISED); + when(paymentsResponse.getResultCode()).thenReturn(PaymentResponse.ResultCodeEnum.AUTHORISED); + when(paymentsDetailsResponse.getResultCode()).thenReturn(PaymentDetailsResponse.ResultCodeEnum.AUTHORISED); doNothing().when(modelService).save(any()); when(orderConverter.convert(any())).thenReturn(orderData); doNothing().when(adyenBusinessProcessService).triggerOrderProcessEvent(any(), any()); @@ -523,20 +518,19 @@ public void testHandle3DResponseAuthorised() throws Exception { OrderData orderDataResult = adyenCheckoutFacade.handle3DSResponse(details); assertEquals(orderData, orderDataResult); - verify(adyenPaymentService).authorise3DSPayment(anyMap()); + verify(adyenCheckoutApiService).authorise3DSPayment(details); verify(orderRepository).getOrderModel(ORDER_CODE); verify(orderConverter).convert(orderModel); } @Test public void testHandle3DResponseError() throws Exception { - when(adyenPaymentService.authorise3DSPayment(any())).thenReturn(paymentsDetailsResponse); + when(adyenCheckoutApiService.authorise3DSPayment(any())).thenReturn(paymentsDetailsResponse); when(paymentsResponse.getMerchantReference()).thenReturn(MERCHANT_REFERENCE); when(orderRepository.getOrderModel(any())).thenReturn(orderModel); doNothing().when(sessionService).removeAttribute(any()); when(adyenTransactionService.createPaymentTransactionFromResultCode(any(), any(), any(), any())).thenReturn(new PaymentTransactionModel()); - doNothing().when(adyenOrderService).updateOrderFromPaymentsResponse(any(), any()); - when(paymentsResponse.getResultCode()).thenReturn(PaymentsResponse.ResultCodeEnum.REFUSED); + when(paymentsResponse.getResultCode()).thenReturn(PaymentResponse.ResultCodeEnum.REFUSED); doNothing().when(modelService).save(any()); when(cartFactory.createCart()).thenReturn(cartModel); doNothing().when(cartService).setSessionCart(any()); @@ -556,14 +550,14 @@ public void testHandle3DResponseError() throws Exception { when(orderModel.getStore()).thenReturn(storeModel); when(cartModel.getStore()).thenReturn(storeModel); when(paymentsDetailsResponse.getMerchantReference()).thenReturn(ORDER_CODE); - when(paymentsResponse.getResultCode()).thenReturn(PaymentsResponse.ResultCodeEnum.CHALLENGESHOPPER); + when(paymentsResponse.getResultCode()).thenReturn(PaymentResponse.ResultCodeEnum.CHALLENGESHOPPER); when(orderRepository.getOrderModel(ORDER_CODE)).thenReturn(orderModel); try { adyenCheckoutFacade.handle3DSResponse(details); fail("Expected AdyenNonAuthorizedPaymentException"); } catch (AdyenNonAuthorizedPaymentException e) { - verify(adyenPaymentService).authorise3DSPayment(anyMap()); + verify(adyenCheckoutApiService).authorise3DSPayment(details); verify(cartFactory).createCart(); verify(cartService).setSessionCart(cartModel); verify(calculationService).calculate(cartModel); @@ -573,7 +567,7 @@ public void testHandle3DResponseError() throws Exception { @Test public void testHandle3DResponseThrowsApiException() throws Exception { when(sessionService.getAttribute(SESSION_PENDING_ORDER_CODE)).thenReturn(PENDING_ORDER_CODE); - when(adyenPaymentService.authorise3DSPayment(any())).thenThrow(new ApiException(EXCEPTION, 999)); + when(adyenCheckoutApiService.authorise3DSPayment(any())).thenThrow(new ApiException(EXCEPTION, 999)); when(orderRepository.getOrderModel(any())).thenReturn(orderModel); doNothing().when(sessionService).removeAttribute(any()); doNothing().when(modelService).save(any()); @@ -600,7 +594,7 @@ public void testHandle3DResponseThrowsApiException() throws Exception { fail("Expected AdyenNonAuthorizedPaymentException"); } catch (AdyenNonAuthorizedPaymentException e) { assertEquals(e.getMessage(), EXCEPTION); - verify(adyenPaymentService).authorise3DSPayment(anyMap()); + verify(adyenCheckoutApiService).authorise3DSPayment(details); verify(orderRepository, times(2)).getOrderModel(PENDING_ORDER_CODE); verify(cartFactory).createCart(); verify(cartService).setSessionCart(cartModel); @@ -612,14 +606,14 @@ public void testHandle3DResponseThrowsApiException() throws Exception { public void testHandle3DS2ResponseAuthorised() throws Exception { when(request.getParameter(FINGERPRINT_RESULT)).thenReturn(null); when(request.getParameter(CHALLENGE_RESULT)).thenReturn(RESULT); - when(adyenPaymentService.authorise3DSPayment(anyMap())).thenReturn(paymentsDetailsResponse); + when(adyenCheckoutApiService.authorise3DSPayment(details)).thenReturn(paymentsDetailsResponse); when(paymentsResponse.getMerchantReference()).thenReturn(MERCHANT_REFERENCE); when(orderRepository.getOrderModel(any())).thenReturn(orderModel); doNothing().when(sessionService).removeAttribute(any()); when(adyenTransactionService.createPaymentTransactionFromResultCode(any(), any(), any(), any())).thenReturn(new PaymentTransactionModel()); - doNothing().when(adyenOrderService).updateOrderFromPaymentsResponse(any(), any()); - when(paymentsDetailsResponse.getResultCode()).thenReturn(PaymentsResponse.ResultCodeEnum.AUTHORISED); - when(paymentsResponse.getResultCode()).thenReturn(PaymentsResponse.ResultCodeEnum.AUTHORISED); + doNothing().when(adyenOrderService).updatePaymentInfo(any(), any(), any()); + when(paymentsDetailsResponse.getResultCode()).thenReturn(PaymentDetailsResponse.ResultCodeEnum.AUTHORISED); + when(paymentsResponse.getResultCode()).thenReturn(PaymentResponse.ResultCodeEnum.AUTHORISED); doNothing().when(modelService).save(any()); when(orderConverter.convert(any())).thenReturn(orderData); doNothing().when(adyenBusinessProcessService).triggerOrderProcessEvent(any(), any()); @@ -628,7 +622,7 @@ public void testHandle3DS2ResponseAuthorised() throws Exception { OrderData orderDataResult = adyenCheckoutFacade.handle3DSResponse(details); assertEquals(orderData, orderDataResult); - verify(adyenPaymentService).authorise3DSPayment(anyMap()); + verify(adyenCheckoutApiService).authorise3DSPayment(details); verify(orderConverter).convert(orderModel); } @@ -636,9 +630,9 @@ public void testHandle3DS2ResponseAuthorised() throws Exception { public void testHandle3DS2ResponseChallengeShopper() throws Exception { when(request.getParameter(FINGERPRINT_RESULT)).thenReturn(RESULT); when(request.getParameter(CHALLENGE_RESULT)).thenReturn(null); - when(adyenPaymentService.authorise3DSPayment(anyMap())).thenReturn(paymentsDetailsResponse); + when(adyenCheckoutApiService.authorise3DSPayment(details)).thenReturn(paymentsDetailsResponse); when(paymentsDetailsResponse.getMerchantReference()).thenReturn(ORDER_CODE); - when(paymentsResponse.getResultCode()).thenReturn(PaymentsResponse.ResultCodeEnum.CHALLENGESHOPPER); + when(paymentsResponse.getResultCode()).thenReturn(PaymentResponse.ResultCodeEnum.CHALLENGESHOPPER); when(orderRepository.getOrderModel(ORDER_CODE)).thenReturn(orderModel); when(orderModel.getEntries()).thenReturn(Collections.emptyList()); @@ -646,7 +640,7 @@ public void testHandle3DS2ResponseChallengeShopper() throws Exception { adyenCheckoutFacade.handle3DSResponse(details); fail("Expected AdyenNonAuthorizedPaymentException"); } catch (AdyenNonAuthorizedPaymentException e) { - verify(adyenPaymentService).authorise3DSPayment(anyMap()); + verify(adyenCheckoutApiService).authorise3DSPayment(details); assertNotNull(e.getPaymentsDetailsResponse()); } } @@ -655,13 +649,13 @@ public void testHandle3DS2ResponseChallengeShopper() throws Exception { public void testHandle3DS2ResponseError() throws Exception { when(request.getParameter(FINGERPRINT_RESULT)).thenReturn(null); when(request.getParameter(CHALLENGE_RESULT)).thenReturn(RESULT); - when(adyenPaymentService.authorise3DSPayment(anyMap())).thenReturn(paymentsDetailsResponse); + when(adyenCheckoutApiService.authorise3DSPayment(details)).thenReturn(paymentsDetailsResponse); when(paymentsResponse.getMerchantReference()).thenReturn(MERCHANT_REFERENCE); when(orderRepository.getOrderModel(any())).thenReturn(orderModel); doNothing().when(sessionService).removeAttribute(any()); when(adyenTransactionService.createPaymentTransactionFromResultCode(any(), any(), any(), any())).thenReturn(new PaymentTransactionModel()); - doNothing().when(adyenOrderService).updateOrderFromPaymentsResponse(any(), any()); - when(paymentsResponse.getResultCode()).thenReturn(PaymentsResponse.ResultCodeEnum.REFUSED); + doNothing().when(adyenOrderService).updatePaymentInfo(any(), any(), any()); + when(paymentsResponse.getResultCode()).thenReturn(PaymentResponse.ResultCodeEnum.REFUSED); doNothing().when(modelService).save(any()); when(cartFactory.createCart()).thenReturn(cartModel); doNothing().when(cartService).setSessionCart(any()); @@ -687,7 +681,7 @@ public void testHandle3DS2ResponseError() throws Exception { adyenCheckoutFacade.handle3DSResponse(details); fail("Expected AdyenNonAuthorizedPaymentException"); } catch (AdyenNonAuthorizedPaymentException e) { - verify(adyenPaymentService).authorise3DSPayment(anyMap()); + verify(adyenCheckoutApiService).authorise3DSPayment(details); verify(cartFactory).createCart(); verify(cartService).setSessionCart(cartModel); verify(calculationService).calculate(cartModel); @@ -699,7 +693,7 @@ public void testHandle3DS2ResponseThrowsApiException() throws Exception { when(request.getParameter(FINGERPRINT_RESULT)).thenReturn(null); when(request.getParameter(CHALLENGE_RESULT)).thenReturn(RESULT); when(sessionService.getAttribute(SESSION_PENDING_ORDER_CODE)).thenReturn(PENDING_ORDER_CODE); - when(adyenPaymentService.authorise3DSPayment(anyMap())).thenThrow(new ApiException(EXCEPTION, 999)); + when(adyenCheckoutApiService.authorise3DSPayment(details)).thenThrow(new ApiException(EXCEPTION, 999)); when(orderRepository.getOrderModel(any())).thenReturn(orderModel); doNothing().when(sessionService).removeAttribute(any()); doNothing().when(modelService).save(any()); @@ -726,7 +720,7 @@ public void testHandle3DS2ResponseThrowsApiException() throws Exception { fail("Expected AdyenNonAuthorizedPaymentException"); } catch (AdyenNonAuthorizedPaymentException e) { assertEquals(e.getMessage(), EXCEPTION); - verify(adyenPaymentService).authorise3DSPayment(anyMap()); + verify(adyenCheckoutApiService).authorise3DSPayment(details); verify(orderRepository, times(2)).getOrderModel(PENDING_ORDER_CODE); verify(cartFactory).createCart(); verify(cartService).setSessionCart(cartModel); @@ -736,37 +730,39 @@ public void testHandle3DS2ResponseThrowsApiException() throws Exception { @Test public void testHandleRedirectPayloadAuthorised() throws Exception { + PaymentCompletionDetails paymentCompletionDetails = new PaymentCompletionDetails(); when(sessionService.getAttribute(Adyenv6coreConstants.PAYMENT_METHOD)).thenReturn(PAYMENT_METHOD); - when(adyenPaymentService.getPaymentDetailsFromPayload(any())).thenReturn(paymentsDetailsResponse); - when(adyenPaymentService.authorise3DSPayment(any())).thenReturn(paymentsDetailsResponse); + when(adyenCheckoutApiService.getPaymentDetailsFromPayload(paymentCompletionDetails)).thenReturn(paymentsDetailsResponse); + when(adyenCheckoutApiService.authorise3DSPayment(any())).thenReturn(paymentsDetailsResponse); when(paymentsResponse.getMerchantReference()).thenReturn(MERCHANT_REFERENCE); when(orderRepository.getOrderModel(any())).thenReturn(orderModel); doNothing().when(sessionService).removeAttribute(any()); - when(paymentsResponse.getResultCode()).thenReturn(PaymentsResponse.ResultCodeEnum.AUTHORISED); - when(paymentsDetailsResponse.getResultCode()).thenReturn(PaymentsResponse.ResultCodeEnum.AUTHORISED); + when(paymentsResponse.getResultCode()).thenReturn(PaymentResponse.ResultCodeEnum.AUTHORISED); + when(paymentsDetailsResponse.getResultCode()).thenReturn(PaymentDetailsResponse.ResultCodeEnum.AUTHORISED); when(adyenTransactionService.createPaymentTransactionFromResultCode(any(), any(), any(), any())).thenReturn(new PaymentTransactionModel()); - doNothing().when(adyenOrderService).updateOrderFromPaymentsResponse(any(), any()); + doNothing().when(adyenOrderService).updatePaymentInfo(any(), any(), any()); doNothing().when(adyenBusinessProcessService).triggerOrderProcessEvent(any(), any()); when(paymentsDetailsResponse.getMerchantReference()).thenReturn(ORDER_CODE); when(orderModel.getEntries()).thenReturn(Collections.emptyList()); - HashMap details = new HashMap<>(); - PaymentsDetailsResponse paymentsDetailsResponseReturned = adyenCheckoutFacade.handleRedirectPayload(details); + + PaymentDetailsResponse paymentsDetailsResponseReturned = adyenCheckoutFacade.handleRedirectPayload(paymentCompletionDetails); assertEquals(paymentsDetailsResponseReturned, paymentsDetailsResponse); - assertEquals(PaymentsResponse.ResultCodeEnum.AUTHORISED, paymentsDetailsResponseReturned.getResultCode()); - verify(adyenPaymentService).getPaymentDetailsFromPayload(details); + assertEquals(PaymentResponse.ResultCodeEnum.AUTHORISED, paymentsDetailsResponseReturned.getResultCode()); + verify(adyenCheckoutApiService).getPaymentDetailsFromPayload(details); verify(orderRepository).getOrderModel(ORDER_CODE); } @Test public void testHandleRedirectPayloadNotAuthorised() throws Exception { + PaymentCompletionDetails paymentCompletionDetails = new PaymentCompletionDetails(); when(sessionService.getAttribute(Adyenv6coreConstants.PAYMENT_METHOD)).thenReturn(PAYMENT_METHOD); - when(adyenPaymentService.getPaymentDetailsFromPayload(any())).thenReturn(paymentsDetailsResponse); + when(adyenCheckoutApiService.getPaymentDetailsFromPayload(paymentCompletionDetails)).thenReturn(paymentsDetailsResponse); when(paymentsResponse.getMerchantReference()).thenReturn(MERCHANT_REFERENCE); when(orderRepository.getOrderModel(any())).thenReturn(orderModel); doNothing().when(sessionService).removeAttribute(any()); - when(paymentsResponse.getResultCode()).thenReturn(PaymentsResponse.ResultCodeEnum.REFUSED); - when(paymentsDetailsResponse.getResultCode()).thenReturn(PaymentsResponse.ResultCodeEnum.REFUSED); + when(paymentsResponse.getResultCode()).thenReturn(PaymentResponse.ResultCodeEnum.REFUSED); + when(paymentsDetailsResponse.getResultCode()).thenReturn(PaymentDetailsResponse.ResultCodeEnum.REFUSED); doNothing().when(modelService).save(any()); when(cartFactory.createCart()).thenReturn(cartModel); doNothing().when(cartService).setSessionCart(any()); @@ -781,7 +777,7 @@ public void testHandleRedirectPayloadNotAuthorised() throws Exception { when(checkoutFacade.setDeliveryMode(any())).thenReturn(true); doNothing().when(calculationService).calculate(any()); when(adyenTransactionService.createPaymentTransactionFromResultCode(any(), any(), any(), any())).thenReturn(new PaymentTransactionModel()); - doNothing().when(adyenOrderService).updateOrderFromPaymentsResponse(any(), any()); + doNothing().when(adyenOrderService).updatePaymentInfo(any(),any(), any()); doNothing().when(adyenBusinessProcessService).triggerOrderProcessEvent(any(), any()); when(orderModel.getUser()).thenReturn(userModel); when(cartModel.getUser()).thenReturn(userModel); @@ -791,11 +787,10 @@ public void testHandleRedirectPayloadNotAuthorised() throws Exception { when(orderModel.getEntries()).thenReturn(Collections.emptyList()); when(paymentsDetailsResponse.getMerchantReference()).thenReturn(ORDER_CODE); - HashMap details = new HashMap<>(); - PaymentsDetailsResponse paymentsDetailsResponseReturned = adyenCheckoutFacade.handleRedirectPayload(details); + PaymentDetailsResponse paymentsDetailsResponseReturned = adyenCheckoutFacade.handleRedirectPayload(paymentCompletionDetails); assertEquals(paymentsDetailsResponseReturned, paymentsDetailsResponse); - assertEquals(PaymentsResponse.ResultCodeEnum.REFUSED, paymentsDetailsResponseReturned.getResultCode()); - verify(adyenPaymentService).getPaymentDetailsFromPayload(details); + assertEquals(PaymentResponse.ResultCodeEnum.REFUSED, paymentsDetailsResponseReturned.getResultCode()); + verify(adyenCheckoutApiService).getPaymentDetailsFromPayload(details); verify(cartFactory).createCart(); verify(cartService).setSessionCart(cartModel); verify(calculationService).calculate(cartModel); diff --git a/adyenv6core/testsrc/com/adyen/v6/factory/AdyenRequestFactoryTest.java b/adyenv6core/testsrc/com/adyen/v6/factory/AdyenRequestFactoryTest.java index d3ecb0cdf..0ff0c3628 100644 --- a/adyenv6core/testsrc/com/adyen/v6/factory/AdyenRequestFactoryTest.java +++ b/adyenv6core/testsrc/com/adyen/v6/factory/AdyenRequestFactoryTest.java @@ -20,19 +20,22 @@ */ package com.adyen.v6.factory; -import com.adyen.model.Name; -import com.adyen.model.PaymentRequest; +import com.adyen.model.checkout.CardDetails; +import com.adyen.model.checkout.CheckoutPaymentMethod; +import com.adyen.model.checkout.GenericIssuerPaymentMethodDetails; +import com.adyen.model.checkout.PayPalDetails; import com.adyen.model.checkout.PaymentDetails; -import com.adyen.model.checkout.PaymentsRequest; -import com.adyen.model.checkout.details.CardDetails; -import com.adyen.model.checkout.details.GenericIssuerPaymentMethodDetails; -import com.adyen.model.nexo.*; +import com.adyen.model.checkout.PaymentRequest; +import com.adyen.model.nexo.AmountsReq; +import com.adyen.model.nexo.MessageCategoryType; +import com.adyen.model.nexo.MessageHeader; +import com.adyen.model.nexo.SaleData; +import com.adyen.model.nexo.TransactionStatusRequest; import com.adyen.model.recurring.Recurring; import com.adyen.model.terminal.SaleToAcquirerData; import com.adyen.model.terminal.TerminalAPIRequest; import com.adyen.v6.enums.RecurringContractMode; import com.adyen.v6.model.RequestInfo; -import com.adyen.v6.paymentmethoddetails.executors.AdyenPaymentMethodDetailsBuilderExecutor; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.commercefacades.order.data.CCPaymentInfoData; import de.hybris.platform.commercefacades.order.data.CartData; @@ -51,13 +54,17 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; -import de.hybris.platform.util.TaxValue; import java.math.BigDecimal; -import java.util.List; -import static com.adyen.v6.constants.Adyenv6coreConstants.*; -import static org.junit.Assert.*; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_CC; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_EPS; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_ONECLICK; +import static com.adyen.v6.constants.Adyenv6coreConstants.PAYMENT_METHOD_PAYPAL; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -100,8 +107,6 @@ public class AdyenRequestFactoryTest { @Mock private ConfigurationService configurationServiceMock; - @Mock - private AdyenPaymentMethodDetailsBuilderExecutor adyenPaymentMethodDetailsStrategyExecutor; @Mock private CartData cartDataMock; @@ -135,7 +140,7 @@ public class AdyenRequestFactoryTest { @Before public void setUp() { - adyenRequestFactory = new AdyenRequestFactory(configurationServiceMock, adyenPaymentMethodDetailsStrategyExecutor); + adyenRequestFactory = new AdyenRequestFactory(configurationServiceMock); PriceData priceData = new PriceData(); priceData.setValue(new BigDecimal(AMOUNT)); priceData.setCurrencyIso(CURRENCY); @@ -174,9 +179,9 @@ public void setUp() { public void testAuthorise() { when(cartDataMock.getAdyenPaymentMethod()).thenReturn(PAYMENT_METHOD_CC); - PaymentsRequest paymentsRequest; + PaymentRequest paymentsRequest; - paymentsRequest = adyenRequestFactory.createPaymentsRequest(MERCHANT_ACCOUNT, cartDataMock, new RequestInfo(requestMock), customerModelMock, RecurringContractMode.RECURRING, false); + paymentsRequest = adyenRequestFactory.createPaymentsRequest(MERCHANT_ACCOUNT, cartDataMock, new CheckoutPaymentMethod(), new RequestInfo(requestMock), customerModelMock, RecurringContractMode.RECURRING, false); //use delivery/billing address from cart assertEquals(DELIVERY_TOWN, paymentsRequest.getDeliveryAddress().getCity()); @@ -195,34 +200,34 @@ public void testAuthorise() { testRecurringOption(null, null); testRecurringOption(RecurringContractMode.NONE, null); testRecurringOption(RecurringContractMode.ONECLICK, null); - //testRecurringOption(RecurringContractMode.RECURRING, Recurring.ContractEnum.RECURRING); - //testRecurringOption(RecurringContractMode.RECURRING, Recurring.ContractEnum.RECURRING); + testRecurringOption(RecurringContractMode.RECURRING, Recurring.ContractEnum.RECURRING); + testRecurringOption(RecurringContractMode.RECURRING, Recurring.ContractEnum.RECURRING); //Test recurring contract when remember-me is set when(cartDataMock.getAdyenRememberTheseDetails()).thenReturn(true); testRecurringOption(null, null); testRecurringOption(RecurringContractMode.NONE, null); - //testRecurringOption(RecurringContractMode.ONECLICK, Recurring.ContractEnum.ONECLICK); - //testRecurringOption(RecurringContractMode.RECURRING, Recurring.ContractEnum.RECURRING); - //testRecurringOption(RecurringContractMode.ONECLICK_RECURRING, Recurring.ContractEnum.ONECLICK_RECURRING); + testRecurringOption(RecurringContractMode.ONECLICK, Recurring.ContractEnum.ONECLICK); + testRecurringOption(RecurringContractMode.RECURRING, Recurring.ContractEnum.RECURRING); + testRecurringOption(RecurringContractMode.ONECLICK_RECURRING, Recurring.ContractEnum.ONECLICK); //When a store card is selected, send the reference and include the recurring contract when(cartDataMock.getAdyenPaymentMethod()).thenReturn(PAYMENT_METHOD_ONECLICK); when(cartDataMock.getAdyenSelectedReference()).thenReturn(RECURRING_REFERENCE); when(cartDataMock.getAdyenRememberTheseDetails()).thenReturn(false); - paymentsRequest = adyenRequestFactory.createPaymentsRequest(MERCHANT_ACCOUNT, cartDataMock, new RequestInfo(requestMock), customerModelMock, null, false); + paymentsRequest = adyenRequestFactory.createPaymentsRequest(MERCHANT_ACCOUNT, cartDataMock, new CheckoutPaymentMethod(), new RequestInfo(requestMock), customerModelMock, null, false); - final CardDetails paymentMethodDetails = (CardDetails) paymentsRequest.getPaymentMethod(); + final CardDetails paymentMethodDetails = paymentsRequest.getPaymentMethod().getCardDetails(); assertEquals(RECURRING_REFERENCE, paymentMethodDetails.getRecurringDetailReference()); } private void testRecurringOption(final RecurringContractMode recurringContractModeSetting, final Recurring.ContractEnum expectedRecurringContractMode) { - PaymentRequest paymentRequest = adyenRequestFactory.createAuthorizationRequest(MERCHANT_ACCOUNT, cartDataMock, requestMock, customerModelMock, recurringContractModeSetting); + PaymentRequest paymentRequest = adyenRequestFactory.createPaymentsRequest(MERCHANT_ACCOUNT, cartDataMock, new CheckoutPaymentMethod(),new RequestInfo(requestMock), customerModelMock, recurringContractModeSetting, false); if (expectedRecurringContractMode == null) { - assertNull(paymentRequest.getRecurring()); + assertFalse(paymentRequest.getEnableRecurring()); } else { - assertEquals(expectedRecurringContractMode, paymentRequest.getRecurring().getContract()); + assertEquals(expectedRecurringContractMode, paymentRequest.getRecurringProcessingModel()); } //when customer is set, shopperReference and Email should be set as well @@ -234,16 +239,15 @@ private void testRecurringOption(final RecurringContractMode recurringContractMo public void testEpsPaymentRequest() throws Exception { when(cartDataMock.getAdyenPaymentMethod()).thenReturn(PAYMENT_METHOD_EPS); when(cartDataMock.getAdyenReturnUrl()).thenReturn(RETURN_URL); - final GenericIssuerPaymentMethodDetails type = new GenericIssuerPaymentMethodDetails().type(PAYMENT_METHOD_EPS).issuer(ISSUER_ID); + final GenericIssuerPaymentMethodDetails type = new GenericIssuerPaymentMethodDetails().type(GenericIssuerPaymentMethodDetails.TypeEnum.EPS).issuer(ISSUER_ID); when(cartDataMock.getAdyenIssuerId()).thenReturn(ISSUER_ID); - when(adyenPaymentMethodDetailsStrategyExecutor.createPaymentMethodDetails(cartDataMock)).thenReturn(type); - final PaymentsRequest paymentsRequest = adyenRequestFactory.createPaymentsRequest(MERCHANT_ACCOUNT, cartDataMock, new RequestInfo(requestMock), customerModelMock, null, false); + final PaymentRequest paymentsRequest = adyenRequestFactory.createPaymentsRequest(MERCHANT_ACCOUNT, cartDataMock, new CheckoutPaymentMethod(),new RequestInfo(requestMock), customerModelMock, null, false); assertNotNull(paymentsRequest); assertEquals(RETURN_URL, paymentsRequest.getReturnUrl()); assertNotNull(paymentsRequest.getPaymentMethod()); - assertEquals(PAYMENT_METHOD_EPS, paymentsRequest.getPaymentMethod().getType()); + //assertEquals(PAYMENT_METHOD_EPS, paymentsRequest.getPaymentMethod().getType()); assertEquals(ISSUER_ID, type.getIssuer()); } @@ -254,19 +258,18 @@ public void testPaypalPaymentRequest() throws Exception { when(deliveryAddressMock.getFirstName()).thenReturn(FIRST_NAME); when(deliveryAddressMock.getLastName()).thenReturn(LAST_NAME); when(deliveryAddressMock.getTitleCode()).thenReturn(TITLE_CODE); - final GenericIssuerPaymentMethodDetails type = new GenericIssuerPaymentMethodDetails().type(PAYMENT_METHOD_PAYPAL).issuer(ISSUER_ID); - when(adyenPaymentMethodDetailsStrategyExecutor.createPaymentMethodDetails(cartDataMock)).thenReturn(type); - final PaymentsRequest paymentsRequest = adyenRequestFactory.createPaymentsRequest(MERCHANT_ACCOUNT, cartDataMock, new RequestInfo(requestMock), customerModelMock, null, false); + + final PaymentRequest paymentsRequest = adyenRequestFactory.createPaymentsRequest(MERCHANT_ACCOUNT, cartDataMock,new CheckoutPaymentMethod(), new RequestInfo(requestMock), customerModelMock, null, false); assertNotNull(paymentsRequest); assertEquals(RETURN_URL, paymentsRequest.getReturnUrl()); assertNotNull(paymentsRequest.getPaymentMethod()); - assertEquals(PAYMENT_METHOD_PAYPAL, paymentsRequest.getPaymentMethod().getType()); + assertTrue(paymentsRequest.getPaymentMethod().getActualInstance() instanceof PayPalDetails); assertNotNull(paymentsRequest.getShopperName()); assertEquals(FIRST_NAME, paymentsRequest.getShopperName().getFirstName()); assertEquals(LAST_NAME, paymentsRequest.getShopperName().getLastName()); - assertEquals(Name.GenderEnum.MALE, paymentsRequest.getShopperName().getGender()); + } @Test @@ -285,7 +288,7 @@ public void testTerminalApiPaymentRequestWithRecurring() throws Exception { assertNotNull(terminalApiRequest.getSaleToPOIRequest().getPaymentRequest().getSaleData().getSaleToAcquirerData()); SaleToAcquirerData saleToAcquirerData = terminalApiRequest.getSaleToPOIRequest().getPaymentRequest().getSaleData().getSaleToAcquirerData(); - assertTrue(saleToAcquirerData.getRecurringContract().equals(Recurring.ContractEnum.ONECLICK_RECURRING.toString())); + assertTrue(saleToAcquirerData.getRecurringContract().equals(Recurring.ContractEnum.RECURRING.toString())); assertTrue(saleToAcquirerData.getShopperEmail().equals(CUSTOMER_EMAIL)); assertTrue(saleToAcquirerData.getShopperReference().equals(CUSTOMER_ID)); } @@ -347,48 +350,4 @@ public void testTerminalApiStatusRequest() throws Exception { assertEquals(SERVICE_ID, transactionStatusRequest.getMessageReference().getServiceID()); } - @Test - public void shouldNotCrashWhenTotalValueCantBeDividedByQuantity() { - - PriceData priceData = createPriceData("100.00"); - orderEntryData = new OrderEntryData(); - - productData = new ProductData(); - productData.setCode("CODE"); - productData.setName("NAME"); - productData.setMultidimensional(Boolean.FALSE); - - orderEntryData.setProduct(productData); - orderEntryData.setEntryNumber(0); - orderEntryData.setQuantity(3L); - orderEntryData.setBasePrice(createPriceData("45.00")); - orderEntryData.setTaxValues(List.of( new TaxValue("VAT FULL", 19.0, false, null) )); - - when(cartDataMock.getTotalPriceWithTax()).thenReturn(priceData); - when(cartDataMock.getCode()).thenReturn(CART_CODE); - when(cartDataMock.getDeliveryAddress()).thenReturn(deliveryAddressMock); - when(cartDataMock.getPaymentInfo()).thenReturn(paymentInfoMock); - when(cartDataMock.getStore()).thenReturn(STORE_NAME); - when(cartDataMock.getAdyenTerminalId()).thenReturn(TERMINAL_ID); - when(cartDataMock.getAdyenPaymentMethod()).thenReturn(PAYMENT_METHOD_KLARNA); - when(cartDataMock.getEntries()).thenReturn(List.of(orderEntryData)); - - - PaymentRequest paymentRequest = adyenRequestFactory.createAuthorizationRequest(MERCHANT_ACCOUNT, - cartDataMock, - requestMock, - customerModelMock, RecurringContractMode.NONE); - - - - assertEquals(10000L, (long) paymentRequest.getAmount().getValue()); - } - - private static PriceData createPriceData(String value) { - PriceData priceData = new PriceData(); - priceData.setValue(new BigDecimal(value)); - priceData.setCurrencyIso(CURRENCY); - return priceData; - } - } diff --git a/adyenv6core/testsrc/com/adyen/v6/service/AdyenTransactionServiceTest.java b/adyenv6core/testsrc/com/adyen/v6/service/AdyenTransactionServiceTest.java index 40c5b126f..1f0bd6a60 100644 --- a/adyenv6core/testsrc/com/adyen/v6/service/AdyenTransactionServiceTest.java +++ b/adyenv6core/testsrc/com/adyen/v6/service/AdyenTransactionServiceTest.java @@ -20,7 +20,7 @@ */ package com.adyen.v6.service; -import com.adyen.model.checkout.PaymentsResponse; +import com.adyen.model.checkout.PaymentDetailsResponse; import com.adyen.v6.factory.AdyenPaymentServiceFactory; import com.adyen.v6.model.AdyenNotificationModel; import de.hybris.bootstrap.annotations.UnitTest; @@ -72,7 +72,7 @@ public class AdyenTransactionServiceTest { @Mock private CommonI18NService commonI18NServiceMock; @Mock - private AdyenPaymentService adyenPaymentServiceMock; + private AdyenCheckoutApiService adyenCheckoutApiServiceMock; @Mock private AdyenPaymentServiceFactory adyenPaymentServiceFactoryMock; @Mock @@ -89,8 +89,8 @@ public class AdyenTransactionServiceTest { public void setUp() { when(modelServiceMock.create(PaymentTransactionEntryModel.class)).thenReturn(new PaymentTransactionEntryModel()); when(baseStoreServiceMock.getCurrentBaseStore()).thenReturn(baseStoreModelMock); - when(adyenPaymentServiceFactoryMock.createFromBaseStore(baseStoreModelMock)).thenReturn(adyenPaymentServiceMock); - when(adyenTransactionService.getAdyenPaymentService()).thenReturn(adyenPaymentServiceMock); + when(adyenPaymentServiceFactoryMock.createAdyenCheckoutApiService(baseStoreModelMock)).thenReturn(adyenCheckoutApiServiceMock); + when(adyenTransactionService.getAdyenPaymentService()).thenReturn(adyenCheckoutApiServiceMock); when(paymentTransactionModel.getEntries()).thenReturn(new ArrayList<>()); when(modelServiceMock.create(PaymentTransactionModel.class)).thenReturn(paymentTransactionModel); @@ -135,7 +135,7 @@ public void testCreateCapturedTransactionFromNotification() { @Test public void testAuthorizeOrderModel() { OrderModel orderModel = createDummyOrderModel(); - when(adyenPaymentServiceMock.calculateAmountWithTaxes(orderModel)).thenReturn(new BigDecimal(10)); + when(adyenCheckoutApiServiceMock.calculateAmountWithTaxes(orderModel)).thenReturn(new BigDecimal(10)); PaymentTransactionModel paymentTransactionModel = adyenTransactionService.authorizeOrderModel(orderModel, MERCHANT_REFERENCE, PSP_REFERENCE); @@ -166,7 +166,7 @@ public void testCreatePaymentTransactionFromAuthorisedResultCode() { when(paymentTransactionModel.getEntries()).thenReturn(Collections.singletonList(paymentTransactionEntryModel)); when(paymentTransactionEntryModel.getTransactionStatus()).thenReturn(ACCEPTED.name()); - PaymentTransactionModel paymentTransactionModel = adyenTransactionService.createPaymentTransactionFromResultCode(orderModel, MERCHANT_REFERENCE, PSP_REFERENCE, PaymentsResponse.ResultCodeEnum.AUTHORISED); + PaymentTransactionModel paymentTransactionModel = adyenTransactionService.createPaymentTransactionFromResultCode(orderModel, MERCHANT_REFERENCE, PSP_REFERENCE, PaymentDetailsResponse.ResultCodeEnum.AUTHORISED); //Verify that the payment transaction is saved verify(modelServiceMock).save(paymentTransactionModel); @@ -182,7 +182,7 @@ public void testCreatePaymentTransactionFromRefusedResultCode() { when(paymentTransactionModel.getEntries()).thenReturn(Collections.singletonList(paymentTransactionEntryModel)); when(paymentTransactionEntryModel.getTransactionStatus()).thenReturn(REJECTED.name()); - PaymentTransactionModel paymentTransactionModel = adyenTransactionService.createPaymentTransactionFromResultCode(orderModel, MERCHANT_REFERENCE, PSP_REFERENCE, PaymentsResponse.ResultCodeEnum.REFUSED); + PaymentTransactionModel paymentTransactionModel = adyenTransactionService.createPaymentTransactionFromResultCode(orderModel, MERCHANT_REFERENCE, PSP_REFERENCE, PaymentDetailsResponse.ResultCodeEnum.REFUSED); //Verify that the payment transaction is saved verify(modelServiceMock).save(paymentTransactionModel); diff --git a/adyenv6subscription/resources/adyenv6subscription-spring.xml b/adyenv6subscription/resources/adyenv6subscription-spring.xml index 84dc2072d..114dda3f8 100644 --- a/adyenv6subscription/resources/adyenv6subscription-spring.xml +++ b/adyenv6subscription/resources/adyenv6subscription-spring.xml @@ -4,17 +4,15 @@ --> + + http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> - - diff --git a/adyenv6subscription/src/com/adyen/v6/factory/SubscriptionAdyenPaymentServiceFactory.java b/adyenv6subscription/src/com/adyen/v6/factory/SubscriptionAdyenPaymentServiceFactory.java index 6203ab845..bc3557686 100644 --- a/adyenv6subscription/src/com/adyen/v6/factory/SubscriptionAdyenPaymentServiceFactory.java +++ b/adyenv6subscription/src/com/adyen/v6/factory/SubscriptionAdyenPaymentServiceFactory.java @@ -2,20 +2,13 @@ import com.adyen.v6.service.AdyenCheckoutApiService; import com.adyen.v6.service.impl.DefaultSubscriptionAdyenCheckoutApiService; -import de.hybris.platform.commercefacades.order.CartFacade; import de.hybris.platform.store.BaseStoreModel; -import de.hybris.platform.store.services.BaseStoreService; public class SubscriptionAdyenPaymentServiceFactory extends AdyenPaymentServiceFactory { - private final CartFacade cartFacade; - private final BaseStoreService baseStoreService; - public SubscriptionAdyenPaymentServiceFactory(SubscriptionPaymentRequestFactory adyenRequestFactory, - CartFacade cartFacade, BaseStoreService baseStoreService) { + public SubscriptionAdyenPaymentServiceFactory(SubscriptionPaymentRequestFactory adyenRequestFactory) { super(adyenRequestFactory); - this.cartFacade = cartFacade; - this.baseStoreService = baseStoreService; } @Override @@ -24,8 +17,6 @@ public AdyenCheckoutApiService createAdyenCheckoutApiService(final BaseStoreMode final DefaultSubscriptionAdyenCheckoutApiService adyenPaymentService = new DefaultSubscriptionAdyenCheckoutApiService( baseStoreModel); adyenPaymentService.setAdyenRequestFactory(getAdyenRequestFactory()); - adyenPaymentService.setCartFacade(cartFacade); - adyenPaymentService.setBaseStoreService(baseStoreService); return adyenPaymentService; } } diff --git a/adyenv6subscription/src/com/adyen/v6/service/impl/DefaultSubscriptionAdyenCheckoutApiService.java b/adyenv6subscription/src/com/adyen/v6/service/impl/DefaultSubscriptionAdyenCheckoutApiService.java index 7fd5fd370..a0b9e4db2 100644 --- a/adyenv6subscription/src/com/adyen/v6/service/impl/DefaultSubscriptionAdyenCheckoutApiService.java +++ b/adyenv6subscription/src/com/adyen/v6/service/impl/DefaultSubscriptionAdyenCheckoutApiService.java @@ -5,11 +5,9 @@ import com.adyen.service.checkout.PaymentsApi; import com.adyen.v6.model.RequestInfo; import com.adyen.v6.service.DefaultAdyenCheckoutApiService; -import de.hybris.platform.commercefacades.order.CartFacade; import de.hybris.platform.commercefacades.order.data.CartData; import de.hybris.platform.core.model.user.CustomerModel; import de.hybris.platform.store.BaseStoreModel; -import de.hybris.platform.store.services.BaseStoreService; import org.apache.commons.lang3.BooleanUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -20,8 +18,6 @@ public class DefaultSubscriptionAdyenCheckoutApiService extends DefaultAdyenCheckoutApiService { protected static final Logger LOG = LogManager.getLogger(DefaultSubscriptionAdyenCheckoutApiService.class); - private CartFacade cartFacade; - private BaseStoreService baseStoreService; public DefaultSubscriptionAdyenCheckoutApiService(final BaseStoreModel baseStore) { super(baseStore); @@ -52,19 +48,4 @@ public PaymentResponse authorisePayment(final CartData cartData, final RequestIn return paymentsResponse; } - public CartFacade getCartFacade() { - return cartFacade; - } - - public void setCartFacade(final CartFacade cartFacade) { - this.cartFacade = cartFacade; - } - - public BaseStoreService getBaseStoreService() { - return baseStoreService; - } - - public void setBaseStoreService(final BaseStoreService baseStoreService) { - this.baseStoreService = baseStoreService; - } }