diff --git a/CHECKOUTCO-SAPCommerceConnector2211v3.pdf b/CHECKOUTCOM-SAPCommerceConnector2211v4.pdf similarity index 91% rename from CHECKOUTCO-SAPCommerceConnector2211v3.pdf rename to CHECKOUTCOM-SAPCommerceConnector2211v4.pdf index 58e4763..a6a9fdf 100644 Binary files a/CHECKOUTCO-SAPCommerceConnector2211v3.pdf and b/CHECKOUTCOM-SAPCommerceConnector2211v4.pdf differ diff --git a/README.md b/README.md index 03cad5a..6071bf8 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ The Connector for SAP Commerce Cloud (formerly Hybris) enables customers to impl This release is compatible with: - SAP Commerce: B2C Accelerator of SAP Commerce Cloud 2211. It is advised to install the latest patch version of SAP Commerce Cloud. - SAP Commerce REST API (OCC). -- Spartacus 4.2.7 +- Spartacus 4.2. - Java 17. - Checkout.com Java SDK version 3. @@ -79,7 +79,11 @@ Follow [this guideline](https://help.sap.com/docs/SAP_COMMERCE_CLOUD_PUBLIC_CLOU Spartacus is a lean, Angular-based JavaScript storefront for SAP Commerce Cloud. Spartacus talks to SAP Commerce Cloud exclusively through the Commerce REST API (OCC). The Connector for SAP Commerce Cloud supports the Spartacus frontend. Check out details and release notes in the Checkout.com repository for Spartacus. # Release Notes -- iDeal updated - BIC removed from the request +## Features: +- New Klarna payment method implemented +## Breaking changes: +- ABC decommissioned +- SOFORT payment method not longer supported # Support Contact your Checkout.com team if you have any question, technical problem or feature request for the SAP Commerce Cloud Connector. diff --git a/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/src/com/checkout/hybris/addon/converters/populators/CheckoutComKlarnaPaymentInfoDataReversePopulator.java b/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/src/com/checkout/hybris/addon/converters/populators/CheckoutComKlarnaPaymentInfoDataReversePopulator.java index 8d24237..27ecc19 100644 --- a/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/src/com/checkout/hybris/addon/converters/populators/CheckoutComKlarnaPaymentInfoDataReversePopulator.java +++ b/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/src/com/checkout/hybris/addon/converters/populators/CheckoutComKlarnaPaymentInfoDataReversePopulator.java @@ -15,6 +15,7 @@ public class CheckoutComKlarnaPaymentInfoDataReversePopulator implements Populator { protected static final String AUTHORIZATION_TOKEN_KEY = "authorizationToken"; + protected static final String PAYMENT_CONTEXT_ID = "paymentContextId"; /** * {@inheritDoc} @@ -27,6 +28,7 @@ public void populate(final PaymentDataForm source, final KlarnaPaymentInfoData t final Map formAttributes = source.getFormAttributes(); target.setAuthorizationToken((String) formAttributes.get(AUTHORIZATION_TOKEN_KEY)); + target.setPaymentContextId((String) formAttributes.get(PAYMENT_CONTEXT_ID)); target.setType(CheckoutComPaymentType.KLARNA.name()); } } diff --git a/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/src/com/checkout/hybris/addon/interceptors/beforeview/CheckoutComIsMerchantABCBeforeViewHandler.java b/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/src/com/checkout/hybris/addon/interceptors/beforeview/CheckoutComIsMerchantABCBeforeViewHandler.java index 0592ff9..46ca392 100644 --- a/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/src/com/checkout/hybris/addon/interceptors/beforeview/CheckoutComIsMerchantABCBeforeViewHandler.java +++ b/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/src/com/checkout/hybris/addon/interceptors/beforeview/CheckoutComIsMerchantABCBeforeViewHandler.java @@ -13,14 +13,13 @@ public class CheckoutComIsMerchantABCBeforeViewHandler implements BeforeViewHand private static final Logger LOG = Logger.getLogger(CheckoutComIsMerchantABCBeforeViewHandler.class); protected final CheckoutComMerchantConfigurationService checkoutComMerchantConfigurationService; - public CheckoutComIsMerchantABCBeforeViewHandler(CheckoutComMerchantConfigurationService checkoutComMerchantConfigurationService) { + public CheckoutComIsMerchantABCBeforeViewHandler(final CheckoutComMerchantConfigurationService checkoutComMerchantConfigurationService) { this.checkoutComMerchantConfigurationService = checkoutComMerchantConfigurationService; } @Override - public void beforeView(HttpServletRequest request, HttpServletResponse response, ModelAndView modelAndView) throws Exception { - Boolean isMerchantABC = !checkoutComMerchantConfigurationService.isNasUsed(); - modelAndView.addObject("isABC", isMerchantABC); - LOG.debug("The configuration of this merchant is " + (Boolean.TRUE.equals(isMerchantABC) ? "ABC" : "NAS")); + public void beforeView(final HttpServletRequest request, final HttpServletResponse response, final ModelAndView modelAndView) { + modelAndView.addObject("isABC", Boolean.FALSE); + LOG.debug("The configuration of this merchant is NAS"); } } diff --git a/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/testsrc/com/checkout/hybris/addon/converters/populators/CheckoutComKlarnaPaymentInfoDataReversePopulatorTest.java b/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/testsrc/com/checkout/hybris/addon/converters/populators/CheckoutComKlarnaPaymentInfoDataReversePopulatorTest.java index a6c9ad3..c2e3cec 100644 --- a/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/testsrc/com/checkout/hybris/addon/converters/populators/CheckoutComKlarnaPaymentInfoDataReversePopulatorTest.java +++ b/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/testsrc/com/checkout/hybris/addon/converters/populators/CheckoutComKlarnaPaymentInfoDataReversePopulatorTest.java @@ -3,31 +3,35 @@ import com.checkout.hybris.addon.forms.PaymentDataForm; import com.checkout.hybris.core.payment.enums.CheckoutComPaymentType; import com.checkout.hybris.facades.beans.KlarnaPaymentInfoData; -import com.google.common.collect.ImmutableMap; import de.hybris.bootstrap.annotations.UnitTest; import org.junit.Test; +import java.util.Map; + import static com.checkout.hybris.addon.converters.populators.CheckoutComKlarnaPaymentInfoDataReversePopulator.AUTHORIZATION_TOKEN_KEY; +import static com.checkout.hybris.addon.converters.populators.CheckoutComKlarnaPaymentInfoDataReversePopulator.PAYMENT_CONTEXT_ID; import static org.junit.Assert.assertEquals; @UnitTest public class CheckoutComKlarnaPaymentInfoDataReversePopulatorTest { private static final String KLARNA_AUTH_TOKEN_VALUE = "12345678901_abdajkdjal"; + private static final String KLARNA_PAYMENT_CONTEXT_VALUE = "12345678901_qwrqwrq"; private CheckoutComKlarnaPaymentInfoDataReversePopulator testObj = new CheckoutComKlarnaPaymentInfoDataReversePopulator(); - private PaymentDataForm source = new PaymentDataForm(); - private KlarnaPaymentInfoData target = new KlarnaPaymentInfoData(); + private final PaymentDataForm source = new PaymentDataForm(); + private final KlarnaPaymentInfoData target = new KlarnaPaymentInfoData(); @Test public void populate_ShouldPopulateTargetCorrectly() { - source.setFormAttributes(ImmutableMap.of(AUTHORIZATION_TOKEN_KEY, KLARNA_AUTH_TOKEN_VALUE)); + source.setFormAttributes(Map.of(AUTHORIZATION_TOKEN_KEY, KLARNA_AUTH_TOKEN_VALUE, PAYMENT_CONTEXT_ID, KLARNA_PAYMENT_CONTEXT_VALUE)); testObj.populate(source, target); assertEquals(CheckoutComPaymentType.KLARNA.name(), target.getType()); assertEquals(KLARNA_AUTH_TOKEN_VALUE, target.getAuthorizationToken()); + assertEquals(KLARNA_PAYMENT_CONTEXT_VALUE, target.getPaymentContextId()); } @Test(expected = IllegalArgumentException.class) diff --git a/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/testsrc/com/checkout/hybris/addon/interceptors/beforeview/CheckoutComIsMerchantABCBeforeViewHandlerTest.java b/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/testsrc/com/checkout/hybris/addon/interceptors/beforeview/CheckoutComIsMerchantABCBeforeViewHandlerTest.java index cbac1c1..cdbf38b 100644 --- a/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/testsrc/com/checkout/hybris/addon/interceptors/beforeview/CheckoutComIsMerchantABCBeforeViewHandlerTest.java +++ b/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/testsrc/com/checkout/hybris/addon/interceptors/beforeview/CheckoutComIsMerchantABCBeforeViewHandlerTest.java @@ -14,13 +14,10 @@ import javax.servlet.http.HttpServletResponse; import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; @UnitTest @RunWith(MockitoJUnitRunner.class) public class CheckoutComIsMerchantABCBeforeViewHandlerTest { - private static final Boolean MERCHANT_IS_ABC = Boolean.FALSE; - private static final Boolean MERCHANT_IS_NAS = Boolean.TRUE; private static final String isABCKey = "isABC"; ModelAndView modelAndView; @@ -43,16 +40,9 @@ public void setUp() { @Test public void beforeView_ShouldReturnFalse_IfMerchantIsNAS() throws Exception { - when(checkoutComMerchantConfigurationService.isNasUsed()).thenReturn(MERCHANT_IS_NAS); testObj.beforeView(request, response, modelAndView); assertEquals(Boolean.FALSE, modelAndView.getModel().get(isABCKey)); } - @Test - public void beforeView_ShouldReturnTrue_IfMerchantIsNAS() throws Exception { - when(checkoutComMerchantConfigurationService.isNasUsed()).thenReturn(MERCHANT_IS_ABC); - testObj.beforeView(request, response, modelAndView); - assertEquals(Boolean.TRUE, modelAndView.getModel().get(isABCKey)); - } } diff --git a/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/fragments/checkout/checkoutCom_KLARNA_PaymentForm.jsp b/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/fragments/checkout/checkoutCom_KLARNA_PaymentForm.jsp index c8cb8d8..c157088 100644 --- a/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/fragments/checkout/checkoutCom_KLARNA_PaymentForm.jsp +++ b/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/webroot/WEB-INF/views/responsive/fragments/checkout/checkoutCom_KLARNA_PaymentForm.jsp @@ -21,6 +21,7 @@ method="POST" action="${submitPaymentDataUrl}"> + @@ -32,19 +33,10 @@ - let paymentMethodCategoryList = [ - - '${paymentMethodCategory}' - - , - - - ]; - window.klarnaSettings = { klarnaInstanceId: '${klarnaClientToken.instanceId}', clientToken: '${klarnaClientToken.clientToken}', - paymentMethodCategories: paymentMethodCategoryList, + paymentContextId: '${klarnaClientToken.paymentContext}', backButton: '', paymentMethod: '${paymentMethod}', billingAddress: { diff --git a/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/webroot/_ui/responsive/common/js/klarna.js b/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/webroot/_ui/responsive/common/js/klarna.js index 8345fb1..dd72c88 100644 --- a/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/webroot/_ui/responsive/common/js/klarna.js +++ b/hybris/bin/modules/checkoutcom/checkoutaddon/acceleratoraddon/web/webroot/_ui/responsive/common/js/klarna.js @@ -30,7 +30,6 @@ ACC.klarna = { try { Klarna.Payments.load({ container: "#klarnaContainer", - payment_method_categories: ACC.klarna.paymentMethodCategories, instance_id: ACC.klarna.klarnaInstanceId }, // data @@ -111,6 +110,7 @@ ACC.klarna = { if (response.approved === true && response.show_form === true) { console.log(response.authorization_token); $('#authorizationToken').val(response.authorization_token); + $('#paymentContextId').val(ACC.klarna.paymentContextId); $('#checkoutComPaymentTokenForm').attr('action', ACC.config.encodedContextPath + '/checkout/multi/checkout-com/payment/submit-payment-data'); $('#checkoutComPaymentTokenForm').submit(); resolve(); diff --git a/hybris/bin/modules/checkoutcom/checkoutaddon/project.properties b/hybris/bin/modules/checkoutcom/checkoutaddon/project.properties index aeaefe4..5468e47 100644 --- a/hybris/bin/modules/checkoutcom/checkoutaddon/project.properties +++ b/hybris/bin/modules/checkoutcom/checkoutaddon/project.properties @@ -1,4 +1,4 @@ -#Tue, 28 May 2024 13:17:07 +0000 +#Tue, 18 Jun 2024 10:08:08 +0000 # Specifies the location of the spring context file added automatically to the global platform application context. checkoutaddon.application-context=checkoutaddon-spring.xml diff --git a/hybris/bin/modules/checkoutcom/checkoutaddon/resources/checkoutaddon.build.number b/hybris/bin/modules/checkoutcom/checkoutaddon/resources/checkoutaddon.build.number index b465158..99ef18b 100644 --- a/hybris/bin/modules/checkoutcom/checkoutaddon/resources/checkoutaddon.build.number +++ b/hybris/bin/modules/checkoutcom/checkoutaddon/resources/checkoutaddon.build.number @@ -1,11 +1,11 @@ #Ant properties -#Tue May 28 13:21:41 GMT 2024 +#Tue Jun 18 10:12:55 GMT 2024 version.api=2211 vendor=hybris group.id=de.hybris.platform name=checkoutaddon description=checkoutaddon -builddate=20240528 1321 +builddate=20240618 1012 releasedate=20240307 1540 version=2211.20 module.name=platform-module diff --git a/hybris/bin/modules/checkoutcom/checkoutbackoffice/resources/checkoutbackoffice-backoffice-config.xml b/hybris/bin/modules/checkoutcom/checkoutbackoffice/resources/checkoutbackoffice-backoffice-config.xml index 1f9402a..ca17e3f 100644 --- a/hybris/bin/modules/checkoutcom/checkoutbackoffice/resources/checkoutbackoffice-backoffice-config.xml +++ b/hybris/bin/modules/checkoutcom/checkoutbackoffice/resources/checkoutbackoffice-backoffice-config.xml @@ -119,17 +119,13 @@ - - - - diff --git a/hybris/bin/modules/checkoutcom/checkoutbackoffice/resources/checkoutbackoffice.build.number b/hybris/bin/modules/checkoutcom/checkoutbackoffice/resources/checkoutbackoffice.build.number index 12bdea8..05f6ab3 100644 --- a/hybris/bin/modules/checkoutcom/checkoutbackoffice/resources/checkoutbackoffice.build.number +++ b/hybris/bin/modules/checkoutcom/checkoutbackoffice/resources/checkoutbackoffice.build.number @@ -1,11 +1,11 @@ #Ant properties -#Tue May 28 13:21:41 GMT 2024 +#Tue Jun 18 10:12:56 GMT 2024 version.api=2211 vendor=hybris group.id=de.hybris.platform name=checkoutbackoffice description=checkoutbackoffice -builddate=20240528 1321 +builddate=20240618 1012 releasedate=20240307 1540 version=2211.20 module.name=platform-module diff --git a/hybris/bin/modules/checkoutcom/checkoutevents/resources/checkoutevents.build.number b/hybris/bin/modules/checkoutcom/checkoutevents/resources/checkoutevents.build.number index 628455d..f6b1584 100644 --- a/hybris/bin/modules/checkoutcom/checkoutevents/resources/checkoutevents.build.number +++ b/hybris/bin/modules/checkoutcom/checkoutevents/resources/checkoutevents.build.number @@ -1,11 +1,11 @@ #Ant properties -#Tue May 28 13:21:42 GMT 2024 +#Tue Jun 18 10:12:56 GMT 2024 version.api=2211 vendor=hybris group.id=de.hybris.platform name=checkoutevents description=checkoutevents -builddate=20240528 1321 +builddate=20240618 1012 releasedate=20240307 1540 version=2211.20 module.name=platform-module diff --git a/hybris/bin/modules/checkoutcom/checkoutevents/src/com/checkout/hybris/events/validators/impl/DefaultCheckoutComRequestEventValidator.java b/hybris/bin/modules/checkoutcom/checkoutevents/src/com/checkout/hybris/events/validators/impl/DefaultCheckoutComRequestEventValidator.java index 6539e2d..c9810d0 100644 --- a/hybris/bin/modules/checkoutcom/checkoutevents/src/com/checkout/hybris/events/validators/impl/DefaultCheckoutComRequestEventValidator.java +++ b/hybris/bin/modules/checkoutcom/checkoutevents/src/com/checkout/hybris/events/validators/impl/DefaultCheckoutComRequestEventValidator.java @@ -18,8 +18,6 @@ import java.lang.reflect.Type; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; -import java.util.Map; -import java.util.Optional; /** * Default implementation of {@link CheckoutComRequestEventValidator} @@ -57,9 +55,7 @@ public boolean isRequestEventValid(final HttpServletRequest request, final Strin LOG.debug("Received event signature: [{}]; ", ckoSignature); LOG.debug("Received event body: [{}]", eventBody); - if (!isNasActive()) { - return !isAbcSignatureKeyActive() || isCkoSignatureValid(ckoSignature, eventBody); - } else if (isNasAuthorizationHeaderActive() && isNasAuthorizationHeaderInvalid(eventAuthorizationHeaderKey)) { + if (isNasAuthorizationHeaderActive() && isNasAuthorizationHeaderInvalid(eventAuthorizationHeaderKey)) { return false; } else { return !isNasSignatureKeyActive() || isCkoSignatureValid(ckoSignature, eventBody); @@ -83,28 +79,17 @@ private String createEventBodyHash(final String eventBody) throws NoSuchAlgorith return new String(convertBytesToHex(bytes)); } - private boolean isNasActive() { - return checkoutComMerchantConfigurationService.isNasUsed(); - } - private boolean isNasAuthorizationHeaderInvalid(final String eventAuthorizationHeaderKey) { final String authorizationKeyForSite = checkoutComMerchantConfigurationService.getAuthorizationKey(); return StringUtils.isNotEmpty(eventAuthorizationHeaderKey) && !eventAuthorizationHeaderKey.equals(authorizationKeyForSite); } private boolean isNasAuthorizationHeaderActive() { - return checkoutComMerchantConfigurationService.isNasUsed() && - checkoutComMerchantConfigurationService.isNasAuthorisationHeaderUsedOnNotificationValidation(); + return checkoutComMerchantConfigurationService.isNasAuthorisationHeaderUsedOnNotificationValidation(); } private boolean isNasSignatureKeyActive() { - return checkoutComMerchantConfigurationService.isNasUsed() && - checkoutComMerchantConfigurationService.isNasSignatureKeyUsedOnNotificationValidation(); - } - - private boolean isAbcSignatureKeyActive() { - return !checkoutComMerchantConfigurationService.isNasUsed() && - checkoutComMerchantConfigurationService.isAbcSignatureKeyUsedOnNotificationValidation(); + return checkoutComMerchantConfigurationService.isNasSignatureKeyUsedOnNotificationValidation(); } private String getSiteIdForTheEvent(final CheckoutComPaymentEventObject eventBody) { @@ -112,10 +97,7 @@ private String getSiteIdForTheEvent(final CheckoutComPaymentEventObject eventBod } private byte[] getSecretPhrase() { - if (checkoutComMerchantConfigurationService.isNasUsed()) { - return checkoutComMerchantConfigurationService.getSignatureKey().getBytes(); - } - return checkoutComMerchantConfigurationService.getSecretKey().getBytes(); + return checkoutComMerchantConfigurationService.getSignatureKey().getBytes(); } private char[] convertBytesToHex(final byte[] bytes) { diff --git a/hybris/bin/modules/checkoutcom/checkoutevents/testsrc/com/checkout/hybris/events/validators/impl/DefaultCheckoutComRequestEventValidatorTest.java b/hybris/bin/modules/checkoutcom/checkoutevents/testsrc/com/checkout/hybris/events/validators/impl/DefaultCheckoutComRequestEventValidatorTest.java index 63a3089..e69b04e 100644 --- a/hybris/bin/modules/checkoutcom/checkoutevents/testsrc/com/checkout/hybris/events/validators/impl/DefaultCheckoutComRequestEventValidatorTest.java +++ b/hybris/bin/modules/checkoutcom/checkoutevents/testsrc/com/checkout/hybris/events/validators/impl/DefaultCheckoutComRequestEventValidatorTest.java @@ -62,46 +62,15 @@ public void setUp() { final ArgumentCaptor objectCaptor = ArgumentCaptor.forClass(CheckoutComPaymentEventObject.class); when(checkoutComPaymentEventServiceMock.getSiteIdForTheEvent(objectCaptor.capture())).thenReturn(SITE_ID); - when(checkoutComMerchantConfigurationServiceMock.getSecretKey()).thenReturn(SECRET_KEY); when(checkoutComMerchantConfigurationServiceMock.getSignatureKey()).thenReturn(SIGNATURE_KEY); when(httpServletRequestMock.getHeader(HEADER_CKO_SIGNATURE)).thenReturn(SECRET_KEY_MESSAGE_HASH); when(httpServletRequestMock.getHeader(HEADER_AUTHORIZATION)).thenReturn(SECRET_KEY); when(baseSiteServiceMock.getBaseSiteForUID(SITE_ID)).thenReturn(baseSiteModelMock); } - @Test - public void isRequestEventValid_whenABCIsActive_andAbcSignatureIsEnabled_andCKOSignatureIsValid_shouldReturnTrue() throws NoSuchAlgorithmException, InvalidKeyException { - when(checkoutComMerchantConfigurationServiceMock.isNasUsed()).thenReturn(false); - when(checkoutComMerchantConfigurationServiceMock.isAbcSignatureKeyUsedOnNotificationValidation()).thenReturn(true); - doReturn(true).when(testObj).isCkoSignatureValid(SECRET_KEY_MESSAGE_HASH, eventBody); - - assertTrue(testObj.isRequestEventValid(httpServletRequestMock, eventBody)); - verify(baseSiteServiceMock).setCurrentBaseSite(baseSiteModelMock, false); - } - - @Test - public void isRequestEventValid_whenABCIsActive_andAbcSignatureIsEnabled_andCKOSignatureIsInvalid_shouldReturnTrue() throws NoSuchAlgorithmException, InvalidKeyException { - when(checkoutComMerchantConfigurationServiceMock.isNasUsed()).thenReturn(false); - when(checkoutComMerchantConfigurationServiceMock.isAbcSignatureKeyUsedOnNotificationValidation()).thenReturn(true); - doReturn(false).when(testObj).isCkoSignatureValid(SECRET_KEY_MESSAGE_HASH, eventBody); - - assertFalse(testObj.isRequestEventValid(httpServletRequestMock, eventBody)); - verify(baseSiteServiceMock).setCurrentBaseSite(baseSiteModelMock, false); - } @Test - public void isRequestEventValid_whenABCIsActive_andAbcSignatureIsDisabled_shouldReturnTrue() throws NoSuchAlgorithmException, InvalidKeyException { - when(checkoutComMerchantConfigurationServiceMock.isNasUsed()).thenReturn(false); - when(checkoutComMerchantConfigurationServiceMock.isAbcSignatureKeyUsedOnNotificationValidation()).thenReturn(false); - - assertTrue(testObj.isRequestEventValid(httpServletRequestMock, eventBody)); - verify(baseSiteServiceMock).setCurrentBaseSite(baseSiteModelMock, false); - verify(testObj, never()).isCkoSignatureValid(SECRET_KEY_MESSAGE_HASH, eventBody); - } - - @Test - public void isRequestEventValid_whenNASIsActive_andAuthorizationHeaderIsActive_andAuthorizationHeaderIsInvalid_shouldReturnFalse() throws NoSuchAlgorithmException, InvalidKeyException { - when(checkoutComMerchantConfigurationServiceMock.isNasUsed()).thenReturn(true); + public void isRequestEventValid_whenAuthorizationHeaderIsActive_andAuthorizationHeaderIsInvalid_shouldReturnFalse() throws NoSuchAlgorithmException, InvalidKeyException { when(checkoutComMerchantConfigurationServiceMock.isNasAuthorisationHeaderUsedOnNotificationValidation()).thenReturn(true); when(checkoutComMerchantConfigurationServiceMock.getAuthorizationKey()).thenReturn(ANOTHER_KEY); @@ -110,8 +79,7 @@ public void isRequestEventValid_whenNASIsActive_andAuthorizationHeaderIsActive_a } @Test - public void isRequestEventValid_whenNASIsActive_andAuthorizationHeaderIsNotActive_andNasSignatureKeyIsInactive_shouldReturnTrue() throws NoSuchAlgorithmException, InvalidKeyException { - when(checkoutComMerchantConfigurationServiceMock.isNasUsed()).thenReturn(true); + public void isRequestEventValid_whenAuthorizationHeaderIsNotActive_andNasSignatureKeyIsInactive_shouldReturnTrue() throws NoSuchAlgorithmException, InvalidKeyException { when(checkoutComMerchantConfigurationServiceMock.isNasSignatureKeyUsedOnNotificationValidation()).thenReturn(false); assertTrue(testObj.isRequestEventValid(httpServletRequestMock, eventBody)); @@ -119,8 +87,7 @@ public void isRequestEventValid_whenNASIsActive_andAuthorizationHeaderIsNotActiv } @Test - public void isRequestEventValid_whenNASIsActive_andAuthorizationHeaderIsNotActive_andNasSignatureKeyIsActive_andCKOSignatureIsValid_shouldReturnTrue() throws NoSuchAlgorithmException, InvalidKeyException { - when(checkoutComMerchantConfigurationServiceMock.isNasUsed()).thenReturn(true); + public void isRequestEventValid_whenAuthorizationHeaderIsNotActive_andNasSignatureKeyIsActive_andCKOSignatureIsValid_shouldReturnTrue() throws NoSuchAlgorithmException, InvalidKeyException { when(checkoutComMerchantConfigurationServiceMock.isNasSignatureKeyUsedOnNotificationValidation()).thenReturn(true); doReturn(true).when(testObj).isCkoSignatureValid(SECRET_KEY_MESSAGE_HASH, eventBody); @@ -129,8 +96,7 @@ public void isRequestEventValid_whenNASIsActive_andAuthorizationHeaderIsNotActiv } @Test - public void isRequestEventValid_whenNASIsActive_andAuthorizationHeaderIsNotActive_andNasSignatureKeyIsActive_andCKOSignatureIsValid_shouldReturnFalse() throws NoSuchAlgorithmException, InvalidKeyException { - when(checkoutComMerchantConfigurationServiceMock.isNasUsed()).thenReturn(true); + public void isRequestEventValid_whenAuthorizationHeaderIsNotActive_andNasSignatureKeyIsActive_andCKOSignatureIsValid_shouldReturnFalse() throws NoSuchAlgorithmException, InvalidKeyException { when(checkoutComMerchantConfigurationServiceMock.isNasSignatureKeyUsedOnNotificationValidation()).thenReturn(true); when(httpServletRequestMock.getHeader(HEADER_CKO_SIGNATURE)).thenReturn(ANOTHER_KEY); doReturn(false).when(testObj).isCkoSignatureValid(ANOTHER_KEY, eventBody); @@ -154,15 +120,8 @@ public void isCkoSignatureValid_whenBodyEmpty_ShouldThrowException() throws NoSu assertFalse(testObj.isCkoSignatureValid(SECRET_KEY_MESSAGE_HASH, emptyEventBody)); } - @Test - public void isCkoSignatureValid_whenABCIsUsed_andEverythingMatches_ShouldReturnTrue() throws NoSuchAlgorithmException, InvalidKeyException { - assertTrue(testObj.isCkoSignatureValid(SECRET_KEY_MESSAGE_HASH, eventBody)); - } - @Test public void isCkoSignatureValid_whenNASIsUsed_andEverythingMatches_ShouldReturnTrue() throws NoSuchAlgorithmException, InvalidKeyException { - when(checkoutComMerchantConfigurationServiceMock.isNasUsed()).thenReturn(true); - assertTrue(testObj.isCkoSignatureValid(SIGNATURE_KEY_MESSAGE_HASH, eventBody)); } diff --git a/hybris/bin/modules/checkoutcom/checkoutfacades/resources/checkoutfacades-beans.xml b/hybris/bin/modules/checkoutcom/checkoutfacades/resources/checkoutfacades-beans.xml index 782b5ee..1ef255f 100644 --- a/hybris/bin/modules/checkoutcom/checkoutfacades/resources/checkoutfacades-beans.xml +++ b/hybris/bin/modules/checkoutcom/checkoutfacades/resources/checkoutfacades-beans.xml @@ -75,6 +75,7 @@ + - + + diff --git a/hybris/bin/modules/checkoutcom/checkoutfacades/resources/checkoutfacades.build.number b/hybris/bin/modules/checkoutcom/checkoutfacades/resources/checkoutfacades.build.number index 3d02433..fadd8f6 100644 --- a/hybris/bin/modules/checkoutcom/checkoutfacades/resources/checkoutfacades.build.number +++ b/hybris/bin/modules/checkoutcom/checkoutfacades/resources/checkoutfacades.build.number @@ -1,11 +1,11 @@ #Ant properties -#Tue May 28 13:21:41 GMT 2024 +#Tue Jun 18 10:12:56 GMT 2024 version.api=2211 vendor=hybris group.id=de.hybris.platform name=checkoutfacades description=checkoutfacades -builddate=20240528 1321 +builddate=20240618 1012 releasedate=20240307 1540 version=2211.20 module.name=platform-module diff --git a/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/commercefacades/user/impl/DefaultCheckoutComUserFacade.java b/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/commercefacades/user/impl/DefaultCheckoutComUserFacade.java index 66564c7..7144463 100644 --- a/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/commercefacades/user/impl/DefaultCheckoutComUserFacade.java +++ b/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/commercefacades/user/impl/DefaultCheckoutComUserFacade.java @@ -39,43 +39,39 @@ public DefaultCheckoutComUserFacade(final UserFacade userFacade, @Override public void removeCCPaymentInfo(final String id) { - if (checkoutComMerchantConfigurationService.isNasUsed()) { - validateParameterNotNullStandardMessage("id", id); - final CustomerModel currentCustomer = (CustomerModel) userService.getCurrentUser(); - final Optional creditCard = getCreditCardForCustomer(id, currentCustomer); - creditCard.ifPresent( - card -> checkoutComCustomerAccountServiceAdapter.deleteCCPaymentInfo(currentCustomer, card)); - } + validateParameterNotNullStandardMessage("id", id); + final CustomerModel currentCustomer = (CustomerModel) userService.getCurrentUser(); + final Optional creditCard = getCreditCardForCustomer(id, currentCustomer); + creditCard.ifPresent( + card -> checkoutComCustomerAccountServiceAdapter.deleteCCPaymentInfo(currentCustomer, card)); + userFacade.removeCCPaymentInfo(id); } @Override public void updateCreditCardDetails(final String code, final CCPaymentInfoData ccPaymentInfoData) { - if (checkoutComMerchantConfigurationService.isNasUsed()) { - validateParameterNotNullStandardMessage("code", code); - final CustomerModel currentCustomer = (CustomerModel) userService.getCurrentUser(); - final Optional creditCard = - getCreditCardForCustomer(code, currentCustomer); - creditCard.ifPresent( - card -> checkoutComCustomerAccountServiceAdapter.updateCreditCardDetails(currentCustomer, card)); - } + validateParameterNotNullStandardMessage("code", code); + final CustomerModel currentCustomer = (CustomerModel) userService.getCurrentUser(); + final Optional creditCard = + getCreditCardForCustomer(code, currentCustomer); + creditCard.ifPresent( + card -> checkoutComCustomerAccountServiceAdapter.updateCreditCardDetails(currentCustomer, card)); } @Override public void updateCCPaymentInfo(final CCPaymentInfoData paymentInfo) { - if (checkoutComMerchantConfigurationService.isNasUsed()) { - validateParameterNotNullStandardMessage("paymentInfo", paymentInfo); - validateParameterNotNullStandardMessage("paymentInfoID", paymentInfo.getId()); - final CustomerModel currentCustomer = (CustomerModel) userService.getCurrentUser(); - final Optional creditCardForCustomer = - getCreditCardForCustomer(paymentInfo.getId(), - currentCustomer); - creditCardForCustomer.ifPresent(card -> { - cardPaymentInfoReversePopulator.populate(paymentInfo, card); - checkoutComCustomerAccountServiceAdapter.updateCreditCardDetails(currentCustomer, - card); + validateParameterNotNullStandardMessage("paymentInfo", paymentInfo); + validateParameterNotNullStandardMessage("paymentInfoID", paymentInfo.getId()); + final CustomerModel currentCustomer = (CustomerModel) userService.getCurrentUser(); + final Optional creditCardForCustomer = + getCreditCardForCustomer(paymentInfo.getId(), + currentCustomer); + creditCardForCustomer.ifPresent(card -> { + cardPaymentInfoReversePopulator.populate(paymentInfo, card); + checkoutComCustomerAccountServiceAdapter.updateCreditCardDetails(currentCustomer, + card); }); - } + userFacade.updateCCPaymentInfo(paymentInfo); } diff --git a/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/merchant/CheckoutComMerchantConfigurationFacade.java b/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/merchant/CheckoutComMerchantConfigurationFacade.java index 626882f..6e94016 100644 --- a/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/merchant/CheckoutComMerchantConfigurationFacade.java +++ b/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/merchant/CheckoutComMerchantConfigurationFacade.java @@ -31,11 +31,4 @@ public interface CheckoutComMerchantConfigurationFacade { */ Optional getGooglePaySettings(); - /** - * Returns true if the merchant is configured as ABC and false if it's NAS. - * - * @return {@link Boolean} the value. - * - */ - Boolean isCheckoutComMerchantABC (); } diff --git a/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/merchant/impl/DefaultCheckoutComMerchantConfigurationFacade.java b/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/merchant/impl/DefaultCheckoutComMerchantConfigurationFacade.java index bb7e337..04c489c 100644 --- a/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/merchant/impl/DefaultCheckoutComMerchantConfigurationFacade.java +++ b/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/merchant/impl/DefaultCheckoutComMerchantConfigurationFacade.java @@ -61,9 +61,4 @@ public Optional getGooglePaySettings() { } } - @Override - public Boolean isCheckoutComMerchantABC() { - boolean isNasUsed = checkoutComMerchantConfigurationService.isNasUsed(); - return (isNasUsed ? Boolean.FALSE : Boolean.TRUE); - } } diff --git a/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/payment/clienttoken/request/converters/populators/CheckoutComKlarnaSessionRequestDtoPopulator.java b/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/payment/clienttoken/request/converters/populators/CheckoutComKlarnaSessionRequestDtoPopulator.java index c62e240..338516f 100644 --- a/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/payment/clienttoken/request/converters/populators/CheckoutComKlarnaSessionRequestDtoPopulator.java +++ b/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/payment/clienttoken/request/converters/populators/CheckoutComKlarnaSessionRequestDtoPopulator.java @@ -1,8 +1,7 @@ package com.checkout.hybris.facades.payment.clienttoken.request.converters.populators; import com.checkout.hybris.core.currency.services.CheckoutComCurrencyService; -import com.checkout.hybris.core.klarna.session.request.KlarnaProductRequestDto; -import com.checkout.hybris.core.klarna.session.request.KlarnaSessionRequestDto; +import com.checkout.hybris.core.klarna.session.request.*; import de.hybris.platform.converters.Populator; import de.hybris.platform.core.model.c2l.C2LItemModel; import de.hybris.platform.core.model.c2l.CurrencyModel; @@ -23,6 +22,9 @@ */ public class CheckoutComKlarnaSessionRequestDtoPopulator implements Populator { + protected static final String KLARNA = "klarna"; + protected static final String REGULAR = "regular"; + protected final CheckoutComCurrencyService checkoutComCurrencyService; protected final Converter> checkoutComKlarnaProductsRequestDtoConverter; @@ -45,17 +47,38 @@ public void populate(final CartModel source, final KlarnaSessionRequestDto targe .filter(StringUtils::isNotBlank); currencyCode.ifPresent(target::setCurrency); - target.setLocale(Optional.ofNullable(source.getSite().getLocale()) - .orElse(Locale.UK.toString()) - .replace("_", "-") - ); + target.setPaymentType(REGULAR); + + currencyCode.ifPresent(currency -> target.setAmount(checkoutComCurrencyService.convertAmountIntoPennies(currency, source.getTotalPrice()))); + target.setProducts(checkoutComKlarnaProductsRequestDtoConverter.convert(source)); + + populateKlarnaSession(source, target); + populateKlarnaProcessing(source, target); + } + + protected void populateKlarnaSession(final CartModel source, final KlarnaSessionRequestDto target) { + final KlarnaSourceRequestDto sourceRequestDto = new KlarnaSourceRequestDto(); + final KlarnaAccountHolderRequestDto accountHolderRequestDto = new KlarnaAccountHolderRequestDto(); + final KlarnaBillingAddressRequestDto billingAddress = new KlarnaBillingAddressRequestDto(); + accountHolderRequestDto.setBillingAddress(billingAddress); + sourceRequestDto.setType(KLARNA); + sourceRequestDto.setAccountHolder(accountHolderRequestDto); + target.setSource(sourceRequestDto); + Optional.ofNullable(source.getPaymentAddress()) .map(AddressModel::getCountry) .map(C2LItemModel::getIsocode) - .ifPresent(target::setPurchaseCountry); + .ifPresent(billingAddress::setCountry); + } - currencyCode.ifPresent(currency -> target.setAmount(checkoutComCurrencyService.convertAmountIntoPennies(currency, source.getTotalPrice()))); - currencyCode.ifPresent(currency -> target.setTaxAmount(checkoutComCurrencyService.convertAmountIntoPennies(currency, source.getTotalTax()))); - target.setProducts(checkoutComKlarnaProductsRequestDtoConverter.convert(source)); + protected void populateKlarnaProcessing(final CartModel source, final KlarnaSessionRequestDto target) { + final KlarnaProcessingRequestDto processing = new KlarnaProcessingRequestDto(); + processing.setLocale(Optional.ofNullable(source.getSite().getLocale()) + .orElse(Locale.UK.toString()) + .replace("_", "-") + ); + + target.setProcessing(processing); } + } diff --git a/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/payment/converters/populators/CheckoutComKlarnaPaymentInfoReversePopulator.java b/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/payment/converters/populators/CheckoutComKlarnaPaymentInfoReversePopulator.java index 5282807..2786c12 100644 --- a/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/payment/converters/populators/CheckoutComKlarnaPaymentInfoReversePopulator.java +++ b/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/payment/converters/populators/CheckoutComKlarnaPaymentInfoReversePopulator.java @@ -20,6 +20,7 @@ public void populate(final KlarnaPaymentInfoData source, final CheckoutComKlarna Assert.notNull(target, "Parameter CheckoutComKlarnaAPMPaymentInfoModel cannot be null."); target.setAuthorizationToken(source.getAuthorizationToken()); + target.setPaymentContext(source.getPaymentContextId()); target.setDeferred(false); } } \ No newline at end of file diff --git a/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/payment/klarna/impl/DefaultCheckoutComKlarnaFacade.java b/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/payment/klarna/impl/DefaultCheckoutComKlarnaFacade.java index 89aa536..e0d2146 100644 --- a/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/payment/klarna/impl/DefaultCheckoutComKlarnaFacade.java +++ b/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/payment/klarna/impl/DefaultCheckoutComKlarnaFacade.java @@ -1,9 +1,9 @@ package com.checkout.hybris.facades.payment.klarna.impl; import com.checkout.hybris.core.klarna.session.request.KlarnaSessionRequestDto; -import com.checkout.hybris.core.klarna.session.response.KlarnaPaymentMethodCategoryDto; import com.checkout.hybris.core.klarna.session.response.KlarnaSessionResponseDto; import com.checkout.hybris.core.merchant.services.CheckoutComMerchantConfigurationService; +import com.checkout.hybris.core.model.CheckoutComKlarnaAPMPaymentInfoModel; import com.checkout.hybris.core.model.CheckoutComKlarnaConfigurationModel; import com.checkout.hybris.core.payment.services.CheckoutComPaymentIntegrationService; import com.checkout.hybris.facades.beans.KlarnaClientTokenData; @@ -11,6 +11,7 @@ import de.hybris.platform.core.model.order.CartModel; import de.hybris.platform.order.CartService; import de.hybris.platform.servicelayer.dto.converter.Converter; +import de.hybris.platform.servicelayer.model.ModelService; import java.util.Set; import java.util.concurrent.ExecutionException; @@ -61,13 +62,10 @@ public KlarnaClientTokenData getKlarnaClientToken() throws IllegalArgumentExcept */ protected void populateKlarnaTokenData(final KlarnaClientTokenData klarnaClientTokenData, final KlarnaSessionResponseDto klarnaSessionResponse) { final CheckoutComKlarnaConfigurationModel klarnaConfiguration = checkoutComMerchantConfigurationService.getKlarnaConfiguration(); - klarnaClientTokenData.setClientToken(klarnaSessionResponse.getClientToken()); + klarnaClientTokenData.setClientToken(klarnaSessionResponse.getPartnerMetadata().getClientToken()); + klarnaClientTokenData.setSessionId(klarnaSessionResponse.getPartnerMetadata().getSessionId()); klarnaClientTokenData.setSuccess(Boolean.TRUE); + klarnaClientTokenData.setPaymentContext(klarnaSessionResponse.getId()); klarnaClientTokenData.setInstanceId(klarnaConfiguration.getInstanceId()); - - final Set paymentMethodCategories = klarnaSessionResponse.getPaymentMethodCategories().stream() - .map(KlarnaPaymentMethodCategoryDto::getIdentifier) - .collect(Collectors.toSet()); - klarnaClientTokenData.setPaymentMethodCategories(paymentMethodCategories); } } diff --git a/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/user/converters/populators/CheckoutComAddressPopulator.java b/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/user/converters/populators/CheckoutComAddressPopulator.java new file mode 100644 index 0000000..473e5b6 --- /dev/null +++ b/hybris/bin/modules/checkoutcom/checkoutfacades/src/com/checkout/hybris/facades/user/converters/populators/CheckoutComAddressPopulator.java @@ -0,0 +1,29 @@ +package com.checkout.hybris.facades.user.converters.populators; + +import de.hybris.platform.commercefacades.user.converters.populator.AddressPopulator; +import de.hybris.platform.commercefacades.user.converters.populator.AddressReversePopulator; +import de.hybris.platform.commercefacades.user.data.AddressData; +import de.hybris.platform.core.model.user.AddressModel; +import de.hybris.platform.servicelayer.dto.converter.ConversionException; + +/** + * Checkout.com populator needed to populate the email address in the model from the data. + * It's always used as populator call and not mapped in a converter, + * for this reason it's impossible to add another populator to a list. + */ +public class CheckoutComAddressPopulator extends AddressPopulator { + + /** + * {@inheritDoc} + */ + @Override + public void populate(final AddressModel source, final AddressData target) throws ConversionException { + callSuperPopulate(source, target); + + target.setEmail(source.getEmail()); + } + + protected void callSuperPopulate(final AddressModel source, final AddressData target) { + super.populate(source, target); + } +} diff --git a/hybris/bin/modules/checkoutcom/checkoutfacades/testsrc/com/checkout/hybris/commercefacades/user/impl/DefaultCheckoutComUserFacadeTest.java b/hybris/bin/modules/checkoutcom/checkoutfacades/testsrc/com/checkout/hybris/commercefacades/user/impl/DefaultCheckoutComUserFacadeTest.java index aebd891..3d89bb2 100644 --- a/hybris/bin/modules/checkoutcom/checkoutfacades/testsrc/com/checkout/hybris/commercefacades/user/impl/DefaultCheckoutComUserFacadeTest.java +++ b/hybris/bin/modules/checkoutcom/checkoutfacades/testsrc/com/checkout/hybris/commercefacades/user/impl/DefaultCheckoutComUserFacadeTest.java @@ -54,11 +54,6 @@ public class DefaultCheckoutComUserFacadeTest { private CreditCardPaymentInfoModel creditCardPaymentInfoModelMock; private final CCPaymentInfoData ccPaymentInfoData = new CCPaymentInfoData(); - @Before - public void setUp() throws Exception { - when(checkoutComMerchantConfigurationServiceMock.isNasUsed()).thenReturn(true); - } - @Test public void removeCCPaymentInfo_shouldCallCheckoutComCustomerAccountServiceAdapterAndRemoveCCPaymentInfo_WhenCreditCardExistsForCurrentCustomer() { ensureCurrentUserExists(); diff --git a/hybris/bin/modules/checkoutcom/checkoutfacades/testsrc/com/checkout/hybris/facades/merchant/impl/DefaultCheckoutComMerchantConfigurationFacadeTest.java b/hybris/bin/modules/checkoutcom/checkoutfacades/testsrc/com/checkout/hybris/facades/merchant/impl/DefaultCheckoutComMerchantConfigurationFacadeTest.java index fb8b727..d3c6e9c 100644 --- a/hybris/bin/modules/checkoutcom/checkoutfacades/testsrc/com/checkout/hybris/facades/merchant/impl/DefaultCheckoutComMerchantConfigurationFacadeTest.java +++ b/hybris/bin/modules/checkoutcom/checkoutfacades/testsrc/com/checkout/hybris/facades/merchant/impl/DefaultCheckoutComMerchantConfigurationFacadeTest.java @@ -102,22 +102,5 @@ public void getGooglePaySettings_WhenNoConfigurationFound_ShouldReturnOptionalEm assertFalse(result.isPresent()); } - - @Test - public void isCheckoutComMerchantABC_WhenMerchantIsNAS_shouldReturnFalse() { - when(checkoutComMerchantConfigurationServiceMock.isNasUsed()).thenReturn(true); - - final Boolean result = testObj.isCheckoutComMerchantABC(); - - assertFalse(result); - } - - @Test - public void isCheckoutComMerchantABC_WhenMerchantIsABC_shouldReturnTrue() { - when(checkoutComMerchantConfigurationServiceMock.isNasUsed()).thenReturn(false); - - final Boolean result = testObj.isCheckoutComMerchantABC(); - assertTrue(result); - } } diff --git a/hybris/bin/modules/checkoutcom/checkoutfacades/testsrc/com/checkout/hybris/facades/payment/clienttoken/request/converters/populators/CheckoutComKlarnaSessionRequestDtoPopulatorTest.java b/hybris/bin/modules/checkoutcom/checkoutfacades/testsrc/com/checkout/hybris/facades/payment/clienttoken/request/converters/populators/CheckoutComKlarnaSessionRequestDtoPopulatorTest.java index d629fdf..868d8d9 100644 --- a/hybris/bin/modules/checkoutcom/checkoutfacades/testsrc/com/checkout/hybris/facades/payment/clienttoken/request/converters/populators/CheckoutComKlarnaSessionRequestDtoPopulatorTest.java +++ b/hybris/bin/modules/checkoutcom/checkoutfacades/testsrc/com/checkout/hybris/facades/payment/clienttoken/request/converters/populators/CheckoutComKlarnaSessionRequestDtoPopulatorTest.java @@ -64,7 +64,6 @@ public class CheckoutComKlarnaSessionRequestDtoPopulatorTest { public void setUp() { when(checkoutComCurrencyServiceMock.convertAmountIntoPennies(CURRENCY_CODE, CHECKOUTCOM_AMOUNT_DOUBLE)).thenReturn(CHECKOUTCOM_AMOUNT_LONG); when(sourceMock.getTotalPrice()).thenReturn(CHECKOUTCOM_AMOUNT_DOUBLE); - when(sourceMock.getTotalTax()).thenReturn(CHECKOUTCOM_AMOUNT_DOUBLE); when(sourceMock.getCurrency()).thenReturn(currencyModelMock); when(currencyModelMock.getIsocode()).thenReturn(CURRENCY_CODE); when(sourceMock.getSite()).thenReturn(cmsSiteMock); @@ -80,10 +79,7 @@ public void populate_WhenEverythingIsFine_ShouldPopulateTheRequest() { testObj.populate(sourceMock, target); assertEquals(CHECKOUTCOM_AMOUNT_LONG, target.getAmount()); - assertEquals(CHECKOUTCOM_AMOUNT_LONG, target.getTaxAmount()); assertEquals(CURRENCY_CODE, target.getCurrency()); - assertEquals(COUNTRY_CODE, target.getPurchaseCountry()); - assertEquals(LOCALE_CODE, target.getLocale()); verify(checkoutComKlarnaProductsRequestDtoConverterMock).convert(sourceMock); assertEquals(2, target.getProducts().size()); assertEquals(product1Mock, target.getProducts().get(0)); diff --git a/hybris/bin/modules/checkoutcom/checkoutfacades/testsrc/com/checkout/hybris/facades/payment/converters/populators/CheckoutComKlarnaPaymentInfoReversePopulatorTest.java b/hybris/bin/modules/checkoutcom/checkoutfacades/testsrc/com/checkout/hybris/facades/payment/converters/populators/CheckoutComKlarnaPaymentInfoReversePopulatorTest.java index 8f2b36c..17dfa82 100644 --- a/hybris/bin/modules/checkoutcom/checkoutfacades/testsrc/com/checkout/hybris/facades/payment/converters/populators/CheckoutComKlarnaPaymentInfoReversePopulatorTest.java +++ b/hybris/bin/modules/checkoutcom/checkoutfacades/testsrc/com/checkout/hybris/facades/payment/converters/populators/CheckoutComKlarnaPaymentInfoReversePopulatorTest.java @@ -1,32 +1,27 @@ package com.checkout.hybris.facades.payment.converters.populators; -import com.checkout.hybris.core.apm.services.CheckoutComAPMConfigurationService; import com.checkout.hybris.core.model.CheckoutComKlarnaAPMPaymentInfoModel; import com.checkout.hybris.facades.beans.KlarnaPaymentInfoData; import de.hybris.bootstrap.annotations.UnitTest; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; -import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static com.checkout.hybris.core.payment.enums.CheckoutComPaymentType.KLARNA; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.mockito.Mockito.when; @UnitTest @RunWith(MockitoJUnitRunner.class) public class CheckoutComKlarnaPaymentInfoReversePopulatorTest { private static final String KLARNA_AUTH_TOKEN_VALUE = "klarna_token"; + private static final String KLARNA_PAYMENT_CONTEXT_VALUE = "payment_context_id"; @InjectMocks private CheckoutComKlarnaPaymentInfoReversePopulator testObj; - @Mock - private CheckoutComAPMConfigurationService checkoutComAPMConfigurationServiceMock; - private KlarnaPaymentInfoData source = new KlarnaPaymentInfoData(); private CheckoutComKlarnaAPMPaymentInfoModel target = new CheckoutComKlarnaAPMPaymentInfoModel(); @@ -34,10 +29,12 @@ public class CheckoutComKlarnaPaymentInfoReversePopulatorTest { public void populate_ShouldPopulateTargetCorrectly() { source.setType(KLARNA.name()); source.setAuthorizationToken(KLARNA_AUTH_TOKEN_VALUE); + source.setPaymentContextId(KLARNA_PAYMENT_CONTEXT_VALUE); testObj.populate(source, target); assertEquals(KLARNA_AUTH_TOKEN_VALUE, target.getAuthorizationToken()); + assertEquals(KLARNA_PAYMENT_CONTEXT_VALUE, target.getPaymentContext()); assertFalse(target.getDeferred()); } diff --git a/hybris/bin/modules/checkoutcom/checkoutfacades/testsrc/com/checkout/hybris/facades/payment/klarna/impl/DefaultCheckoutComKlarnaFacadeTest.java b/hybris/bin/modules/checkoutcom/checkoutfacades/testsrc/com/checkout/hybris/facades/payment/klarna/impl/DefaultCheckoutComKlarnaFacadeTest.java index 3077d26..2a8578b 100644 --- a/hybris/bin/modules/checkoutcom/checkoutfacades/testsrc/com/checkout/hybris/facades/payment/klarna/impl/DefaultCheckoutComKlarnaFacadeTest.java +++ b/hybris/bin/modules/checkoutcom/checkoutfacades/testsrc/com/checkout/hybris/facades/payment/klarna/impl/DefaultCheckoutComKlarnaFacadeTest.java @@ -1,7 +1,8 @@ + package com.checkout.hybris.facades.payment.klarna.impl; import com.checkout.hybris.core.klarna.session.request.KlarnaSessionRequestDto; -import com.checkout.hybris.core.klarna.session.response.KlarnaPaymentMethodCategoryDto; +import com.checkout.hybris.core.klarna.session.response.KlarnaPartnerMetadataResponseDto; import com.checkout.hybris.core.klarna.session.response.KlarnaSessionResponseDto; import com.checkout.hybris.core.merchant.services.CheckoutComMerchantConfigurationService; import com.checkout.hybris.core.model.CheckoutComKlarnaConfigurationModel; @@ -18,7 +19,6 @@ import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; -import java.util.Arrays; import java.util.concurrent.ExecutionException; import static org.assertj.core.api.Assertions.*; @@ -29,9 +29,9 @@ public class DefaultCheckoutComKlarnaFacadeTest { private static final String CLIENT_TOKEN = "client_token"; - private static final String PAY_LATER = "pay_later"; - private static final String PAY_OVER_TIME = "pay_over_time"; private static final String INSTANCE_ID = "instance_id"; + private static final String ID = "id"; + private static final String SESSION_ID = "session_id"; @InjectMocks private DefaultCheckoutComKlarnaFacade testObj; @@ -53,7 +53,7 @@ public class DefaultCheckoutComKlarnaFacadeTest { @Mock private CheckoutComKlarnaConfigurationModel klarnaConfigurationMock; @Mock - private KlarnaPaymentMethodCategoryDto klarnaPaymentMethodCategory1Mock, klarnaPaymentMethodCategory2Mock; + private KlarnaPartnerMetadataResponseDto klarnaPartnerMetadataResponseDtoMock; @Before public void setUp() throws ExecutionException { @@ -61,10 +61,10 @@ public void setUp() throws ExecutionException { when(cartServiceMock.hasSessionCart()).thenReturn(true); when(checkoutComKlarnaSessionRequestDtoConverterMock.convert(cartModelMock)).thenReturn(klarnaRequestSessionMock); when(checkoutComPaymentIntegrationServiceMock.createKlarnaSession(klarnaRequestSessionMock)).thenReturn(klarnaSessionResponseMock); - when(klarnaSessionResponseMock.getClientToken()).thenReturn(CLIENT_TOKEN); - when(klarnaSessionResponseMock.getPaymentMethodCategories()).thenReturn(Arrays.asList(klarnaPaymentMethodCategory1Mock, klarnaPaymentMethodCategory2Mock)); - when(klarnaPaymentMethodCategory1Mock.getIdentifier()).thenReturn(PAY_OVER_TIME); - when(klarnaPaymentMethodCategory2Mock.getIdentifier()).thenReturn(PAY_LATER); + when(klarnaSessionResponseMock.getPartnerMetadata()).thenReturn(klarnaPartnerMetadataResponseDtoMock); + when(klarnaPartnerMetadataResponseDtoMock.getClientToken()).thenReturn(CLIENT_TOKEN); + when(klarnaPartnerMetadataResponseDtoMock.getSessionId()).thenReturn(SESSION_ID); + when(klarnaSessionResponseMock.getId()).thenReturn(ID); when(checkoutComMerchantConfigurationServiceMock.getKlarnaConfiguration()).thenReturn(klarnaConfigurationMock); when(klarnaConfigurationMock.getInstanceId()).thenReturn(INSTANCE_ID); } @@ -89,7 +89,8 @@ public void getKlarnaClientToken_ShouldReturnPopulateClientToken() throws Execut assertThat(result.getClientToken()).isEqualTo(CLIENT_TOKEN); assertThat(result.getInstanceId()).isEqualTo(INSTANCE_ID); - assertThat(result.getPaymentMethodCategories()).containsExactlyInAnyOrder(PAY_LATER, PAY_OVER_TIME); + assertThat(result.getPaymentContext()).isEqualTo(ID); + assertThat(result.getSessionId()).isEqualTo(SESSION_ID); assertThat(result.getSuccess()).isTrue(); } } diff --git a/hybris/bin/modules/checkoutcom/checkoutfulfilmentprocess/resources/checkoutfulfilmentprocess.build.number b/hybris/bin/modules/checkoutcom/checkoutfulfilmentprocess/resources/checkoutfulfilmentprocess.build.number index 27230da..2d5e410 100644 --- a/hybris/bin/modules/checkoutcom/checkoutfulfilmentprocess/resources/checkoutfulfilmentprocess.build.number +++ b/hybris/bin/modules/checkoutcom/checkoutfulfilmentprocess/resources/checkoutfulfilmentprocess.build.number @@ -1,11 +1,11 @@ #Ant properties -#Tue May 28 13:21:42 GMT 2024 +#Tue Jun 18 10:12:56 GMT 2024 version.api=2211 vendor=hybris group.id=de.hybris.platform name=checkoutfulfilmentprocess description=checkoutfulfilmentprocess -builddate=20240528 1321 +builddate=20240618 1012 releasedate=20240307 1540 version=2211.20 module.name=platform-module diff --git a/hybris/bin/modules/checkoutcom/checkoutocc/resources/checkoutocc-beans.xml b/hybris/bin/modules/checkoutcom/checkoutocc/resources/checkoutocc-beans.xml index 2b7bc8b..000b095 100644 --- a/hybris/bin/modules/checkoutcom/checkoutocc/resources/checkoutocc-beans.xml +++ b/hybris/bin/modules/checkoutcom/checkoutocc/resources/checkoutocc-beans.xml @@ -25,6 +25,7 @@ + diff --git a/hybris/bin/modules/checkoutcom/checkoutocc/resources/checkoutocc.build.number b/hybris/bin/modules/checkoutcom/checkoutocc/resources/checkoutocc.build.number index 1b2f3fa..e1e7ea0 100644 --- a/hybris/bin/modules/checkoutcom/checkoutocc/resources/checkoutocc.build.number +++ b/hybris/bin/modules/checkoutcom/checkoutocc/resources/checkoutocc.build.number @@ -1,11 +1,11 @@ #Ant properties -#Tue May 28 13:21:42 GMT 2024 +#Tue Jun 18 10:12:56 GMT 2024 version.api=2211 vendor=hybris group.id=de.hybris.platform name=checkoutocc description=checkoutocc -builddate=20240528 1321 +builddate=20240618 1012 releasedate=20240307 1540 version=2211.20 module.name=platform-module diff --git a/hybris/bin/modules/checkoutcom/checkoutocc/resources/occ/v2/checkoutocc/web/spring/checkoutocc-dto-level-mappings-v2-spring.xml b/hybris/bin/modules/checkoutcom/checkoutocc/resources/occ/v2/checkoutocc/web/spring/checkoutocc-dto-level-mappings-v2-spring.xml index a8ea69f..00be123 100644 --- a/hybris/bin/modules/checkoutcom/checkoutocc/resources/occ/v2/checkoutocc/web/spring/checkoutocc-dto-level-mappings-v2-spring.xml +++ b/hybris/bin/modules/checkoutcom/checkoutocc/resources/occ/v2/checkoutocc/web/spring/checkoutocc-dto-level-mappings-v2-spring.xml @@ -61,12 +61,24 @@ - + + + + + + + + + + + + diff --git a/hybris/bin/modules/checkoutcom/checkoutocc/src/com/checkout/hybris/occ/controllers/CheckoutComCartsController.java b/hybris/bin/modules/checkoutcom/checkoutocc/src/com/checkout/hybris/occ/controllers/CheckoutComCartsController.java index ff3c955..e18ded3 100644 --- a/hybris/bin/modules/checkoutcom/checkoutocc/src/com/checkout/hybris/occ/controllers/CheckoutComCartsController.java +++ b/hybris/bin/modules/checkoutcom/checkoutocc/src/com/checkout/hybris/occ/controllers/CheckoutComCartsController.java @@ -145,8 +145,9 @@ should be set as default (defaultPaymentInfo), and the billing address (billingA @PostMapping(value = "/{cartId}/checkoutoccbillingaddress", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) @ResponseStatus(HttpStatus.CREATED) @ResponseBody - public void addBillingAddressToCart(@RequestBody final AddressWsDTO address) { - saveBillingAddress(address); + @ApiBaseSiteIdUserIdAndCartIdParam + public AddressWsDTO addBillingAddressToCart(@RequestBody final AddressWsDTO address, @ApiFieldsParam @RequestParam(defaultValue = DEFAULT_FIELD_SET, required = false) final String fields) { + return saveBillingAddress(address, fields); } @Secured({"ROLE_CUSTOMERGROUP", "ROLE_CUSTOMERMANAGERGROUP", "ROLE_GUEST", "ROLE_TRUSTED_CLIENT"}) @@ -167,6 +168,7 @@ the country (country.isocode), the first part of the address (line1), the second validate(address, OBJECT_NAME_ADDRESS, addressDTOValidator); AddressData addressData = dataMapper.map(address, AddressData.class, DEFAULT_FIELD_SET); addressData = createAddressInternal(addressData); + addressData.setEmail(checkoutCustomerStrategy.getCurrentUserForCheckout().getContactEmail()); setCartDeliveryAddressInternal(addressData.getId()); checkoutComAddressFacade.setCartBillingDetails(addressData); return dataMapper.map(addressData, AddressWsDTO.class, fields); @@ -189,12 +191,13 @@ public void replaceCartDeliveryAndBillingAddress( * * @param address The billing address */ - protected void saveBillingAddress(final AddressWsDTO address) { + protected AddressWsDTO saveBillingAddress(final AddressWsDTO address, final String fields) { address.setEmail(checkoutCustomerStrategy.getCurrentUserForCheckout().getContactEmail()); address.setVisibleInAddressBook(Boolean.FALSE); - final AddressData addressData = dataMapper.map(address, AddressData.class); + final AddressData addressData = dataMapper.map(address, AddressData.class, fields); userFacade.addAddress(addressData); checkoutComAddressFacade.setCartBillingDetails(addressData); + return dataMapper.map(addressData, AddressWsDTO.class, fields); } /** diff --git a/hybris/bin/modules/checkoutcom/checkoutocc/src/com/checkout/hybris/occ/controllers/CheckoutComMerchantController.java b/hybris/bin/modules/checkoutcom/checkoutocc/src/com/checkout/hybris/occ/controllers/CheckoutComMerchantController.java index 957b599..afa17b7 100644 --- a/hybris/bin/modules/checkoutcom/checkoutocc/src/com/checkout/hybris/occ/controllers/CheckoutComMerchantController.java +++ b/hybris/bin/modules/checkoutcom/checkoutocc/src/com/checkout/hybris/occ/controllers/CheckoutComMerchantController.java @@ -38,8 +38,6 @@ public ResponseEntity getMerchantKey() { @Secured({"ROLE_CUSTOMERGROUP", "ROLE_CUSTOMERMANAGERGROUP", "ROLE_GUEST", "ROLE_TRUSTED_CLIENT", "ROLE_CLIENT"}) @GetMapping(value = "/isABC", produces = MediaType.TEXT_PLAIN_VALUE) public ResponseEntity isMerchantABC() { - Boolean isABC = checkoutComMerchantConfigurationFacade.isCheckoutComMerchantABC(); - return isABC == null ? ResponseEntity.status(INTERNAL_SERVER_ERROR).body(IS_ABC_FALSE) : - ResponseEntity.ok().body(isABC.toString()); + return ResponseEntity.ok().body(IS_ABC_FALSE); } } diff --git a/hybris/bin/modules/checkoutcom/checkoutocc/src/com/checkout/hybris/occ/controllers/CheckoutComOrdersController.java b/hybris/bin/modules/checkoutcom/checkoutocc/src/com/checkout/hybris/occ/controllers/CheckoutComOrdersController.java index cff25af..6ef8312 100644 --- a/hybris/bin/modules/checkoutcom/checkoutocc/src/com/checkout/hybris/occ/controllers/CheckoutComOrdersController.java +++ b/hybris/bin/modules/checkoutcom/checkoutocc/src/com/checkout/hybris/occ/controllers/CheckoutComOrdersController.java @@ -87,21 +87,20 @@ public OrderWsDTO placeDirectOrder( throws PaymentAuthorizationException, InvalidCartException, NoCheckoutCartException, PlaceOrderException { validateCartForPlaceOrder(); - if (!CheckoutComPaymentType.KLARNA.name().equalsIgnoreCase(checkoutFlowFacade.getCurrentPaymentMethodType())) { - - //authorize - final AuthorizeResponseData authorizeResponseData = checkoutFlowFacade.authorizePayment(); - - if (!authorizeResponseData.getIsSuccess() || Boolean.TRUE.equals(authorizeResponseData.getIsRedirect())) { - if (Boolean.TRUE.equals(authorizeResponseData.getIsRedirect())) { - LOG.debug("Redirecting to checkout.com url [{}] for 3d secure.", authorizeResponseData.getRedirectUrl()); - final OrderWsDTO orderWsDTO = new OrderWsDTO(); - orderWsDTO.setRedirectUrl(authorizeResponseData.getRedirectUrl()); - return orderWsDTO; - } else { - LOG.error("Error with the authorization process. Redirecting to payment method step."); - throw new PaymentAuthorizationException(); - } + + + //authorize + final AuthorizeResponseData authorizeResponseData = checkoutFlowFacade.authorizePayment(); + + if (!authorizeResponseData.getIsSuccess() || Boolean.TRUE.equals(authorizeResponseData.getIsRedirect())) { + if (Boolean.TRUE.equals(authorizeResponseData.getIsRedirect())) { + LOG.debug("Redirecting to checkout.com url [{}] for 3d secure.", authorizeResponseData.getRedirectUrl()); + final OrderWsDTO orderWsDTO = new OrderWsDTO(); + orderWsDTO.setRedirectUrl(authorizeResponseData.getRedirectUrl()); + return orderWsDTO; + } else { + LOG.error("Error with the authorization process. Redirecting to payment method step."); + throw new PaymentAuthorizationException(); } } diff --git a/hybris/bin/modules/checkoutcom/checkoutocc/src/com/checkout/hybris/occ/converters/populators/CheckoutComKlarnaPaymentDetailsDTOToKlarnaPaymentInfoDataPopulator.java b/hybris/bin/modules/checkoutcom/checkoutocc/src/com/checkout/hybris/occ/converters/populators/CheckoutComKlarnaPaymentDetailsDTOToKlarnaPaymentInfoDataPopulator.java index 4f2a057..06e1b13 100644 --- a/hybris/bin/modules/checkoutcom/checkoutocc/src/com/checkout/hybris/occ/converters/populators/CheckoutComKlarnaPaymentDetailsDTOToKlarnaPaymentInfoDataPopulator.java +++ b/hybris/bin/modules/checkoutcom/checkoutocc/src/com/checkout/hybris/occ/converters/populators/CheckoutComKlarnaPaymentDetailsDTOToKlarnaPaymentInfoDataPopulator.java @@ -21,6 +21,7 @@ public void populate(final PaymentDetailsWsDTO source, final KlarnaPaymentInfoDa Assert.notNull(target, "KlarnaPaymentInfoData cannot be null."); target.setAuthorizationToken(source.getAuthorizationToken()); + target.setPaymentContextId(source.getPaymentContextId()); target.setType(CheckoutComPaymentType.KLARNA.name()); } } diff --git a/hybris/bin/modules/checkoutcom/checkoutocc/testsrc/com/checkout/hybris/occ/controllers/CheckoutComCartsControllerTest.java b/hybris/bin/modules/checkoutcom/checkoutocc/testsrc/com/checkout/hybris/occ/controllers/CheckoutComCartsControllerTest.java index 0276be6..e35d7b5 100644 --- a/hybris/bin/modules/checkoutcom/checkoutocc/testsrc/com/checkout/hybris/occ/controllers/CheckoutComCartsControllerTest.java +++ b/hybris/bin/modules/checkoutcom/checkoutocc/testsrc/com/checkout/hybris/occ/controllers/CheckoutComCartsControllerTest.java @@ -70,7 +70,7 @@ public class CheckoutComCartsControllerTest { @Mock private AddressData addressDataMock; @Mock - private AddressWsDTO addressWsDTOMock; + private AddressWsDTO addressWsDTOMock, addressWsDTOTwoMock; @Mock private CustomerModel customerModelMock; @Mock @@ -131,18 +131,21 @@ public void createAPMCartPaymentDetails_WhenHasNoCheckoutCart_ShouldThrowNoCheck @Test public void addBillingAddressToCart_ShouldPopulateFieldsWithDataMapperAddingAddressWithUserFacadeAndSetBillingDetails() { - when(dataMapperMock.map(addressWsDTOMock, AddressData.class)).thenReturn(addressDataMock); + when(dataMapperMock.map(addressWsDTOMock, AddressData.class, DEFAULT_FIELD_SET)).thenReturn(addressDataMock); when(checkoutCustomerStrategyMock.getCurrentUserForCheckout()).thenReturn(customerModelMock); when(customerModelMock.getContactEmail()).thenReturn(CUSTOMER_EMAIL); + when(dataMapperMock.map(addressDataMock, AddressWsDTO.class, DEFAULT_FIELD_SET)).thenReturn(addressWsDTOTwoMock); + - testObj.addBillingAddressToCart(addressWsDTOMock); + testObj.addBillingAddressToCart(addressWsDTOMock, DEFAULT_FIELD_SET); final InOrder inOrder = Mockito.inOrder(addressWsDTOMock, addressDataMock, dataMapperMock, userFacadeMock, checkoutComAddressFacadeMock); inOrder.verify(addressWsDTOMock).setEmail(CUSTOMER_EMAIL); inOrder.verify(addressWsDTOMock).setVisibleInAddressBook(Boolean.FALSE); - inOrder.verify(dataMapperMock).map(addressWsDTOMock, AddressData.class); + inOrder.verify(dataMapperMock, times(1)).map(eq(addressWsDTOMock), eq(AddressData.class), anyString()); inOrder.verify(userFacadeMock).addAddress(addressDataMock); inOrder.verify(checkoutComAddressFacadeMock).setCartBillingDetails(addressDataMock); + inOrder.verify(dataMapperMock, times(1)).map(eq(addressDataMock), eq(AddressWsDTO.class), anyString()); } @Test @@ -171,6 +174,8 @@ public void createCartDeliveryAndBillingAddress_WhenAddressIsDefaultAddress_Shou when(dataMapperMock.map(addressWsDTOMock, AddressData.class, DEFAULT_FIELD_SET)).thenReturn(addressDataMock); when(addressDataMock.isDefaultAddress()).thenReturn(Boolean.TRUE); when(dataMapperMock.map(addressDataMock, AddressWsDTO.class, DEFAULT_FIELD_SET)).thenReturn(addressWsDTOMock); + when(checkoutCustomerStrategyMock.getCurrentUserForCheckout()).thenReturn(customerModelMock); + when(customerModelMock.getContactEmail()).thenReturn(CUSTOMER_EMAIL); final AddressWsDTO result = testObj.createCartDeliveryAndBillingAddress(addressWsDTOMock, DEFAULT_FIELD_SET); @@ -189,6 +194,8 @@ public void createCartDeliveryAndBillingAddress_WhenAddressIsNotDefaultAddress_S when(dataMapperMock.map(addressWsDTOMock, AddressData.class, DEFAULT_FIELD_SET)).thenReturn(addressDataMock); when(addressDataMock.isDefaultAddress()).thenReturn(Boolean.FALSE); when(dataMapperMock.map(addressDataMock, AddressWsDTO.class, DEFAULT_FIELD_SET)).thenReturn(addressWsDTOMock); + when(checkoutCustomerStrategyMock.getCurrentUserForCheckout()).thenReturn(customerModelMock); + when(customerModelMock.getContactEmail()).thenReturn(CUSTOMER_EMAIL); final AddressWsDTO result = testObj.createCartDeliveryAndBillingAddress(addressWsDTOMock, DEFAULT_FIELD_SET); diff --git a/hybris/bin/modules/checkoutcom/checkoutocc/testsrc/com/checkout/hybris/occ/controllers/CheckoutComMerchantControllerTest.java b/hybris/bin/modules/checkoutcom/checkoutocc/testsrc/com/checkout/hybris/occ/controllers/CheckoutComMerchantControllerTest.java index b775b4c..a9e87d4 100644 --- a/hybris/bin/modules/checkoutcom/checkoutocc/testsrc/com/checkout/hybris/occ/controllers/CheckoutComMerchantControllerTest.java +++ b/hybris/bin/modules/checkoutcom/checkoutocc/testsrc/com/checkout/hybris/occ/controllers/CheckoutComMerchantControllerTest.java @@ -46,20 +46,8 @@ public void getMerchantKey_WhenPublicKeyIsEmpty_ShouldReturnError() { assertThat(result.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); } - @Test - public void isMerchantABC_WhenMerchantIsABC_ShouldReturnTrue() { - when(checkoutComMerchantConfigurationFacadeMock.isCheckoutComMerchantABC()).thenReturn(Boolean.TRUE); - - final ResponseEntity result = testObj.isMerchantABC(); - - assertThat(result).hasFieldOrPropertyWithValue("body", Boolean.TRUE.toString()); - assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); - } - @Test public void isMerchantABC_WhenMerchantIsNAS_ShouldReturnFalse() { - when(checkoutComMerchantConfigurationFacadeMock.isCheckoutComMerchantABC()).thenReturn(Boolean.FALSE); - final ResponseEntity result = testObj.isMerchantABC(); assertThat(result).hasFieldOrPropertyWithValue("body", IS_ABC_FALSE); @@ -67,13 +55,11 @@ public void isMerchantABC_WhenMerchantIsNAS_ShouldReturnFalse() { } @Test - public void isMerchantABC_WhenMerchantIsUndefined_ShouldReturnError() { - when(checkoutComMerchantConfigurationFacadeMock.isCheckoutComMerchantABC()).thenReturn(null); - + public void isMerchantABC_WhenMerchantIsUndefined_ShouldReturnFalse() { final ResponseEntity result = testObj.isMerchantABC(); assertThat(result).hasFieldOrPropertyWithValue("body", IS_ABC_FALSE); - assertThat(result.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR); + assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); } diff --git a/hybris/bin/modules/checkoutcom/checkoutocc/testsrc/com/checkout/hybris/occ/controllers/CheckoutComOrdersControllerTest.java b/hybris/bin/modules/checkoutcom/checkoutocc/testsrc/com/checkout/hybris/occ/controllers/CheckoutComOrdersControllerTest.java index b96be8c..aa7042f 100644 --- a/hybris/bin/modules/checkoutcom/checkoutocc/testsrc/com/checkout/hybris/occ/controllers/CheckoutComOrdersControllerTest.java +++ b/hybris/bin/modules/checkoutcom/checkoutocc/testsrc/com/checkout/hybris/occ/controllers/CheckoutComOrdersControllerTest.java @@ -185,14 +185,12 @@ public void placeDirectOrder_WhenPlaceOrderThrowsException_ShouldThrowException( } @Test - public void placeDirectOrder_WhenKlarna_ShouldNotAuthorize() throws InvalidCartException, PaymentAuthorizationException, PlaceOrderException, NoCheckoutCartException { - when(checkoutFlowFacadeMock.getCurrentPaymentMethodType()).thenReturn("KLARNA"); - + public void placeDirectOrder_WhenKlarna_ShouldAuthorize() throws InvalidCartException, PaymentAuthorizationException, PlaceOrderException, NoCheckoutCartException { final OrderWsDTO result = testObj.placeDirectOrder(DEFAULT_FIELD_SET); assertThat(result).isEqualTo(orderWsDTOMock); verify(acceleratorCheckoutFacadeCheckoutFacadeMock).placeOrder(); - verify(checkoutFlowFacadeMock, never()).authorizePayment(); + verify(checkoutFlowFacadeMock).authorizePayment(); } @Test diff --git a/hybris/bin/modules/checkoutcom/checkoutocc/testsrc/com/checkout/hybris/occ/converters/populators/CheckoutComKlarnaPaymentDetailsDTOToKlarnaPaymentInfoDataPopulatorTest.java b/hybris/bin/modules/checkoutcom/checkoutocc/testsrc/com/checkout/hybris/occ/converters/populators/CheckoutComKlarnaPaymentDetailsDTOToKlarnaPaymentInfoDataPopulatorTest.java index 119b6a8..9bab098 100644 --- a/hybris/bin/modules/checkoutcom/checkoutocc/testsrc/com/checkout/hybris/occ/converters/populators/CheckoutComKlarnaPaymentDetailsDTOToKlarnaPaymentInfoDataPopulatorTest.java +++ b/hybris/bin/modules/checkoutcom/checkoutocc/testsrc/com/checkout/hybris/occ/converters/populators/CheckoutComKlarnaPaymentDetailsDTOToKlarnaPaymentInfoDataPopulatorTest.java @@ -16,6 +16,7 @@ public class CheckoutComKlarnaPaymentDetailsDTOToKlarnaPaymentInfoDataPopulatorTest { private static final String KLARNA_AUTH_TOKEN_VALUE = "12345678901_abdajkdjal"; + private static final String KLARNA_PAYMENT_CONTEXT_VALUE = "12345678901_qweqweqw"; @InjectMocks private CheckoutComKlarnaPaymentDetailsDTOToKlarnaPaymentInfoDataPopulator testObj; @@ -26,11 +27,13 @@ public class CheckoutComKlarnaPaymentDetailsDTOToKlarnaPaymentInfoDataPopulatorT @Test public void populate_ShouldPopulateTargetCorrectly() { source.setAuthorizationToken(KLARNA_AUTH_TOKEN_VALUE); + source.setPaymentContextId(KLARNA_PAYMENT_CONTEXT_VALUE); testObj.populate(source, target); assertEquals(CheckoutComPaymentType.KLARNA.name(), target.getType()); assertEquals(KLARNA_AUTH_TOKEN_VALUE, target.getAuthorizationToken()); + assertEquals(KLARNA_PAYMENT_CONTEXT_VALUE, target.getPaymentContextId()); } @Test(expected = IllegalArgumentException.class) diff --git a/hybris/bin/modules/checkoutcom/checkoutocctests/resources/checkoutocctests.build.number b/hybris/bin/modules/checkoutcom/checkoutocctests/resources/checkoutocctests.build.number index fb4d59d..0e93d38 100644 --- a/hybris/bin/modules/checkoutcom/checkoutocctests/resources/checkoutocctests.build.number +++ b/hybris/bin/modules/checkoutcom/checkoutocctests/resources/checkoutocctests.build.number @@ -1,11 +1,11 @@ #Ant properties -#Tue May 28 13:21:42 GMT 2024 +#Tue Jun 18 10:12:56 GMT 2024 version.api=2211 vendor=hybris group.id=de.hybris.platform name=checkoutocctests description=checkoutocctests -builddate=20240528 1321 +builddate=20240618 1012 releasedate=20240307 1540 version=2211.20 module.name=platform-module diff --git a/hybris/bin/modules/checkoutcom/checkoutocctests/resources/checkoutocctests/import/sampledata/essential-data.impex b/hybris/bin/modules/checkoutcom/checkoutocctests/resources/checkoutocctests/import/sampledata/essential-data.impex index aac4f7c..5a705b6 100644 --- a/hybris/bin/modules/checkoutcom/checkoutocctests/resources/checkoutocctests/import/sampledata/essential-data.impex +++ b/hybris/bin/modules/checkoutcom/checkoutocctests/resources/checkoutocctests/import/sampledata/essential-data.impex @@ -51,8 +51,8 @@ INSERT_UPDATE CheckoutComFawryConfiguration; code[unique = true]; name[lang = en INSERT_UPDATE CheckoutComOxxoConfiguration; code[unique = true]; name[lang = en]; restrictedCountries(isocode); restrictedCurrencies(isocode); description[lang = en] ; integrationType(code) ; OXXO ; Oxxo ; MX ; MXN ; redirect OXXO Demo Payment ; redirect -INSERT_UPDATE CheckoutComGlobalAPMConfiguration; abcAPMs(code) ; nasAPMs(code); - ; SOFORT,PAYPAL,POLI,IDEAL,KLARNA,ALIPAY,BENEFITPAY,BANCONTACT,EPS,KNET,QPAY,MULTIBANCO,SEPA,P24,FAWRY,OXXO ; SOFORT,IDEAL,BANCONTACT,GIROPAY,EPS,MULTIBANCO,P24,FAWRY +INSERT_UPDATE CheckoutComGlobalAPMConfiguration; nasAPMs(code); + ; IDEAL,BANCONTACT,GIROPAY,EPS,MULTIBANCO,P24,FAWRY,KLARNA INSERT_UPDATE ZoneDeliveryModeValue; deliveryMode(code)[unique = true]; value ; minimum[unique = true]; currency(isocode)[unique = true]; zone(code)[default = 'brazil'][unique = true] ; premium-gross ; 10.99 ; 0.00 ; USD ; diff --git a/hybris/bin/modules/checkoutcom/checkoutocctests/resources/checkoutocctests/import/sampledata/merchant-config.impex b/hybris/bin/modules/checkoutcom/checkoutocctests/resources/checkoutocctests/import/sampledata/merchant-config.impex index 3302979..e329a07 100644 --- a/hybris/bin/modules/checkoutcom/checkoutocctests/resources/checkoutocctests/import/sampledata/merchant-config.impex +++ b/hybris/bin/modules/checkoutcom/checkoutocctests/resources/checkoutocctests/import/sampledata/merchant-config.impex @@ -2,8 +2,8 @@ $siteUid = wsTest # Merchant keys UPDATE GenericItem[processor = de.hybris.platform.commerceservices.impex.impl.ConfigPropertyImportProcessor]; pk[unique = true] -$secretKey = $config-checkout.secret.key -$publicKey = $config-checkout.public.key +$secretKey = $config-checkout.nas.secret.key +$publicKey = $config-checkout.nas.public.key $privateSharedKey = $config-checkout.private.shared.key $nasSecretKey = Bearer $config-checkout.nas.secret.key $nasPublicKey = Bearer $config-checkout.nas.public.key @@ -19,15 +19,15 @@ INSERT_UPDATE CheckoutComKlarnaConfiguration; &klarnaConfigurationId; instanceId INSERT_UPDATE CheckoutComApplePayConfiguration; &applePayConfigurationId; certificate[unique = true]; privateKey ; supportedNetworks(code) ; countryCode; merchantCapabilities(code) ; merchantId ; merchantName ; applePayConfig ; $applePayCertificate ; $applePayPrivateKey ; amex, cartesBancaires, chinaUnionPay, discover, eftpos, electron, elo, interac, jcb, mada, maestro, masterCard, privateLabel, visa, vPay ; GB ; supportsCredit, supportsDebit, supports3DS, supportsEMV ; merchant.com.checkout.sandbox.e2y ; e2yCheckoutCom -INSERT_UPDATE CheckoutComGooglePayConfiguration; &googlePayConfigurationId; merchantId[unique = true]; merchantName ; environment(code); type ; gateway ; gatewayMerchantId; allowedCardNetworks(code) ; allowedCardAuthMethods(code) +INSERT_UPDATE CheckoutComGooglePayConfiguration; &googlePayConfigurationId; merchantId[unique = true]; merchantName ; environment(code); type ; gateway ; gatewayMerchantId ; allowedCardNetworks(code) ; allowedCardAuthMethods(code) ; googlePayConfig ; 01234567890123456789 ; e2yCheckoutCom ; test ; CARD ; checkoutltd ; $publicKey ; AMEX, DISCOVER, INTERAC, JCB, MASTERCARD, VISA ; PAN_ONLY, CRYPTOGRAM_3DS INSERT_UPDATE CheckoutComMerchantConfiguration; code[unique = true] ; applePayConfiguration(&applePayConfigurationId); googlePayConfiguration(&googlePayConfigurationId); klarnaConfiguration(&klarnaConfigurationId) ; merchantConfiguration-$siteUid ; applePayConfig ; googlePayConfig ; klarnaConfig # Merchant configuration -INSERT_UPDATE CheckoutComMerchantConfiguration; code[unique = true] ; secretKey ; publicKey ; privateSharedKey ; nasSecretKey ; nasPublicKey ; nasSignatureKey ; nasAuthorisationHeaderKey ; environment(code); paymentAction(code) ; reviewTransactionsAtRisk; klarnaConfiguration(&klarnaConfigurationId); authorisationAmountValidationThreshold; threeDSEnabled; noThreeDSAttempt; checkoutComPaymentEventTypes(code) ; includeBillingDescriptor; billingDescriptorName; billingDescriptorCity - ; merchantConfiguration-$siteUid ; $secretKey ; $publicKey ; $privateSharedKey ; $nasSecretKey ; $nasPublicKey ; $nasSignatureKey ; $nasAuthorisationHeaderKey ; test ; authorize_and_capture ; true ; klarnaConfig ; 0.01 ; false ; true ; payment_approved, payment_voided, payment_void_declined, payment_captured, payment_capture_declined, payment_refunded, payment_refund_declined, payment_pending, payment_declined, payment_expired, payment_canceled, payment_returned ; true ; $siteUid ; INTERNET +INSERT_UPDATE CheckoutComMerchantConfiguration; code[unique = true] ; secretKey ; publicKey ; privateSharedKey ; nasSecretKey ; nasPublicKey ; nasSignatureKey ; nasAuthorisationHeaderKey ; environment(code); paymentAction(code) ; reviewTransactionsAtRisk; klarnaConfiguration(&klarnaConfigurationId); authorisationAmountValidationThreshold; threeDSEnabled; noThreeDSAttempt; checkoutComPaymentEventTypes(code) ; includeBillingDescriptor; billingDescriptorName; billingDescriptorCity + ; merchantConfiguration-$siteUid ; $nasSecretKey ; $nasPublicKey ; $privateSharedKey ; $nasSecretKey ; $nasPublicKey ; $nasSignatureKey ; $nasAuthorisationHeaderKey ; test ; authorize_and_capture ; true ; klarnaConfig ; 0.01 ; false ; true ; payment_approved, payment_voided, payment_void_declined, payment_captured, payment_capture_declined, payment_refunded, payment_refund_declined, payment_pending, payment_declined, payment_expired, payment_canceled, payment_returned ; true ; $siteUid ; INTERNET # Set merchant configuration and payment redirect urls to the site INSERT_UPDATE BaseSite ; uid[unique = true]; checkoutComMerchantConfiguration(code); diff --git a/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/apmConfiguration/CheckoutComApmConfigurationTest.groovy b/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/apmConfiguration/CheckoutComApmConfigurationTest.groovy index b1396dc..f7b10e1 100644 --- a/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/apmConfiguration/CheckoutComApmConfigurationTest.groovy +++ b/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/apmConfiguration/CheckoutComApmConfigurationTest.groovy @@ -17,6 +17,7 @@ class CheckoutComApmConfigurationTest extends AbstractCheckoutComPaymentsTest { def customer = customerWithCart[0] def cart = customerWithCart[1] createBillingAddress(customer.id, cart.code) + //useNAS() when: "A request to get all available apms for the cart is made" def response = restClient.get( @@ -29,11 +30,11 @@ class CheckoutComApmConfigurationTest extends AbstractCheckoutComPaymentsTest { if (isNotEmpty(data) && isNotEmpty(data.errors)) println(data) status == SC_OK CollectionUtils.isNotEmpty(responseData.availableApmConfigurations) - def paypal = responseData.availableApmConfigurations.find { it.code == "PAYPAL" } - paypal.name == "PayPal" - paypal.isRedirect == true - paypal.isUserDataRequired == false - paypal.media != null + def apm = responseData.availableApmConfigurations.find { it.code == "GIROPAY" } + apm.name == "Giropay" + apm.isRedirect == true + apm.isUserDataRequired == false + apm.media != null } } } diff --git a/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/apmConfiguration/CheckoutComKlarnaTest.groovy b/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/apmConfiguration/CheckoutComKlarnaTest.groovy index b947183..d49bbeb 100644 --- a/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/apmConfiguration/CheckoutComKlarnaTest.groovy +++ b/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/apmConfiguration/CheckoutComKlarnaTest.groovy @@ -21,7 +21,6 @@ class CheckoutComKlarnaTest extends AbstractCheckoutComPaymentsTest { addProductToCartOnline(restClient, customer, cart.code, PRODUCT_POWER_SHOT_A480) setDeliveryModeForCart(restClient, customer, cart.code, DELIVERY_STANDARD, JSON) createBillingAddress(customer.id, cart.code) - useABC() when: "API call to get klarna token data is made" def response = restClient.get( @@ -33,7 +32,8 @@ class CheckoutComKlarnaTest extends AbstractCheckoutComPaymentsTest { if (isNotEmpty(data) && isNotEmpty(data.errors)) println(data) status == SC_OK isNotEmpty(data.clientToken) - isNotEmpty(data.paymentMethodCategories) + isNotEmpty(data.paymentContext) + isNotEmpty(data.sessionId) data.success == true data.instanceId == "e2yCheckoutCom" } diff --git a/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/orders/CheckoutComAPMOrdersTest.groovy b/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/orders/CheckoutComAPMOrdersTest.groovy index abf5086..6fb147c 100644 --- a/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/orders/CheckoutComAPMOrdersTest.groovy +++ b/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/orders/CheckoutComAPMOrdersTest.groovy @@ -8,65 +8,12 @@ import spock.lang.Unroll import static com.checkout.hybris.core.payment.enums.CheckoutComPaymentType.* import static de.hybris.platform.commercewebservicestests.test.groovy.webservicetests.http.ContentType.JSON import static de.hybris.platform.commercewebservicestests.test.groovy.webservicetests.http.ContentType.XML -import static org.apache.http.HttpStatus.SC_BAD_REQUEST import static org.apache.http.HttpStatus.SC_CREATED @ManualTest @Unroll class CheckoutComAPMOrdersTest extends AbstractCheckoutComPaymentsTest { - def "Authorized customer gets redirect url when places an order in ABC Site with #currency currency with a billing address from #billingCountry with #APM: #format"() { - given: "authorized customer" - def customerWithCart = createAndAuthorizeCustomerWithCart(restClient, format) - def customer = customerWithCart[0] - def cart = customerWithCart[1] - def address = createAddressWithOptions(restClient, customer) - setDeliveryAddressForCart(restClient, customer, cart.code, address.id, format) - addProductToCartOnline(restClient, customer, cart.code, PRODUCT_POWER_SHOT_A480) - setDeliveryModeForCart(restClient, customer, cart.code, DELIVERY_STANDARD, format) - createBillingAddress(customer.id, cart.code, billingAddressPostBody) - createAPMPaymentInfo(restClient, customer, cart.code, paymentInfoPostBody) - useABC() - - when: "authorized customer places order" - def response = placeCheckoutComOrder(customer, cart.code, currency, format) - - then: "customer is redirected to #APM" - with(response) { - if (isNotEmpty(data) && isNotEmpty(data.errors)) println(data) - status == SC_CREATED - isNotEmpty(data.redirectUrl) - StringUtils.contains((String) data.redirectUrl, getConfigurationProperty(redirectKey)) - } - - where: - format | APM | currency | billingCountry | paymentInfoPostBody | billingAddressPostBody | redirectKey - JSON | MULTIBANCO | EUR_CURRENCY_CODE | 'Portugal' | DEFAULT_CHECKOUT_MULTIBANCO_PAYMENT_JSON | PORTUGAL_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.multibanco.sandbox' - XML | MULTIBANCO | EUR_CURRENCY_CODE | 'Portugal' | DEFAULT_CHECKOUT_MULTIBANCO_PAYMENT_JSON | PORTUGAL_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.multibanco.sandbox' - JSON | PAYPAL | EUR_CURRENCY_CODE | 'Germany' | DEFAULT_CHECKOUT_PAYPAL_PAYMENT_JSON | DEFAULT_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.paypal.sandbox' - XML | PAYPAL | EUR_CURRENCY_CODE | 'Germany' | DEFAULT_CHECKOUT_PAYPAL_PAYMENT_JSON | DEFAULT_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.paypal.sandbox' - JSON | SOFORT | EUR_CURRENCY_CODE | 'Germany' | DEFAULT_CHECKOUT_SOFORT_PAYMENT_JSON | DEFAULT_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.sofort.sandbox' - XML | SOFORT | EUR_CURRENCY_CODE | 'Germany' | DEFAULT_CHECKOUT_SOFORT_PAYMENT_JSON | DEFAULT_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.sofort.sandbox' - JSON | BANCONTACT | EUR_CURRENCY_CODE | 'Belgium' | DEFAULT_CHECKOUT_BANCONTACT_PAYMENT_JSON | BELGIUM_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.bancontact.sandbox' - XML | BANCONTACT | EUR_CURRENCY_CODE | 'Belgium' | DEFAULT_CHECKOUT_BANCONTACT_PAYMENT_JSON | BELGIUM_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.bancontact.sandbox' - JSON | KNET | KWD_CURRENCY_CODE | 'Kuwait' | DEFAULT_CHECKOUT_KNET_PAYMENT_JSON | KW_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.knet.sandbox' - XML | KNET | KWD_CURRENCY_CODE | 'Kuwait' | DEFAULT_CHECKOUT_KNET_PAYMENT_JSON | KW_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.knet.sandbox' - JSON | POLI | NZD_CURRENCY_CODE | 'New Zealand' | DEFAULT_CHECKOUT_POLI_PAYMENT_JSON | NZ_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.poli.nz.sandbox' - XML | POLI | NZD_CURRENCY_CODE | 'New Zealand' | DEFAULT_CHECKOUT_POLI_PAYMENT_JSON | NZ_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.poli.nz.sandbox' - JSON | QPAY | QAR_CURRENCY_CODE | 'Qatar' | DEFAULT_CHECKOUT_QPAY_PAYMENT_JSON | QATAR_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.qpay.sandbox' - XML | QPAY | QAR_CURRENCY_CODE | 'Qatar' | DEFAULT_CHECKOUT_QPAY_PAYMENT_JSON | QATAR_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.qpay.sandbox' - JSON | ALIPAY | USD_CURRENCY_CODE | 'USA' | DEFAULT_CHECKOUT_ALIPAY_PAYMENT_JSON | US_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.alipay.sandbox' - XML | ALIPAY | USD_CURRENCY_CODE | 'USA' | DEFAULT_CHECKOUT_ALIPAY_PAYMENT_JSON | US_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.alipay.sandbox' - JSON | ALIPAY | USD_CURRENCY_CODE | 'China' | DEFAULT_CHECKOUT_ALIPAY_PAYMENT_JSON | CN_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.alipay.sandbox' - XML | ALIPAY | USD_CURRENCY_CODE | 'China' | DEFAULT_CHECKOUT_ALIPAY_PAYMENT_JSON | CN_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.alipay.sandbox' - JSON | P24 | EUR_CURRENCY_CODE | 'Germany' | DEFAULT_CHECKOUT_P24_PAYMENT_JSON | POLAND_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.p24.sandbox' - XML | P24 | EUR_CURRENCY_CODE | 'Germany' | DEFAULT_CHECKOUT_P24_PAYMENT_JSON | POLAND_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.p24.sandbox' - JSON | EPS | EUR_CURRENCY_CODE | 'Austria' | DEFAULT_CHECKOUT_EPS_PAYMENT_JSON | AT_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.eps.sandbox' - XML | EPS | EUR_CURRENCY_CODE | 'Austria' | DEFAULT_CHECKOUT_EPS_PAYMENT_JSON | AT_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.eps.sandbox' - //JSON | OXXO | MXN_CURRENCY_CODE | 'Mexico' | DEFAULT_CHECKOUT_OXXO_PAYMENT_JSON | MX_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.oxxo.sandbox' - //XML | OXXO | MXN_CURRENCY_CODE | 'Mexico' | DEFAULT_CHECKOUT_OXXO_PAYMENT_JSON | MX_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.oxxo.sandbox' - } - def "Authorized customer gets redirect url when places an order in NAS Site with #currency currency with a billing address from #billingCountry with #APM: #format"() { given: "authorized customer" def customerWithCart = createAndAuthorizeCustomerWithCart(restClient, format) @@ -78,7 +25,6 @@ class CheckoutComAPMOrdersTest extends AbstractCheckoutComPaymentsTest { setDeliveryModeForCart(restClient, customer, cart.code, DELIVERY_STANDARD, format) createBillingAddress(customer.id, cart.code, billingAddressPostBody) createAPMPaymentInfo(restClient, customer, cart.code, paymentInfoPostBody) - useNAS() when: "authorized customer places order" def response = placeCheckoutComOrder(customer, cart.code, currency, format) @@ -95,8 +41,6 @@ class CheckoutComAPMOrdersTest extends AbstractCheckoutComPaymentsTest { format | APM | currency | billingCountry | paymentInfoPostBody | billingAddressPostBody | redirectKey JSON | GIROPAY | EUR_CURRENCY_CODE | 'Germany' | DEFAULT_CHECKOUT_GIROPAY_PAYMENT_JSON | DEFAULT_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.giropay.sandbox' XML | GIROPAY | EUR_CURRENCY_CODE | 'Germany' | DEFAULT_CHECKOUT_GIROPAY_PAYMENT_JSON | DEFAULT_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.giropay.sandbox' - JSON | SOFORT | EUR_CURRENCY_CODE | 'Germany' | DEFAULT_CHECKOUT_SOFORT_PAYMENT_JSON | DEFAULT_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.sofort.nas.sandbox' - XML | SOFORT | EUR_CURRENCY_CODE | 'Germany' | DEFAULT_CHECKOUT_SOFORT_PAYMENT_JSON | DEFAULT_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.sofort.nas.sandbox' JSON | P24 | EUR_CURRENCY_CODE | 'Germany' | DEFAULT_CHECKOUT_P24_PAYMENT_JSON | POLAND_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.p24.sandbox' XML | P24 | EUR_CURRENCY_CODE | 'Germany' | DEFAULT_CHECKOUT_P24_PAYMENT_JSON | POLAND_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.p24.sandbox' JSON | IDEAL | EUR_CURRENCY_CODE | 'Netherlands' | DEFAULT_CHECKOUT_IDEAL_PAYMENT_JSON | NL_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.ideal.sandbox' @@ -109,43 +53,6 @@ class CheckoutComAPMOrdersTest extends AbstractCheckoutComPaymentsTest { XML | MULTIBANCO | EUR_CURRENCY_CODE | 'Portugal' | DEFAULT_CHECKOUT_MULTIBANCO_PAYMENT_JSON | PORTUGAL_BILLING_ADDRESS_JSON | 'checkoutocctests.checkout.multibanco.sandbox' } - def "Authorized customer places an order in ABC site with #currency currency with a billing address from #billingCountry with #APM: #format"() { - given: "authorized customer" - def customerWithCart = createAndAuthorizeCustomerWithCart(restClient, format) - def customer = customerWithCart[0] - def cart = customerWithCart[1] - def address = createAddressWithOptions(restClient, customer) - setDeliveryAddressForCart(restClient, customer, cart.code, address.id, format) - addProductToCartOnline(restClient, customer, cart.code, PRODUCT_POWER_SHOT_A480) - setDeliveryModeForCart(restClient, customer, cart.code, DELIVERY_STANDARD, format) - createBillingAddress(customer.id, cart.code, billingAddressPostBody) - createAPMPaymentInfo(restClient, customer, cart.code, paymentInfoPostBody) - useABC() - - when: "authorized customer places order" - def response = placeCheckoutComOrder(customer, cart.code, currency, format) - - then: "the order is placed" - with(response) { - if (isNotEmpty(data) && isNotEmpty(data.errors)) println(data) - status == SC_CREATED - isNotEmpty(data.code) - data.paymentType == APM.name() - if (data.paymentType == BENEFITPAY.name()) { - isNotEmpty(data.qrCodeData) - } - } - - where: - format | APM | currency | billingCountry | paymentInfoPostBody | billingAddressPostBody - JSON | FAWRY | EGP_CURRENCY_CODE | 'Egypt' | DEFAULT_CHECKOUT_FAWRY_PAYMENT_JSON | DEFAULT_BILLING_ADDRESS_JSON - XML | FAWRY | EGP_CURRENCY_CODE | 'Egypt' | DEFAULT_CHECKOUT_FAWRY_PAYMENT_JSON | DEFAULT_BILLING_ADDRESS_JSON - //JSON | BENEFITPAY | BHD_CURRENCY_CODE | 'Bahrain' | DEFAULT_CHECKOUT_BENEFIT_PAYMENT_JSON | BH_BILLING_ADDRESS_JSON - //XML | BENEFITPAY | BHD_CURRENCY_CODE | 'Bahrain' | DEFAULT_CHECKOUT_BENEFIT_PAYMENT_JSON | BH_BILLING_ADDRESS_JSON - JSON | SEPA | EUR_CURRENCY_CODE | 'Austria' | DEFAULT_CHECKOUT_SEPA_PAYMENT_JSON | AT_BILLING_ADDRESS_JSON - XML | SEPA | EUR_CURRENCY_CODE | 'Austria' | DEFAULT_CHECKOUT_SEPA_PAYMENT_JSON | AT_BILLING_ADDRESS_JSON - } - def "Authorized customer places an order in NAS site with #currency currency with a billing address from #billingCountry with #APM: #format"() { given: "authorized customer" def customerWithCart = createAndAuthorizeCustomerWithCart(restClient, format) @@ -157,7 +64,6 @@ class CheckoutComAPMOrdersTest extends AbstractCheckoutComPaymentsTest { setDeliveryModeForCart(restClient, customer, cart.code, DELIVERY_STANDARD, format) createBillingAddress(customer.id, cart.code, billingAddressPostBody) createAPMPaymentInfo(restClient, customer, cart.code, paymentInfoPostBody) - useNAS() when: "authorized customer places order" def response = placeCheckoutComOrder(customer, cart.code, currency, format) @@ -179,54 +85,4 @@ class CheckoutComAPMOrdersTest extends AbstractCheckoutComPaymentsTest { XML | FAWRY | EGP_CURRENCY_CODE | 'Egypt' | DEFAULT_CHECKOUT_FAWRY_PAYMENT_JSON | DEFAULT_BILLING_ADDRESS_JSON } - def "Authorized customer can't place an order with #currency currency with a billing address from #billingCountry with #APM: #format"() { - given: "authorized customer" - def customerWithCart = createAndAuthorizeCustomerWithCart(restClient, format) - def customer = customerWithCart[0] - def cart = customerWithCart[1] - def address = createAddressWithOptions(restClient, customer) - setDeliveryAddressForCart(restClient, customer, cart.code, address.id, format) - addProductToCartOnline(restClient, customer, cart.code, PRODUCT_POWER_SHOT_A480) - setDeliveryModeForCart(restClient, customer, cart.code, DELIVERY_STANDARD, format) - createBillingAddress(customer.id, cart.code, billingAddressPostBody) - createAPMPaymentInfo(restClient, customer, cart.code, paymentInfoPostBody) - useABC() - - when: "authorized customer places order" - def response = placeCheckoutComOrder(customer, cart.code, currency, format) - - then: "error message is thrown" - with(response) { - status == SC_BAD_REQUEST - data.errors[0].message == 'The application has encountered an error' - data.errors[0].type == 'PaymentAuthorizationError' - } - - where: - format | APM | currency | billingCountry | paymentInfoPostBody | billingAddressPostBody - JSON | MULTIBANCO | EGP_CURRENCY_CODE | 'Portugal' | DEFAULT_CHECKOUT_MULTIBANCO_PAYMENT_JSON | PORTUGAL_BILLING_ADDRESS_JSON - XML | MULTIBANCO | EGP_CURRENCY_CODE | 'Portugal' | DEFAULT_CHECKOUT_MULTIBANCO_PAYMENT_JSON | PORTUGAL_BILLING_ADDRESS_JSON - JSON | MULTIBANCO | EUR_CURRENCY_CODE | 'Germany' | DEFAULT_CHECKOUT_MULTIBANCO_PAYMENT_JSON | DEFAULT_BILLING_ADDRESS_JSON - XML | MULTIBANCO | EUR_CURRENCY_CODE | 'Germany' | DEFAULT_CHECKOUT_MULTIBANCO_PAYMENT_JSON | DEFAULT_BILLING_ADDRESS_JSON - JSON | BANCONTACT | EGP_CURRENCY_CODE | 'Belgium' | DEFAULT_CHECKOUT_BANCONTACT_PAYMENT_JSON | BELGIUM_BILLING_ADDRESS_JSON - XML | BANCONTACT | EGP_CURRENCY_CODE | 'Belgium' | DEFAULT_CHECKOUT_BANCONTACT_PAYMENT_JSON | BELGIUM_BILLING_ADDRESS_JSON - JSON | BANCONTACT | EGP_CURRENCY_CODE | 'Germany' | DEFAULT_CHECKOUT_BANCONTACT_PAYMENT_JSON | DEFAULT_BILLING_ADDRESS_JSON - XML | BANCONTACT | EGP_CURRENCY_CODE | 'Germany' | DEFAULT_CHECKOUT_BANCONTACT_PAYMENT_JSON | DEFAULT_BILLING_ADDRESS_JSON - JSON | KNET | EUR_CURRENCY_CODE | 'Kuwait' | DEFAULT_CHECKOUT_KNET_PAYMENT_JSON | KW_BILLING_ADDRESS_JSON - XML | KNET | EUR_CURRENCY_CODE | 'Kuwait' | DEFAULT_CHECKOUT_KNET_PAYMENT_JSON | KW_BILLING_ADDRESS_JSON - JSON | BENEFITPAY | EGP_CURRENCY_CODE | 'Bahrain' | DEFAULT_CHECKOUT_BENEFIT_PAYMENT_JSON | BH_BILLING_ADDRESS_JSON - XML | BENEFITPAY | EGP_CURRENCY_CODE | 'Bahrain' | DEFAULT_CHECKOUT_BENEFIT_PAYMENT_JSON | BH_BILLING_ADDRESS_JSON - JSON | POLI | EUR_CURRENCY_CODE | 'New Zealand' | DEFAULT_CHECKOUT_POLI_PAYMENT_JSON | NZ_BILLING_ADDRESS_JSON - XML | POLI | EUR_CURRENCY_CODE | 'New Zealand' | DEFAULT_CHECKOUT_POLI_PAYMENT_JSON | NZ_BILLING_ADDRESS_JSON - JSON | ALIPAY | EUR_CURRENCY_CODE | 'China' | DEFAULT_CHECKOUT_ALIPAY_PAYMENT_JSON | CN_BILLING_ADDRESS_JSON - XML | ALIPAY | EUR_CURRENCY_CODE | 'China' | DEFAULT_CHECKOUT_ALIPAY_PAYMENT_JSON | CN_BILLING_ADDRESS_JSON - JSON | SEPA | USD_CURRENCY_CODE | 'Austria' | DEFAULT_CHECKOUT_SEPA_PAYMENT_JSON | AT_BILLING_ADDRESS_JSON - XML | SEPA | USD_CURRENCY_CODE | 'Austria' | DEFAULT_CHECKOUT_SEPA_PAYMENT_JSON | AT_BILLING_ADDRESS_JSON - JSON | IDEAL | AUD_CURRENCY_CODE | 'Netherlands' | DEFAULT_CHECKOUT_IDEAL_PAYMENT_JSON | NL_BILLING_ADDRESS_JSON - XML | IDEAL | AUD_CURRENCY_CODE | 'Netherlands' | DEFAULT_CHECKOUT_IDEAL_PAYMENT_JSON | NL_BILLING_ADDRESS_JSON - JSON | EPS | AUD_CURRENCY_CODE | 'Austria' | DEFAULT_CHECKOUT_EPS_PAYMENT_JSON | AT_BILLING_ADDRESS_JSON - XML | EPS | AUD_CURRENCY_CODE | 'Austria' | DEFAULT_CHECKOUT_EPS_PAYMENT_JSON | AT_BILLING_ADDRESS_JSON - JSON | OXXO | EUR_CURRENCY_CODE | 'Mexico' | DEFAULT_CHECKOUT_OXXO_PAYMENT_JSON | MX_BILLING_ADDRESS_JSON - XML | OXXO | EUR_CURRENCY_CODE | 'Mexico' | DEFAULT_CHECKOUT_OXXO_PAYMENT_JSON | MX_BILLING_ADDRESS_JSON - } } diff --git a/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/orders/CheckoutComCCOrdersTest.groovy b/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/orders/CheckoutComCCOrdersTest.groovy index 7f06caa..294fbe9 100644 --- a/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/orders/CheckoutComCCOrdersTest.groovy +++ b/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/orders/CheckoutComCCOrdersTest.groovy @@ -148,32 +148,7 @@ class CheckoutComCCOrdersTest extends AbstractCheckoutComPaymentsTest { format << [XML, JSON] } - def "Authorized customer places an order with MADA 3ds flow card with 3DS Active: #format"() { - given: "an authorized customer" - def customerWithCart = createAndAuthorizeCustomerWithCart(restClient, format) - def customer = customerWithCart[0] - def cart = customerWithCart[1] - def address = createAddressWithOptions(restClient, customer) - setDeliveryAddressForCart(restClient, customer, cart.code, address.id, format) - addProductToCartOnline(restClient, customer, cart.code, PRODUCT_POWER_SHOT_A480) - setDeliveryModeForCart(restClient, customer, cart.code, DELIVERY_STANDARD, format) - createBillingAddress(customer.id, cart.code) - createPaymentInfo(restClient, customer, cart.code, MADA_3DS_CHECKOUT_CC_PAYMENT_JSON, MADA_3DS_GET_CC_TOKEN_JSON) - activate3ds() - when: "authorized customer places order" - def response = placeCheckoutComOrder(customer, cart.code, EUR_CURRENCY_CODE, format) - - then: "redirect URL is returned" - with(response) { - if (isNotEmpty(data) && isNotEmpty(data.errors)) println(data) - status == SC_CREATED - isNotEmpty(data.redirectUrl) - } - - where: - format << [XML, JSON] - } def "Authorized customer places an order with MADA card 3DS flow with 3DS Inactive: #format"() { given: "an authorized customer" @@ -185,7 +160,7 @@ class CheckoutComCCOrdersTest extends AbstractCheckoutComPaymentsTest { addProductToCartOnline(restClient, customer, cart.code, PRODUCT_POWER_SHOT_A480) setDeliveryModeForCart(restClient, customer, cart.code, DELIVERY_STANDARD, format) createBillingAddress(customer.id, cart.code) - createPaymentInfo(restClient, customer, cart.code, MADA_3DS_CHECKOUT_CC_PAYMENT_JSON, MADA_3DS_GET_CC_TOKEN_JSON) + createPaymentInfo(restClient, customer, cart.code, MADA_3DS_CHECKOUT_CC_PAYMENT_JSON, MADA_GET_CC_TOKEN_JSON) deactivate3ds() when: "authorized customer places order" @@ -202,33 +177,6 @@ class CheckoutComCCOrdersTest extends AbstractCheckoutComPaymentsTest { format << [XML, JSON] } - def "Authorized customer places an order with MADA frictionless flow card with 3DS Active: #format"() { - given: "an authorized customer" - def customerWithCart = createAndAuthorizeCustomerWithCart(restClient, format) - def customer = customerWithCart[0] - def cart = customerWithCart[1] - def address = createAddressWithOptions(restClient, customer) - setDeliveryAddressForCart(restClient, customer, cart.code, address.id, format) - addProductToCartOnline(restClient, customer, cart.code, PRODUCT_POWER_SHOT_A480) - setDeliveryModeForCart(restClient, customer, cart.code, DELIVERY_STANDARD, format) - createBillingAddress(customer.id, cart.code) - createPaymentInfo(restClient, customer, cart.code, MADA_FRICTIONLESS_CHECKOUT_CC_PAYMENT_JSON, MADA_FRICTIONLESS_GET_CC_TOKEN_JSON) - activate3ds() - - when: "authorized customer places order" - def response = placeCheckoutComOrder(customer, cart.code, EUR_CURRENCY_CODE, format) - - then: "redirect URL is returned" - with(response) { - if (isNotEmpty(data) && isNotEmpty(data.errors)) println(data) - status == SC_CREATED - isNotEmpty(data.redirectUrl) - } - - where: - format << [XML, JSON] - } - def "Authorized customer places an order with MADA frictionless flow with 3DS Inactive: #format"() { given: "an authorized customer" def customerWithCart = createAndAuthorizeCustomerWithCart(restClient, format) @@ -343,7 +291,7 @@ class CheckoutComCCOrdersTest extends AbstractCheckoutComPaymentsTest { given: "a guest customer" def userGuid = getGuestUid() def cart = prepareCartForGuestOrder(restClient, userGuid, format) - createPaymentInfo(restClient, ANONYMOUS_USER, cart.guid, MADA_3DS_CHECKOUT_CC_PAYMENT_JSON, MADA_3DS_GET_CC_TOKEN_JSON) + createPaymentInfo(restClient, ANONYMOUS_USER, cart.guid, MADA_3DS_CHECKOUT_CC_PAYMENT_JSON, MADA_GET_CC_TOKEN_JSON) activate3ds() when: "guest customer places order" @@ -364,7 +312,7 @@ class CheckoutComCCOrdersTest extends AbstractCheckoutComPaymentsTest { given: "a guest customer" def userGuid = getGuestUid() def cart = prepareCartForGuestOrder(restClient, userGuid, format) - createPaymentInfo(restClient, ANONYMOUS_USER, cart.guid, MADA_3DS_CHECKOUT_CC_PAYMENT_JSON, MADA_3DS_GET_CC_TOKEN_JSON) + createPaymentInfo(restClient, ANONYMOUS_USER, cart.guid, MADA_3DS_CHECKOUT_CC_PAYMENT_JSON, MADA_GET_CC_TOKEN_JSON) deactivate3ds() when: "guest customer places order" diff --git a/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/paymentdetails/AbstractCheckoutComPaymentsTest.groovy b/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/paymentdetails/AbstractCheckoutComPaymentsTest.groovy index 9765bcc..edac345 100644 --- a/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/paymentdetails/AbstractCheckoutComPaymentsTest.groovy +++ b/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/paymentdetails/AbstractCheckoutComPaymentsTest.groovy @@ -35,9 +35,9 @@ abstract class AbstractCheckoutComPaymentsTest extends AbstractCartTest { protected static final String DEFAULT_CHECKOUT_CC_PAYMENT_JSON = "{\"accountHolderName\" : \"John Doe\", \"cardNumber\" : \"4242424242424242\", \"cardType\" : {\"code\":\"visa\"}, \"expiryMonth\" : \"2\", \"expiryYear\" : \"2050\", \"defaultPayment\" : true, \"saved\" : true, \"cardBin\" : \"424242\", \"paymentToken\" : \"paymentToken-mock\", \"type\" : \"CARD\", \"saved\" : \"true\"}" protected static final String DEFAULT_CHECKOUT_CC_PAYMENT_XML = "John Doe4242424242424242visa22050truetrue4111111paymentToken-mockCARDtrue" - protected static final String INVALID_CHECKOUT_CC_PAYMENT_JSON = "{\"accountHolderName\" : \"John Doe\", \"cardNumber\" : \"4111111111111111\", \"cardType\" : {\"code\":\"visa\"}, \"expiryMonth\" : \"2\", \"expiryYear\" : \"2050\", \"defaultPayment\" : true, \"saved\" : true, \"cardBin\" : \"424242\", \"paymentToken\" : \"paymentToken-mock\", \"type\" : \"CARD\", \"saved\" : \"true\"}" - protected static final String BAD_CHECKOUT_CC_PAYMENT_JSON = "{\"cardNumber\" : \"4111111111111111\", \"cardType\" : {\"code\":\"visa\"}, \"expiryMonth\" : \"01\", \"expiryYear\" : \"2117\", \"defaultPayment\" : true, \"saved\" : true, \"cardBin\" : \"424242\", \"type\" : \"CARD\", \"saved\" : \"true\"}" - protected static final String BAD_CHECKOUT_CC_PAYMENT_XML = "John Doe4111111111111111visa12117truetrue4111111CARDtrue" + protected static final String INVALID_CHECKOUT_CC_PAYMENT_JSON = "{\"accountHolderName\" : \"John Doe\", \"cardNumber\" : \"4024007103573027\", \"cardType\" : {\"code\":\"visa\"}, \"expiryMonth\" : \"2\", \"expiryYear\" : \"2050\", \"defaultPayment\" : true, \"saved\" : true, \"cardBin\" : \"424242\", \"paymentToken\" : \"paymentToken-mock\", \"type\" : \"CARD\", \"saved\" : \"true\"}" + protected static final String BAD_CHECKOUT_CC_PAYMENT_JSON = "{\"cardNumber\" : \"4024007103573027\", \"cardType\" : {\"code\":\"visa\"}, \"expiryMonth\" : \"01\", \"expiryYear\" : \"2117\", \"defaultPayment\" : true, \"saved\" : true, \"cardBin\" : \"424242\", \"type\" : \"CARD\", \"saved\" : \"true\"}" + protected static final String BAD_CHECKOUT_CC_PAYMENT_XML = "John Doe4024007103573027visa12117truetrue4111111CARDtrue" protected static final String MADA_3DS_CHECKOUT_CC_PAYMENT_JSON = "{\"accountHolderName\" : \"John Doe\", \"cardNumber\" : \"5385308360135181\", \"cardType\" : {\"code\":\"visa\"}, \"expiryMonth\" : \"2\", \"expiryYear\" : \"2050\", \"defaultPayment\" : true, \"saved\" : true, \"cardBin\" : \"538530\", \"paymentToken\" : \"paymentToken-mock\", \"type\" : \"CARD\", \"saved\" : \"true\"}" protected static final String MADA_FRICTIONLESS_CHECKOUT_CC_PAYMENT_JSON = "{\"accountHolderName\" : \"John Doe\", \"cardNumber\" : \"4485040371536584\", \"cardType\" : {\"code\":\"visa\"}, \"expiryMonth\" : \"2\", \"expiryYear\" : \"2050\", \"defaultPayment\" : true, \"saved\" : true, \"cardBin\" : \"448504\", \"paymentToken\" : \"paymentToken-mock\", \"type\" : \"CARD\", \"saved\" : \"true\"}" @@ -131,9 +131,9 @@ abstract class AbstractCheckoutComPaymentsTest extends AbstractCartTest { protected static final String EMPTY_CKO_SESSION_ID_JSON = "{}" protected static final String DEFAULT_GET_CC_TOKEN_JSON = "{\"type\":\"card\",\"number\":\"4242424242424242\",\"expiry_month\":02,\"expiry_year\":2050,\"cvv\":\"100\",\"name\":\"Sven Haiges\",\"billing_address\":{},\"phone\":{},\"requestSource\":\"JS\"}" - protected static final String MADA_3DS_GET_CC_TOKEN_JSON = "{\"type\":\"card\",\"number\":\"5385308360135181\",\"expiry_month\":02,\"expiry_year\":2050,\"cvv\":\"100\",\"name\":\"Sven Haiges\",\"billing_address\":{},\"phone\":{},\"requestSource\":\"JS\"}" - protected static final String MADA_FRICTIONLESS_GET_CC_TOKEN_JSON = "{\"type\":\"card\",\"number\":\"4485040371536584\",\"expiry_month\":02,\"expiry_year\":2050,\"cvv\":\"100\",\"name\":\"Sven Haiges\",\"billing_address\":{},\"phone\":{},\"requestSource\":\"JS\"}" - protected static final String INVALID_GET_CC_TOKEN_JSON = "{\"type\":\"card\",\"number\":\"4111111111111111\",\"expiry_month\":02,\"expiry_year\":2050,\"cvv\":\"321\",\"name\":\"Sven Haiges\",\"billing_address\":{},\"phone\":{},\"requestSource\":\"JS\"}" + protected static final String MADA_GET_CC_TOKEN_JSON = "{\"type\":\"card\",\"number\":\"5541805721646120\",\"expiry_month\":02,\"expiry_year\":2050,\"cvv\":\"100\",\"name\":\"Sven Haiges\",\"billing_address\":{},\"phone\":{},\"requestSource\":\"JS\"}" + protected static final String MADA_FRICTIONLESS_GET_CC_TOKEN_JSON = "{\"type\":\"card\",\"number\":\"4407954943022953\",\"expiry_month\":02,\"expiry_year\":2050,\"cvv\":\"100\",\"name\":\"Sven Haiges\",\"billing_address\":{},\"phone\":{},\"requestSource\":\"JS\"}" + protected static final String INVALID_GET_CC_TOKEN_JSON = "{\"type\":\"card\",\"number\":\"4024007103573027\",\"expiry_month\":02,\"expiry_year\":2050,\"cvv\":\"321\",\"name\":\"Sven Haiges\",\"billing_address\":{},\"phone\":{},\"requestSource\":\"JS\"}" protected static final String SITE_UID = "wsTest" @@ -245,7 +245,7 @@ abstract class AbstractCheckoutComPaymentsTest extends AbstractCartTest { def response = client.post( path: getConfigurationProperty('checkoutocctests.checkout.sandbox.tokens.path'), body: paymentInfo, - headers: ["Authorization": getConfigurationProperty("checkout.public.key")], + headers: ["Authorization": getConfigurationProperty("checkout.nas.public.key")], requestContentType: JSON) with(response) { if (isNotEmpty(data) && isNotEmpty(data.errors)) println(data) diff --git a/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/paymentdetails/CheckoutComAPMPaymentsTest.groovy b/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/paymentdetails/CheckoutComAPMPaymentsTest.groovy index 030baee..0aa3b43 100644 --- a/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/paymentdetails/CheckoutComAPMPaymentsTest.groovy +++ b/hybris/bin/modules/checkoutcom/checkoutocctests/testsrc/com/checkout/hybris/occtests/test/groovy/v2/spock/paymentdetails/CheckoutComAPMPaymentsTest.groovy @@ -67,7 +67,7 @@ class CheckoutComAPMPaymentsTest extends AbstractCheckoutComPaymentsTest { XML | OXXO | DEFAULT_CHECKOUT_OXXO_PAYMENT_XML } - def "User can not create #APM payment info with invalid #subjectAttr when request: #requestFormat"() { + /**def "User can not create #APM payment info with invalid #subjectAttr when request: #requestFormat"() { given: "a logged in user with created cart" def customerWithCart = createAndAuthorizeCustomerWithCart(restClient) def customer = customerWithCart[0] @@ -110,5 +110,5 @@ class CheckoutComAPMPaymentsTest extends AbstractCheckoutComPaymentsTest { XML | OXXO | MISSING_DOCUMENT_CHECKOUT_OXXO_PAYMENT_XML | 'document' | 'Document is required for this payment' JSON | OXXO | WRONG_DOCUMENT_CHECKOUT_OXXO_PAYMENT_JSON | 'document' | 'Document must have 18 alphanumeric characters' XML | OXXO | WRONG_DOCUMENT_CHECKOUT_OXXO_PAYMENT_XML | 'document' | 'Document must have 18 alphanumeric characters' - } + }**/ } diff --git a/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/project.properties b/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/project.properties index e80c3bf..b02f36c 100644 --- a/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/project.properties +++ b/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/project.properties @@ -1,4 +1,4 @@ -#Tue, 28 May 2024 13:17:07 +0000 +#Tue, 18 Jun 2024 10:08:08 +0000 # ----------------------------------------------------------------------- # Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. # ----------------------------------------------------------------------- diff --git a/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/resources/checkoutsampledataaddon.build.number b/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/resources/checkoutsampledataaddon.build.number index 971f38d..adac92a 100644 --- a/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/resources/checkoutsampledataaddon.build.number +++ b/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/resources/checkoutsampledataaddon.build.number @@ -1,11 +1,11 @@ #Ant properties -#Tue May 28 13:21:41 GMT 2024 +#Tue Jun 18 10:12:56 GMT 2024 version.api=2211 vendor=hybris group.id=de.hybris.platform name=checkoutsampledataaddon description=checkoutsampledataaddon -builddate=20240528 1321 +builddate=20240618 1012 releasedate=20240307 1540 version=2211.20 module.name=platform-module diff --git a/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/resources/checkoutsampledataaddon/import/common/common-addon-extra.impex b/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/resources/checkoutsampledataaddon/import/common/common-addon-extra.impex index 8f76ca0..bbd8f35 100644 --- a/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/resources/checkoutsampledataaddon/import/common/common-addon-extra.impex +++ b/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/resources/checkoutsampledataaddon/import/common/common-addon-extra.impex @@ -819,8 +819,8 @@ INSERT_UPDATE CheckoutComFawryConfiguration; code[unique = true]; name[lang = en INSERT_UPDATE CheckoutComOxxoConfiguration; code[unique = true]; name[lang = en]; restrictedCountries(isocode); restrictedCurrencies(isocode); description[lang = en] ; integrationType(code) ; OXXO ; Oxxo ; MX ; MXN ; redirect OXXO Demo Payment ; redirect -INSERT_UPDATE CheckoutComGlobalAPMConfiguration; abcAPMs(code) ; nasAPMs(code); - ; SOFORT,PAYPAL,POLI,IDEAL,KLARNA,ALIPAY,BENEFITPAY,BANCONTACT,EPS,KNET,QPAY,MULTIBANCO,SEPA,P24,FAWRY,OXXO ; SOFORT,IDEAL,BANCONTACT,GIROPAY,EPS,MULTIBANCO,P24,ACH,FAWRY +INSERT_UPDATE CheckoutComGlobalAPMConfiguration; nasAPMs(code) + ; IDEAL,BANCONTACT,GIROPAY,EPS,MULTIBANCO,P24,ACH,FAWRY,KLARNA INSERT_UPDATE Trigger; cronJob(code)[unique = true] ; cronExpression ; active[default = true] ; checkoutComCompletedPaymentEventCleanupCronJob ; 0 0 23 1/1 * ? * ; diff --git a/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/resources/checkoutsampledataaddon/import/stores/apparel-de/site.impex b/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/resources/checkoutsampledataaddon/import/stores/apparel-de/site.impex index c3ade5d..4219b76 100644 --- a/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/resources/checkoutsampledataaddon/import/stores/apparel-de/site.impex +++ b/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/resources/checkoutsampledataaddon/import/stores/apparel-de/site.impex @@ -11,8 +11,8 @@ $webServiceSiteUid = $siteUidWS UPDATE GenericItem[processor = de.hybris.platform.commerceservices.impex.impl.ConfigPropertyImportProcessor]; pk[unique = true] -$secretKey = $config-checkout.secret.key -$publicKey = $config-checkout.public.key +$secretKey = $config-checkout.nas.secret.key +$publicKey = $config-checkout.nas.public.key $privateSharedKey = $config-checkout.private.shared.key $nasSecretKey = Bearer $config-checkout.nas.secret.key $nasPublicKey = Bearer $config-checkout.nas.public.key @@ -23,11 +23,11 @@ INSERT_UPDATE CheckoutComKlarnaConfiguration; &klarnaConfigurationId; instanceId ; klarnaConfig ; e2yCheckoutCom # Merchant configuration -INSERT_UPDATE CheckoutComMerchantConfiguration; code[unique = true] ; secretKey ; publicKey ; privateSharedKey ; nasSecretKey ; nasPublicKey ; nasSignatureKey ; nasAuthorisationHeaderKey ; environment(code); paymentAction(code); klarnaConfiguration(&klarnaConfigurationId); authorisationAmountValidationThreshold; threeDSEnabled; noThreeDSAttempt; checkoutComPaymentEventTypes(code) - ; merchantConfiguration-$siteUid ; $secretKey ; $publicKey ; $privateSharedKey ; $nasSecretKey ; $nasPublicKey ; $nasSignatureKey ; $nasAuthorizationHeaderKey ; test ; authorize ; klarnaConfig ; 0.01 ; true ; false ; payment_approved, payment_voided, payment_void_declined, payment_captured, payment_capture_declined, payment_refunded, payment_refund_declined, payment_pending, payment_declined, payment_expired, payment_canceled, payment_capture_pending +INSERT_UPDATE CheckoutComMerchantConfiguration; code[unique = true] ; secretKey ; publicKey ; privateSharedKey ; nasSecretKey ; nasPublicKey ; nasSignatureKey ; nasAuthorisationHeaderKey ; environment(code); paymentAction(code); klarnaConfiguration(&klarnaConfigurationId); authorisationAmountValidationThreshold; threeDSEnabled; noThreeDSAttempt; checkoutComPaymentEventTypes(code) + ; merchantConfiguration-$siteUid ; $nasSecretKey ; $nasPublicKey ; $privateSharedKey ; $nasSecretKey ; $nasPublicKey ; $nasSignatureKey ; $nasAuthorizationHeaderKey ; test ; authorize ; klarnaConfig ; 0.01 ; true ; false ; payment_approved, payment_voided, payment_void_declined, payment_captured, payment_capture_declined, payment_refunded, payment_refund_declined, payment_pending, payment_declined, payment_expired, payment_canceled, payment_capture_pending -INSERT_UPDATE CheckoutComMerchantConfiguration; code[unique = true] ; useNas; useNasAuthorisationKeyOnNotifications; useNasSignatureKeyOnNotifications; useAbcSignatureKeyOnNotifications - ; merchantConfiguration-$siteUid ; false ; false ; false ; false +INSERT_UPDATE CheckoutComMerchantConfiguration; code[unique = true] ; useNasAuthorisationKeyOnNotifications; useNasSignatureKeyOnNotifications; + ; merchantConfiguration-$siteUid ; false ; false ; UPDATE BaseSite; uid[unique = true]; checkoutComMerchantConfiguration(code) ; $siteUid ; merchantConfiguration-$siteUid diff --git a/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/resources/checkoutsampledataaddon/import/stores/apparel-uk/site.impex b/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/resources/checkoutsampledataaddon/import/stores/apparel-uk/site.impex index b95412a..4566181 100644 --- a/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/resources/checkoutsampledataaddon/import/stores/apparel-uk/site.impex +++ b/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/resources/checkoutsampledataaddon/import/stores/apparel-uk/site.impex @@ -11,8 +11,8 @@ $webServiceSiteUid = $siteUidWS UPDATE GenericItem[processor = de.hybris.platform.commerceservices.impex.impl.ConfigPropertyImportProcessor]; pk[unique = true] -$secretKey = $config-checkout.secret.key -$publicKey = $config-checkout.public.key +$secretKey = $config-checkout.nas.secret.key +$publicKey = $config-checkout.nas.public.key $privateSharedKey = $config-checkout.private.shared.key $nasSecretKey = Bearer $config-checkout.nas.secret.key $nasPublicKey = Bearer $config-checkout.nas.public.key @@ -23,11 +23,11 @@ INSERT_UPDATE CheckoutComKlarnaConfiguration; &klarnaConfigurationId; instanceId ; klarnaConfig ; e2yCheckoutCom # Merchant configuration -INSERT_UPDATE CheckoutComMerchantConfiguration; code[unique = true] ; secretKey ; publicKey ; privateSharedKey ; nasSecretKey ; nasPublicKey ; nasSignatureKey ; nasAuthorisationHeaderKey ; environment(code); paymentAction(code) ; reviewTransactionsAtRisk; klarnaConfiguration(&klarnaConfigurationId); authorisationAmountValidationThreshold; threeDSEnabled; noThreeDSAttempt; checkoutComPaymentEventTypes(code) ; includeBillingDescriptor; billingDescriptorName; billingDescriptorCity - ; merchantConfiguration-$siteUid ; $secretKey ; $publicKey ; $privateSharedKey ; $nasSecretKey ; $nasPublicKey ; $nasSignatureKey ; $nasAuthorizationHeaderKey ; test ; authorize_and_capture ; true ; klarnaConfig ; 0.01 ; false ; true ; payment_approved, payment_voided, payment_void_declined, payment_captured, payment_capture_declined, payment_refunded, payment_refund_declined, payment_pending, payment_declined, payment_expired, payment_canceled, payment_capture_pending ; true ; $siteUid ; INTERNET +INSERT_UPDATE CheckoutComMerchantConfiguration; code[unique = true] ; secretKey ; publicKey ; privateSharedKey ; nasSecretKey ; nasPublicKey ; nasSignatureKey ; nasAuthorisationHeaderKey ; environment(code); paymentAction(code) ; reviewTransactionsAtRisk; klarnaConfiguration(&klarnaConfigurationId); authorisationAmountValidationThreshold; threeDSEnabled; noThreeDSAttempt; checkoutComPaymentEventTypes(code) ; includeBillingDescriptor; billingDescriptorName; billingDescriptorCity + ; merchantConfiguration-$siteUid ; $nasSecretKey ; $nasPublicKey ; $privateSharedKey ; $nasSecretKey ; $nasPublicKey ; $nasSignatureKey ; $nasAuthorizationHeaderKey ; test ; authorize_and_capture ; true ; klarnaConfig ; 0.01 ; false ; true ; payment_approved, payment_voided, payment_void_declined, payment_captured, payment_capture_declined, payment_refunded, payment_refund_declined, payment_pending, payment_declined, payment_expired, payment_canceled, payment_capture_pending ; true ; $siteUid ; INTERNET -INSERT_UPDATE CheckoutComMerchantConfiguration; code[unique = true] ; useNas; useNasAuthorisationKeyOnNotifications; useNasSignatureKeyOnNotifications; useAbcSignatureKeyOnNotifications - ; merchantConfiguration-$siteUid ; false ; false ; false ; false +INSERT_UPDATE CheckoutComMerchantConfiguration; code[unique = true] ; useNasAuthorisationKeyOnNotifications; useNasSignatureKeyOnNotifications; + ; merchantConfiguration-$siteUid ; false ; false ; UPDATE BaseSite; uid[unique = true]; checkoutComMerchantConfiguration(code) ; $siteUid ; merchantConfiguration-$siteUid diff --git a/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/resources/checkoutsampledataaddon/import/stores/electronics/site.impex b/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/resources/checkoutsampledataaddon/import/stores/electronics/site.impex index 3f7a3fa..55da2f2 100644 --- a/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/resources/checkoutsampledataaddon/import/stores/electronics/site.impex +++ b/hybris/bin/modules/checkoutcom/checkoutsampledataaddon/resources/checkoutsampledataaddon/import/stores/electronics/site.impex @@ -13,8 +13,8 @@ $currencies = JPY, USD, BRL, AUD, NZD, BHD, KWD, QAR, EGP, PLN, MXN, GBP, EUR UPDATE GenericItem[processor = de.hybris.platform.commerceservices.impex.impl.ConfigPropertyImportProcessor]; pk[unique = true] -$secretKey = $config-checkout.secret.key -$publicKey = $config-checkout.public.key +$secretKey = $config-checkout.nas.secret.key +$publicKey = $config-checkout.nas.public.key $privateSharedKey = $config-checkout.private.shared.key $nasSecretKey = Bearer $config-checkout.nas.secret.key $nasPublicKey = Bearer $config-checkout.nas.public.key @@ -25,7 +25,7 @@ $applePayPrivateKey = $config-checkout.applepay.privatekey # Merchant configuration INSERT_UPDATE CheckoutComMerchantConfiguration; code[unique = true] ; secretKey ; publicKey ; privateSharedKey ; nasSecretKey ; nasPublicKey ; nasSignatureKey ; nasAuthorisationHeaderKey ; environment(code); paymentAction(code); reviewTransactionsAtRisk; authorisationAmountValidationThreshold; threeDSEnabled; noThreeDSAttempt; checkoutComPaymentEventTypes(code) ; includeBillingDescriptor; billingDescriptorName; billingDescriptorCity - ; merchantConfiguration-$siteUid ; $secretKey ; $publicKey ; $privateSharedKey ; $nasSecretKey ; $nasPublicKey ; $nasSignatureKey ; $nasAuthorizationHeaderKey ; test ; authorize ; true ; 0.01 ; true ; true ; payment_approved, payment_voided, payment_void_declined, payment_captured, payment_capture_declined, payment_refunded, payment_refund_declined, payment_pending, payment_declined, payment_expired, payment_canceled, payment_capture_pending, payment_returned ; true ; $siteUid ; INTERNET + ; merchantConfiguration-$siteUid ; $nasSecretKey ; $nasPublicKey ; $privateSharedKey ; $nasSecretKey ; $nasPublicKey ; $nasSignatureKey ; $nasAuthorizationHeaderKey ; test ; authorize ; true ; 0.01 ; true ; true ; payment_approved, payment_voided, payment_void_declined, payment_captured, payment_capture_declined, payment_refunded, payment_refund_declined, payment_pending, payment_declined, payment_expired, payment_canceled, payment_capture_pending, payment_returned ; true ; $siteUid ; INTERNET INSERT_UPDATE CheckoutComApplePayConfiguration; &applePayConfigurationId; certificate[unique = true]; privateKey ; supportedNetworks(code) ; countryCode; merchantCapabilities(code) ; merchantId ; merchantName ; applePayConfig ; $applePayCertificate ; $applePayPrivateKey ; amex, cartesBancaires, chinaUnionPay, discover, eftpos, electron, elo, interac, jcb, mada, maestro, masterCard, privateLabel, visa, vPay ; GB ; supportsCredit, supportsDebit, supports3DS, supportsEMV ; merchant.com.checkout.sandbox.e2y ; e2yCheckoutCom @@ -39,8 +39,8 @@ INSERT_UPDATE CheckoutComKlarnaConfiguration; &klarnaConfigurationId; instanceId INSERT_UPDATE CheckoutComMerchantConfiguration; code[unique = true] ; applePayConfiguration(&applePayConfigurationId); googlePayConfiguration(&googlePayConfigurationId); klarnaConfiguration(&klarnaConfigurationId) ; merchantConfiguration-$siteUid ; applePayConfig ; googlePayConfig ; klarnaConfig -INSERT_UPDATE CheckoutComMerchantConfiguration; code[unique = true] ; useNas; useNasAuthorisationKeyOnNotifications; useNasSignatureKeyOnNotifications; useAbcSignatureKeyOnNotifications; achConfiguration(code) - ; merchantConfiguration-$siteUid ; true ; true ; true ; true ; checkoutComACHConfiguration +INSERT_UPDATE CheckoutComMerchantConfiguration; code[unique = true] ; useNasAuthorisationKeyOnNotifications; useNasSignatureKeyOnNotifications; achConfiguration(code) + ; merchantConfiguration-$siteUid ; true ; true ; checkoutComACHConfiguration INSERT_UPDATE CheckoutComACHConfiguration; code[unique = true] ; clientId ; clientName ; linkCustomizationName ; redirectUri ; name ; language(isocode); secret ; webhook ; checkoutComACHConfiguration ; 639a5791eb85d80013b0a14f ; clientName ; linkCustomizationName ; redirectUri ; name ; en ; a829b3a6e0b2d927287e28fb11af2b ; webhook diff --git a/hybris/bin/modules/checkoutcom/checkoutservices/project.properties b/hybris/bin/modules/checkoutcom/checkoutservices/project.properties index 5d662bd..1d8e5ef 100644 --- a/hybris/bin/modules/checkoutcom/checkoutservices/project.properties +++ b/hybris/bin/modules/checkoutcom/checkoutservices/project.properties @@ -16,12 +16,12 @@ log4j2.logger.helloController.appenderRef.stdout.ref=STDOUT #checkoutservices.tomcat.pluggability.scan=displaytag*.jar,javax.servlet.jsp.jstl-*.jar #checkoutservices.tomcat.pluggability.default.scan.enabled=false -checkoutservices.klarna.createsession.api.url.production=https://api.checkout.com/klarna/credit-sessions -checkoutservices.klarna.createsession.api.url.test=https://api.sandbox.checkout.com/klarna-external/credit-sessions +checkoutservices.klarna.createsession.api.url.production=https://api.checkout.com/payment-contexts +checkoutservices.klarna.createsession.api.url.test=https://api.sandbox.checkout.com/payment-contexts -checkoutservices.klarna.capture.api.url.production=https://api.checkout.com/klarna/orders/%s/captures -checkoutservices.klarna.capture.api.url.test=https://api.sandbox.checkout.com/klarna-external/orders/%s/captures +checkoutservices.klarna.capture.api.url.production=https://api.checkout.com//payments/%s/captures +checkoutservices.klarna.capture.api.url.test=https://api.sandbox.checkout.com/payments/%s/captures -checkoutservices.klarna.void.api.url.production=https://api.checkout.com/klarna/orders/%s/voids -checkoutservices.klarna.void.api.url.test=https://api.sandbox.checkout.com/klarna-external/orders/%s/voids -checkoutservices.connector.version=1 +checkoutservices.klarna.void.api.url.production=https://api.checkout.com/payments/%s/voids +checkoutservices.klarna.void.api.url.test=https://api.sandbox.checkout.com/payments/%s/voids +checkoutservices.connector.version=2211-v4 diff --git a/hybris/bin/modules/checkoutcom/checkoutservices/resources/checkoutservices-beans.xml b/hybris/bin/modules/checkoutcom/checkoutservices/resources/checkoutservices-beans.xml index 234618e..a40a350 100644 --- a/hybris/bin/modules/checkoutcom/checkoutservices/resources/checkoutservices-beans.xml +++ b/hybris/bin/modules/checkoutcom/checkoutservices/resources/checkoutservices-beans.xml @@ -58,24 +58,61 @@ @JsonInclude(JsonInclude.Include.NON_NULL) - - @JsonProperty("purchase_country") - @JsonProperty("currency") - - @JsonProperty("locale") - @JsonProperty("amount") - - @JsonProperty("tax_amount") + + @JsonProperty("payment_type") + + + @JsonProperty("source") - @JsonProperty("products") + @JsonProperty("items") + + + @JsonProperty("processing") + + + @JsonProperty("processing_channel_id") + + + + + + + @JsonProperty("locale") + + + + + + + @JsonProperty("type") + + + @JsonProperty("account_holder") + + + + + + + @JsonProperty("billing_address") + + + + + + + @JsonProperty("country") @@ -99,11 +136,8 @@ @JsonProperty("unit_price") - - @JsonProperty("tax_rate") - - - @JsonProperty("type") + + @JsonProperty("reference") @@ -111,15 +145,12 @@ @JsonInclude(JsonInclude.Include.NON_NULL) - - @JsonProperty("session_id") - - - @JsonProperty("client_token") + + @JsonProperty("id") - - @JsonProperty("payment_method_categories") + + @JsonProperty("partner_metadata") @JsonProperty("_links") @@ -136,18 +167,18 @@ - + @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty("asset_urls") - - @JsonProperty("identifier") + + @JsonProperty("session_id") - - @JsonProperty("name") + + @JsonProperty("client_token") diff --git a/hybris/bin/modules/checkoutcom/checkoutservices/resources/checkoutservices-items.xml b/hybris/bin/modules/checkoutcom/checkoutservices/resources/checkoutservices-items.xml index 3f225bf..5d41ba6 100644 --- a/hybris/bin/modules/checkoutcom/checkoutservices/resources/checkoutservices-items.xml +++ b/hybris/bin/modules/checkoutcom/checkoutservices/resources/checkoutservices-items.xml @@ -385,6 +385,11 @@ The generated Payment Token from checkout.com + + + + The Payment Context from checkout.com + @@ -583,8 +588,7 @@ - Use the valid secret key of your Checkout.com account. You can find this in the - Hub. + Use the valid secret key of your Checkout.com account. You can find this in the Hub. @@ -613,12 +617,6 @@ Your NAS Authorisation header key. You can find it in the Hub, Notifications settings. - - - - java.lang.Boolean.FALSE - Determines whether to use NAS or ABC. - @@ -631,12 +629,6 @@ java.lang.Boolean.FALSE Determines whether to use signature key to verify NAS Notifications - - - - java.lang.Boolean.TRUE - Determines whether to use signature key to verify NAS Notifications - The Checkout.com environment to which we is integrated. @@ -902,10 +894,6 @@ - - - APMs that are enabled for ABC - APMs that are enabled for NAS diff --git a/hybris/bin/modules/checkoutcom/checkoutservices/resources/checkoutservices.build.number b/hybris/bin/modules/checkoutcom/checkoutservices/resources/checkoutservices.build.number index a058b8a..60647a7 100644 --- a/hybris/bin/modules/checkoutcom/checkoutservices/resources/checkoutservices.build.number +++ b/hybris/bin/modules/checkoutcom/checkoutservices/resources/checkoutservices.build.number @@ -1,11 +1,11 @@ #Ant properties -#Tue May 28 13:21:41 GMT 2024 +#Tue Jun 18 10:12:55 GMT 2024 version.api=2211 vendor=hybris group.id=de.hybris.platform name=checkoutservices description=checkoutservices -builddate=20240528 1321 +builddate=20240618 1012 releasedate=20240307 1540 version=2211.20 module.name=platform-module diff --git a/hybris/bin/modules/checkoutcom/checkoutservices/resources/localization/checkoutservices-locales_en.properties b/hybris/bin/modules/checkoutcom/checkoutservices/resources/localization/checkoutservices-locales_en.properties index 1bf70a5..be0ec18 100644 --- a/hybris/bin/modules/checkoutcom/checkoutservices/resources/localization/checkoutservices-locales_en.properties +++ b/hybris/bin/modules/checkoutcom/checkoutservices/resources/localization/checkoutservices-locales_en.properties @@ -25,8 +25,6 @@ type.CheckoutComMerchantConfiguration.privateSharedKey.name type.CheckoutComMerchantConfiguration.privateSharedKey.description = Your private key. You can find it in the Hub type.CheckoutComMerchantConfiguration.nasSecretKey.name = NAS Secret Key type.CheckoutComMerchantConfiguration.nasSecretKey.description = Use the valid NAS secret key of your Checkout.com account. You can find this in the Hub -type.CheckoutComMerchantConfiguration.useNas.name = Use NAS? -type.CheckoutComMerchantConfiguration.useNas.description = Use NAS configuration? type.CheckoutComMerchantConfiguration.nasPublicKey.name = NAS Public Key type.CheckoutComMerchantConfiguration.nasPublicKey.description = Your NAS public key. You can find it in the Hub type.CheckoutComMerchantConfiguration.nasSignatureKey.name = NAS Signature Key @@ -37,8 +35,6 @@ type.CheckoutComMerchantConfiguration.useNasAuthorisationKeyOnNotifications.name type.CheckoutComMerchantConfiguration.useNasAuthorisationKeyOnNotifications.description = Activate the validation of your NAS authorisation header key on notifications/events. type.CheckoutComMerchantConfiguration.useNasSignatureKeyOnNotifications.name = Use NAS Signature key? type.CheckoutComMerchantConfiguration.useNasSignatureKeyOnNotifications.description = Activate the checking of your NAS signature key to validate notifications/events -type.CheckoutComMerchantConfiguration.useAbcSignatureKeyOnNotifications.name = Use ABC Signature key? -type.CheckoutComMerchantConfiguration.useAbcSignatureKeyOnNotifications.description = Activate the checking of your ABC signature key to validate notifications/events type.CheckoutComMerchantConfiguration.environment.name = Environment type.CheckoutComMerchantConfiguration.environment.description = The Checkout.com environment type.CheckoutComMerchantConfiguration.paymentAction.name = Payment Action diff --git a/hybris/bin/modules/checkoutcom/checkoutservices/resources/spring/checkoutservices-strategies-spring.xml b/hybris/bin/modules/checkoutcom/checkoutservices/resources/spring/checkoutservices-strategies-spring.xml index eb374b0..daeb329 100644 --- a/hybris/bin/modules/checkoutcom/checkoutservices/resources/spring/checkoutservices-strategies-spring.xml +++ b/hybris/bin/modules/checkoutcom/checkoutservices/resources/spring/checkoutservices-strategies-spring.xml @@ -179,7 +179,6 @@ - @@ -241,6 +240,13 @@ + + + + + diff --git a/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/apm/services/impl/DefaultCheckoutComAPMConfigurationService.java b/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/apm/services/impl/DefaultCheckoutComAPMConfigurationService.java index d36e47c..0670252 100644 --- a/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/apm/services/impl/DefaultCheckoutComAPMConfigurationService.java +++ b/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/apm/services/impl/DefaultCheckoutComAPMConfigurationService.java @@ -71,12 +71,7 @@ public boolean isApmAvailable(final CheckoutComAPMConfigurationModel apmConfigur .findAny() .orElseThrow(() -> new IllegalStateException("No CheckoutComAPMConfiguration has been found in the system")); - final Collection allowedAPMs; - if (Boolean.TRUE.equals(checkoutComMerchantConfigurationService.isNasUsed())) { - allowedAPMs = globalAPMConfig.getNasAPMs(); - } else { - allowedAPMs = globalAPMConfig.getAbcAPMs(); - } + final Collection allowedAPMs = globalAPMConfig.getNasAPMs(); if (!allowedAPMs.contains(apmConfiguration)) { return false; diff --git a/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/merchant/services/CheckoutComMerchantConfigurationService.java b/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/merchant/services/CheckoutComMerchantConfigurationService.java index cf8ac81..7097d92 100644 --- a/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/merchant/services/CheckoutComMerchantConfigurationService.java +++ b/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/merchant/services/CheckoutComMerchantConfigurationService.java @@ -36,13 +36,6 @@ public interface CheckoutComMerchantConfigurationService { */ String getAuthorizationKey(); - /** - * Returns whether Nas is used on the merchant configuration of the current site - * - * @return the activated value - */ - boolean isNasUsed(); - /** * Returns whether Nas authorisation header is used on the merchant configuration of the current site to validate * incoming notifications @@ -59,13 +52,6 @@ public interface CheckoutComMerchantConfigurationService { */ boolean isNasSignatureKeyUsedOnNotificationValidation(); - /** - * Returns whether the ABC signature key is used on the merchant configuration of the current site to validate - * incoming notifications - * - * @return {@code True} if enabled, {@code False} otherwise - */ - boolean isAbcSignatureKeyUsedOnNotificationValidation(); /** * Returns the secret key from the merchant configuration of the current site @@ -78,7 +64,7 @@ public interface CheckoutComMerchantConfigurationService { * Returns the public key from the merchant configuration of the given site * * @param siteId the site id for which to get the secret - * @return the secret key + * @return the public key */ String getPublicKeyForSite(String siteId); @@ -182,4 +168,12 @@ public interface CheckoutComMerchantConfigurationService { * @return a {@link CheckoutComKlarnaConfigurationModel} */ CheckoutComKlarnaConfigurationModel getKlarnaConfiguration(); + + /** + * Returns the secret key from the merchant configuration of the given site + * + * @param siteId the site id for which to get the secret + * @return the secret key + */ + String getSecretKeyForSite(String siteId); } diff --git a/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/merchant/services/impl/DefaultCheckoutComMerchantConfigurationService.java b/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/merchant/services/impl/DefaultCheckoutComMerchantConfigurationService.java index 7d13bd0..bb2d1d0 100644 --- a/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/merchant/services/impl/DefaultCheckoutComMerchantConfigurationService.java +++ b/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/merchant/services/impl/DefaultCheckoutComMerchantConfigurationService.java @@ -31,8 +31,7 @@ public DefaultCheckoutComMerchantConfigurationService(final BaseSiteService base */ @Override public String getSecretKey() { - final CheckoutComMerchantConfigurationModel currentConfiguration = getCurrentConfiguration(); - return currentConfiguration.getUseNas() ? currentConfiguration.getNasSecretKey() : currentConfiguration.getSecretKey(); + return getCurrentConfiguration().getNasSecretKey(); } /** @@ -51,14 +50,6 @@ public String getAuthorizationKey() { return getCurrentConfiguration().getNasAuthorisationHeaderKey(); } - /** - * {@inheritDoc} - */ - @Override - public boolean isNasUsed() { - return getCurrentConfiguration().getUseNas(); - } - /** * {@inheritDoc} */ @@ -75,21 +66,13 @@ public boolean isNasSignatureKeyUsedOnNotificationValidation() { return getCurrentConfiguration().getUseNasSignatureKeyOnNotifications(); } - /** - * {@inheritDoc} - */ - @Override - public boolean isAbcSignatureKeyUsedOnNotificationValidation() { - return getCurrentConfiguration().getUseAbcSignatureKeyOnNotifications(); - } /** * {@inheritDoc} */ @Override public String getPublicKey() { - final CheckoutComMerchantConfigurationModel currentConfiguration = getCurrentConfiguration(); - return currentConfiguration.getUseNas() ? currentConfiguration.getNasPublicKey() : currentConfiguration.getPublicKey(); + return getCurrentConfiguration().getNasPublicKey(); } /** @@ -97,8 +80,7 @@ public String getPublicKey() { */ @Override public String getPublicKeyForSite(final String siteId) { - final CheckoutComMerchantConfigurationModel currentConfiguration = getConfigurationForSiteId(siteId); - return currentConfiguration.getUseNas() ? currentConfiguration.getNasPublicKey() : currentConfiguration.getPublicKey(); + return getConfigurationForSiteId(siteId).getNasPublicKey(); } /** @@ -106,8 +88,7 @@ public String getPublicKeyForSite(final String siteId) { */ @Override public String getPrivateSharedKey() { - final CheckoutComMerchantConfigurationModel currentConfiguration = getCurrentConfiguration(); - return currentConfiguration.getUseNas() ? currentConfiguration.getNasSignatureKey() : currentConfiguration.getPrivateSharedKey(); + return getCurrentConfiguration().getNasSignatureKey(); } /** @@ -224,6 +205,14 @@ public Double getAuthorisationAmountValidationThreshold(final String siteId) { return authorisationAmountValidationTolerance != null ? authorisationAmountValidationTolerance : Double.valueOf(0.0d); } + /** + * {@inheritDoc} + */ + @Override + public String getSecretKeyForSite(final String siteId) { + return getConfigurationForSiteId(siteId).getNasSecretKey(); + } + protected CheckoutComMerchantConfigurationModel getCurrentConfiguration() { final BaseSiteModel currentBaseSite = baseSiteService.getCurrentBaseSite(); checkArgument(currentBaseSite != null, "Current base site cannot be null"); diff --git a/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/payment/klarna/request/converters/populators/CheckoutComKlarnaProductsRequestDtoPopulator.java b/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/payment/klarna/request/converters/populators/CheckoutComKlarnaProductsRequestDtoPopulator.java index 7efecec..dcea9e4 100644 --- a/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/payment/klarna/request/converters/populators/CheckoutComKlarnaProductsRequestDtoPopulator.java +++ b/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/payment/klarna/request/converters/populators/CheckoutComKlarnaProductsRequestDtoPopulator.java @@ -3,18 +3,15 @@ import com.checkout.hybris.core.currency.services.CheckoutComCurrencyService; import com.checkout.hybris.core.klarna.session.request.KlarnaProductRequestDto; import com.checkout.hybris.core.payment.klarna.request.strategies.CheckoutComKlarnaDiscountAmountStrategy; -import com.google.common.util.concurrent.AtomicDouble; import de.hybris.platform.converters.Populator; import de.hybris.platform.core.model.order.AbstractOrderEntryModel; import de.hybris.platform.core.model.order.CartModel; import de.hybris.platform.core.model.product.ProductModel; import de.hybris.platform.servicelayer.dto.converter.ConversionException; import de.hybris.platform.util.DiscountValue; -import de.hybris.platform.util.TaxValue; import org.apache.commons.lang.math.NumberUtils; import java.util.List; -import java.util.concurrent.atomic.AtomicLong; import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; import static org.apache.commons.collections.CollectionUtils.isNotEmpty; @@ -24,10 +21,6 @@ */ public class CheckoutComKlarnaProductsRequestDtoPopulator implements Populator> { - protected static final String SHIPPING_FEE_VALUE = "shipping_fee"; - protected static final String ORDER_DISCOUNT = "discount"; - protected static final String SURCHARGE_VALUE = "surcharge"; - protected final CheckoutComCurrencyService checkoutComCurrencyService; protected final CheckoutComKlarnaDiscountAmountStrategy checkoutComKlarnaDiscountAmountStrategy; @@ -58,7 +51,6 @@ public void populate(final CartModel source, final List final double totalAmount = cartEntry.getBasePrice() * cartEntry.getQuantity() - discountAmount; //TaxRate calculated for Gross tax mode final double totalTaxAmount = totalAmount * taxRate; - final double cartEntryTaxRate = totalTaxAmount / (totalAmount - totalTaxAmount); final ProductModel product = cartEntry.getProduct(); productRequestDto.setName(product != null ? product.getName() : null); @@ -66,8 +58,8 @@ public void populate(final CartModel source, final List productRequestDto.setTotalDiscountAmount(checkoutComCurrencyService.convertAmountIntoPennies(currencyCode, discountAmount)); productRequestDto.setTotalAmount(checkoutComCurrencyService.convertAmountIntoPennies(currencyCode, totalAmount)); productRequestDto.setTotalTaxAmount(checkoutComCurrencyService.convertAmountIntoPennies(currencyCode,totalTaxAmount)); - productRequestDto.setTaxRate(checkoutComCurrencyService.convertAmountIntoPennies(currencyCode,cartEntryTaxRate * 100)); productRequestDto.setUnitPrice(checkoutComCurrencyService.convertAmountIntoPennies(currencyCode, cartEntry.getBasePrice())); + productRequestDto.setReference(product != null ? product.getCode() : null); target.add(productRequestDto); } @@ -98,17 +90,14 @@ protected void populateShippingLine(final CartModel cart, shippingLine.setQuantity(NumberUtils.LONG_ONE); if (doesCartContainsTaxes(cart)) { - shippingLine.setTaxRate(checkoutComCurrencyService.convertAmountIntoPennies(currencyCode, getTotalTaxPercent(cart))); final double totalShippingTaxes = taxRate * cart.getDeliveryCost(); shippingLine.setTotalTaxAmount(checkoutComCurrencyService.convertAmountIntoPennies(currencyCode, totalShippingTaxes)); } else { - shippingLine.setTaxRate(0L); shippingLine.setTotalTaxAmount(0L); } final long totalAmount = checkoutComCurrencyService.convertAmountIntoPennies(currencyCode, cart.getDeliveryCost()); shippingLine.setTotalAmount(totalAmount); shippingLine.setUnitPrice(checkoutComCurrencyService.convertAmountIntoPennies(currencyCode, cart.getDeliveryCost())); - shippingLine.setType(SHIPPING_FEE_VALUE); shippingLine.setTotalDiscountAmount(NumberUtils.LONG_ZERO); klarnaProductRequestDtos.add(shippingLine); } @@ -134,14 +123,11 @@ protected void populateOrderDiscount(final CartModel cart, final long totalDiscount = checkoutComCurrencyService.convertAmountIntoPennies(currencyCode, cart.getTotalDiscounts()) * -1; orderDiscount.setTotalAmount(totalDiscount); orderDiscount.setUnitPrice(totalDiscount); - orderDiscount.setType(ORDER_DISCOUNT); if (doesCartContainsTaxes(cart)) { - orderDiscount.setTaxRate(checkoutComCurrencyService.convertAmountIntoPennies(currencyCode, getTotalTaxPercent(cart))); final double totalDiscountTaxes = taxRate * cart.getTotalDiscounts() * -1; orderDiscount.setTotalTaxAmount(checkoutComCurrencyService.convertAmountIntoPennies(currencyCode, totalDiscountTaxes)); } else { - orderDiscount.setTaxRate(0L); orderDiscount.setTotalTaxAmount(0L); } klarnaProductRequestDtos.add(orderDiscount); @@ -165,14 +151,11 @@ protected void populatePaymentCost(CartModel cart, String currencyCode, List> checkoutComKlarnaProductsRequestDtoConverter; - public CheckoutComKlarnaPaymentRequestStrategy(final CheckoutComPhoneNumberStrategy checkoutComPhoneNumberStrategy, final CheckoutComPaymentRequestStrategyMapper checkoutComPaymentRequestStrategyMapper, final CheckoutComCartModelToPaymentL2AndL3Converter checkoutComCartModelToPaymentL2AndL3Converter, - final CheckoutPaymentRequestServicesWrapper checkoutPaymentRequestServicesWrapper, - final Converter> checkoutComKlarnaProductsRequestDtoConverter) { + final CheckoutPaymentRequestServicesWrapper checkoutPaymentRequestServicesWrapper) { super(checkoutComPhoneNumberStrategy, checkoutComPaymentRequestStrategyMapper, checkoutComCartModelToPaymentL2AndL3Converter, checkoutPaymentRequestServicesWrapper); - this.checkoutComKlarnaProductsRequestDtoConverter = checkoutComKlarnaProductsRequestDtoConverter; } /** @@ -64,33 +42,10 @@ public CheckoutComPaymentType getStrategyKey() { @Override protected PaymentRequest getRequestSourcePaymentRequest(final CartModel cart, final String currencyIsoCode, final Long amount) { - final PaymentRequest paymentRequest = super.getRequestSourcePaymentRequest(cart, currencyIsoCode, amount); - final AlternativePaymentSource source = (AlternativePaymentSource) paymentRequest.getSource(); - final CustomerModel customer = (CustomerModel) cart.getUser(); final CheckoutComKlarnaAPMPaymentInfoModel klarnaPaymentInfo = (CheckoutComKlarnaAPMPaymentInfoModel) cart.getPaymentInfo(); - source.put(AUTHORIZATION_TOKEN_KEY, klarnaPaymentInfo.getAuthorizationToken()); - - final String currencyCode = cart.getCurrency() != null ? cart.getCurrency().getIsocode() : null; - final CMSSiteModel site = (CMSSiteModel) cart.getSite(); - validateParameterNotNull(site, "CMSSite model cannot be null"); - source.put(LOCALE_KEY, site.getLocale().replace("_", "-")); - - final AddressModel billingAddress = klarnaPaymentInfo.getBillingAddress(); - validateParameterNotNull(billingAddress, "Billing address model cannot be null"); - validateParameterNotNull(cart.getDeliveryAddress(), "Delivery address model cannot be null"); - validateParameterNotNull(billingAddress.getCountry(), "Billing address country cannot be null"); - source.put(PURCHASE_COUNTRY_KEY, billingAddress.getCountry().getIsocode()); - source.put(BILLING_ADDRESS_KEY, createAddressDto(billingAddress, customer.getContactEmail())); - source.put(SHIPPING_ADDRESS_KEY, createAddressDto(cart.getDeliveryAddress(), customer.getContactEmail())); - - source.put(TAX_AMOUNT_KEY, checkoutPaymentRequestServicesWrapper.checkoutComCurrencyService - .convertAmountIntoPennies(currencyCode, cart.getTotalTax())); - source.put(MERCHANT_REFERENCE_KEY, cart.getCheckoutComPaymentReference()); - source.put(PRODUCTS_KEY, checkoutComKlarnaProductsRequestDtoConverter.convert(cart)); - - return paymentRequest; + return PaymentRequest.forKlarna(klarnaPaymentInfo.getPaymentContext()); } /** @@ -101,26 +56,4 @@ protected Optional isCapture() { return Optional.of(Boolean.FALSE); } - /** - * Populates the address dto from the given address model - * - * @param address the source address - * @param email the customer email - * @return the klarna address dto - */ - protected KlarnaAddressDto createAddressDto(final AddressModel address, final String email) { - final KlarnaAddressDto klarnaAddressDto = new KlarnaAddressDto(); - klarnaAddressDto.setTitle(address.getTitle() != null ? address.getTitle().getName() : null); - klarnaAddressDto.setGivenName(address.getFirstname()); - klarnaAddressDto.setFamilyName(address.getLastname()); - klarnaAddressDto.setStreetAddress(address.getLine1()); - klarnaAddressDto.setStreetAddress2(address.getLine2()); - klarnaAddressDto.setCity(address.getTown()); - klarnaAddressDto.setPostalCode(address.getPostalcode()); - klarnaAddressDto.setRegion(address.getRegion() != null ? address.getRegion().getName() : null); - klarnaAddressDto.setCountry(address.getCountry() != null ? address.getCountry().getIsocode() : null); - klarnaAddressDto.setEmail(email); - klarnaAddressDto.setPhone(address.getPhone1()); - return klarnaAddressDto; - } } diff --git a/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/payment/response/strategies/impl/CheckoutComKlarnaPaymentResponseStrategy.java b/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/payment/response/strategies/impl/CheckoutComKlarnaPaymentResponseStrategy.java new file mode 100644 index 0000000..203b17a --- /dev/null +++ b/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/payment/response/strategies/impl/CheckoutComKlarnaPaymentResponseStrategy.java @@ -0,0 +1,54 @@ +package com.checkout.hybris.core.payment.response.strategies.impl; + +import com.checkout.hybris.core.authorisation.AuthorizeResponse; +import com.checkout.hybris.core.model.CheckoutComKlarnaAPMPaymentInfoModel; +import com.checkout.hybris.core.payment.enums.CheckoutComPaymentType; +import com.checkout.hybris.core.payment.response.mappers.CheckoutComPaymentResponseStrategyMapper; +import com.checkout.hybris.core.payment.response.strategies.CheckoutComPaymentResponseStrategy; +import com.checkout.hybris.core.payment.services.CheckoutComPaymentInfoService; +import com.checkout.sdk.payments.PaymentPending; +import com.google.common.base.Preconditions; +import de.hybris.platform.core.model.order.payment.PaymentInfoModel; + +import static de.hybris.platform.servicelayer.util.ServicesUtil.validateParameterNotNull; + +/** + * Specific {@link CheckoutComPaymentResponseStrategy} implementation for Klarna apm payment responses + */ +public class CheckoutComKlarnaPaymentResponseStrategy extends CheckoutComAbstractPaymentResponseStrategy { + + protected final CheckoutComPaymentInfoService paymentInfoService; + + public CheckoutComKlarnaPaymentResponseStrategy(final CheckoutComPaymentResponseStrategyMapper checkoutComPaymentResponseStrategyMapper, + final CheckoutComPaymentInfoService paymentInfoService) { + super(checkoutComPaymentResponseStrategyMapper); + this.paymentInfoService = paymentInfoService; + } + + @Override + protected CheckoutComPaymentType getStrategyKey() { + return CheckoutComPaymentType.KLARNA; + } + + /** + * {@inheritDoc} + */ + @Override + public AuthorizeResponse handlePendingPaymentResponse(final PaymentPending paymentPendingResponse, final PaymentInfoModel paymentInfo) { + validateParameterNotNull(paymentPendingResponse, "Payment pending response cannot be null"); + Preconditions.checkArgument(paymentInfo instanceof CheckoutComKlarnaAPMPaymentInfoModel, "Payment info null or not valid for Sepa."); + + paymentInfoService.addPaymentId(paymentPendingResponse.getId(), paymentInfo); + + return populateAuthorizeResponse(); + } + + protected AuthorizeResponse populateAuthorizeResponse() { + final AuthorizeResponse response = new AuthorizeResponse(); + response.setIsRedirect(false); + response.setIsSuccess(true); + response.setIsDataRequired(true); + + return response; + } +} diff --git a/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/payment/services/impl/DefaultCheckoutComPaymentIntegrationService.java b/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/payment/services/impl/DefaultCheckoutComPaymentIntegrationService.java index 3981284..7d907eb 100644 --- a/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/payment/services/impl/DefaultCheckoutComPaymentIntegrationService.java +++ b/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/payment/services/impl/DefaultCheckoutComPaymentIntegrationService.java @@ -258,7 +258,7 @@ public TokenResponse generateWalletPaymentToken(final WalletTokenRequest walletT public KlarnaSessionResponseDto createKlarnaSession(final KlarnaSessionRequestDto klarnaSessionRequestDto) throws ExecutionException { final String createSessionUrl = getKlarnaApiUrlForEnvironment(null, PREFIX_KLARNA_CREATE_SESSION_URL); - final HttpEntity request = new HttpEntity<>(klarnaSessionRequestDto, createKlarnaRequestHeaders(checkoutComMerchantConfigurationService.getPublicKey())); + final HttpEntity request = new HttpEntity<>(klarnaSessionRequestDto, createKlarnaRequestHeaders(checkoutComMerchantConfigurationService.getSecretKey())); try { return restTemplate.postForEntity(createSessionUrl, request, KlarnaSessionResponseDto.class).getBody(); @@ -282,7 +282,7 @@ public KlarnaSessionResponseDto createKlarnaSession(final KlarnaSessionRequestDt protected CaptureResponse captureKlarnaPayment(final CaptureRequest captureRequest, final String paymentId, final String siteId) throws ExecutionException { final String capturePaymentUrl = getKlarnaApiUrlForEnvironment(siteId, PREFIX_KLARNA_CAPTURE_URL); - final HttpEntity request = new HttpEntity<>(createKlarnaCaptureRequest(captureRequest), createKlarnaRequestHeaders(checkoutComMerchantConfigurationService.getPublicKeyForSite(siteId))); + final HttpEntity request = new HttpEntity<>(createKlarnaCaptureRequest(captureRequest), createKlarnaRequestHeaders(checkoutComMerchantConfigurationService.getSecretKeyForSite(siteId))); final String url = String.format(capturePaymentUrl, paymentId); @@ -309,7 +309,7 @@ protected CaptureResponse captureKlarnaPayment(final CaptureRequest captureReque protected VoidResponse voidKlarnaPayment(final VoidRequest voidRequest, final String paymentId, final String siteId) throws ExecutionException { final String voidPaymentUrl = getKlarnaApiUrlForEnvironment(siteId, PREFIX_KLARNA_VOID_URL); - final HttpEntity request = new HttpEntity<>(createKlarnaVoidRequest(voidRequest), createKlarnaRequestHeaders(checkoutComMerchantConfigurationService.getPublicKeyForSite(siteId))); + final HttpEntity request = new HttpEntity<>(createKlarnaVoidRequest(voidRequest), createKlarnaRequestHeaders(checkoutComMerchantConfigurationService.getSecretKeyForSite(siteId))); final String url = String.format(voidPaymentUrl, paymentId); diff --git a/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/payment/services/impl/DefaultCheckoutComPaymentService.java b/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/payment/services/impl/DefaultCheckoutComPaymentService.java index b264699..f6f36f6 100644 --- a/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/payment/services/impl/DefaultCheckoutComPaymentService.java +++ b/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/hybris/core/payment/services/impl/DefaultCheckoutComPaymentService.java @@ -230,7 +230,7 @@ public boolean isAutoCapture(final OrderModel order) { if (paymentInfo instanceof CheckoutComCreditCardPaymentInfoModel) { return ((CheckoutComCreditCardPaymentInfoModel) order.getPaymentInfo()).getAutoCapture(); } else { - return order.getSite().getCheckoutComMerchantConfiguration().getUseNas(); + return Boolean.TRUE; } } diff --git a/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/sdk/payments/PaymentRequest.java b/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/sdk/payments/PaymentRequest.java index 419e049..68b872d 100644 --- a/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/sdk/payments/PaymentRequest.java +++ b/hybris/bin/modules/checkoutcom/checkoutservices/src/com/checkout/sdk/payments/PaymentRequest.java @@ -17,11 +17,10 @@ @Builder @AllArgsConstructor public class PaymentRequest { - private final T source; - private final T destination; - private final Long amount; - @NonNull - private final String currency; + private T source; + private T destination; + private Long amount; + private String currency; private String paymentType; private Boolean merchantInitiated; private String reference; @@ -46,6 +45,7 @@ public class PaymentRequest { private String processingChannelId; private AuthorizationType authorizationType; private MarketplaceData marketplace; + private String paymentContextId; private PaymentSender sender; @@ -68,6 +68,10 @@ private PaymentRequest(T sourceOrDestination, String currency, Long amount, bool this.metadata = new HashMap<>(); } + private PaymentRequest(String paymentContextId) { + this.paymentContextId = paymentContextId; + } + public static PaymentRequest fromSource(T source, String currency, Long amount) { return new PaymentRequest<>(source, currency, amount, true); } @@ -75,4 +79,8 @@ public static PaymentRequest fromSource(T source, S public static PaymentRequest fromDestination(T destination, String currency, Long amount) { return new PaymentRequest<>(destination, currency, amount, false); } + + public static PaymentRequest forKlarna(String paymentContextId) { + return new PaymentRequest<>(paymentContextId); + } } diff --git a/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/apm/services/impl/DefaultCheckoutComAPMConfigurationServiceTest.java b/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/apm/services/impl/DefaultCheckoutComAPMConfigurationServiceTest.java index c6d9cad..2acdaa7 100644 --- a/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/apm/services/impl/DefaultCheckoutComAPMConfigurationServiceTest.java +++ b/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/apm/services/impl/DefaultCheckoutComAPMConfigurationServiceTest.java @@ -6,8 +6,6 @@ import com.checkout.hybris.core.model.CheckoutComAPMConfigurationModel; import com.checkout.hybris.core.model.CheckoutComFawryConfigurationModel; import com.checkout.hybris.core.model.CheckoutComGlobalAPMConfigurationModel; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.core.model.c2l.CountryModel; import de.hybris.platform.core.model.c2l.CurrencyModel; @@ -25,14 +23,11 @@ import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; +import java.util.*; +import static com.checkout.hybris.core.payment.enums.CheckoutComPaymentType.FAWRY; import static com.checkout.sdk.common.Currency.EUR; import static com.checkout.sdk.common.Currency.GBP; -import static com.checkout.hybris.core.payment.enums.CheckoutComPaymentType.FAWRY; import static java.util.Collections.emptyList; import static java.util.Collections.emptySet; import static java.util.Locale.FRANCE; @@ -96,8 +91,8 @@ public void setUp() { when(restrictedCountryMock.getIsocode()).thenReturn(FRANCE.getCountry()); when(restrictedCurrencyMock.getIsocode()).thenReturn(EUR); - when(apmConfiguration1Mock.getRestrictedCountries()).thenReturn(ImmutableSet.of(restrictedCountryMock)); - when(apmConfiguration1Mock.getRestrictedCurrencies()).thenReturn(ImmutableSet.of(restrictedCurrencyMock)); + when(apmConfiguration1Mock.getRestrictedCountries()).thenReturn(Set.of(restrictedCountryMock)); + when(apmConfiguration1Mock.getRestrictedCurrencies()).thenReturn(Set.of(restrictedCurrencyMock)); when(checkoutComAPMConfigurationSettingsMock.containsKey(APM_CODE)).thenReturn(Boolean.TRUE); when(checkoutComAPMConfigurationSettingsMock.get(APM_CODE)).thenReturn(apmConfigurationSettingsMock); @@ -113,7 +108,6 @@ public void setUp() { when(component2Mock.getApmConfiguration()).thenReturn(apmConfiguration2Mock); when(component1Mock.getVisible()).thenReturn(Boolean.TRUE); when(component2Mock.getVisible()).thenReturn(Boolean.TRUE); - when(checkoutComMerchantConfigurationServiceMock.isNasUsed()).thenReturn(true); when(globalAPMConfigurationDaoMock.find()).thenReturn(List.of(checkoutComGlobalAPMConfigurationMock)); } @@ -143,18 +137,6 @@ public void isApmAvailable_WhenSiteConfigurationIsEnabledForNAS_andAPMIsNot_Shou assertFalse(result); } - @Test - public void isApmAvailable_WhenSiteConfigurationAndAPMAreNotEnabledForNAS_andAPMOrBaseSiteDoNotHaveRestrictions_ShouldReturnTrue() { - when(checkoutComMerchantConfigurationServiceMock.isNasUsed()).thenReturn(false); - when(checkoutComGlobalAPMConfigurationMock.getAbcAPMs()).thenReturn(List.of(apmConfiguration1Mock)); - when(apmConfiguration1Mock.getRestrictedCountries()).thenReturn(emptySet()); - when(apmConfiguration1Mock.getRestrictedCurrencies()).thenReturn(emptySet()); - - final boolean result = testObj.isApmAvailable(apmConfiguration1Mock, UK.getCountry(), GBP); - - assertTrue(result); - } - @Test public void isApmAvailable_WhenSiteConfigurationAndAPMAreEnabledForNAS_andApmConfigurationDoesNotHaveRestrictions_andBaseSite_ShouldReturnTrue() { when(apmConfiguration1Mock.getRestrictedCountries()).thenReturn(emptySet()); @@ -191,7 +173,7 @@ public void isApmAvailable_WhenApmRestrictedForDifferentCountryAndCurrency_Shoul @Test public void getApmConfigurationByCode_WhenConfigurationIsFound_ShouldReturnIt() { - when(checkoutComApmConfigurationDaoMock.find(ImmutableMap.of(CheckoutComAPMConfigurationModel.CODE, FAWRY.name()))).thenReturn(List.of(fawryConfigurationModelMock)); + when(checkoutComApmConfigurationDaoMock.find(Map.of(CheckoutComAPMConfigurationModel.CODE, FAWRY.name()))).thenReturn(List.of(fawryConfigurationModelMock)); final Optional result = testObj.getApmConfigurationByCode(FAWRY.name()); @@ -201,7 +183,7 @@ public void getApmConfigurationByCode_WhenConfigurationIsFound_ShouldReturnIt() @Test public void getApmConfigurationByCode_WhenConfigurationIsNotFound_ShouldReturnOptionalEmpty() { - when(checkoutComApmConfigurationDaoMock.find(ImmutableMap.of(CheckoutComAPMConfigurationModel.CODE, FAWRY.name()))).thenReturn(emptyList()); + when(checkoutComApmConfigurationDaoMock.find(Map.of(CheckoutComAPMConfigurationModel.CODE, FAWRY.name()))).thenReturn(emptyList()); final Optional result = testObj.getApmConfigurationByCode(FAWRY.name()); @@ -314,7 +296,7 @@ public void getAvailableApms_WhenComponentIsNotVisible_ShouldReturnAvailableApms @Test public void getApmConfigurationMedia_WhenNoApmComponentFound_ShouldReturnOptionalEmpty() { - when(checkoutComApmComponentDaoMock.find(ImmutableMap.of(CheckoutComAPMComponentModel.APMCONFIGURATION, apmConfiguration1Mock))).thenReturn(Collections.emptyList()); + when(checkoutComApmComponentDaoMock.find(Map.of(CheckoutComAPMComponentModel.APMCONFIGURATION, apmConfiguration1Mock))).thenReturn(Collections.emptyList()); final Optional result = testObj.getApmConfigurationMedia(apmConfiguration1Mock); @@ -323,7 +305,7 @@ public void getApmConfigurationMedia_WhenNoApmComponentFound_ShouldReturnOptiona @Test public void getApmConfigurationMedia_WhenApmComponentFound_ShouldReturnMedia() { - when(checkoutComApmComponentDaoMock.find(ImmutableMap.of(CheckoutComAPMComponentModel.APMCONFIGURATION, apmConfiguration1Mock))).thenReturn(List.of(component1Mock)); + when(checkoutComApmComponentDaoMock.find(Map.of(CheckoutComAPMComponentModel.APMCONFIGURATION, apmConfiguration1Mock))).thenReturn(List.of(component1Mock)); when(component1Mock.getMedia()).thenReturn(mediaMock); final Optional result = testObj.getApmConfigurationMedia(apmConfiguration1Mock); diff --git a/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/merchant/services/impl/DefaultCheckoutComMerchantConfigurationServiceTest.java b/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/merchant/services/impl/DefaultCheckoutComMerchantConfigurationServiceTest.java index 1ab57c9..a7a12bf 100644 --- a/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/merchant/services/impl/DefaultCheckoutComMerchantConfigurationServiceTest.java +++ b/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/merchant/services/impl/DefaultCheckoutComMerchantConfigurationServiceTest.java @@ -22,9 +22,6 @@ @RunWith(MockitoJUnitRunner.class) public class DefaultCheckoutComMerchantConfigurationServiceTest { - private static final String SECRET_KEY = "secretKey"; - private static final String PUBLIC_KEY = "publicKey"; - private static final String PRIVATE_SHARED_KEY = "privateSharedKey"; private static final String NAS_SECRET_KEY = "nasSecretKey"; private static final String NAS_PUBLIC_KEY = "nasPublicKey"; private static final String NAS_AUTH_HEADER_KEY = "nasAuthHeaderKey"; @@ -63,45 +60,9 @@ public void setUp() { when(baseSiteMock.getCheckoutComMerchantConfiguration()).thenReturn(merchantConfigurationMock); } - @Test - public void getSecretKey_ShouldReturnTheValueAsExpected() { - when(merchantConfigurationMock.getSecretKey()).thenReturn(SECRET_KEY); - - final String result = testObj.getSecretKey(); - - assertEquals(SECRET_KEY, result); - } - - @Test - public void getPublicKey_ShouldReturnTheValueAsExpected() { - when(merchantConfigurationMock.getPublicKey()).thenReturn(PUBLIC_KEY); - - final String result = testObj.getPublicKey(); - - assertEquals(PUBLIC_KEY, result); - } - - @Test - public void getPublicKeyForSite_ShouldReturnTheValueAsExpected() { - when(merchantConfigurationMock.getPublicKey()).thenReturn(PUBLIC_KEY); - - final String result = testObj.getPublicKeyForSite(BASE_SITE_ID); - - assertEquals(PUBLIC_KEY, result); - } - - @Test - public void getPrivateSharedKey_ShouldReturnTheValueAsExpected() { - when(merchantConfigurationMock.getPrivateSharedKey()).thenReturn(PRIVATE_SHARED_KEY); - - final String result = testObj.getPrivateSharedKey(); - - assertEquals(PRIVATE_SHARED_KEY, result); - } @Test - public void getSecretKey_WhenNASEnabled_ShouldReturnTheValueAsExpected() { - when(merchantConfigurationMock.getUseNas()).thenReturn(Boolean.TRUE); + public void getSecretKey_ShouldReturnTheValueAsExpected() { when(merchantConfigurationMock.getNasSecretKey()).thenReturn(NAS_SECRET_KEY); final String result = testObj.getSecretKey(); @@ -110,8 +71,7 @@ public void getSecretKey_WhenNASEnabled_ShouldReturnTheValueAsExpected() { } @Test - public void getPublicKey_WhenNASEnabled_ShouldReturnTheValueAsExpected() { - when(merchantConfigurationMock.getUseNas()).thenReturn(Boolean.TRUE); + public void getPublicKey_ShouldReturnTheValueAsExpected() { when(merchantConfigurationMock.getNasPublicKey()).thenReturn(NAS_PUBLIC_KEY); final String result = testObj.getPublicKey(); @@ -120,8 +80,7 @@ public void getPublicKey_WhenNASEnabled_ShouldReturnTheValueAsExpected() { } @Test - public void getPublicKeyForSite_WhenNASEnabled_ShouldReturnTheValueAsExpected() { - when(merchantConfigurationMock.getUseNas()).thenReturn(Boolean.TRUE); + public void getPublicKeyForSite_ShouldReturnTheValueAsExpected() { when(merchantConfigurationMock.getNasPublicKey()).thenReturn(NAS_PUBLIC_KEY); final String result = testObj.getPublicKeyForSite(BASE_SITE_ID); @@ -130,8 +89,7 @@ public void getPublicKeyForSite_WhenNASEnabled_ShouldReturnTheValueAsExpected() } @Test - public void getPrivateSharedKey_WhenNASEnabled_ShouldReturnTheValueAsExpected() { - when(merchantConfigurationMock.getUseNas()).thenReturn(Boolean.TRUE); + public void getPrivateSharedKey_ShouldReturnTheValueAsExpected() { when(merchantConfigurationMock.getNasSignatureKey()).thenReturn(NAS_SIGNATURE_KEY); final String result = testObj.getPrivateSharedKey(); @@ -318,13 +276,6 @@ public void getNasAuthorizationKey_shouldReturnNASAuthorizationKey() { assertEquals(NAS_AUTH_HEADER_KEY, result); } - @Test - public void isNasUsed_shouldReturnConfigurationNASFlag() { - when(merchantConfigurationMock.getUseNas()).thenReturn(true); - - assertTrue(testObj.isNasUsed()); - } - @Test public void isNasAuthorisationHeaderUsedOnNotificationValidation_shouldReturnConfigurationFlag() { when(merchantConfigurationMock.getUseNasAuthorisationKeyOnNotifications()).thenReturn(true); @@ -339,13 +290,6 @@ public void isNasSignatureKeyUsedOnNotificationValidation_shouldReturnConfigurat assertTrue(testObj.isNasSignatureKeyUsedOnNotificationValidation()); } - @Test - public void isAbcSignatureKeyUsedOnNotificationValidation_shouldReturnConfigurationFlag() { - when(merchantConfigurationMock.getUseAbcSignatureKeyOnNotifications()).thenReturn(true); - - assertTrue(testObj.isAbcSignatureKeyUsedOnNotificationValidation()); - } - @Test public void getAchConfiguration_shouldReturnAchConfiguration() { when(merchantConfigurationMock.getAchConfiguration()).thenReturn(achConfigurationMock); @@ -354,4 +298,13 @@ public void getAchConfiguration_shouldReturnAchConfiguration() { assertThat(result).isSameAs(achConfigurationMock); } + + @Test + public void getSecretKeyForSite_ShouldReturnTheValueAsExpected() { + when(merchantConfigurationMock.getNasSecretKey()).thenReturn(NAS_SECRET_KEY); + + final String result = testObj.getSecretKeyForSite(BASE_SITE_ID); + + assertEquals(NAS_SECRET_KEY, result); + } } diff --git a/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/payment/klarna/request/converters/populators/CheckoutComKlarnaProductsRequestDtoPopulatorTest.java b/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/payment/klarna/request/converters/populators/CheckoutComKlarnaProductsRequestDtoPopulatorTest.java index 639e15e..d05acf2 100644 --- a/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/payment/klarna/request/converters/populators/CheckoutComKlarnaProductsRequestDtoPopulatorTest.java +++ b/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/payment/klarna/request/converters/populators/CheckoutComKlarnaProductsRequestDtoPopulatorTest.java @@ -36,7 +36,6 @@ public class CheckoutComKlarnaProductsRequestDtoPopulatorTest { private static final Long CHECKOUTCOM_CONVERTED_DISCOUNT_AMOUNT_LONG = -1000L; private static final double CHECKOUTCOM_DISCOUNT_AMOUNT_DOUBLE = 10.00d; private static final double CHECKOUTCOM_TOTAL_PRICE_AMOUNT_DOUBLE = 800.00d; - private static final Long CHECKOUTCOM_TOTAL_PRICE_AMOUNT_LONG = 80000L; private static final double CHECKOUTCOM_TAX_RATE_DOUBLE = 0.1539d; private static final double CHECKOUTCOM_PAYMENT_COST_AMOUNT_DOUBLE = 3.99d; private static final Long CHECKOUTCOM_PAYMENT_COST_AMOUNT_LONG = 399L; @@ -45,8 +44,6 @@ public class CheckoutComKlarnaProductsRequestDtoPopulatorTest { private static final String DELIVERY_NAME = "Delivery name"; private static final String DISCOUNT_NAME = "Order total discount"; private static final String PAYMENT_COST_NAME = "Order payment cost"; - private static final double CHECKOUTCOM_TAXPERCENT_AMOUNT_DOUBLE = 18.189339321593195D; - private static final Long CHECKOUTCOM_TAXPERCENT_AMOUNT_LONG = 1819L; private static final double CHECKOUTCOM_TAXAMOUNT_DOUBLE = 18.948168000000003D; private static final Long CHECKOUTCOM_TAXAMOUNT_LONG = 1895L; @@ -71,8 +68,6 @@ public class CheckoutComKlarnaProductsRequestDtoPopulatorTest { private TaxValue taxValueMock; @Mock private DiscountModel discountModelMock; - @Mock - private KlarnaProductRequestDto product1Mock, product2Mock; private List target = new ArrayList<>(); @@ -83,7 +78,6 @@ public void setUp() { when(checkoutComCurrencyServiceMock.convertAmountIntoPennies(CURRENCY_CODE, CHECKOUTCOM_AMOUNT_DOUBLE)).thenReturn(CHECKOUTCOM_AMOUNT_LONG); when(checkoutComCurrencyServiceMock.convertAmountIntoPennies(CURRENCY_CODE, CHECKOUTCOM_DISCOUNT_AMOUNT_DOUBLE)).thenReturn(CHECKOUTCOM_DISCOUNT_AMOUNT_LONG); when(checkoutComCurrencyServiceMock.convertAmountIntoPennies(CURRENCY_CODE, CHECKOUTCOM_PAYMENT_COST_AMOUNT_DOUBLE)).thenReturn(CHECKOUTCOM_PAYMENT_COST_AMOUNT_LONG); - when(checkoutComCurrencyServiceMock.convertAmountIntoPennies(CURRENCY_CODE, CHECKOUTCOM_TAXPERCENT_AMOUNT_DOUBLE)).thenReturn(0L).thenReturn(CHECKOUTCOM_TAXPERCENT_AMOUNT_LONG); when(checkoutComCurrencyServiceMock.convertAmountIntoPennies(CURRENCY_CODE, CHECKOUTCOM_TAXAMOUNT_DOUBLE)).thenReturn(0L).thenReturn(CHECKOUTCOM_TAXAMOUNT_LONG); when(sourceMock.getTotalTax()).thenReturn(CHECKOUTCOM_AMOUNT_DOUBLE); @@ -92,7 +86,6 @@ public void setUp() { when(entry2Mock.getBasePrice()).thenReturn(CHECKOUTCOM_AMOUNT_DOUBLE); when(entry1Mock.getQuantity()).thenReturn(1l); when(entry2Mock.getQuantity()).thenReturn(1l); - when(taxValueMock.getValue()).thenReturn(CHECKOUTCOM_AMOUNT_DOUBLE); when(entry1Mock.getProduct()).thenReturn(productModelMock); when(entry2Mock.getProduct()).thenReturn(productModelMock); when(productModelMock.getName()).thenReturn(PRODUCT_NAME); @@ -111,35 +104,30 @@ public void populate_ShouldPopulateTheProductsProperly() { assertEquals(PRODUCT_NAME, target.get(0).getName()); assertEquals(Long.valueOf(1), target.get(0).getQuantity()); - assertEquals(Long.valueOf(0), target.get(0).getTaxRate()); assertEquals(Long.valueOf(0), target.get(0).getTotalTaxAmount()); assertEquals(CHECKOUTCOM_AMOUNT_LONG, target.get(0).getUnitPrice()); assertEquals(CHECKOUTCOM_AMOUNT_LONG, target.get(0).getTotalAmount()); assertEquals(PRODUCT_NAME, target.get(1).getName()); assertEquals(Long.valueOf(1), target.get(1).getQuantity()); - assertEquals(CHECKOUTCOM_TAXPERCENT_AMOUNT_LONG, target.get(1).getTaxRate()); assertEquals(CHECKOUTCOM_TAXAMOUNT_LONG, target.get(1).getTotalTaxAmount()); assertEquals(CHECKOUTCOM_AMOUNT_LONG, target.get(1).getUnitPrice()); assertEquals(CHECKOUTCOM_AMOUNT_LONG, target.get(1).getTotalAmount()); assertEquals(DELIVERY_NAME, target.get(2).getName()); assertEquals(Long.valueOf(1), target.get(2).getQuantity()); - assertEquals(Long.valueOf(0), target.get(2).getTaxRate()); assertEquals(Long.valueOf(0), target.get(2).getTotalTaxAmount()); assertEquals(CHECKOUTCOM_AMOUNT_LONG, target.get(2).getUnitPrice()); assertEquals(CHECKOUTCOM_AMOUNT_LONG, target.get(2).getTotalAmount()); assertEquals(DISCOUNT_NAME, target.get(3).getName()); assertEquals(Long.valueOf(1), target.get(3).getQuantity()); - assertEquals(Long.valueOf(0), target.get(3).getTaxRate()); assertEquals(Long.valueOf(0), target.get(3).getTotalTaxAmount()); assertEquals(CHECKOUTCOM_CONVERTED_DISCOUNT_AMOUNT_LONG, target.get(3).getUnitPrice()); assertEquals(CHECKOUTCOM_CONVERTED_DISCOUNT_AMOUNT_LONG, target.get(3).getTotalAmount()); assertEquals(PAYMENT_COST_NAME, target.get(4).getName()); assertEquals(Long.valueOf(1), target.get(4).getQuantity()); - assertEquals(Long.valueOf(0), target.get(4).getTaxRate()); assertEquals(Long.valueOf(0), target.get(4).getTotalTaxAmount()); assertEquals(CHECKOUTCOM_PAYMENT_COST_AMOUNT_LONG, target.get(4).getUnitPrice()); assertEquals(CHECKOUTCOM_PAYMENT_COST_AMOUNT_LONG, target.get(4).getTotalAmount()); @@ -165,10 +153,6 @@ public void populateShippingLine_ShouldNotSetTaxRate_WhenTaxIsZero() { testObj.populateShippingLine(sourceMock, CURRENCY_CODE, productRequestDtos, 0.00d); assertThat(productRequestDtos).isNotEmpty(); - - final KlarnaProductRequestDto shippingRequestDto = productRequestDtos.get(0); - - assertThat(shippingRequestDto.getTaxRate()).isZero(); } @Test @@ -178,10 +162,6 @@ public void populateShippingLine_ShouldNotSetTaxRateIfTax_WhenLessThanZero() { testObj.populateShippingLine(sourceMock, CURRENCY_CODE, productRequestDtos, 0.00d); assertThat(productRequestDtos).isNotEmpty(); - - final KlarnaProductRequestDto shippingRequestDto = productRequestDtos.get(0); - - assertThat(shippingRequestDto.getTaxRate()).isZero(); } @Test @@ -193,10 +173,6 @@ public void populateShippingLine_ShouldSetTaxRate_WhenIfTaxIsGreaterThanZero() { testObj.populateShippingLine(sourceMock, CURRENCY_CODE, productRequestDtos, CHECKOUTCOM_TAX_RATE_DOUBLE); assertThat(productRequestDtos).isNotEmpty(); - - final KlarnaProductRequestDto shippingRequestDto = productRequestDtos.get(0); - - assertThat(shippingRequestDto.getTaxRate()).isNotZero(); } @Test @@ -217,10 +193,6 @@ public void populateOrderDiscount_ShouldNotSetTaxRate_WhenTaxIsZero() { testObj.populateOrderDiscount(sourceMock, CURRENCY_CODE, productRequestDtos, 0.00d); assertThat(productRequestDtos).isNotEmpty(); - - final KlarnaProductRequestDto discountRequestDto = productRequestDtos.get(0); - - assertThat(discountRequestDto.getTaxRate()).isZero(); } @Test @@ -231,10 +203,6 @@ public void populateOrderDiscount_ShouldSetTaxRate_WhenIfTaxIsGreaterThanZero() testObj.populateOrderDiscount(sourceMock, CURRENCY_CODE, productRequestDtos, CHECKOUTCOM_TAX_RATE_DOUBLE); assertThat(productRequestDtos).isNotEmpty(); - - final KlarnaProductRequestDto discountRequestDto = productRequestDtos.get(0); - - assertThat(discountRequestDto.getTaxRate()).isNotZero(); } @Test @@ -244,10 +212,6 @@ public void populateOrderDiscount_ShouldNotSetTaxRateIfTax_WhenLessThanZero() { testObj.populateOrderDiscount(sourceMock, CURRENCY_CODE, productRequestDtos, 0.00d); assertThat(productRequestDtos).isNotEmpty(); - - final KlarnaProductRequestDto discountRequestDto = productRequestDtos.get(0); - - assertThat(discountRequestDto.getTaxRate()).isZero(); } @Test @@ -268,10 +232,6 @@ public void populatePaymentCost_ShouldNotSetTaxRate_WhenTaxIsZero() { testObj.populatePaymentCost(sourceMock, CURRENCY_CODE, productRequestDtos, 0.00d); assertThat(productRequestDtos).isNotEmpty(); - - final KlarnaProductRequestDto paymentCostRequestDto = productRequestDtos.get(0); - - assertThat(paymentCostRequestDto.getTaxRate()).isZero(); } @Test @@ -283,8 +243,6 @@ public void populatePaymentCost_ShouldSetTaxRate_WhenIfTaxIsGreaterThanZero() { testObj.populatePaymentCost(sourceMock, CURRENCY_CODE, productRequestDtos, CHECKOUTCOM_TAX_RATE_DOUBLE); assertThat(productRequestDtos).isNotEmpty(); - final KlarnaProductRequestDto paymentCostRequestDto = productRequestDtos.get(0); - assertThat(paymentCostRequestDto.getTaxRate()).isNotZero(); } @Test @@ -294,10 +252,6 @@ public void populatePaymentCost_ShouldNotSetTaxRateIfTax_WhenLessThanZero() { testObj.populatePaymentCost(sourceMock, CURRENCY_CODE, productRequestDtos, 0.00d); assertThat(productRequestDtos).isNotEmpty(); - - final KlarnaProductRequestDto paymentCostRequestDto = productRequestDtos.get(0); - - assertThat(paymentCostRequestDto.getTaxRate()).isZero(); } @Test(expected = IllegalArgumentException.class) diff --git a/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/payment/request/strategies/impl/CheckoutComKlarnaPaymentRequestStrategyTest.java b/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/payment/request/strategies/impl/CheckoutComKlarnaPaymentRequestStrategyTest.java index 0ad667d..392a656 100644 --- a/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/payment/request/strategies/impl/CheckoutComKlarnaPaymentRequestStrategyTest.java +++ b/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/payment/request/strategies/impl/CheckoutComKlarnaPaymentRequestStrategyTest.java @@ -1,21 +1,11 @@ package com.checkout.hybris.core.payment.request.strategies.impl; import com.checkout.hybris.core.currency.services.CheckoutComCurrencyService; -import com.checkout.hybris.core.klarna.request.KlarnaAddressDto; -import com.checkout.hybris.core.klarna.session.request.KlarnaProductRequestDto; import com.checkout.hybris.core.model.CheckoutComKlarnaAPMPaymentInfoModel; -import com.checkout.sdk.payments.AlternativePaymentSource; import com.checkout.sdk.payments.PaymentRequest; import com.checkout.sdk.payments.RequestSource; import de.hybris.bootstrap.annotations.UnitTest; -import de.hybris.platform.cms2.model.site.CMSSiteModel; -import de.hybris.platform.core.model.c2l.CountryModel; -import de.hybris.platform.core.model.c2l.CurrencyModel; -import de.hybris.platform.core.model.order.AbstractOrderEntryModel; import de.hybris.platform.core.model.order.CartModel; -import de.hybris.platform.core.model.user.AddressModel; -import de.hybris.platform.core.model.user.CustomerModel; -import de.hybris.platform.servicelayer.dto.converter.Converter; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -24,31 +14,18 @@ import org.mockito.runners.MockitoJUnitRunner; import org.springframework.test.util.ReflectionTestUtils; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; - import static com.checkout.hybris.core.payment.enums.CheckoutComPaymentType.KLARNA; -import static com.checkout.hybris.core.payment.request.strategies.impl.CheckoutComKlarnaPaymentRequestStrategy.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @UnitTest @RunWith(MockitoJUnitRunner.class) public class CheckoutComKlarnaPaymentRequestStrategyTest { - private static final String CURRENCY_ISO_CODE = "USD"; - private static final String KLARNA_AUTH_TOKEN_VALUE = "klarna_token"; + private static final String CURRENCY_ISO_CODE = "EUR"; + private static final String KLARNA_PAYMENT_CONTEXT_VALUE = "klarna_context"; private static final Long CHECKOUT_COM_TOTAL_PRICE = 10000L; - private static final Long CHECKOUTCOM_AMOUNT_LONG = 12312L; - private static final double CHECKOUTCOM_AMOUNT_DOUBLE = 123.12d; - private static final String CURRENCY_CODE = "GBP"; - private static final String COUNTRY_CODE = "GB"; - private static final String LOCALE_CODE = Locale.UK.toString().replace("_", "-"); - private static final String EMAIL_VALUE = "email@test.com"; - private static final String CHECKOUTCOM_PAYMENT_REFERENCE_VALUE = "checkout_payment_ref"; @InjectMocks private CheckoutComKlarnaPaymentRequestStrategy testObj; @@ -58,72 +35,24 @@ public class CheckoutComKlarnaPaymentRequestStrategyTest { @Mock private CheckoutComCurrencyService checkoutComCurrencyServiceMock; @Mock - private Converter> checkoutComKlarnaProductsRequestDtoPopulatorMock; - @Mock private CartModel cartModelMock; - @Mock - private CurrencyModel currencyModelMock; - @Mock - private AddressModel addressMock; - @Mock - private CountryModel countryModelMock; - @Mock - private CMSSiteModel cmsSiteMock; + @Mock private CheckoutComKlarnaAPMPaymentInfoModel klarnaPaymentInfoMock; - @Mock - private AbstractOrderEntryModel entry1Mock, entry2Mock; - @Mock - private KlarnaProductRequestDto product1Mock, product2Mock; - @Mock - private CustomerModel customerMock; @Before public void setUp() { ReflectionTestUtils.setField(testObj, "checkoutPaymentRequestServicesWrapper", checkoutPaymentRequestServicesWrapperMock); ReflectionTestUtils.setField(checkoutPaymentRequestServicesWrapperMock, "checkoutComCurrencyService", checkoutComCurrencyServiceMock); when(cartModelMock.getPaymentInfo()).thenReturn(klarnaPaymentInfoMock); - when(cartModelMock.getUser()).thenReturn(customerMock); - when(customerMock.getContactEmail()).thenReturn(EMAIL_VALUE); - when(klarnaPaymentInfoMock.getType()).thenReturn(KLARNA.name()); - when(klarnaPaymentInfoMock.getAuthorizationToken()).thenReturn(KLARNA_AUTH_TOKEN_VALUE); - when(klarnaPaymentInfoMock.getBillingAddress()).thenReturn(addressMock); - when(cartModelMock.getDeliveryAddress()).thenReturn(addressMock); - when(checkoutComCurrencyServiceMock.convertAmountIntoPennies(CURRENCY_CODE, CHECKOUTCOM_AMOUNT_DOUBLE)).thenReturn(CHECKOUTCOM_AMOUNT_LONG); - when(cartModelMock.getTotalTax()).thenReturn(CHECKOUTCOM_AMOUNT_DOUBLE); - when(cartModelMock.getCurrency()).thenReturn(currencyModelMock); - when(currencyModelMock.getIsocode()).thenReturn(CURRENCY_CODE); - when(cartModelMock.getSite()).thenReturn(cmsSiteMock); - when(cmsSiteMock.getLocale()).thenReturn(LOCALE_CODE); - when(addressMock.getCountry()).thenReturn(countryModelMock); - when(countryModelMock.getIsocode()).thenReturn(COUNTRY_CODE); - when(cartModelMock.getCheckoutComPaymentReference()).thenReturn(CHECKOUTCOM_PAYMENT_REFERENCE_VALUE); - when(checkoutComKlarnaProductsRequestDtoPopulatorMock.convert(cartModelMock)).thenReturn(Arrays.asList(product1Mock, product2Mock)); - + when(klarnaPaymentInfoMock.getPaymentContext()).thenReturn(KLARNA_PAYMENT_CONTEXT_VALUE); } @Test public void getRequestSourcePaymentRequest_WhenEverythingIsCorrect_ShouldPopulateTheRequest() { final PaymentRequest result = testObj.getRequestSourcePaymentRequest(cartModelMock, CURRENCY_ISO_CODE, CHECKOUT_COM_TOTAL_PRICE); - assertEquals(KLARNA.name().toLowerCase(), result.getSource().getType()); - final AlternativePaymentSource source = (AlternativePaymentSource) result.getSource(); - assertEquals(KLARNA_AUTH_TOKEN_VALUE, source.get(AUTHORIZATION_TOKEN_KEY)); - assertEquals(LOCALE_CODE, source.get(LOCALE_KEY)); - assertEquals(COUNTRY_CODE, source.get(PURCHASE_COUNTRY_KEY)); - assertEquals(CHECKOUTCOM_AMOUNT_LONG, source.get(TAX_AMOUNT_KEY)); - assertEquals(CHECKOUTCOM_PAYMENT_REFERENCE_VALUE, source.get(MERCHANT_REFERENCE_KEY)); - final KlarnaAddressDto billingAddressDto = (KlarnaAddressDto) source.get(BILLING_ADDRESS_KEY); - final KlarnaAddressDto deliveryAddressDto = (KlarnaAddressDto) source.get(SHIPPING_ADDRESS_KEY); - - assertEquals(COUNTRY_CODE, billingAddressDto.getCountry()); - assertEquals(COUNTRY_CODE, deliveryAddressDto.getCountry()); - - final List products = (List) source.get(PRODUCTS_KEY); - verify(checkoutComKlarnaProductsRequestDtoPopulatorMock).convert(cartModelMock); - assertEquals(2, products.size()); - assertEquals(product1Mock, products.get(0)); - assertEquals(product2Mock, products.get(1)); + assertEquals(KLARNA_PAYMENT_CONTEXT_VALUE, result.getPaymentContextId()); } @Test diff --git a/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/payment/response/strategies/impl/CheckoutComKlarnaPaymentResponseStrategyTest.java b/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/payment/response/strategies/impl/CheckoutComKlarnaPaymentResponseStrategyTest.java new file mode 100644 index 0000000..be5f6cf --- /dev/null +++ b/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/payment/response/strategies/impl/CheckoutComKlarnaPaymentResponseStrategyTest.java @@ -0,0 +1,57 @@ +package com.checkout.hybris.core.payment.response.strategies.impl; + +import com.checkout.hybris.core.authorisation.AuthorizeResponse; +import com.checkout.hybris.core.model.CheckoutComKlarnaAPMPaymentInfoModel; +import com.checkout.hybris.core.payment.services.CheckoutComPaymentInfoService; +import com.checkout.sdk.payments.PaymentPending; +import de.hybris.bootstrap.annotations.UnitTest; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static com.checkout.hybris.core.payment.enums.CheckoutComPaymentType.KLARNA; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +@UnitTest +@RunWith(MockitoJUnitRunner.class) +public class CheckoutComKlarnaPaymentResponseStrategyTest { + + private static final String PAYMENT_ID = "paymentId"; + + @InjectMocks + private CheckoutComKlarnaPaymentResponseStrategy testObj; + + @Mock + private PaymentPending pendingResponseMock; + @Mock + private CheckoutComKlarnaAPMPaymentInfoModel klarnaPaymentInfoMock; + @Mock + private CheckoutComPaymentInfoService paymentInfoServiceMock; + + @Before + public void setUp() { + when(pendingResponseMock.getId()).thenReturn(PAYMENT_ID); + doNothing().when(paymentInfoServiceMock).addPaymentId(PAYMENT_ID, klarnaPaymentInfoMock); + } + + @Test + public void getStrategyKey_ShouldReturnAchPaymentType() { + assertEquals(KLARNA, testObj.getStrategyKey()); + } + + @Test + public void handlePendingPaymentResponse_WhenKlarna_ShouldReturnAuthorizeResponseSuccess() { + final AuthorizeResponse result = testObj.handlePendingPaymentResponse(pendingResponseMock, klarnaPaymentInfoMock); + + verify(paymentInfoServiceMock).addPaymentId(PAYMENT_ID, klarnaPaymentInfoMock); + assertFalse(result.getIsRedirect()); + assertTrue(result.getIsDataRequired()); + assertTrue(result.getIsSuccess()); + assertNull(result.getRedirectUrl()); + } + +} diff --git a/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/payment/services/impl/DefaultCheckoutComPaymentIntegrationServiceTest.java b/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/payment/services/impl/DefaultCheckoutComPaymentIntegrationServiceTest.java index 69cfcff..1b8020f 100644 --- a/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/payment/services/impl/DefaultCheckoutComPaymentIntegrationServiceTest.java +++ b/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/payment/services/impl/DefaultCheckoutComPaymentIntegrationServiceTest.java @@ -1,5 +1,6 @@ package com.checkout.hybris.core.payment.services.impl; +import com.checkout.hybris.core.klarna.session.response.KlarnaPartnerMetadataResponseDto; import com.checkout.hybris.core.payment.services.CheckoutComPaymentInfoService; import com.checkout.sdk.CheckoutApi; import com.checkout.hybris.core.enums.EnvironmentType; @@ -71,6 +72,7 @@ public class DefaultCheckoutComPaymentIntegrationServiceTest { private static final String KLARNA_VOID_URL = "https://prod.url/%s/void"; private static final String SITE_ID = "siteId"; private static final Long CHECKOUTCOM_AMOUNT_LONG = 12312L; + private static final String ID = "id"; @Spy @InjectMocks @@ -172,8 +174,8 @@ public class DefaultCheckoutComPaymentIntegrationServiceTest { @Before public void setUp() throws ExecutionException, InterruptedException { when(checkoutComMerchantConfigurationServiceMock.getEnvironment()).thenReturn(EnvironmentType.TEST); - when(checkoutComMerchantConfigurationServiceMock.getPublicKey()).thenReturn(PUBLIC_KEY); - when(checkoutComMerchantConfigurationServiceMock.getPublicKeyForSite(SITE_ID)).thenReturn(PUBLIC_KEY); + when(checkoutComMerchantConfigurationServiceMock.getSecretKey()).thenReturn(SECRET_KEY); + when(checkoutComMerchantConfigurationServiceMock.getSecretKeyForSite(SITE_ID)).thenReturn(SECRET_KEY); when(checkoutApiMock.paymentsClient()).thenReturn(paymentsClientMock); when(checkoutApiMock.tokensClient()).thenReturn(tokensClientMock); when(paymentsClientMock.requestAsync(paymentRequestMock)).thenReturn(completableFutureAuthMock); @@ -380,8 +382,11 @@ public void generateWalletPaymentToken_ShouldGiveBackTheTokenResponse() { @Test public void createKlarnaSession_ShouldGiveBackTheKlarnaSessionResponse() throws ExecutionException { final KlarnaSessionResponseDto klarnaSessionResponseDto = new KlarnaSessionResponseDto(); - klarnaSessionResponseDto.setClientToken(CLIENT_TOKEN); - klarnaSessionResponseDto.setSessionId(SESSION_ID); + final KlarnaPartnerMetadataResponseDto klarnaPartnerMetadataResponseDto = new KlarnaPartnerMetadataResponseDto(); + klarnaSessionResponseDto.setPartnerMetadata(klarnaPartnerMetadataResponseDto); + klarnaPartnerMetadataResponseDto.setClientToken(CLIENT_TOKEN); + klarnaPartnerMetadataResponseDto.setSessionId(SESSION_ID); + klarnaSessionResponseDto.setId(ID); doReturn(KLARNA_SESSION_URL).when(testObj).getKlarnaApiUrlForEnvironment(null, "checkoutservices.klarna.createsession.api.url"); when(restTemplateMock.postForEntity(eq(KLARNA_SESSION_URL), any(HttpEntity.class), eq(KlarnaSessionResponseDto.class))).thenReturn(klarnaSessionResponseEntityMock); @@ -389,23 +394,20 @@ public void createKlarnaSession_ShouldGiveBackTheKlarnaSessionResponse() throws final KlarnaSessionResponseDto result = testObj.createKlarnaSession(klarnaSessionRequestDtoMock); - assertEquals(CLIENT_TOKEN, result.getClientToken()); - assertEquals(SESSION_ID, result.getSessionId()); + assertEquals(CLIENT_TOKEN, result.getPartnerMetadata().getClientToken()); + assertEquals(SESSION_ID, result.getPartnerMetadata().getSessionId()); + assertEquals(ID, result.getId()); verify(restTemplateMock).postForEntity(eq(KLARNA_SESSION_URL), klarnaHttpEntityCaptor.capture(), eq(KlarnaSessionResponseDto.class)); final HttpEntity entityCaptorValue = klarnaHttpEntityCaptor.getValue(); assertEquals(MediaType.APPLICATION_JSON, entityCaptorValue.getHeaders().getContentType()); - assertEquals(Collections.singletonList(PUBLIC_KEY), entityCaptorValue.getHeaders().get(HttpHeaders.AUTHORIZATION)); + assertEquals(Collections.singletonList(SECRET_KEY), entityCaptorValue.getHeaders().get(HttpHeaders.AUTHORIZATION)); assertSame(klarnaSessionRequestDtoMock, entityCaptorValue.getBody()); } @Test(expected = ExecutionException.class) public void createKlarnaSession_WhenHttpStatusCodeException_ShouldThrowExecutionException() throws ExecutionException { - final KlarnaSessionResponseDto klarnaSessionResponseDto = new KlarnaSessionResponseDto(); - klarnaSessionResponseDto.setClientToken(CLIENT_TOKEN); - klarnaSessionResponseDto.setSessionId(SESSION_ID); - doReturn(KLARNA_SESSION_URL).when(testObj).getKlarnaApiUrlForEnvironment(null, "checkoutservices.klarna.createsession.api.url"); when(restTemplateMock.postForEntity(eq(KLARNA_SESSION_URL), any(HttpEntity.class), eq(KlarnaSessionResponseDto.class))).thenReturn(klarnaSessionResponseEntityMock); doThrow(new HttpClientErrorException(HttpStatus.CONFLICT)).when(restTemplateMock).postForEntity(eq(KLARNA_SESSION_URL), any(HttpEntity.class), eq(KlarnaSessionResponseDto.class)); @@ -416,8 +418,6 @@ public void createKlarnaSession_WhenHttpStatusCodeException_ShouldThrowExecution @Test(expected = MockitoException.class) public void createKlarnaSession_WhenConnectException_ShouldThrowExecutionException() throws ExecutionException { final KlarnaSessionResponseDto klarnaSessionResponseDto = new KlarnaSessionResponseDto(); - klarnaSessionResponseDto.setClientToken(CLIENT_TOKEN); - klarnaSessionResponseDto.setSessionId(SESSION_ID); doThrow(ConnectException.class).when(restTemplateMock).postForEntity(eq(KLARNA_SESSION_URL), any(HttpEntity.class), eq(KlarnaSessionResponseDto.class)); when(klarnaSessionResponseEntityMock.getBody()).thenReturn(klarnaSessionResponseDto); @@ -444,7 +444,7 @@ public void captureKlarnaPayment_ShouldGiveBackTheCaptureResponse() throws Execu final HttpEntity entityCaptorValue = klarnaHttpEntityCaptor.getValue(); assertEquals(MediaType.APPLICATION_JSON, entityCaptorValue.getHeaders().getContentType()); - assertEquals(Collections.singletonList(PUBLIC_KEY), entityCaptorValue.getHeaders().get(HttpHeaders.AUTHORIZATION)); + assertEquals(Collections.singletonList(SECRET_KEY), entityCaptorValue.getHeaders().get(HttpHeaders.AUTHORIZATION)); assertSame(klarnaCaptureRequestMock, entityCaptorValue.getBody()); final String klarnaCaptureUrl = klarnaUrlCaptor.getValue(); @@ -494,7 +494,7 @@ public void voidKlarnaPayment_ShouldGiveBackTheVoidResponse() throws ExecutionEx final HttpEntity entityCaptorValue = klarnaHttpEntityCaptor.getValue(); assertEquals(MediaType.APPLICATION_JSON, entityCaptorValue.getHeaders().getContentType()); - assertEquals(Collections.singletonList(PUBLIC_KEY), entityCaptorValue.getHeaders().get(HttpHeaders.AUTHORIZATION)); + assertEquals(Collections.singletonList(SECRET_KEY), entityCaptorValue.getHeaders().get(HttpHeaders.AUTHORIZATION)); assertSame(klarnaVoidRequestMock, entityCaptorValue.getBody()); final String klarnaVoidUrl = klarnaUrlCaptor.getValue(); diff --git a/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/payment/services/impl/DefaultCheckoutComPaymentServiceTest.java b/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/payment/services/impl/DefaultCheckoutComPaymentServiceTest.java index fcff5bf..e73705c 100644 --- a/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/payment/services/impl/DefaultCheckoutComPaymentServiceTest.java +++ b/hybris/bin/modules/checkoutcom/checkoutservices/testsrc/com/checkout/hybris/core/payment/services/impl/DefaultCheckoutComPaymentServiceTest.java @@ -11,21 +11,16 @@ import com.checkout.hybris.core.payment.services.CheckoutComPaymentReturnedService; import com.checkout.hybris.core.payment.services.CheckoutComPaymentTransactionService; import com.checkout.hybris.events.model.CheckoutComPaymentEventModel; -import com.checkout.sdk.payments.CardSourceResponse; import com.checkout.sdk.payments.PaymentPending; import de.hybris.bootstrap.annotations.UnitTest; -import de.hybris.platform.commerceservices.order.CommercePaymentProviderStrategy; import de.hybris.platform.core.enums.OrderStatus; import de.hybris.platform.core.model.c2l.CurrencyModel; -import de.hybris.platform.core.model.order.CartModel; import de.hybris.platform.core.model.order.OrderModel; -import de.hybris.platform.core.model.user.CustomerModel; import de.hybris.platform.payment.dto.TransactionStatus; import de.hybris.platform.payment.enums.PaymentTransactionType; import de.hybris.platform.payment.model.PaymentTransactionEntryModel; import de.hybris.platform.payment.model.PaymentTransactionModel; import de.hybris.platform.servicelayer.model.ModelService; -import de.hybris.platform.servicelayer.time.TimeService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -63,15 +58,11 @@ public class DefaultCheckoutComPaymentServiceTest { @InjectMocks private DefaultCheckoutComPaymentService testObj; - @Mock - private TimeService timeServiceMock; @Mock private ModelService modelServiceMock; @Mock private CheckoutComPaymentTypeResolver checkoutComPaymentTypeResolverMock; @Mock - private CommercePaymentProviderStrategy commercePaymentProviderStrategyMock; - @Mock private CheckoutComPaymentTransactionService checkoutComPaymentTransactionServiceMock; @Mock private CheckoutComMerchantConfigurationService checkoutComMerchantConfigurationServiceMock; @@ -82,15 +73,9 @@ public class DefaultCheckoutComPaymentServiceTest { @Mock private CheckoutComPaymentReturnedService checkoutComPaymentReturnedServiceMock; - @Mock - private CartModel cartMock; @Mock(answer = Answers.RETURNS_DEEP_STUBS) private OrderModel orderMock; @Mock - private CustomerModel userMock; - @Mock - private CardSourceResponse sourceMock; - @Mock private CurrencyModel currencyModelMock; @Mock private PaymentPending paymentPendingMock; @@ -105,13 +90,12 @@ public class DefaultCheckoutComPaymentServiceTest { @Mock private CheckoutComApplePayPaymentInfoModel nonCardPaymentInfoMock; @Mock - private CheckoutComCreditCardPaymentInfoModel cardPaymentInfoMock, userPaymentInfo1Mock, userPaymentInfo2Mock; + private CheckoutComCreditCardPaymentInfoModel cardPaymentInfoMock; @Mock private PaymentTransactionEntryModel paymentTransactionEntryMock, capturePaymentTransactionEntryMock, capturePendingPaymentTransactionEntryMock, rejectedAuthorizationPaymentTransactionEntryMock, acceptedAuthorizationPaymentTransactionEntryMock, reviewAuthorizationPaymentTransactionEntryMock, - refundPaymentTransactionEntry1Mock, refundPaymentTransactionEntry2Mock, - cancelPaymentTransactionEntryMock, authorizationPendingPaymentTransactionEntryMock; + refundPaymentTransactionEntry1Mock, cancelPaymentTransactionEntryMock; @Before public void setUp() { @@ -304,24 +288,14 @@ public void isAutoCapture_When_WhenPaymentInfoIsCardPayment_andDoesHaveAutoCaptu } @Test - public void isAutoCapture_When_WhenPaymentInfoIsNotCardPayment_andSiteIsUsingNAS_ShouldReturnTrue() { + public void isAutoCapture_When_WhenPaymentInfoIsNotCardPayment_ShouldReturnTrue() { when(orderMock.getPaymentInfo()).thenReturn(nonCardPaymentInfoMock); - when(orderMock.getSite().getCheckoutComMerchantConfiguration().getUseNas()).thenReturn(true); final boolean result = testObj.isAutoCapture(orderMock); assertTrue(result); } - @Test - public void isAutoCapture_When_WhenPaymentInfoIsNotCardPayment_andSiteIsNotUsingNAS_ShouldReturnFalse() { - when(orderMock.getPaymentInfo()).thenReturn(nonCardPaymentInfoMock); - when(orderMock.getSite().getCheckoutComMerchantConfiguration().getUseNas()).thenReturn(false); - - final boolean result = testObj.isAutoCapture(orderMock); - - assertFalse(result); - } @Test(expected = IllegalArgumentException.class) public void captureExists_WhenTransactionIsNull_ShouldThrowException() { diff --git a/hybris/bin/modules/checkoutcom/checkoutspartacussampledata/resources/checkoutspartacussampledata.build.number b/hybris/bin/modules/checkoutcom/checkoutspartacussampledata/resources/checkoutspartacussampledata.build.number index 8cc1f8d..d167910 100644 --- a/hybris/bin/modules/checkoutcom/checkoutspartacussampledata/resources/checkoutspartacussampledata.build.number +++ b/hybris/bin/modules/checkoutcom/checkoutspartacussampledata/resources/checkoutspartacussampledata.build.number @@ -1,11 +1,11 @@ #Ant properties -#Tue May 28 13:21:42 GMT 2024 +#Tue Jun 18 10:12:56 GMT 2024 version.api=2211 vendor=hybris group.id=de.hybris.platform name=checkoutspartacussampledata description=checkoutspartacussampledata -builddate=20240528 1321 +builddate=20240618 1012 releasedate=20240307 1540 version=2211.20 module.name=platform-module diff --git a/hybris/bin/modules/checkoutcom/checkoutspartacussampledata/resources/checkoutspartacussampledata/import/stores/electronics/site.impex b/hybris/bin/modules/checkoutcom/checkoutspartacussampledata/resources/checkoutspartacussampledata/import/stores/electronics/site.impex index e7f0df8..cf0cf75 100644 --- a/hybris/bin/modules/checkoutcom/checkoutspartacussampledata/resources/checkoutspartacussampledata/import/stores/electronics/site.impex +++ b/hybris/bin/modules/checkoutcom/checkoutspartacussampledata/resources/checkoutspartacussampledata/import/stores/electronics/site.impex @@ -5,8 +5,8 @@ $catalogVersion=catalogversion(catalog(id[default=$productCatalog]),version[defa # Merchant keys "#% if: de.hybris.platform.jalo.extension.ExtensionManager.getInstance().isExtensionInstalled(""spartacussampledata"")" UPDATE GenericItem[processor = de.hybris.platform.commerceservices.impex.impl.ConfigPropertyImportProcessor]; pk[unique = true] -$secretKey = $config-checkout.secret.key -$publicKey = $config-checkout.public.key +$secretKey = $config-checkout.nas.secret.key +$publicKey = $config-checkout.nas.public.key $privateSharedKey = $config-checkout.private.shared.key $nasSecretKey = Bearer $config-checkout.nas.secret.key $nasPublicKey = Bearer $config-checkout.nas.public.key @@ -24,17 +24,17 @@ INSERT_UPDATE CheckoutComApplePayConfiguration; &applePayConfigurationId; certif ; applePayConfig ; $applePayCertificate ; $applePayPrivateKey ; amex, cartesBancaires, chinaUnionPay, discover, eftpos, electron, elo, interac, jcb, mada, maestro, masterCard, privateLabel, visa, vPay ; GB ; supportsCredit, supportsDebit, supports3DS, supportsEMV ; merchant.com.checkout.sandbox.e2y ; e2yCheckoutCom INSERT_UPDATE CheckoutComGooglePayConfiguration; &googlePayConfigurationId; merchantId[unique = true]; merchantName ; environment(code); type ; gateway ; gatewayMerchantId; allowedCardNetworks(code) ; allowedCardAuthMethods(code); threeDSEnabled[default = true] - ; googlePayConfig ; 01234567890123456789 ; e2yCheckoutCom ; test ; CARD ; checkoutltd ; $publicKey ; AMEX, DISCOVER, INTERAC, JCB, MASTERCARD, VISA ; PAN_ONLY, CRYPTOGRAM_3DS + ; googlePayConfig ; 01234567890123456789 ; e2yCheckoutCom ; test ; CARD ; checkoutltd ; $publicKey ; AMEX, DISCOVER, INTERAC, JCB, MASTERCARD, VISA ; PAN_ONLY, CRYPTOGRAM_3DS ; INSERT_UPDATE CheckoutComMerchantConfiguration; code[unique = true] ; applePayConfiguration(&applePayConfigurationId); googlePayConfiguration(&googlePayConfigurationId); klarnaConfiguration(&klarnaConfigurationId) ; merchantConfiguration-$spaSiteUid ; applePayConfig ; googlePayConfig ; klarnaConfig # Merchant configuration -INSERT_UPDATE CheckoutComMerchantConfiguration; code[unique = true] ; secretKey ; publicKey ; privateSharedKey ; nasSecretKey ; nasPublicKey ; nasSignatureKey ; nasAuthorisationHeaderKey ; environment(code); paymentAction(code) ; reviewTransactionsAtRisk; klarnaConfiguration(&klarnaConfigurationId); authorisationAmountValidationThreshold; threeDSEnabled; noThreeDSAttempt; checkoutComPaymentEventTypes(code) ; includeBillingDescriptor; billingDescriptorName; billingDescriptorCity; achConfiguration(code) - ; merchantConfiguration-$spaSiteUid ; $secretKey ; $publicKey ; $privateSharedKey ; $nasSecretKey ; $nasPublicKey ; $nasSignatureKey ; $nasAuthorizationHeaderKey ; test ; authorize_and_capture ; true ; klarnaConfig ; 0.01 ; true ; true ; payment_approved, payment_voided, payment_void_declined, payment_captured, payment_capture_declined, payment_refunded, payment_refund_declined, payment_pending, payment_declined, payment_expired, payment_canceled, payment_capture_pending, payment_returned ; true ; $spaSiteUid ; INTERNET ; checkoutComACHConfiguration-spa +INSERT_UPDATE CheckoutComMerchantConfiguration; code[unique = true] ; secretKey ; publicKey ; privateSharedKey ; nasSecretKey ; nasPublicKey ; nasSignatureKey ; nasAuthorisationHeaderKey ; environment(code); paymentAction(code) ; reviewTransactionsAtRisk; klarnaConfiguration(&klarnaConfigurationId); authorisationAmountValidationThreshold; threeDSEnabled; noThreeDSAttempt; checkoutComPaymentEventTypes(code) ; includeBillingDescriptor; billingDescriptorName; billingDescriptorCity; achConfiguration(code) + ; merchantConfiguration-$spaSiteUid ; $nasSecretKey ; $nasPublicKey ; $privateSharedKey ; $nasSecretKey ; $nasPublicKey ; $nasSignatureKey ; $nasAuthorizationHeaderKey ; test ; authorize_and_capture ; true ; klarnaConfig ; 0.01 ; true ; true ; payment_approved, payment_voided, payment_void_declined, payment_captured, payment_capture_declined, payment_refunded, payment_refund_declined, payment_pending, payment_declined, payment_expired, payment_canceled, payment_capture_pending, payment_returned ; true ; $spaSiteUid ; INTERNET ; checkoutComACHConfiguration-spa -INSERT_UPDATE CheckoutComMerchantConfiguration; code[unique = true] ; useNas; useNasAuthorisationKeyOnNotifications; useNasSignatureKeyOnNotifications; useAbcSignatureKeyOnNotifications - ; merchantConfiguration-$spaSiteUid ; true ; true ; true ; true +INSERT_UPDATE CheckoutComMerchantConfiguration; code[unique = true] ; useNasAuthorisationKeyOnNotifications; useNasSignatureKeyOnNotifications; + ; merchantConfiguration-$spaSiteUid ; true ; true ; INSERT_UPDATE CheckoutComACHConfiguration; code[unique = true] ; clientId ; clientName ; linkCustomizationName ; redirectUri ; name ; language(isocode); secret ; webhook ; checkoutComACHConfiguration-spa ; 639a5791eb85d80013b0a14f ; clientName ; linkCustomizationName ; redirectUri ; name ; en ; a829b3a6e0b2d927287e28fb11af2b ; webhook diff --git a/hybris/bin/modules/checkoutcom/checkouttest/resources/checkouttest.build.number b/hybris/bin/modules/checkoutcom/checkouttest/resources/checkouttest.build.number index 3a29eae..d7fa8a9 100644 --- a/hybris/bin/modules/checkoutcom/checkouttest/resources/checkouttest.build.number +++ b/hybris/bin/modules/checkoutcom/checkouttest/resources/checkouttest.build.number @@ -1,11 +1,11 @@ #Ant properties -#Tue May 28 13:21:42 GMT 2024 +#Tue Jun 18 10:12:56 GMT 2024 version.api=2211 vendor=hybris group.id=de.hybris.platform name=checkouttest description=checkouttest -builddate=20240528 1321 +builddate=20240618 1012 releasedate=20240307 1540 version=2211.20 module.name=platform-module diff --git a/hybris/bin/modules/checkoutcom/checkouttest/resources/impex/essentialdata-InboundMerchantConfiguration.impex b/hybris/bin/modules/checkoutcom/checkouttest/resources/impex/essentialdata-InboundMerchantConfiguration.impex index 461f380..55b79d3 100644 --- a/hybris/bin/modules/checkoutcom/checkouttest/resources/impex/essentialdata-InboundMerchantConfiguration.impex +++ b/hybris/bin/modules/checkoutcom/checkouttest/resources/impex/essentialdata-InboundMerchantConfiguration.impex @@ -7,11 +7,9 @@ INSERT_UPDATE IntegrationObjectItem; integrationObject(code)[unique = true] ; c INSERT_UPDATE IntegrationObjectItemAttribute; integrationObjectItem(integrationObject(code), code)[unique = true] ; attributeName[unique = true] ; attributeDescriptor(enclosingType(code), qualifier) ; returnIntegrationObjectItem(integrationObject(code), code); unique[default = false]; autoCreate[default = false] ; InboundCheckoutComMerchantConfiguration:CheckoutComMerchantConfiguration ; secretKey ; CheckoutComMerchantConfiguration:secretKey ; ; ; ; InboundCheckoutComMerchantConfiguration:CheckoutComMerchantConfiguration ; noThreeDSAttempt ; CheckoutComMerchantConfiguration:noThreeDSAttempt ; ; ; - ; InboundCheckoutComMerchantConfiguration:CheckoutComMerchantConfiguration ; useAbcSignatureKeyOnNotifications ; CheckoutComMerchantConfiguration:useAbcSignatureKeyOnNotifications ; ; ; ; InboundCheckoutComMerchantConfiguration:CheckoutComMerchantConfiguration ; useNasSignatureKeyOnNotifications ; CheckoutComMerchantConfiguration:useNasSignatureKeyOnNotifications ; ; ; ; InboundCheckoutComMerchantConfiguration:CheckoutComMerchantConfiguration ; useNasAuthorisationKeyOnNotifications ; CheckoutComMerchantConfiguration:useNasAuthorisationKeyOnNotifications ; ; ; ; InboundCheckoutComMerchantConfiguration:CheckoutComMerchantConfiguration ; code ; CheckoutComMerchantConfiguration:code ; ; true ; - ; InboundCheckoutComMerchantConfiguration:CheckoutComMerchantConfiguration ; useNas ; CheckoutComMerchantConfiguration:useNas ; ; ; ; InboundCheckoutComMerchantConfiguration:CheckoutComMerchantConfiguration ; threeDSEnabled ; CheckoutComMerchantConfiguration:threeDSEnabled ; ; ; INSERT_UPDATE InboundChannelConfiguration; integrationObject(code)[unique = true] ; authenticationType(code) diff --git a/js-storefront/checkout-spartacus-connector/README.md b/js-storefront/checkout-spartacus-connector/README.md index b97f8d4..b4f039b 100644 --- a/js-storefront/checkout-spartacus-connector/README.md +++ b/js-storefront/checkout-spartacus-connector/README.md @@ -8,7 +8,7 @@ This library is tailored to the [Spartacus](https://sap.github.io/spartacus-docs This release is compatible with: * Spartacus: version 4.2 -* Node module `checkout-spartacus-translations` v4.2.5 +* Node module `checkout-spartacus-translations` v4.2.8 * SAP Commerce Cloud: version 2011/2105/2205/2211 * Angular CLI: Version 12.0.5 or later, < 13. * Node.js: Version 14.15 is required. Version 12.x reached end-of-life on April 30, 2022, and is no longer supported by Spartacus. It is strongly recommended that you migrate any existing Spartacus storefronts to Node.js 14 as soon as possible. If there are any issues with Spartacus and Node.js 14, please upgrade to the latest releases. If you continue to experience issues with Node.js 14, create a support ticket with SAP. diff --git a/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/README.md b/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/README.md index fcd94a8..7358b2b 100644 --- a/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/README.md +++ b/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/README.md @@ -95,6 +95,9 @@ If you don't want to fork, you can `extend` components, copy the template and th ## Release notes +### Release 4.2.8 +* Updated Klarna APM Configuration + ### Release 4.2.7 * Removed BIC from iDeal APM form diff --git a/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/package.json b/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/package.json index 2afbf73..098efbe 100644 --- a/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/package.json +++ b/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/package.json @@ -1,6 +1,6 @@ { "name": "@checkout.com/checkout-spartacus-connector", - "version": "4.2.7", + "version": "4.2.8", "repository": "https://github.com/checkout/Checkout-SAP-Cloud-Commerce-2211", "peerDependencies": { "@angular/common": "^10.2.4", diff --git a/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/core/interfaces.ts b/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/core/interfaces.ts index f489701..752750b 100644 --- a/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/core/interfaces.ts +++ b/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/core/interfaces.ts @@ -8,7 +8,7 @@ export interface CheckoutComRedirect { export interface KlarnaInitParams { clientToken?: string; - paymentMethodCategories?: KlarnaPaymentMethodCategory[]; + paymentContext?: string; instanceId?: string; success?: boolean; httpError?: HttpErrorResponse; diff --git a/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/core/store/checkout-com.effects.ts b/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/core/store/checkout-com.effects.ts index a8c2df9..51bb6c6 100644 --- a/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/core/store/checkout-com.effects.ts +++ b/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/core/store/checkout-com.effects.ts @@ -5,7 +5,7 @@ import { Observable, of } from 'rxjs'; import * as CheckoutComActions from './checkout-com.actions'; import { catchError, exhaustMap, map, mergeMap, switchMap } from 'rxjs/operators'; import { CheckoutComOccAdapter } from '../adapters/occ/checkout-com-occ.adapter'; -import { CartActions, GlobalMessage, GlobalMessageActions, GlobalMessageType, normalizeHttpError, Translatable, UserActions } from '@spartacus/core'; +import { Address, CartActions, GlobalMessage, GlobalMessageActions, GlobalMessageType, normalizeHttpError, Translatable, UserActions } from '@spartacus/core'; import { CheckoutActions } from '@spartacus/checkout/core'; import { CheckoutComRedirect } from '../interfaces'; import { ApmData } from '../model/ApmData'; @@ -69,7 +69,7 @@ export class CheckoutComEffects { map((action: any) => action.payload), mergeMap(payload => this.checkoutComAdapter.setPaymentAddress(payload.cartId, payload.userId, payload.address) .pipe( - switchMap(_ => [new CheckoutComActions.SetPaymentAddressSuccess(payload.address)]), + switchMap((address: Address) => [new CheckoutComActions.SetPaymentAddressSuccess(address)]), catchError(error => of(new CheckoutComActions.SetPaymentAddressFail(error))) ) ) diff --git a/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/storefrontlib/cms-components/checkout-com-apm-component/checkout-com-apm-klarna/checkout-com-klarna.component.html b/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/storefrontlib/cms-components/checkout-com-apm-component/checkout-com-apm-klarna/checkout-com-klarna.component.html index 227d1f6..1ac43a2 100644 --- a/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/storefrontlib/cms-components/checkout-com-apm-component/checkout-com-apm-klarna/checkout-com-klarna.component.html +++ b/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/storefrontlib/cms-components/checkout-com-apm-component/checkout-com-apm-klarna/checkout-com-klarna.component.html @@ -2,21 +2,13 @@
- -
-
- {{category.key|cxTranslate}} - -
-
-
+ + +
+
-
- + +
diff --git a/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/storefrontlib/cms-components/checkout-com-apm-component/checkout-com-apm-klarna/checkout-com-klarna.component.spec.ts b/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/storefrontlib/cms-components/checkout-com-apm-component/checkout-com-apm-klarna/checkout-com-klarna.component.spec.ts index 2e3d517..69009d4 100644 --- a/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/storefrontlib/cms-components/checkout-com-apm-component/checkout-com-apm-klarna/checkout-com-klarna.component.spec.ts +++ b/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/storefrontlib/cms-components/checkout-com-apm-component/checkout-com-apm-klarna/checkout-com-klarna.component.spec.ts @@ -1,15 +1,16 @@ import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { CheckoutComKlarnaComponent } from './checkout-com-klarna.component'; -import { BehaviorSubject, of } from 'rxjs'; +import { CheckoutComKlarnaComponent, KlarnaAddress } from './checkout-com-klarna.component'; +import { BehaviorSubject, EMPTY, of, throwError } from 'rxjs'; import { PaymentType } from '../../../../core/model/ApmData'; import { CheckoutComApmService } from '../../../../core/services/checkout-com-apm.service'; -import { GlobalMessageService, I18nTestingModule } from '@spartacus/core'; +import { Address, GlobalMessageService, GlobalMessageType, I18nTestingModule } from '@spartacus/core'; import { CheckoutComPaymentService } from '../../../../core/services/checkout-com-payment.service'; import { CheckoutDeliveryFacade } from '@spartacus/checkout/root'; -import createSpy = jasmine.createSpy; import { Component, Input, Output } from '@angular/core'; -import { FormGroup } from '@angular/forms'; +import { FormControl, FormGroup } from '@angular/forms'; +import { KlarnaInitParams } from '../../../../core/interfaces'; +import createSpy = jasmine.createSpy; @Component({ selector: 'lib-checkout-com-billing-address', @@ -20,16 +21,19 @@ export class MockCheckoutComBillingAddressComponent { @Output() sameAsShippingAddressChange = new BehaviorSubject(true); } - -const apm = {code: PaymentType.Klarna}; +const apm = { code: PaymentType.Klarna }; class CheckoutComApmServiceStub { getSelectedApmFromState = createSpy('getSelectedApmFromState').and.returnValue(of(apm)); selectApm = createSpy('selectApm').and.stub(); - getKlarnaInitParams = createSpy('getKlarnaInitParams').and.returnValue(of({})); + + getKlarnaInitParams() { + return of(EMPTY); + }; } -class MockCheckoutComStore {} +class MockCheckoutComStore { +} class MockGlobalMessageService { add = createSpy(); @@ -37,28 +41,82 @@ class MockGlobalMessageService { class MockCheckoutDeliveryFacade { getDeliveryAddress() { - return of({country: 'ES'}); + return of({ country: 'ES' }); } } class CheckoutComPaymentStub { setPaymentAddress = createSpy('setPaymentAddress').and.stub(); getPaymentAddressFromState = createSpy('getPaymentAddressFromState').and.returnValue(of({})); + + updatePaymentAddress() { + return of(EMPTY); + }; } +const billingAddressForm = new FormGroup({ + firstName: new FormControl(''), + lastName: new FormControl(''), + line1: new FormControl(''), + postalCode: new FormControl(''), + town: new FormControl(''), + phone: new FormControl(''), + country: new FormGroup({ + isocode: new FormControl('') + }) +}); + +const shippingAddress: Address = { + firstName: 'firstName', + lastName: 'lastName', + email: 'test@test.com', + line1: 'line1', + postalCode: '000000', + town: 'town', + phone: '+000000', + country: { isocode: 'US' }, +}; +const billingAddress: Address = { + firstName: 'billingFirstName', + lastName: 'billingLastName', + line1: 'line1', + postalCode: '000000', + town: 'town', + phone: '+000000', + country: { isocode: 'CA' }, +}; + describe('CheckoutComKlarnaComponent', () => { let component: CheckoutComKlarnaComponent; let fixture: ComponentFixture; + let checkoutDeliveryFacade: CheckoutDeliveryFacade; + let checkoutComApmSrv: CheckoutComApmService; + let msgSrv: GlobalMessageService; + let checkoutComPaymentService: CheckoutComPaymentService; + let initParamsSpy; + let spyOnWinref; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [CheckoutComKlarnaComponent, MockCheckoutComBillingAddressComponent], imports: [I18nTestingModule], providers: [ - {provide: CheckoutComApmService, useClass: CheckoutComApmServiceStub}, - {provide: GlobalMessageService, useClass: MockGlobalMessageService}, - {provide: CheckoutComPaymentService, useClass: CheckoutComPaymentStub}, - {provide: CheckoutDeliveryFacade, useClass: MockCheckoutDeliveryFacade}, + { + provide: CheckoutComApmService, + useClass: CheckoutComApmServiceStub + }, + { + provide: GlobalMessageService, + useClass: MockGlobalMessageService + }, + { + provide: CheckoutComPaymentService, + useClass: CheckoutComPaymentStub + }, + { + provide: CheckoutDeliveryFacade, + useClass: MockCheckoutDeliveryFacade + }, ] }).compileComponents(); }); @@ -66,10 +124,486 @@ describe('CheckoutComKlarnaComponent', () => { beforeEach(() => { fixture = TestBed.createComponent(CheckoutComKlarnaComponent); component = fixture.componentInstance; + checkoutDeliveryFacade = TestBed.inject(CheckoutDeliveryFacade); + checkoutComApmSrv = TestBed.inject(CheckoutComApmService); + msgSrv = TestBed.inject(GlobalMessageService); + checkoutComPaymentService = TestBed.inject(CheckoutComPaymentService); + initParamsSpy = spyOn(checkoutComApmSrv, 'getKlarnaInitParams'); + initParamsSpy.and.callThrough(); + // @ts-ignore + spyOn(component, 'loadWidget').and.callThrough(); + // @ts-ignore + spyOnWinref = spyOnProperty(component.windowRef, 'nativeWindow'); + spyOnWinref.and.returnValue({}); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); + + describe('normalizeKlarnaAddress', () => { + it('should return KlarnaAddress with all fields filled when Address is complete', () => { + component.emailAddress = 'john.doe@example.com'; + const address: Address = { + firstName: 'John', + lastName: 'Doe', + email: 'john.doe@example.com', + line1: '123 Street', + postalCode: '12345', + town: 'Town', + phone: '1234567890', + country: { isocode: 'US' }, + }; + const expected: KlarnaAddress = { + given_name: 'John', + family_name: 'Doe', + email: 'john.doe@example.com', + street_address: '123 Street', + postal_code: '12345', + city: 'Town', + phone: '1234567890', + country: 'US', + }; + expect(component.normalizeKlarnaAddress(address)).toEqual(expected); + }); + + it('should return KlarnaAddress with empty fields when Address is incomplete', () => { + const address: Address = { + firstName: '', + lastName: '', + email: component.emailAddress, + line1: '', + postalCode: '', + town: '', + phone: '', + country: null, + }; + const expected: KlarnaAddress = { + given_name: '', + family_name: '', + email: '', + street_address: '', + postal_code: '', + city: '', + phone: '', + country: '', + }; + expect(component.normalizeKlarnaAddress(address)).toEqual(expected); + }); + + it('should return KlarnaAddress with emailAddress when Address email is missing', () => { + const address: Address = { + firstName: 'John', + lastName: 'Doe', + email: component.emailAddress, + line1: '123 Street', + postalCode: '12345', + town: 'Town', + country: { isocode: 'US' }, + phone: '1234567890', + }; + const expected: KlarnaAddress = { + given_name: 'John', + family_name: 'Doe', + email: '', + street_address: '123 Street', + postal_code: '12345', + city: 'Town', + phone: '1234567890', + country: 'US', + }; + expect(component.normalizeKlarnaAddress(address)).toEqual(expected); + }); + }); + + describe('listenForAddressSourceChange', () => { + it('should update klarnaShippingAddressData and klarnaBillingAddressData when sameAsShippingAddress is true', () => { + component.sameAsShippingAddress$.next(true); + spyOn(checkoutDeliveryFacade, 'getDeliveryAddress').and.returnValue(of(shippingAddress)); + component.listenForAddressSourceChange(); + expect(component.klarnaShippingAddressData).toEqual(component.normalizeKlarnaAddress(shippingAddress)); + expect(component.klarnaBillingAddressData).toEqual(component.klarnaShippingAddressData); + }); + + it('should update klarnaShippingAddressData and klarnaBillingAddressData separately when sameAsShippingAddress is false', () => { + component.billingAddressForm = billingAddressForm; + component.billingAddressForm.patchValue(billingAddress); + component.sameAsShippingAddress$.next(false); + fixture.detectChanges(); + spyOn(checkoutDeliveryFacade, 'getDeliveryAddress').and.returnValue(of(shippingAddress)); + component.listenForAddressSourceChange(); + fixture.detectChanges(); + expect(component.klarnaShippingAddressData).toEqual(component.normalizeKlarnaAddress(shippingAddress)); + expect(component.klarnaBillingAddressData).toEqual(component.normalizeKlarnaAddress(billingAddress)); + }); + + it('should not update klarnaBillingAddressData when sameAsShippingAddress is false and country is not selected', () => { + component.billingAddressForm.patchValue(billingAddress); + component.sameAsShippingAddress$.next(false); + spyOn(checkoutDeliveryFacade, 'getDeliveryAddress').and.returnValue(of(shippingAddress)); + component.listenForAddressSourceChange(); + expect(component.klarnaShippingAddressData).toEqual(component.normalizeKlarnaAddress(shippingAddress)); + expect(component.klarnaBillingAddressData).not.toEqual(component.normalizeKlarnaAddress(billingAddress)); + }); + }); + + describe('authorize', () => { + it('should not authorize when sameAsShippingAddress is false and billingAddressForm is invalid', () => { + component.sameAsShippingAddress$.next(false); + component.billingAddressForm.setErrors({ invalid: true }); + component.authorize(); + expect(component.authorizing$.getValue()).toBe(false); + }); + + it('should not authorize when authorizing$ is true', () => { + component.authorizing$.next(true); + component.authorize(); + expect(component.authorizing$.getValue()).toBe(true); + }); + + it('should not authorize when Klarna is not set', () => { + // @ts-ignore + spyOnWinref.and.returnValue({}); + component.authorize(); + expect(component.authorizing$.getValue()).toBe(false); + }); + + it('should authorize when sameAsShippingAddress is true', () => { + component.sameAsShippingAddress$.next(true); + // @ts-ignore + spyOnWinref.and.returnValue({ + Klarna: { + Payments: { + authorize: jasmine.createSpy().and.callFake((_, __, callback) => callback({ + approved: true, + authorization_token: 'token' + })) + } + } + }); + component.authorize(); + expect(component.authorizing$.getValue()).toBe(false); + }); + + it('should authorize when sameAsShippingAddress is false and billingAddressForm is valid', () => { + component.sameAsShippingAddress$.next(false); + component.billingAddressForm.setErrors(null); + // @ts-ignore + spyOnWinref.and.returnValue({ + Klarna: { + Payments: { + authorize: jasmine.createSpy().and.callFake((_, __, callback) => callback({ + approved: true, + authorization_token: 'token' + })) + } + } + }); + component.authorize(); + expect(component.authorizing$.getValue()).toBe(false); + }); + }); + + describe('listenForCountryCode', () => { + beforeEach(() => { + component.billingAddressForm = billingAddressForm; + // @ts-ignore + component.billingAddressHasBeenSet = false; + // @ts-ignore + component.currentCountryCode.next(null); + }); + it('should initialize Klarna when country code is set and billing address has been set', () => { + initParamsSpy.and.returnValue(of({ + clientToken: 'token', + paymentContext: 'context', + instanceId: 'id' + })); + // @ts-ignore + component.billingAddressHasBeenSet = true; + // @ts-ignore + component.currentCountryCode.next('US'); + // @ts-ignore + spyOn(component, 'initKlarna'); + // @ts-ignore + component.listenForCountryCode(); + // @ts-ignore + expect(component.initKlarna).toHaveBeenCalledWith({ + clientToken: 'token', + paymentContext: 'context', + instanceId: 'id' + }); + }); + + it('should not initialize Klarna when country code is not set', () => { + // @ts-ignore + component.billingAddressHasBeenSet = false; + // @ts-ignore + component.currentCountryCode.next(null); + // @ts-ignore + spyOn(component, 'initKlarna'); + // @ts-ignore + component.listenForCountryCode(); + expect(checkoutComApmSrv.getKlarnaInitParams).not.toHaveBeenCalled(); + // @ts-ignore + expect(component.initKlarna).not.toHaveBeenCalled(); + }); + + it('should not initialize Klarna when billing address has not been set', () => { + // @ts-ignore + component.billingAddressHasBeenSet = false; + // @ts-ignore + component.currentCountryCode.next('US'); + // @ts-ignore + spyOn(component, 'initKlarna'); + // @ts-ignore + component.listenForCountryCode(); + //expect(checkoutComApmSrv.getKlarnaInitParams).not.toHaveBeenCalled(); + // @ts-ignore + expect(component.initKlarna).not.toHaveBeenCalled(); + }); + + it('should handle error when getting Klarna init params fails', () => { + initParamsSpy.and.returnValue(throwError('error')); + // @ts-ignore + component.billingAddressHasBeenSet = true; + // @ts-ignore + component.currentCountryCode.next('US'); + // @ts-ignore + component.listenForCountryCode(); + expect(msgSrv.add).toHaveBeenCalledWith({ key: 'paymentForm.klarna.initializationFailed' }, GlobalMessageType.MSG_TYPE_ERROR); + }); + }); + + describe('listenForCountrySelection', () => { + it('should update currentCountryCode when country is selected', () => { + component.billingAddressForm = billingAddressForm; + // @ts-ignore + component.listenForCountrySelection(); + component.billingAddressForm.setValue(billingAddress); + fixture.detectChanges(); + // @ts-ignore + component.currentCountryCode.subscribe(value => { + expect(value).toEqual('CA'); + }); + }); + + it('should not update currentCountryCode when country is not selected', () => { + component.billingAddressForm = billingAddressForm; + // @ts-ignore + component.listenForCountrySelection(); + const countryControl = component.billingAddressForm.get('country.isocode'); + countryControl.setValue(null); + // @ts-ignore + component.currentCountryCode.subscribe(value => { + expect(value).toBeNull(); + }); + }); + + it('should not update currentCountryCode when form value changes are not related to country', () => { + component.billingAddressForm = billingAddressForm; + const countryControl = component.billingAddressForm.get('country.isocode'); + countryControl.setValue('US'); + // @ts-ignore + component.listenForCountrySelection(); + component.billingAddressForm.get('firstName').setValue('John'); + // @ts-ignore + component.currentCountryCode.subscribe(value => { + expect(value).toEqual('US'); + }); + }); + }); + + describe('klarnaIsReady', () => { + beforeEach(() => { + component.billingAddressForm = billingAddressForm; + }); + + it('should update currentCountryCode and klarnaShippingAddressData when shipping address is valid', () => { + const shippingAddress: Address = { + firstName: 'John', + lastName: 'Doe', + email: 'john.doe@example.com', + line1: '123 Street', + postalCode: '12345', + town: 'Town', + phone: '1234567890', + country: { isocode: 'US' }, + }; + component.billingAddressForm = billingAddressForm; + fixture.detectChanges(); + spyOn(checkoutDeliveryFacade, 'getDeliveryAddress').and.returnValue(of(shippingAddress)); + spyOn(checkoutComPaymentService, 'updatePaymentAddress').and.returnValue(of(shippingAddress)); + // @ts-ignore + component.klarnaIsReady(); + // @ts-ignore + expect(component.currentCountryCode.getValue()).toEqual('US'); + expect(component.klarnaShippingAddressData).toEqual(component.normalizeKlarnaAddress(shippingAddress)); + }); + + it('should not update currentCountryCode and klarnaShippingAddressData when shipping address is null', () => { + spyOn(checkoutDeliveryFacade, 'getDeliveryAddress').and.returnValue(of(null)); + // @ts-ignore + component.klarnaIsReady(); + // @ts-ignore + expect(component.currentCountryCode.getValue()).toBeNull(); + expect(component.klarnaShippingAddressData).toBeUndefined(); + expect(msgSrv.add).toHaveBeenCalledWith({ key: 'paymentForm.klarna.countryIsRequired' }, GlobalMessageType.MSG_TYPE_ERROR); + }); + + it('should handle error when updatePaymentAddress fails', () => { + const shippingAddress: Address = { + firstName: 'John', + lastName: 'Doe', + email: 'john.doe@example.com', + line1: '123 Street', + postalCode: '12345', + town: 'Town', + phone: '1234567890', + country: { isocode: 'US' }, + }; + spyOn(checkoutDeliveryFacade, 'getDeliveryAddress').and.returnValue(of(shippingAddress)); + spyOn(checkoutComPaymentService, 'updatePaymentAddress').and.returnValue(throwError('error')); + // @ts-ignore + component.klarnaIsReady(); + expect(msgSrv.add).toHaveBeenCalledWith({ key: 'paymentForm.klarna.countryIsRequired' }, GlobalMessageType.MSG_TYPE_ERROR); + }); + }); + + describe('initKlarna', () => { + it('should initialize Klarna when Klarna is set', () => { + const k = { + Payments: { + init: jasmine.createSpy(), + load: jasmine.createSpy() + } + }; + // @ts-ignore + spyOnWinref.and.returnValue({ Klarna: k }); + const params: KlarnaInitParams = { + clientToken: 'token', + paymentContext: 'context', + instanceId: 'id' + }; + // @ts-ignore + component.initKlarna(params); + expect(k.Payments.init).toHaveBeenCalledWith({ client_token: 'token' }); + // @ts-ignore + expect(component.loadWidget).toHaveBeenCalled(); + }); + + it('should not initialize Klarna when Klarna is not set', () => { + // @ts-ignore + spyOnWinref.and.returnValue({}); + const params: KlarnaInitParams = { + clientToken: 'token', + paymentContext: 'context', + instanceId: 'id' + }; + // @ts-ignore + component.initKlarna(params); + // @ts-ignore + expect(component.loadWidget).not.toHaveBeenCalled(); + }); + + it('should handle error when initializing Klarna fails', () => { + const k = { + Payments: { + init: jasmine.createSpy().and.throwError('error'), + load: jasmine.createSpy() + } + }; + // @ts-ignore + spyOnWinref.and.returnValue({ Klarna: k }); + const params: KlarnaInitParams = { + clientToken: 'token', + paymentContext: 'context', + instanceId: 'id' + }; + spyOn(console, 'error'); + // @ts-ignore + component.initKlarna(params); + expect(console.error).toHaveBeenCalledWith('CheckoutComKlarnaComponent::initKlarna', jasmine.any(Error)); + }); + }); + + describe('addScript', () => { + it('should add script and define klarnaAsyncCallback when Klarna is not set', () => { + // @ts-ignore + spyOnWinref.and.returnValue({}); + const script = document.createElement('script'); + spyOn(document, 'createElement').and.returnValue(script); + // @ts-ignore + spyOn(component.windowRef.document.body, 'appendChild'); + // @ts-ignore + component.addScript(); + expect(script.src).toEqual('https://x.klarnacdn.net/kp/lib/v1/api.js'); + expect(script.async).toEqual(true); + // @ts-ignore + expect(component.windowRef.document.body.appendChild).toHaveBeenCalledWith(script); + }); + + it('should not add script but call klarnaIsReady when Klarna is set', () => { + // @ts-ignore + spyOnWinref.and.returnValue({ Klarna: {} }); + // @ts-ignore + spyOn(component.windowRef.document.body, 'appendChild'); + // @ts-ignore + spyOn(component.ngZone, 'run'); + // @ts-ignore + component.addScript(); + // @ts-ignore + expect(component.windowRef.document.body.appendChild).not.toHaveBeenCalled(); + // @ts-ignore + expect(component.ngZone.run).toHaveBeenCalled(); + }); + }); + + describe('loadWidget', () => { + it('should load widget when Klarna is set', () => { + const k = { + load: jasmine.createSpy().and.callFake((_, __, callback) => callback({})) + }; + // @ts-ignore + spyOnWinref.and.returnValue({ Klarna: { Payments: k } }); + // @ts-ignore + component.loadWidget(); + expect(k.load).toHaveBeenCalled(); + expect(component.loadingWidget$.getValue()).toBe(false); + }); + + it('should not load widget when Klarna is not set', () => { + // @ts-ignore + spyOnWinref.and.returnValue({}); + // @ts-ignore + component.loadWidget(); + expect(component.loadingWidget$.getValue()).toBe(false); + }); + + it('should handle error when loading widget fails', () => { + const k = { + load: jasmine.createSpy().and.throwError('error') + }; + // @ts-ignore + spyOnWinref.and.returnValue({ Klarna: { Payments: k } }); + spyOn(console, 'error'); + // @ts-ignore + component.loadWidget(); + expect(console.error).toHaveBeenCalledWith('CheckoutComKlarnaComponent::loadWidget', jasmine.any(Error)); + expect(component.loadingWidget$.getValue()).toBe(false); + }); + + it('should handle error when response contains error', () => { + const k = { + load: jasmine.createSpy().and.callFake((_, __, callback) => callback({ error: { invalid_fields: ['field'] } })) + }; + // @ts-ignore + spyOnWinref.and.returnValue({ Klarna: { Payments: k } }); + spyOn(console, 'error'); + // @ts-ignore + component.loadWidget(); + expect(console.error).toHaveBeenCalledWith('CheckoutComKlarnaComponent::loadWidget::response', { invalid_fields: ['field'] }); + expect(component.loadingWidget$.getValue()).toBe(false); + }); + }); }); diff --git a/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/storefrontlib/cms-components/checkout-com-apm-component/checkout-com-apm-klarna/checkout-com-klarna.component.ts b/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/storefrontlib/cms-components/checkout-com-apm-component/checkout-com-apm-klarna/checkout-com-klarna.component.ts index 33b38bb..2270f41 100644 --- a/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/storefrontlib/cms-components/checkout-com-apm-component/checkout-com-apm-klarna/checkout-com-klarna.component.ts +++ b/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/storefrontlib/cms-components/checkout-com-apm-component/checkout-com-apm-klarna/checkout-com-klarna.component.ts @@ -1,22 +1,16 @@ import { ChangeDetectionStrategy, Component, ElementRef, EventEmitter, Input, NgZone, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'; import { CheckoutComApmService } from '../../../../core/services/checkout-com-apm.service'; -import { BehaviorSubject, EMPTY, Subject, throwError } from 'rxjs'; -import { debounceTime, distinctUntilChanged, filter, finalize, switchMap, take, takeUntil, tap } from 'rxjs/operators'; +import { BehaviorSubject, Subject, throwError } from 'rxjs'; +import { distinctUntilChanged, filter, finalize, switchMap, take, takeUntil, tap } from 'rxjs/operators'; import { KlarnaInitParams } from '../../../../core/interfaces'; -import { ApmPaymentDetails, KlarnaPaymentMethodCategory } from '../../../interfaces'; +import { ApmPaymentDetails } from '../../../interfaces'; import { Address, GlobalMessageService, GlobalMessageType, WindowRef } from '@spartacus/core'; import { PaymentType } from '../../../../core/model/ApmData'; -import { FormGroup } from '@angular/forms'; +import { AbstractControl, FormGroup } from '@angular/forms'; import { CheckoutComPaymentService } from '../../../../core/services/checkout-com-payment.service'; import { makeFormErrorsVisible } from '../../../../core/shared/make-form-errors-visible'; import { CheckoutDeliveryFacade } from '@spartacus/checkout/root'; -interface DisplayKlarnaPaymentMethodCategory { - code: KlarnaPaymentMethodCategory; - key: string; - disabled?: boolean; -} - interface KlarnaLoadError { invalid_fields?: string[]; } @@ -28,12 +22,24 @@ interface KlarnaLoadResponse { interface KlarnaAuthResponse { authorization_token?: string; + payment_context?: string; show_form: boolean; approved?: boolean; finalize_required?: boolean; error?: KlarnaLoadError; } +export interface KlarnaAddress { + given_name?: string; + family_name?: string; + email?: string; + street_address?: string; + postal_code?: string; + city?: string; + phone?: string; + country?: string; +} + @Component({ selector: 'lib-checkout-com-apm-klarna', templateUrl: './checkout-com-klarna.component.html', @@ -42,20 +48,26 @@ interface KlarnaAuthResponse { }) export class CheckoutComKlarnaComponent implements OnInit, OnDestroy { @Input() billingAddressForm: FormGroup = new FormGroup({}); - @Output() setPaymentDetails = new EventEmitter<{ paymentDetails: ApmPaymentDetails, billingAddress: Address }>(); + @Output() setPaymentDetails: EventEmitter<{ paymentDetails: ApmPaymentDetails, billingAddress: Address }> = new EventEmitter<{ + paymentDetails: ApmPaymentDetails, + billingAddress: Address + }>(); @ViewChild('widget') widget: ElementRef; - public selectedCategory$ = new BehaviorSubject(null); - public categories$ = new BehaviorSubject([]); - public loadingWidget$ = new BehaviorSubject(false); - public authorizing$ = new BehaviorSubject(false); - public initializing$ = new BehaviorSubject(false); - public sameAsShippingAddress$ = new BehaviorSubject(true); + public loadingWidget$: BehaviorSubject = new BehaviorSubject(false); + public authorizing$: BehaviorSubject = new BehaviorSubject(false); + public initializing$: BehaviorSubject = new BehaviorSubject(false); + public sameAsShippingAddress$: BehaviorSubject = new BehaviorSubject(true); private sameAsShippingAddress: boolean = true; - private allCategories: KlarnaPaymentMethodCategory[] = []; - private drop = new Subject(); - private currentCountryCode = new BehaviorSubject(null); - private billingAddressHasBeenSet = false; + private drop: Subject = new Subject(); + private currentCountryCode: BehaviorSubject = new BehaviorSubject(null); + private billingAddressHasBeenSet: boolean = false; + + public paymentContext: string = null; + public instanceId: string = null; + public emailAddress: string = ''; + public klarnaShippingAddressData: KlarnaAddress; + public klarnaBillingAddressData: KlarnaAddress; constructor( protected checkoutComApmSrv: CheckoutComApmService, @@ -69,39 +81,53 @@ export class CheckoutComKlarnaComponent implements OnInit, OnDestroy { ngOnInit(): void { this.addScript(); - this.listenForCountryCode(); - this.listenForCountrySelection(); - this.listenForCategorySelection(); - this.listenForAddressSourceChange(); } - listenForAddressSourceChange() { + listenForAddressSourceChange(): void { this.sameAsShippingAddress$.pipe( - switchMap((sameAsShippingAddress) => { + switchMap((sameAsShippingAddress: boolean) => { this.sameAsShippingAddress = sameAsShippingAddress; - if (sameAsShippingAddress) { - return this.checkoutDeliveryFacade.getDeliveryAddress().pipe( - take(1), - tap((address) => { - this.currentCountryCode.next(address?.country?.isocode); - }) - ); - } else { - const countryCtrl = this.billingAddressForm.get('country.isocode'); + if (!sameAsShippingAddress) { + const countryCtrl: AbstractControl = this.billingAddressForm.get('country.isocode'); if (countryCtrl && countryCtrl.value) { this.currentCountryCode.next(countryCtrl.value); } - return EMPTY; } + return this.checkoutDeliveryFacade.getDeliveryAddress().pipe( + take(1), + tap((address: Address): void => { + this.currentCountryCode.next(address?.country?.isocode); + this.klarnaShippingAddressData = this.normalizeKlarnaAddress(address); + + if (this.sameAsShippingAddress) { + this.klarnaBillingAddressData = this.klarnaShippingAddressData; + } else { + this.klarnaBillingAddressData = this.normalizeKlarnaAddress(this.billingAddressForm.value); + } + }) + ); }), takeUntil(this.drop) ).subscribe(); } - ngOnDestroy() { + ngOnDestroy(): void { this.drop.next(); } + normalizeKlarnaAddress(address: Address): KlarnaAddress { + return { + given_name: address.firstName || '', + family_name: address.lastName || '', + email: this.emailAddress, + street_address: address.line1 || '', + postal_code: address.postalCode || '', + city: address.town || '', + phone: address.phone || '', + country: address.country?.isocode || '' + }; + } + public authorize(): void { if (!this.sameAsShippingAddress && !this.billingAddressForm.valid) { makeFormErrorsVisible(this.billingAddressForm); @@ -110,10 +136,6 @@ export class CheckoutComKlarnaComponent implements OnInit, OnDestroy { if (this.authorizing$.getValue()) { return; } - const category = this.selectedCategory$.getValue(); - if (!category) { - return; - } try { const k = (this.windowRef.nativeWindow as { [key: string]: any })['Klarna']?.Payments; @@ -126,33 +148,35 @@ export class CheckoutComKlarnaComponent implements OnInit, OnDestroy { billingAddress = this.billingAddressForm.value; } this.authorizing$.next(true); - k.authorize({ payment_method_category: category.code }, this.getKlarnaCountryParams(), (response: KlarnaAuthResponse): void => { - this.authorizing$.next(false); - if (response != null && response.approved === true && response.authorization_token) { - this.setPaymentDetails.next({ - paymentDetails: { - type: PaymentType.Klarna, - authorizationToken: response.authorization_token, - } as ApmPaymentDetails, - billingAddress - }); - } - }); + k.authorize({ + instance_id: this.instanceId + }, + { + billing_address: this.klarnaBillingAddressData, + shipping_address: this.klarnaShippingAddressData + }, + (response: KlarnaAuthResponse): void => { + this.authorizing$.next(false); + if (response != null && response.approved === true && response.authorization_token) { + this.setPaymentDetails.next({ + paymentDetails: { + type: PaymentType.Klarna, + authorizationToken: response.authorization_token, + paymentContextId: this.paymentContext, + } as ApmPaymentDetails, + billingAddress + }); + } + }); } catch (e) { this.authorizing$.next(false); console.error('CheckoutComKlarnaComponent::initKlarna', e); } } - selectCategory(category: DisplayKlarnaPaymentMethodCategory) { - if (category && !category.disabled) { - this.selectedCategory$.next(category); - } - } - - private listenForCountryCode() { + private listenForCountryCode(): void { this.currentCountryCode.pipe( - filter(c => !!c && this.billingAddressHasBeenSet), + filter((c: string) => !!c && this.billingAddressHasBeenSet), distinctUntilChanged(), switchMap(() => { this.initializing$.next(true); @@ -162,12 +186,8 @@ export class CheckoutComKlarnaComponent implements OnInit, OnDestroy { }), takeUntil(this.drop) ).subscribe({ - next: (params) => { + next: (params: KlarnaInitParams): void => { this.initKlarna(params); - const allSrc = params.paymentMethodCategories ?? []; - this.allCategories = allSrc.map(c => c); - this.selectedCategory$.next(null); - this.renderCategories(this.allCategories); }, error: (error) => { console.error(error); @@ -176,54 +196,73 @@ export class CheckoutComKlarnaComponent implements OnInit, OnDestroy { }); } - private listenForCountrySelection() { + private listenForCountrySelection(): void { this.billingAddressForm.valueChanges.pipe( filter(values => values?.country?.isocode), distinctUntilChanged(), takeUntil(this.drop) - ).subscribe((values) => { + ).subscribe((values): void => { this.currentCountryCode.next(values?.country?.isocode); }, err => console.error('listenForCountrySelection with errors', { err })); } - private klarnaIsReady() { + private klarnaIsReady(): void { this.initializing$.next(true); this.checkoutDeliveryFacade.getDeliveryAddress().pipe( - switchMap((shippingAddress) => { + switchMap((shippingAddress: Address) => { if (shippingAddress == null || typeof shippingAddress !== 'object') { return throwError('Shipping address is required'); } return this.checkoutComPaymentService.updatePaymentAddress(shippingAddress) - .pipe(tap(() => this.billingAddressHasBeenSet = true)); + .pipe(tap((response: Address): void => { + this.billingAddressHasBeenSet = true; + this.emailAddress = response.email; + this.klarnaShippingAddressData = this.normalizeKlarnaAddress(shippingAddress); + })); }), take(1), - ).pipe(finalize(() => this.initializing$.next(false)), takeUntil(this.drop)).subscribe({ - next: (address) => { + ).pipe( + finalize( + () => this.initializing$.next(false) + ), + takeUntil(this.drop) + ).subscribe({ + next: (address: Address): void => { if (address?.country?.isocode) { this.currentCountryCode.next(address.country.isocode); } else { this.msgSrv.add({ key: 'paymentForm.klarna.countryIsRequired' }, GlobalMessageType.MSG_TYPE_ERROR); } + this.listenForCountryCode(); + this.listenForCountrySelection(); + this.listenForAddressSourceChange(); }, - error: () => { + error: (): void => { this.msgSrv.add({ key: 'paymentForm.klarna.countryIsRequired' }, GlobalMessageType.MSG_TYPE_ERROR); } }); } - private initKlarna(params: KlarnaInitParams) { + private initKlarna(params: KlarnaInitParams): void { try { const k = (this.windowRef.nativeWindow as { [key: string]: any })['Klarna']?.Payments; if (!k) { console.error('Klarna is not set'); return; } - k.init({ client_token: params.clientToken }); + + this.paymentContext = params.paymentContext; + this.instanceId = params.instanceId; + + k.init({ + client_token: params.clientToken, + }); + this.loadWidget(); } catch (e) { console.error('CheckoutComKlarnaComponent::initKlarna', e); } } - private addScript() { - if (!(this.windowRef.nativeWindow as { [key: string]: any })['Klarna'] as any) { + private addScript(): void { + if (this.windowRef && !(this.windowRef?.nativeWindow as { [key: string]: any })['Klarna'] as any) { Object.defineProperty(this.windowRef.nativeWindow, 'klarnaAsyncCallback', { value: () => { this.ngZone.run(() => { @@ -231,53 +270,18 @@ export class CheckoutComKlarnaComponent implements OnInit, OnDestroy { }); }, }); - const script = this.windowRef.document.createElement('script'); script.setAttribute('src', 'https://x.klarnacdn.net/kp/lib/v1/api.js'); script.setAttribute('async', 'true'); this.windowRef.document.body.appendChild(script); } else { - this.ngZone.run(() => { + this.ngZone.run((): void => { this.klarnaIsReady(); }); } } - private getTranslationKeyForCategory(category: KlarnaPaymentMethodCategory): string { - switch (category) { - case KlarnaPaymentMethodCategory.payNow: - return 'paymentForm.klarna.paymentMethodCategory.payNow'; - case KlarnaPaymentMethodCategory.payLater: - return 'paymentForm.klarna.paymentMethodCategory.payLater'; - case KlarnaPaymentMethodCategory.payOverTime: - return 'paymentForm.klarna.paymentMethodCategory.payOverTime'; - } - return null; - } - - private listenForCategorySelection() { - this.selectedCategory$.pipe( - distinctUntilChanged(), - debounceTime(1), // let Angular render the widget container - takeUntil(this.drop) - ).subscribe((category) => { - if (this.widget?.nativeElement) { - this.loadWidget(category, this.widget.nativeElement); - } - }, err => console.error('listenForCategorySelection with errors', { err })); - } - - private getKlarnaCountryParams(): { purchase_country: string } { - if (!this.sameAsShippingAddress) { - const ctrlCountryIsoCode = this.billingAddressForm.get('country.isocode'); - if (ctrlCountryIsoCode && ctrlCountryIsoCode.value) { - return { purchase_country: ctrlCountryIsoCode.value }; - } - } - return null; - } - - private loadWidget(category: DisplayKlarnaPaymentMethodCategory, container: HTMLElement | string) { + private loadWidget(): void { try { const k: any = (this.windowRef.nativeWindow as { [key: string]: any })['Klarna']?.Payments; if (!k) { @@ -285,42 +289,24 @@ export class CheckoutComKlarnaComponent implements OnInit, OnDestroy { return; } this.loadingWidget$.next(true); - k.load({ - container, - payment_method_category: category.code - }, this.getKlarnaCountryParams(), (response: KlarnaLoadResponse) => { - this.loadingWidget$.next(false); - if (response != null && typeof response === 'object') { - if (response.hasOwnProperty('show_form')) { - if (response.show_form === false) { - category.disabled = true; + + k.load( + { + container: '#klarnaContainer', + instance_id: this.instanceId + }, + {}, + (response: KlarnaLoadResponse): void => { + this.loadingWidget$.next(false); + if (response != null && typeof response === 'object') { + if (response.error) { + console.error('CheckoutComKlarnaComponent::loadWidget::response', response.error); } } - if (response.error) { - console.error('CheckoutComKlarnaComponent::loadWidget::response', response.error); - } - } - }); + }); } catch (e) { this.loadingWidget$.next(false); console.error('CheckoutComKlarnaComponent::loadWidget', e); } } - - private renderCategories(paymentMethodCategories: KlarnaPaymentMethodCategory[]) { - const categories: any[] = []; - if (paymentMethodCategories?.length) { - paymentMethodCategories.forEach((category: KlarnaPaymentMethodCategory): void => { - const key = this.getTranslationKeyForCategory(category); - if (key) { - categories.push({ - code: category, - key - }); - } - }); - } - this.categories$.next(categories); - } } - diff --git a/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/storefrontlib/cms-components/checkout-com-apm-component/checkout-com-apm.component.html b/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/storefrontlib/cms-components/checkout-com-apm-component/checkout-com-apm.component.html index 5139cd2..a567c2d 100644 --- a/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/storefrontlib/cms-components/checkout-com-apm-component/checkout-com-apm.component.html +++ b/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/storefrontlib/cms-components/checkout-com-apm-component/checkout-com-apm.component.html @@ -5,7 +5,6 @@
-
diff --git a/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/storefrontlib/cms-components/checkout-com-frames-input/checkout-com-frames-input.component.html b/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/storefrontlib/cms-components/checkout-com-frames-input/checkout-com-frames-input.component.html index 13b68f2..1f296b9 100644 --- a/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/storefrontlib/cms-components/checkout-com-frames-input/checkout-com-frames-input.component.html +++ b/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-connector/src/storefrontlib/cms-components/checkout-com-frames-input/checkout-com-frames-input.component.html @@ -1,11 +1,13 @@

- {{tooltipLabel | cxTranslate}} - + {{ tooltipLabel | cxTranslate }} + + +

diff --git a/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-translations/README.md b/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-translations/README.md index 9dbf7f1..092452e 100644 --- a/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-translations/README.md +++ b/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-translations/README.md @@ -8,13 +8,16 @@ This library is tailored to the [Spartacus](https://sap.github.io/spartacus-docs This release is compatible with: * Spartacus: version 4.2 -* Node module `checkout-spartacus-connector` v4.2.7 +* Node module `checkout-spartacus-connector` v4.2.8 * SAP Commerce Cloud: version 2011/2105/2205/2211 * Angular CLI: Version 12.0.5 or later, < 13. * Node.js: Version 14.15 is required. Version 12.x reached end-of-life on April 30, 2022, and is no longer supported by Spartacus. It is strongly recommended that you migrate any existing Spartacus storefronts to Node.js 14 as soon as possible. If there are any issues with Spartacus and Node.js 14, please upgrade to the latest releases. If you continue to experience issues with Node.js 14, create a support ticket with SAP. * Yarn: Version 1.15 or later. ## Release notes +### Release 4.2.8 +* Updated readme file dependencies to be compatible with Spartacus 4.2.8 + ### Release 4.2.7 * Removed translations for iDeal APM form diff --git a/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-translations/package.json b/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-translations/package.json index f06fe40..992f786 100644 --- a/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-translations/package.json +++ b/js-storefront/checkout-spartacus-connector/projects/checkout-spartacus-translations/package.json @@ -1,6 +1,6 @@ { "name": "@checkout.com/checkout-spartacus-translations", - "version": "4.2.6", + "version": "4.2.8", "repository": "https://github.com/checkout/Checkout-SAP-Cloud-Commerce-2211", "peerDependencies": { "@angular/common": "^10.2.4",