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/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/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..40797dfca 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"> + + 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 4e068b78f..bc3557686 100644 --- a/adyenv6subscription/src/com/adyen/v6/factory/SubscriptionAdyenPaymentServiceFactory.java +++ b/adyenv6subscription/src/com/adyen/v6/factory/SubscriptionAdyenPaymentServiceFactory.java @@ -1,31 +1,22 @@ package com.adyen.v6.factory; -import com.adyen.v6.service.AdyenPaymentService; -import com.adyen.v6.service.impl.DefaultSubscriptionAdyenPaymentService; -import de.hybris.platform.commercefacades.order.CartFacade; +import com.adyen.v6.service.AdyenCheckoutApiService; +import com.adyen.v6.service.impl.DefaultSubscriptionAdyenCheckoutApiService; 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 - 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); - adyenPaymentService.setBaseStoreService(baseStoreService); return adyenPaymentService; } } diff --git a/adyenv6subscription/src/com/adyen/v6/factory/SubscriptionPaymentRequestFactory.java b/adyenv6subscription/src/com/adyen/v6/factory/SubscriptionPaymentRequestFactory.java index 6653b44df..3acb840f2 100644 --- a/adyenv6subscription/src/com/adyen/v6/factory/SubscriptionPaymentRequestFactory.java +++ b/adyenv6subscription/src/com/adyen/v6/factory/SubscriptionPaymentRequestFactory.java @@ -1,25 +1,18 @@ 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; -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 { @@ -28,14 +21,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,99 +41,23 @@ 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, - 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 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(setAddressData(deliveryAddress)); - } - - if (billingAddress != null) - { - paymentsRequest.setBillingAddress(setAddressData(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())) { 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..a0b9e4db2 --- /dev/null +++ b/adyenv6subscription/src/com/adyen/v6/service/impl/DefaultSubscriptionAdyenCheckoutApiService.java @@ -0,0 +1,51 @@ +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.data.CartData; +import de.hybris.platform.core.model.user.CustomerModel; +import de.hybris.platform.store.BaseStoreModel; +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); + + 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; + } + +} 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()); } }