diff --git a/README.md b/README.md
index f271edf..c432af4 100644
--- a/README.md
+++ b/README.md
@@ -3,9 +3,9 @@
* **Description:** Worldpay is a leading global provider of payment and risk services, processing millions of transactions every day. We provide an end-to-end service including card acquiring, treasury, gateway, alternative payments and risk management, all of which can be accessed through a single integration.As leaders in payment processing, our focus is helping clients accept payments from all over the world and increase customer conversions.Offer shoppers fast, secure and seamless checkout experience with Apple Pay. Now available with our global payments integration. For more information, visit our Salesforce Commerce Cloud integration page at www.worldpay.com/global/partners/directory/demandware. Commerce Cloud clients can now implement Apple Pay for the web. With a simple configuration you can benefit from higher mobile conversion, improved security on every transaction, and out of the box functionality that reduce development time and cost. .
* **Categories:** Payment Processing, Fraud Detection
-* **Version:** q1-23-v23.1.0
-* **SFRA Compatibility:** v6.1.0
-* **Last Certification Date:** 20-Feb-2023
+* **Version:** q3-24-v24.1.0
+* **SFRA Compatibility:** v7.0.0
+* **Last Certification Date:** 30-Aug-2024
* [SFRA Installation and Overview Guide](https://github.com/Worldpay/salesforce-commerce-cloud/blob/master/documentation/worldpay-sfra-installation-and-overview-guide.pdf)
* [Test Case Guide](https://github.com/Worldpay/salesforce-commerce-cloud/blob/master/documentation/worldpay-testing-guide.pdf)
* [Technical Guide](https://github.com/Worldpay/salesforce-commerce-cloud/blob/master/documentation/worldpay-technical-guide.pdf)
diff --git a/cartridges/int_worldpay/.project b/cartridges/int_worldpay/.project
new file mode 100644
index 0000000..f57df8f
--- /dev/null
+++ b/cartridges/int_worldpay/.project
@@ -0,0 +1,22 @@
+
+
+ int_worldpay
+
+
+
+
+
+ com.demandware.studio.core.beehiveElementBuilder
+
+
+
+
+ org.sonarlint.eclipse.core.sonarlintBuilder
+
+
+
+
+
+ com.demandware.studio.core.beehiveNature
+
+
diff --git a/cartridges/int_worldpay/.tern-project b/cartridges/int_worldpay/.tern-project
new file mode 100644
index 0000000..070051a
--- /dev/null
+++ b/cartridges/int_worldpay/.tern-project
@@ -0,0 +1,17 @@
+{
+ "ecmaVersion": 5,
+ "plugins": {
+ "guess-types": {
+
+ },
+ "outline": {
+
+ },
+ "demandware": {
+
+ },
+ "eslint": {
+
+ }
+ }
+}
\ No newline at end of file
diff --git a/cartridges/int_worldpay/cartridge/controllers/Worldpay.js b/cartridges/int_worldpay/cartridge/controllers/Worldpay.js
new file mode 100644
index 0000000..9c515c0
--- /dev/null
+++ b/cartridges/int_worldpay/cartridge/controllers/Worldpay.js
@@ -0,0 +1,784 @@
+'use strict';
+/**
+ * Controller that creates an order from the current basket. It's a pure processing controller and does
+ * no page rendering. The controller is used by checkout and is called upon the triggered place order action.
+ * It contains the actual logic to authorize the payment and create the order. The controller communicates the result
+ * of the order creation process and uses a status object PlaceOrderError to set proper error states.
+ * The calling controller is must handle the results of the order creation and evaluate any errors returned by it.
+ *
+ * @module controllers/Worldpay
+ */
+var Site = require('dw/system/Site');
+var siteController = Site.getCurrent().getCustomPreferenceValue('siteController');
+var siteCore = Site.getCurrent().getCustomPreferenceValue('siteCore');
+var app = require(siteController + '/cartridge/scripts/app');
+var guard = require(siteController + '/cartridge/scripts/guard');
+var Logger = require('dw/system/Logger');
+var Transaction = require('dw/system/Transaction');
+var worldpayHelper = require('~/cartridge/scripts/worldpayHelper');
+var PaymentMgr = require('dw/order/PaymentMgr');
+var Countries = require(siteCore + '/cartridge/scripts/util/Countries');
+var Order = require('dw/order/Order');
+var OrderMgr = require('dw/order/OrderMgr');
+var worldpayConstants = require('*/cartridge/scripts/common/worldpayConstants');
+var utils = require('*/cartridge/scripts/common/utils');
+var serviceFacade = require('*/cartridge/scripts/service/serviceFacade');
+var StringUtils = require('dw/util/StringUtils');
+var Resource = require('dw/web/Resource');
+var ArrayList = require('dw/util/ArrayList');
+var sessionObject = session;
+var requestObject = request;
+var customerObject = customer;
+/**
+ * Verifies a credit card against a valid card number and expiration date and possibly invalidates invalid form fields.
+ * If the verification was successful a credit card payment instrument is created.
+ * @param {Object} args - Arguments
+ * @return {Object} returns a result object
+ */
+function handle(args) {
+ var result = worldpayHelper.handle(args);
+ return result;
+}
+
+/**
+ * Authorize call for worldpay processor
+ * @param {Object} args - Arguments
+ * @return {Object} returns a result object
+ */
+function authorize(args) {
+ var result = worldpayHelper.authorize(args);
+ return result;
+}
+
+/**
+ * APM lookup for worldpay processor
+ */
+function apmLookupService() {
+ var BasketMgr = require('dw/order/BasketMgr');
+ var paymentAmount = BasketMgr.getCurrentBasket().totalGrossPrice.value;
+ if (requestObject.httpParameterMap.billingCountry.value && paymentAmount > 0) {
+ var paymentMethods = PaymentMgr.getApplicablePaymentMethods(customerObject, requestObject.httpParameterMap.billingCountry.value.toUpperCase(), paymentAmount);
+ var WorldpayPreferences = require('*/cartridge/scripts/object/worldpayPreferences');
+ var worldpayPreferences = new WorldpayPreferences();
+ var preferences = worldpayPreferences.worldpayPreferencesInit();
+
+ var applicablePMResult = require('*/cartridge/scripts/order/worldpayPayment').applicablePaymentMethods(paymentMethods, request.httpParameterMap.billingCountry.value, preferences);
+ var applicableAPMs = applicablePMResult.applicableAPMs;
+ app.getView({
+ APMList: applicableAPMs
+ }).render('apmlookupoptions');
+ }
+}
+
+/**
+ * Handles the failed order implementation
+ * @param {Object} order - Order Object
+ * @param {string} errorMessage - errorMessage
+ * @return {JSON} returns an JSON object
+ */
+function failImpl(order, errorMessage) {
+ var orderstatus;
+ Transaction.wrap(function () {
+ orderstatus = OrderMgr.failOrder(order, true);
+ });
+ if (orderstatus && !orderstatus.isError()) {
+ app.getController('COBilling').Start({// eslint-disable-line
+ errorMessage: errorMessage
+ });
+ return {
+ error: false
+ };
+ }
+ return {
+ error: true,
+ errorMessage: errorMessage
+ };
+}
+
+/**
+ * Handles the failed order
+ * @return {JSON} returns an JSON object
+ */
+function failOrder() {
+ var order;
+ if (sessionObject.privacy.order_id) {
+ order = OrderMgr.getOrder(sessionObject.privacy.order_id);
+ }
+ if (order) {
+ if (failImpl(order, '').error) {
+ return app.getController('COSummary').Start();// eslint-disable-line
+ }
+ } else {
+ app.getController('Cart').Show();// eslint-disable-line
+ }
+ return { success: false };
+}
+
+/**
+ * Handle 3D response for worldpay processor
+ * @param {Object} args - Arguments
+ * @return {JSON} returns an JSON object
+ */
+function handleAuthenticationResponse() {
+ var params = requestObject.getHttpParameters();
+ var error = null;
+ var orderObj;
+ // md - merchant supplied data contains the OrderNo
+ var md = (params.containsKey('MD')) ? params.get('MD')[0] : null;
+ var orderNo = md;
+
+ if (!orderNo) {
+ Logger.getLogger('worldpay').error(
+ 'Worldpay.ds HandleAuthenticationResponse : Order no. not present in parameters');
+ error = utils.worldpayErrorMessage();
+ failOrder();
+ return {
+ error: true,
+ success: false,
+ errorMessage: error.errorMessage
+ };
+ }
+
+ try {
+ orderObj = OrderMgr.getOrder(orderNo);
+ } catch (ex) {
+ Logger.getLogger('worldpay').error('Worldpay.ds HandleAuthenticationResponse : Invalid Order ');
+ error = utils.worldpayErrorMessage();
+ failOrder();
+ return {
+ error: true,
+ success: false,
+ errorMessage: error.errorMessage
+ };
+ }
+
+ // Fetch the APM Name from the Payment isntrument.
+ var paymentIntrument = utils.getPaymentInstrument(orderObj);
+ var apmName = paymentIntrument.getPaymentMethod();
+ // Fetch the APM Type from the Payment Method i.e. if the Payment Methoid is of DIRECT or REDIRECT type.
+ var paymentMthd = PaymentMgr.getPaymentMethod(apmName);
+ var WorldpayPreferences = require('*/cartridge/scripts/object/worldpayPreferences');
+ WorldpayPreferences = new WorldpayPreferences();
+ var preferences = WorldpayPreferences.worldPayPreferencesInit(paymentMthd, orderObj);
+
+ if (preferences.missingPreferences()) {
+ Logger.getLogger('worldpay').error(
+ 'Worldpay.ds HandleAuthenticationResponse : Worldpay preferences are not properly set.');
+ error = utils.worldpayErrorMessage();
+ failImpl(orderObj, error.errorMessage);
+ return {
+ error: true,
+ success: false,
+ errorMessage: error.errorMessage,
+ orderNo: orderObj.orderNo,
+ orderToken: orderObj.orderToken
+ };
+ }
+
+ var paRes = (params.containsKey('PaRes')) ? params.get('PaRes')[0] : null;
+
+ // Checks if paRes is exist in error codes (Issuer Response fro 3D check)
+ if (!paRes || paRes.equals(worldpayConstants.UNKNOWN_ENTITY) || paRes.equals(worldpayConstants.CANCELLEDBYSHOPPER)
+ || paRes.equals(worldpayConstants.THREEDERROR) || paRes.equals(worldpayConstants.THREEDSINVALIDERROR)
+ || paRes.equals(worldpayConstants.NOT_IDENTIFIED_NOID)) {
+ var errorMessage = utils.getErrorMessage(paRes);
+ Logger.getLogger('worldpay').error(
+ 'Worldpay.js HandleAuthenticationResponse : issuerResponse Error Message : ' + errorMessage);
+ failImpl(orderObj, errorMessage);
+ return {
+ error: true,
+ success: false,
+ errorMessage: errorMessage,
+ issuerResponse: errorMessage,
+ orderNo: orderObj.orderNo,
+ orderToken: orderObj.orderToken
+ };
+ }
+ // Capturing Issuer Response
+ var cardNumber = sessionObject.forms.billing.paymentMethods.creditCard.number.value;
+ var encryptedData = sessionObject.forms.billing.paymentMethods.creditCard.encryptedData.value;
+ var cvn = sessionObject.forms.billing.paymentMethods.creditCard.cvn.value;
+ var echoData = sessionObject.privacy.echoData;
+ var cardOrderObj = {
+ cvn: cvn,
+ cardNumber: cardNumber,
+ md: md,
+ paRes: paRes
+ };
+ var SecondAuthorizeRequestResult = serviceFacade.secondAuthorizeRequestService(orderObj, requestObject, paymentIntrument, preferences, echoData, encryptedData, cardOrderObj);
+
+ if (SecondAuthorizeRequestResult.error) {
+ Logger.getLogger('worldpay').error(
+ 'Worldpay.js HandleAuthenticationResponse : ErrorCode : ' + SecondAuthorizeRequestResult.errorCode
+ + ' : Error Message : ' + SecondAuthorizeRequestResult.errorMessage);
+ failImpl(orderObj, SecondAuthorizeRequestResult.errorMessage);
+ return {
+ error: true,
+ success: false,
+ errorCode: SecondAuthorizeRequestResult.errorCode,
+ errorMessage: SecondAuthorizeRequestResult.errorMessage,
+ orderNo: orderObj.orderNo,
+ orderToken: orderObj.orderToken
+ };
+ }
+
+ // success handling
+ if (sessionObject.privacy.order_id) {
+ orderObj = OrderMgr.getOrder(sessionObject.privacy.order_id);
+ }
+
+ if (!orderObj) {
+ app.getController('Cart').Show();// eslint-disable-line
+ return { error: true, success: false };
+ }
+ if (orderObj.getStatus().value === Order.ORDER_STATUS_FAILED) {
+ Transaction.wrap(function () {
+ orderObj.custom.worldpayMACMissingVal = true;
+ });
+ error = utils.worldpayErrorMessage();
+ app.getController('COBilling').Start({// eslint-disable-line
+ errorMessage: error.errorMessage
+ });
+ return {
+ error: true,
+ success: false,
+ errorMessage: error.errorMessage
+ };
+ }
+ var customerObj = orderObj.customer.authenticated ? orderObj.customer : null;
+ var tokenProcessutils = require('*/cartridge/scripts/common/tokenProcessutils');
+ var resultCheckAuthorization = tokenProcessutils.checkAuthorization(SecondAuthorizeRequestResult.response, paymentIntrument, customerObj);
+ if (resultCheckAuthorization.error) {
+ failImpl(orderObj, resultCheckAuthorization.errorMessage);
+ return {
+ error: true,
+ success: false,
+ errorMessage: resultCheckAuthorization.lastEvent
+ };
+ }
+ if (app.getController('COPlaceOrder').SubmitImpl(orderObj).error) {// eslint-disable-line
+ app.getController('COSummary').Start();// eslint-disable-line
+ return { error: true, success: false };
+ }
+ app.getController('COSummary').ShowConfirmation(orderObj);// eslint-disable-line
+ return { error: false, success: true };
+}
+
+/**
+ * Notification for worldpay processor
+ * @return {JSON} returns an JSON object
+ */
+function notify() {
+ var isValidateIPAddress = Boolean(Site.getCurrent().getCustomPreferenceValue('ValidateIPAddress'));
+ if (isValidateIPAddress) {
+ var validateIPStatus = utils.validateIP();
+ if (validateIPStatus.error) {
+ return {
+ error: true,
+ success: false
+ };
+ }
+ }
+ var xmlString;
+ xmlString = requestObject.httpParameterMap.requestBodyAsString;
+ if (!xmlString) {
+ Logger.getLogger('worldpay').error('Worldpay-Notify : Add Custom Object : xmlString IS NULL');
+ return {
+ error: true
+ };
+ }
+ if (utils.addNotifyCustomObject(xmlString).error) {
+ Transaction.wrap(function () {
+ return {
+ error: true
+ };
+ });
+ }
+ app.getView().render('notifyResponsejson');
+ return {
+ error: false
+ };
+}
+
+/**
+* Service to get Notification updates (latest update and all updates) based on parameter "allupdates"
+*/
+function getNotificationUpdates() {
+ var params = requestObject.getHttpParameters();
+ var orderNo = (params.containsKey('orderNo')) ? params.get('orderNo')[0] : null;
+ var allupdates = (params.containsKey('allupdates')) ? params.get('allupdates')[0] : '';
+ var ErrorCode;
+ var ErrorMessage;
+ var orderObj;
+ if (orderNo) {
+ try {
+ orderObj = OrderMgr.getOrder(orderNo);
+ } catch (ex) {
+ ErrorCode = Resource.msg('notify.error.code120', 'worldpayerror', null);
+ ErrorMessage = utils.getErrorMessage(ErrorCode);
+ app.getView({
+ ErrorCode: ErrorCode,
+ ErrorMessage: ErrorMessage
+ }).render('errorjson');
+ return;
+ }
+ if (orderObj) {
+ try {
+ var statusHist = orderObj.custom.transactionStatus;
+ var statusList = new ArrayList(statusHist);
+ if (!statusList || statusList.length <= 0) {
+ if (allupdates.equalsIgnoreCase('true')) {
+ ErrorCode = worldpayConstants.NOTIFYERRORCODE118;
+ } else {
+ ErrorCode = worldpayConstants.NOTIFYERRORCODE119;
+ }
+ ErrorMessage = utils.getErrorMessage(ErrorCode);
+ app.getView({
+ ErrorCode: ErrorCode,
+ ErrorMessage: ErrorMessage
+ }).render('errorjson');
+ } else if (allupdates.equalsIgnoreCase('true')) {
+ app.getView({
+ statusList: statusList
+ }).render('allstatusjson');
+ } else {
+ app.getView({
+ status: statusList.get(0)
+ }).render('lateststatusjson');
+ }
+ } catch (ex) {
+ var errorCode = worldpayConstants.NOTIFYERRORCODE115;
+ var errorMessage = utils.getErrorMessage(errorCode);
+ Logger.getLogger('worldpay').error('Order Notification : Get All Status Update Notifications recieved : ' + errorCode + ' : ' + errorMessage + ' : ' + ex);
+ app.getView({
+ ErrorCode: errorCode,
+ ErrorMessage: errorMessage
+ }).render('errorjson');
+ }
+ return;
+ }
+ }
+ ErrorCode = Resource.msg('notify.error.code120', 'worldpayerror', null);
+ ErrorMessage = utils.getErrorMessage(ErrorCode);
+ app.getView({
+ ErrorCode: ErrorCode,
+ ErrorMessage: ErrorMessage
+ }).render('errorjson');
+}
+
+/**
+ * This function take the user to billing page.
+ * @param {Object} selectedPayment - selected payment method in an order
+ * @param {Object} paymentStatus - payment status arrived in request
+ * @param {Object} orderInfo - redirect request Object
+ * @param {Object} order - Order Object
+ * @return {JSON} returns an JSON object
+ */
+function failureStatusOrderPlacement(selectedPayment, paymentStatus, orderInfo, order) {
+ var error;
+ if (!selectedPayment.equals(worldpayConstants.KLARNA) && !selectedPayment.equals(worldpayConstants.IDEAL) && !selectedPayment.equals(worldpayConstants.PAYPAL) && !selectedPayment.equals(worldpayConstants.WORLDPAY) && !selectedPayment.equals(worldpayConstants.CHINAUNIONPAY)) {
+ if (paymentStatus
+ && (paymentStatus.equals(worldpayConstants.CANCELLEDSTATUS) || paymentStatus.equals(worldpayConstants.REFUSED))) {
+ if (utils.verifyMac(orderInfo.mac,
+ orderInfo.orderKey, orderInfo.orderAmount, orderInfo.orderCurrency, orderInfo.orderStatus).error) {
+ app.getController('Cart').Show();// eslint-disable-line
+ return {
+ success: false
+ };
+ }
+ if (paymentStatus.equals(worldpayConstants.CANCELLEDSTATUS)) {
+ Transaction.wrap(function () {
+ order.custom.transactionStatus = new ArrayList('POST_AUTH_CANCELLED');// eslint-disable-line
+ return {
+ success: false
+ };
+ });
+ }
+ }
+ }
+ error = utils.worldpayErrorMessage();
+ if (selectedPayment.equals(worldpayConstants.KONBINI)) {
+ Transaction.wrap(function () { OrderMgr.cancelOrder(order); });
+ app.getController('Cart').Show();// eslint-disable-line
+ } else {
+ Transaction.wrap(function () { OrderMgr.failOrder(order); });
+ app.getController('COBilling').Start({// eslint-disable-line
+ errorMessage: error.errorMessage
+ });
+ }
+ return {
+ success: false
+ };
+}
+
+/**
+ * This function place the order in pending state and fails rest of the case.
+ * @param {Object} selectedPayment - selected payment method in an order
+ * @param {Object} order - Order Object
+ * @return {JSON} returns an JSON object
+ */
+function pendingStatusOrderPlacement(selectedPayment, order) {
+ var error;
+ if (selectedPayment.equals(worldpayConstants.KONBINI)) {
+ Transaction.wrap(function () { OrderMgr.cancelOrder(order); });
+ app.getController('Cart').Show();// eslint-disable-line
+ return {
+ success: false
+ };
+ }
+ var PendingStatus = requestObject.httpParameterMap.status.value;
+ if (!PendingStatus || PendingStatus.equals(worldpayConstants.OPEN)) {
+ if (order.status.value === Order.ORDER_STATUS_FAILED) {
+ error = utils.worldpayErrorMessage();
+ app.getController('COBilling').Start({// eslint-disable-line
+ errorMessage: error.errorMessage
+ });
+ return {
+ success: false
+ };
+ }
+ // Send order confirmation and clear used forms within the checkout process.
+ utils.sendEmailNotification(order);
+ // Clears all forms used in the checkout process.
+ worldpayHelper.worldPayClearFormElement();
+ app.getController('COSummary').ShowConfirmation(order);// eslint-disable-line
+ return {
+ success: false
+ };
+ }
+ error = utils.worldpayErrorMessage();
+ failImpl(order, error.errorMessage);
+ return {
+ error: true,
+ success: false,
+ errorMessage: error.errorMessage
+ };
+}
+
+/**
+ * This function places order of authorise state.
+ * @param {Object} selectedPayment - selected payment method in an order
+ * @param {Object} orderInfo - redirect request Object
+ * @param {Object} order - Order Object
+ * @return {JSON} returns an JSON object
+ */
+function authStatusOrderPlacement(selectedPayment, orderInfo, order) {
+ var error;
+ if (!selectedPayment.equals(worldpayConstants.KLARNA) && !selectedPayment.equals(worldpayConstants.IDEAL)
+ && !selectedPayment.equals(worldpayConstants.PAYPAL)
+ && !selectedPayment.equals(worldpayConstants.WORLDPAY)
+ && !selectedPayment.equals(worldpayConstants.CHINAUNIONPAY)) {
+ var macstatus = utils.verifyMac(orderInfo.mac, orderInfo.orderKey, orderInfo.orderAmount,
+ orderInfo.orderCurrency, orderInfo.orderStatus);
+ if (macstatus.error) {
+ Transaction.wrap(function () {
+ order.custom.worldpayMACMissingVal = true;// eslint-disable-line
+ });
+ error = utils.worldpayErrorMessage();
+ failImpl(order, error.errorMessage);
+ Logger.getLogger('worldpay').error(' mac issue ');
+ return {
+ error: true,
+ success: false,
+ errorMessage: error.errorMessage
+ };
+ }
+ }
+ sessionObject.privacy.order_id = '';
+ if (order.status.value === Order.ORDER_STATUS_FAILED) {
+ Transaction.wrap(function () {
+ order.custom.worldpayMACMissingVal = true;// eslint-disable-line
+ });
+ error = utils.worldpayErrorMessage();
+ app.getController('COBilling').Start({// eslint-disable-line
+ errorMessage: error.errorMessage
+ });
+ return {
+ success: false
+ };
+ }
+ var klarnasnippet;
+ if (selectedPayment.equals(worldpayConstants.KLARNA)) {
+ // Service Request - for Klarna Confirmation Inquiry
+ var paymentMthd = PaymentMgr.getPaymentMethod(worldpayConstants.KLARNA);
+ var WorldpayPreferences = require('*/cartridge/scripts/object/worldpayPreferences');
+ WorldpayPreferences = new WorldpayPreferences();
+ var preferences = WorldpayPreferences.worldPayPreferencesInit(paymentMthd, order);
+ var confirmationRequestKlarnaResult = serviceFacade.confirmationRequestKlarnaService(order.orderNo, preferences, preferences.merchantCode);
+ if (confirmationRequestKlarnaResult.error) {
+ Logger.getLogger('worldpay').error(
+ 'COPlaceOrder.js HandleAuthenticationResponse : ErrorCode : '
+ + confirmationRequestKlarnaResult.errorCode + ' : Error Message : '
+ + confirmationRequestKlarnaResult.errorMessage);
+ failImpl(order, confirmationRequestKlarnaResult.errorMessage);
+ app.getController('COBilling').Start({// eslint-disable-line
+ errorMessage: confirmationRequestKlarnaResult.errorMessage
+ });
+ return {
+ success: false
+ };
+ }
+ klarnasnippet = confirmationRequestKlarnaResult.response.reference.toString();
+ klarnasnippet = StringUtils.decodeString(StringUtils.decodeBase64(klarnasnippet), StringUtils.ENCODE_TYPE_HTML);
+ klarnasnippet = klarnasnippet.replace(new RegExp('/window.location.href/g'), 'window.top.location.href');
+ }
+ return {
+ success: true,
+ klarnasnippet: klarnasnippet
+ };
+}
+
+/**
+ * Handle redirection for redirect credit card response or APM where Mac is compared for Authorized and Refused
+ * @param {Object} order - Order Object
+ * @return {JSON} returns an JSON object
+ */
+function handleRedirection(order) {
+ if (!order) {
+ app.getController('Cart').Show();// eslint-disable-line
+ return {
+ success: false
+ };
+ }
+ var paymentStatus = requestObject.httpParameterMap.paymentStatus.value;
+ var orderInfo = utils.getWorldpayOrderInfo(paymentStatus);
+ var selectedPayment = sessionObject.forms.billing.paymentMethods.selectedPaymentMethodID.value.toString();
+ if (paymentStatus && paymentStatus.equals(worldpayConstants.AUTHORIZED)) {
+ return authStatusOrderPlacement(selectedPayment, orderInfo, order);
+ } else if (paymentStatus && paymentStatus.equals(worldpayConstants.PENDING)) {
+ return pendingStatusOrderPlacement(selectedPayment, order);
+ }
+ // else block
+ return failureStatusOrderPlacement(selectedPayment, paymentStatus, orderInfo, order);
+}
+
+/**
+ * Load payment methods
+ */
+function loadPaymentMethods() {
+ var PaymentInstrument = require('dw/order/PaymentInstrument');
+ var cart;
+ cart = app.getModel('Cart').get();
+ var applicableCreditCards = app.getController('COBilling').InitCreditCardList(cart).ApplicableCreditCards;// eslint-disable-line
+ var paymentAmount = cart.getNonGiftCertificateAmount();
+ var countryCode;
+ countryCode = cart.object.billingAddress && cart.object.billingAddress.countryCode.value ? cart.object.billingAddress.countryCode.value : Countries.getCurrent({
+ CurrentRequest: {
+ locale: requestObject.locale
+ }
+ }).countryCode;
+
+ app.getView({
+ ApplicableCreditCards: applicableCreditCards,
+ ApplicablePaymentCards: PaymentMgr.getPaymentMethod(PaymentInstrument.METHOD_CREDIT_CARD).getApplicablePaymentCards(customerObject, countryCode, paymentAmount.value),
+ Basket: cart.object,
+ selectedPaymentID: requestObject.httpParameterMap.selectedPaymentMethodId.value
+ }).render('worldpaypaymentmethods');
+}
+
+/**
+ * Validates the order id and token upon match it will proceed for capture service initiation
+ */
+function testCaptureService() {
+ var params = requestObject.getHttpParameters();
+ var orderId = (params.containsKey('order_id')) ? params.get('order_id')[0] : null;
+ var orderToken = (params.containsKey('order_token')) ? params.get('order_token')[0] : null;
+ var order = OrderMgr.getOrder(orderId);
+ if (order && orderId && orderToken && orderId.equals(order.orderNo) && orderToken.equals(order.orderToken)) {
+ var CaptureServiceRequestResult = serviceFacade.createCaptureService(
+ orderId);
+ if (CaptureServiceRequestResult.error) {
+ app.getView({
+ serviceResponse: {
+ errorCode: CaptureServiceRequestResult.errorCode,
+ errorMessage: CaptureServiceRequestResult.errorMessage
+ }
+ }).render('/service/capture_service');
+ } else {
+ app.getView({
+ serviceResponse: CaptureServiceRequestResult.response
+ }).render('/service/capture_service');
+ }
+ } else {
+ app.getView({
+ serviceResponse: {
+ errorCode: Resource.msg('worldpay.error.codeCAPTURE', 'worldpayerror', null),
+ errorMessage: Resource.msg('worldpay.error.codeCAPTURE', 'worldpayerror', null)
+ }
+ }).render('/service/capture_service');
+ }
+}
+/**
+ * function to initiate Device data collection
+ */
+function Ddc() {
+ var threeDFlexHelper = require('*/cartridge/scripts/common/threeDFlexHelper');
+ var intJwtResult = threeDFlexHelper.initJwtcreation();
+ var cardNumber = requestObject.httpParameterMap.cardNum.value;
+ var Bin = cardNumber.slice(0, 6);
+ var JWTdata = {
+ jti: intJwtResult.jti,
+ iat: intJwtResult.iat,
+ iss: intJwtResult.iss,
+ OrgUnitId: intJwtResult.OrgUnitId
+ };
+ var JWT = threeDFlexHelper.createJwt(JWTdata, intJwtResult.jwtMacKey);
+ app.getView({
+ Bin: Bin,
+ JWT: JWT
+ }).render('ddcIframe');
+}
+
+/**
+ * Captures Session Id as a result of device data collection. This would be used as a part of first request for 3ds2
+ */
+function Sess() {
+ var BasketMgr = require('dw/order/BasketMgr');
+ var sessionID = requestObject.httpParameterMap.dataSessionId;
+ var basket = BasketMgr.getCurrentBasket();
+ Transaction.wrap(function () {
+ basket.custom.dataSessionID = sessionID;
+ });
+}
+
+/**
+ * Handle 3DS Flex response for worldpay processor
+ * @return {JSON} returns an JSON object
+ */
+function Handle3ds() {
+ var params = requestObject.getHttpParameters();
+ var error = null;
+ var orderObj;
+ // md - merchant supplied data contains the OrderNo
+ var md = (params.containsKey('MD')) ? params.get('MD')[0] : null;
+ var orderNo = md;
+ if (!orderNo) {
+ Logger.getLogger('worldpay').error(
+ 'Worldpay.ds HandleAuthenticationResponse : Order no. not present in parameters');
+ error = utils.worldpayErrorMessage();
+ failOrder();
+ return {
+ error: true,
+ success: false,
+ errorMessage: error.errorMessage
+ };
+ }
+ try {
+ orderObj = OrderMgr.getOrder(orderNo);
+ } catch (ex) {
+ Logger.getLogger('worldpay').error('Worldpay.ds HandleAuthenticationResponse : Invalid Order ');
+ error = utils.worldpayErrorMessage();
+ failOrder();
+ return {
+ error: true,
+ success: false,
+ errorMessage: error.errorMessage
+ };
+ }
+ // Fetch the APM Name from the Payment isntrument.
+ var paymentIntrument = utils.getPaymentInstrument(orderObj);
+ var apmName = paymentIntrument.getPaymentMethod();
+ // Fetch the APM Type from the Payment Method i.e. if the Payment Methoid is of DIRECT or REDIRECT type.
+ var paymentMthd = PaymentMgr.getPaymentMethod(apmName);
+ var WorldpayPreferences = require('*/cartridge/scripts/object/worldpayPreferences');
+ WorldpayPreferences = new WorldpayPreferences();
+ var preferences = WorldpayPreferences.worldPayPreferencesInit(paymentMthd, orderObj);
+ if (preferences.missingPreferences()) {
+ Logger.getLogger('worldpay').error(
+ 'Worldpay.ds HandleAuthenticationResponse : Worldpay preferences are not properly set.');
+ error = utils.worldpayErrorMessage();
+ failImpl(orderObj, error.errorMessage);
+ return {
+ error: true,
+ success: false,
+ errorMessage: error.errorMessage,
+ orderNo: orderObj.orderNo,
+ orderToken: orderObj.orderToken
+ };
+ }
+ var SecondAuthorizeRequestResult = require('*/cartridge/scripts/service/serviceFacade').secondAuthorizeRequestService2(orderNo, paymentIntrument, null, preferences);
+ if (SecondAuthorizeRequestResult.error) {
+ Logger.getLogger('worldpay').error(
+ 'Worldpay.js HandleAuthenticationResponse : ErrorCode : ' + SecondAuthorizeRequestResult.errorCode +
+ ' : Error Message : ' + SecondAuthorizeRequestResult.errorMessage);
+ failImpl(orderObj, SecondAuthorizeRequestResult.errorMessage);
+ return {
+ error: true,
+ success: false,
+ errorCode: SecondAuthorizeRequestResult.errorCode,
+ errorMessage: SecondAuthorizeRequestResult.errorMessage,
+ orderNo: orderObj.orderNo,
+ orderToken: orderObj.orderToken
+ };
+ }
+ // success handling
+ if (sessionObject.privacy.order_id) {
+ orderObj = OrderMgr.getOrder(sessionObject.privacy.order_id);
+ }
+ if (!orderObj) {
+ app.getController('Cart').Show(); // eslint-disable-line
+ return {
+ error: true,
+ success: false
+ };
+ }
+ if (orderObj.getStatus().value === Order.ORDER_STATUS_FAILED) {
+ Transaction.wrap(function () {
+ if (orderObj) {
+ orderObj.custom.worldpayMACMissingVal = true;
+ }
+ });
+ error = utils.worldpayErrorMessage();
+ app.getController('COBilling').Start({ // eslint-disable-line
+ errorMessage: error.errorMessage
+ });
+ return {
+ error: true,
+ success: false,
+ errorMessage: error.errorMessage
+ };
+ }
+ var customerObj = orderObj.customer.authenticated ? orderObj.customer : null;
+ var tokenProcessutils = require('*/cartridge/scripts/common/tokenProcessutils');
+ var resultCheckAuthorization = tokenProcessutils.checkAuthorization(SecondAuthorizeRequestResult.serviceresponse, paymentIntrument, customerObj);
+ if (resultCheckAuthorization.error) {
+ failImpl(orderObj, resultCheckAuthorization.errorMessage);
+ return {
+ error: true,
+ success: false,
+ errorMessage: resultCheckAuthorization.lastEvent
+ };
+ }
+ if (app.getController('COPlaceOrder').SubmitImpl(orderObj).error) { // eslint-disable-line
+ app.getController('COSummary').Start(); // eslint-disable-line
+ return {
+ error: true,
+ success: false
+ };
+ }
+ app.getController('COSummary').ShowConfirmation(orderObj); // eslint-disable-line
+ return {
+ error: false,
+ success: true
+ };
+}
+
+/*
+ * Module exports
+ */
+
+/*
+ * Local methods
+ */
+exports.Handle = handle;
+exports.Authorize = authorize;
+exports.HandleRedirection = handleRedirection;
+exports.Notify = guard.ensure(['https', 'post'], notify);
+exports.GetNotificationUpdates = guard.ensure(['https'], getNotificationUpdates);
+exports.LoadPaymentMethods = guard.ensure(['https', 'post'], loadPaymentMethods);
+exports.HandleAuthenticationResponse = guard.ensure(['https', 'post'], handleAuthenticationResponse);
+exports.APMLookupService = guard.ensure(['https', 'post'], apmLookupService);
+exports.TestCaptureService = guard.ensure(['https', 'get'], testCaptureService);
+exports.Ddc = guard.ensure(['https', 'get'], Ddc);
+exports.Sess = guard.ensure(['https', 'post'], Sess);
+exports.Handle3ds = guard.ensure(['https', 'post'], Handle3ds);
diff --git a/cartridges/int_worldpay/cartridge/int_worldpay.properties b/cartridges/int_worldpay/cartridge/int_worldpay.properties
new file mode 100644
index 0000000..d2ddc76
--- /dev/null
+++ b/cartridges/int_worldpay/cartridge/int_worldpay.properties
@@ -0,0 +1,4 @@
+## cartridge.properties for cartridge int_worldpay
+#Thu May 17 14:14:45 IST 2018
+demandware.cartridges.int_worldpay.multipleLanguageStorefront=true
+demandware.cartridges.int_worldpay.id=int_worldpay
diff --git a/cartridges/int_worldpay/cartridge/scripts/hooks.json b/cartridges/int_worldpay/cartridge/scripts/hooks.json
new file mode 100644
index 0000000..96b4be0
--- /dev/null
+++ b/cartridges/int_worldpay/cartridge/scripts/hooks.json
@@ -0,0 +1,8 @@
+{
+ "hooks": [
+ {
+ "name": "app.payment.processor.Worldpay",
+ "script": "./../controllers/Worldpay"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/cartridges/int_worldpay/cartridge/scripts/worldpayHelper.js b/cartridges/int_worldpay/cartridge/scripts/worldpayHelper.js
new file mode 100644
index 0000000..87e7b77
--- /dev/null
+++ b/cartridges/int_worldpay/cartridge/scripts/worldpayHelper.js
@@ -0,0 +1,479 @@
+/* API Includes */
+var Site = require('dw/system/Site');
+var Transaction = require('dw/system/Transaction');
+var paymentInstrumentUtils = require('*/cartridge/scripts/common/paymentInstrumentUtils');
+var worldpayConstants = require('*/cartridge/scripts/common/worldpayConstants');
+var Logger = require('dw/system/Logger');
+var PaymentStatusCodes = require('dw/order/PaymentStatusCodes');
+var Status = require('dw/system/Status');
+var worldpayPayment = require('*/cartridge/scripts/order/worldpayPayment');
+var OrderMgr = require('dw/order/OrderMgr');
+var PaymentInstrument = require('dw/order/PaymentInstrument');
+var ArrayList = require('dw/util/ArrayList');
+var Resource = require('dw/web/Resource');
+var PaymentMgr = require('dw/order/PaymentMgr');
+var sessionObject = session;
+var requestObject = request;
+var customerObject = customer;
+var utils = require('*/cartridge/scripts/common/utils');
+/**
+ * This controller implements the billing logic. It is used by both the single shipping and the multi shipping
+ * scenario and is responsible for providing the payment method selection as well as entering a billing address.
+ *
+ * @module scripts/worldpayHelper
+ */
+/**
+* Replace token from old to new card
+* @param {Object} newCreditCard - newCreditCard
+* @param {Object} creditcard - old creditcard
+*/
+function replaceToken(newCreditCard, creditcard) {
+ if (Site.getCurrent().getCustomPreferenceValue('WorldpayEnableTokenization')
+ && creditcard.getCreditCardToken() && !newCreditCard.getCreditCardToken()) {
+ newCreditCard.setCreditCardToken(creditcard.getCreditCardToken());
+ Transaction.wrap(function () {
+ if (creditcard.custom.tokenScope && !(newCreditCard.custom.tokenScope)) {
+ newCreditCard.custom.tokenScope = creditcard.custom.tokenScope; // eslint-disable-line
+ }
+ });
+ }
+ if (Site.getCurrent().getCustomPreferenceValue('enableStoredCredentials') && creditcard.custom.transactionIdentifier && !(newCreditCard.custom.transactionIdentifier)) {
+ Transaction.wrap(function () {
+ newCreditCard.custom.transactionIdentifier = creditcard.custom.transactionIdentifier; // eslint-disable-line
+ });
+ }
+}
+/**
+ * Retrive order based on order_id from session
+ * @param {Object} order - Order Object
+ * @return {Object} returns an object
+ */
+function getOrder(order) {
+ if (!order) {
+ if (requestObject.httpParameterMap.order_id.stringValue) {
+ var orderObj = OrderMgr.getOrder(requestObject.httpParameterMap.order_id.stringValue);
+ if (orderObj && (requestObject.httpParameterMap.order_token.stringValue === orderObj.getOrderToken())) {
+ return {
+ success: true,
+ Order: orderObj
+ };
+ }
+ return {
+ error: true,
+ Order: null
+ };
+ }
+ return {
+ error: true,
+ Order: null
+ };
+ }
+ return {
+ success: true,
+ Order: order
+ };
+}
+
+/**
+ * Return applicable cards based on tokenization and encryption setting in Worldpay
+ * @param {Object} ApplicableCreditCards - ApplicableCreditCards
+ * @return {Object} ApplicableCreditCards - ApplicableCreditCards
+ */
+function availableCreditCards(ApplicableCreditCards) {
+ var NewApplicableCreditCards = new ArrayList();
+ if (ApplicableCreditCards) {
+ for (const ApplicableCreditCard of ApplicableCreditCards) {
+ NewApplicableCreditCards.add(ApplicableCreditCard);
+ }
+ }
+ return NewApplicableCreditCards;
+}
+
+/**
+ * get form errors and add them to an object
+ * @param {Object} form - the target product line item
+ * @returns {Object} - an object that contain the error in the form
+ */
+function getFormErrors(form) {
+ var results = {};
+ if (!form) {
+ return {};
+ }
+ Object.keys(form).forEach(function (key) {
+ if (form[key]) {
+ if (form[key].toString().indexOf('FormField') > -1 && !form[key].valid) {
+ results[form[key].htmlName] = form[key].error;
+ form[key].invalidateFormElement(form[key].error);
+ }
+ if (form[key].toString().indexOf('FormGroup') > -1) {
+ var innerFormResult = getFormErrors(form[key]);
+ Object.keys(innerFormResult).forEach(function (innerKey) {
+ results[innerKey] = innerFormResult[innerKey];
+ });
+ }
+ }
+ });
+ return results;
+}
+
+/**
+ * Verifies a credit card against a valid card number and expiration date and possibly invalidates invalid form fields.
+ * If the verification was successful a credit card payment instrument is created.
+ * @param {Object} args - Arguments
+ * @return {JSON} returns an JSON object
+ */
+function handle(args) {
+ var BasketMgr = require('dw/order/BasketMgr');
+ var tokenId = '';
+ var paymentFieldErrors = {};
+ var paymentForm = sessionObject.forms.billing.paymentMethods;
+ var basket = args.Basket;
+ // object formation based on form fields
+ var paymentInformation = {
+ selectedPaymentMethodID: {
+ value: paymentForm.selectedPaymentMethodID ? paymentForm.selectedPaymentMethodID.value : '',
+ htmlName: paymentForm.selectedPaymentMethodID.value
+ },
+ cardType: {
+ value: paymentForm.creditCard.type ? paymentForm.creditCard.type.value : '',
+ htmlName: paymentForm.creditCard.type.htmlName
+ },
+ cardOwner: {
+ value: paymentForm.creditCard.owner ? paymentForm.creditCard.owner.value : '',
+ htmlName: paymentForm.creditCard.owner.htmlName
+ },
+ cardNumber: {
+ value: paymentForm.creditCard.number ? paymentForm.creditCard.number.value : '',
+ htmlName: paymentForm.creditCard.number.htmlName
+ },
+ securityCode: {
+ value: paymentForm.creditCard.cvn ? paymentForm.creditCard.cvn.value : '',
+ htmlName: paymentForm.creditCard.cvn.htmlName
+ },
+ expirationMonth: {
+ value: paymentForm.creditCard.expiration.month.selectedOption ? parseInt(
+ paymentForm.creditCard.expiration.month.selectedOption.htmlValue, 10) : '',
+ htmlName: paymentForm.creditCard.expiration.month.htmlName
+ },
+ expirationYear: {
+ value: paymentForm.creditCard.expiration.year ? parseInt(paymentForm.creditCard.expiration.year.value, 10)
+ : '',
+ htmlName: paymentForm.creditCard.expiration.year.htmlName
+ },
+ encryptedData: {
+ value: paymentForm.creditCard.encryptedData ? paymentForm.creditCard.encryptedData.value : '',
+ htmlName: paymentForm.creditCard.encryptedData.htmlName
+ },
+ preferredCard: {
+ value: paymentForm.creditCard.cards ? paymentForm.creditCard.cards.value : '',
+ htmlName: paymentForm.creditCard.cards.htmlName
+ },
+ idealFields: {
+ bank: {
+ value: paymentForm.idealFields.bank ? paymentForm.idealFields.bank.value : '',
+ htmlName: paymentForm.idealFields.bank.htmlName
+ }
+ },
+ brazilFields: {
+ cpf: {
+ value: paymentForm.creditCard.cpf ? paymentForm.creditCard.cpf.value : '',
+ htmlName: paymentForm.creditCard.cpf.htmlName
+ },
+ installments: {
+ value: paymentForm.creditCard.installments ? paymentForm.creditCard.installments.value : '',
+ htmlName: paymentForm.creditCard.installments.htmlName
+ }
+ },
+ elvFields: {
+ elvMandateType: {
+ value: paymentForm.elvFields.elvMandateType ? paymentForm.elvFields.elvMandateType.value : '',
+ htmlName: paymentForm.elvFields.elvMandateType.htmlName
+ },
+ elvMandateID: {
+ value: paymentForm.elvFields.elvMandateID ? paymentForm.elvFields.elvMandateID.value : '',
+ htmlName: paymentForm.elvFields.elvMandateID.htmlName
+ },
+ iban: {
+ value: paymentForm.elvFields.iban ? paymentForm.elvFields.iban.value : '',
+ htmlName: paymentForm.elvFields.iban.htmlName
+ },
+ accountHolderName: {
+ value: paymentForm.elvFields.accountHolderName ? paymentForm.elvFields.accountHolderName.value : '',
+ htmlName: paymentForm.elvFields.accountHolderName.htmlName
+ },
+ elvConsent: {
+ value: paymentForm.elvFields.elvConsent ? paymentForm.elvFields.elvConsent.value : false,
+ htmlName: paymentForm.elvFields.elvConsent.htmlName
+ }
+ }
+ };
+ // remove existing payment instruments
+ var paymentMethod = paymentInformation.selectedPaymentMethodID.value;
+ paymentInformation.paymentPrice = basket.totalGrossPrice;
+ Transaction.wrap(function () {
+ paymentInstrumentUtils.removeExistingPaymentInstruments(basket);
+ });
+ var matchedPaymentInstrument;
+ // retrieve saved card token for creditcard or redirect
+ if (paymentForm.selectedPaymentMethodID.value.equals('CREDIT_CARD')
+ || paymentForm.selectedPaymentMethodID.value.equals(worldpayConstants.WORLDPAY)) {
+ if (customerObject.authenticated) {
+ var wallet = customerObject.getProfile().getWallet();
+
+ var paymentInstruments = wallet.getPaymentInstruments(PaymentInstrument.METHOD_CREDIT_CARD);
+ matchedPaymentInstrument = paymentInstrumentUtils.getTokenPaymentInstrument(paymentInstruments,
+ sessionObject.forms.billing.paymentMethods.creditCard.number.value,
+ sessionObject.forms.billing.paymentMethods.creditCard.type.value, paymentInformation.expirationMonth.value,
+ paymentInformation.expirationYear.value);
+ if (matchedPaymentInstrument && matchedPaymentInstrument.getCreditCardToken()) {
+ tokenId = matchedPaymentInstrument.getCreditCardToken();
+ }
+ }
+ }
+ // when saved card has token
+ if (matchedPaymentInstrument && tokenId) {
+ paymentInformation.cardOwner.value = matchedPaymentInstrument.creditCardHolder;
+ paymentInformation.cardNumber.value = matchedPaymentInstrument.creditCardNumber;
+ paymentInformation.cardType.value = matchedPaymentInstrument.creditCardType;
+ paymentInformation.securityCode.value = paymentInformation.securityCode.value ? paymentInformation.securityCode.value
+ : '';
+ paymentInformation.expirationMonth.value = matchedPaymentInstrument.creditCardExpirationMonth;
+ paymentInformation.expirationYear.value = matchedPaymentInstrument.creditCardExpirationYear;
+ paymentInformation.creditCardToken = matchedPaymentInstrument.getCreditCardToken();
+ }
+ // when token not available for credit card then perform basic field vaildation
+ if (!tokenId && paymentForm.selectedPaymentMethodID.value.equals('CREDIT_CARD')) {
+ // verify credit card form data
+ if (!paymentForm.creditCard.encryptedData || !paymentForm.creditCard.encryptedData.value) {
+ paymentFieldErrors = getFormErrors(paymentForm.creditCard);
+ if (!paymentForm.selectedPaymentMethodID.value) {
+ if (BasketMgr.getCurrentBasket().totalGrossPrice.value > 0) {
+ paymentFieldErrors[paymentForm.selectedPaymentMethodID.htmlName] = Resource.msg(
+ 'error.no.selected.payment.method', 'creditCard', null);
+ paymentForm.selectedPaymentMethodID.invalidateFormElement(Resource.msg(
+ 'error.no.selected.payment.method', 'creditCard', null));
+ }
+ }
+ }
+ }
+ if (Object.keys(paymentFieldErrors).length > 0) {
+ return {
+ fieldErrors: [paymentFieldErrors],
+ serverErrors: {},
+ error: true
+ };
+ }
+ var regex = /^(\d{3})$/;
+ var regexAmex = /^(\d{4})$/;
+ // credit card complete validation flow
+ if (paymentMethod && paymentMethod.equals(PaymentInstrument.METHOD_CREDIT_CARD)) {
+ // save card opted by user
+ if (paymentForm.creditCard.saveCard && paymentForm.creditCard.saveCard.value) {
+ paymentInformation.saveCard = {
+ value: paymentForm.creditCard.saveCard.value,
+ htmlName: paymentForm.creditCard.saveCard.htmlName
+ };
+ }
+ var cardNumber = paymentInformation.cardNumber.value;
+ var cardSecurityCode = paymentInformation.securityCode.value;
+ var expirationMonth = paymentInformation.expirationMonth.value;
+ var expirationYear = paymentInformation.expirationYear.value;
+
+ var serverErrors = [];
+ var creditCardStatus = {};
+ var cvvDisabled = Site.getCurrent().getCustomPreferenceValue('WorldpayDisableCVV');
+ var cardType = paymentInformation.cardType.value;
+ var paymentCard = PaymentMgr.getPaymentCard(cardType);
+
+ if (paymentCard) {
+ if (!paymentInformation.creditCardToken) {
+ creditCardStatus = paymentCard.verify(expirationMonth, expirationYear, cardNumber, cardSecurityCode);
+ } else if (paymentInformation.creditCardToken && !cvvDisabled) {
+ if (!regex.test(cardSecurityCode) && !cardType.equalsIgnoreCase('AMEX')) {
+ creditCardStatus = new Status(Status.ERROR, PaymentStatusCodes.CREDITCARD_INVALID_SECURITY_CODE);
+ }
+ if (!regexAmex.test(cardSecurityCode) && cardType.equalsIgnoreCase('AMEX')) {
+ creditCardStatus = new Status(Status.ERROR, PaymentStatusCodes.CREDITCARD_INVALID_SECURITY_CODE);
+ }
+ }
+ } else {
+ creditCardStatus = {
+ error: true,
+ cardUnknown: true
+ };
+ }
+
+ if (!creditCardStatus.error && !cvvDisabled) {
+ if (!regex.test(cardSecurityCode) && !cardType.equalsIgnoreCase('AMEX')) {
+ creditCardStatus = new Status(Status.ERROR, PaymentStatusCodes.CREDITCARD_INVALID_SECURITY_CODE);
+ }
+ if (!regexAmex.test(cardSecurityCode) && cardType.equalsIgnoreCase('AMEX')) {
+ creditCardStatus = new Status(Status.ERROR, PaymentStatusCodes.CREDITCARD_INVALID_SECURITY_CODE);
+ }
+ }
+ if (creditCardStatus.error) {
+ if (!(creditCardStatus instanceof Status) && creditCardStatus.cardUnknown) {
+ paymentFieldErrors[paymentInformation.cardNumber.htmlName] = utils.getConfiguredLabel('error.invalid.card.number', 'creditCard');
+ paymentForm.creditCard.number.invalidateFormElement(utils.getConfiguredLabel('error.invalid.card.number', 'creditCard'));
+ } else if (creditCardStatus.items) {
+ var item;
+ for (var k = 0; k < creditCardStatus.items.size(); k++) {
+ item = creditCardStatus.items[k];
+ switch (item.code) {
+ case PaymentStatusCodes.CREDITCARD_INVALID_CARD_NUMBER:
+ paymentFieldErrors[paymentInformation.cardNumber.htmlName] = utils.getConfiguredLabel('error.invalid.card.number', 'creditCard');
+ paymentForm.creditCard.number.invalidateFormElement(utils.getConfiguredLabel('error.invalid.card.number', 'creditCard'));
+ break;
+
+ case PaymentStatusCodes.CREDITCARD_INVALID_EXPIRATION_DATE:
+ paymentFieldErrors[paymentInformation.expirationMonth.htmlName] = utils.getConfiguredLabel('error.expired.credit.card', 'creditCard');
+ paymentForm.creditCard.expiration.month.invalidateFormElement(utils.getConfiguredLabel('error.expired.credit.card', 'creditCard'));
+ paymentFieldErrors[paymentInformation.expirationYear.htmlName] = utils.getConfiguredLabel('error.expired.credit.card', 'creditCard');
+ paymentForm.creditCard.expiration.year.invalidateFormElement(utils.getConfiguredLabel('error.expired.credit.card', 'creditCard'));
+ break;
+
+ case PaymentStatusCodes.CREDITCARD_INVALID_SECURITY_CODE:
+ paymentFieldErrors[paymentInformation.securityCode.htmlName] = utils.getConfiguredLabel('error.invalid.security.code', 'creditCard');
+ paymentForm.creditCard.cvn.invalidateFormElement(utils.getConfiguredLabel('error.invalid.security.code', 'creditCard'));
+ break;
+ default:
+ serverErrors.push(Resource.msg('error.card.information.error', 'creditCard', null));
+ }
+ }
+ }
+ return {
+ fieldErrors: [paymentFieldErrors],
+ serverErrors: serverErrors,
+ error: true
+ };
+ }
+ // payment instrument creation for credit card
+ var cardHandleResult = worldpayPayment.handleCreditCard(basket, paymentInformation);
+ if (cardHandleResult.error) {
+ sessionObject.forms.billing.paymentMethods.creditCard.encryptedData.value = '';
+ }
+ } else if (paymentMethod && (paymentMethod.equals(worldpayConstants.WORLDPAY))) {
+ // save card opted by user
+ if (paymentForm.creditCard.saveCard && paymentForm.creditCard.saveCard.value) {
+ paymentInformation.saveCard = {
+ value: paymentForm.creditCard.saveCard.value,
+ htmlName: paymentForm.creditCard.saveCard.htmlName
+ };
+ }
+ // saved card handling for redirect
+ if (paymentMethod.equals(worldpayConstants.WORLDPAY)
+ && Site.getCurrent().getCustomPreferenceValue('WorldpayEnableTokenization')
+ && basket.getCustomer().authenticated && paymentInformation.cardNumber.value) {
+ if (paymentInformation.creditCardToken && !Site.getCurrent().getCustomPreferenceValue('WorldpayDisableCVV')) {
+ if (!regex.test(paymentInformation.securityCode.value) && !paymentInformation.cardType.value.equalsIgnoreCase('AMEX')) {
+ paymentForm.creditCard.cvn.invalidateFormElement(utils.getConfiguredLabel('error.invalid.security.code', 'creditCard'));
+ return { fieldErrors: {}, serverErrors: {}, error: true, success: false };
+ }
+ if (!regexAmex.test(paymentInformation.securityCode.value) && paymentInformation.cardType.value.equalsIgnoreCase('AMEX')) {
+ paymentForm.creditCard.cvn.invalidateFormElement(utils.getConfiguredLabel('error.invalid.security.code', 'creditCard'));
+ return { fieldErrors: {}, serverErrors: {}, error: true, success: false };
+ }
+ }
+ sessionObject.forms.billing.paymentMethods.selectedPaymentMethodID.value = worldpayConstants.CREDITCARD;
+ }
+ // payment instrument handling redirect
+ return worldpayPayment.handleCardRedirect(basket, paymentInformation);
+ } else if (paymentMethod) {
+ // payment instrument handling for APM
+ var handleAPMResult = worldpayPayment.handleAPM(basket, paymentInformation);
+ if (handleAPMResult.success) {
+ if (paymentForm.selectedPaymentMethodID.value.equals(worldpayConstants.IDEAL)) {
+ paymentFieldErrors = getFormErrors(paymentForm.idealFields);
+ } else if (paymentForm.selectedPaymentMethodID.value.equals(worldpayConstants.ELV)) {
+ if (!paymentInformation.elvFields.elvConsent.value) {
+ paymentFieldErrors[paymentForm.elvFields.elvConsent.htmlName] = utils.getConfiguredLabel('error.message.required', 'forms');
+ paymentForm.elvFields.elvConsent.invalidateFormElement(utils.getConfiguredLabel('error.message.required', 'forms'));
+ }
+ paymentFieldErrors = getFormErrors(paymentForm.elvFields);
+ }
+ if (Object.keys(paymentFieldErrors).length > 0) {
+ return {
+ fieldErrors: [paymentFieldErrors],
+ serverErrors: {},
+ error: true
+ };
+ }
+ }
+ }
+ return {
+ fieldErrors: {},
+ serverErrors: {},
+ error: false,
+ success: true
+ };
+}
+
+/**
+ * Authorizes a payment using a credit card. The payment is authorized by using the BASIC_CREDIT processor
+ * only and setting the order no as the transaction ID. Customizations may use other processors and custom
+ * logic to authorize credit card payment.
+ * @param {Object} args - Arguments
+ * @return {Object} returns an object
+ */
+function authorize(args) {
+ var orderNo = args.OrderNo;
+ var paymentforms = sessionObject.forms.billing.paymentMethods.creditCard;
+ var cardNumber = paymentforms.number ? paymentforms.number.value : '';
+ var encryptedData = paymentforms.encryptedData ? paymentforms.encryptedData.value : '';
+ var cvn = paymentforms.cvn ? paymentforms.cvn.value : '';
+
+ var order = OrderMgr.getOrder(orderNo);
+ sessionObject.privacy.order_id = order.orderNo;
+ var authResponse = worldpayPayment.authorize(orderNo, cardNumber, encryptedData, cvn);
+ if (authResponse.is3D) {
+ sessionObject.privacy.echoData = authResponse.echoData;
+ } else if (authResponse.worldpayredirect) {
+ sessionObject.privacy.worldpayRedirectURL = authResponse.redirectUrl;
+ }
+ return authResponse;
+}
+
+/**
+ * Replace the Payment Instrument with matching Customer Payment Instrument along with card token. Match criteria:- last 4 digits of crad number and card type
+ * @param {PaymentInstrument} paymentInstrument - The payment instrument
+ * @param {PaymentInstrument} customerPaymentInstruments - Customer payment instrument
+ * @return {Object} returns an object
+ */
+function replacePaymentInstrument(paymentInstrument, customerPaymentInstruments) {
+ var cardNumber = sessionObject.forms.paymentinstruments.creditcards.newcreditcard.number.value;
+ var cardType = sessionObject.forms.paymentinstruments.creditcards.newcreditcard.type.value;
+ try {
+ var creditCardInstrument = null;
+ // find credit card in payment instruments
+ creditCardInstrument = paymentInstrumentUtils.getTokenPaymentInstrument(customerPaymentInstruments, cardNumber,
+ cardType);
+ if (creditCardInstrument) {
+ var wallet = customerObject.getProfile().getWallet();
+ wallet.removePaymentInstrument(creditCardInstrument);
+ if (creditCardInstrument.getCreditCardToken()) {
+ paymentInstrument.setCreditCardToken(creditCardInstrument.getCreditCardToken());
+ }
+ }
+ } catch (ex) {
+ Logger.getLogger('worldpay').error('worldpayHelper-ReplacePaymentInstrument error recieved : ' + ex.message);
+ }
+ return {};
+}
+
+/**
+ * Clear worldpay form elements
+ */
+function worldPayClearFormElement() {
+ sessionObject.forms.singleshipping.clearFormElement();
+ sessionObject.forms.multishipping.clearFormElement();
+ sessionObject.forms.billing.clearFormElement();
+ sessionObject.privacy.order_id = '';
+}
+
+exports.handle = handle;
+exports.authorize = authorize;
+exports.ReplaceToken = replaceToken;
+exports.AvailableCreditCards = availableCreditCards;
+exports.GetOrder = getOrder;
+exports.ReplacePaymentInstrument = replacePaymentInstrument;
+exports.worldPayClearFormElement = worldPayClearFormElement;
diff --git a/cartridges/int_worldpay/cartridge/templates/default/apmlookupoptions.isml b/cartridges/int_worldpay/cartridge/templates/default/apmlookupoptions.isml
new file mode 100644
index 0000000..65ed422
--- /dev/null
+++ b/cartridges/int_worldpay/cartridge/templates/default/apmlookupoptions.isml
@@ -0,0 +1,17 @@
+
+
\ No newline at end of file
diff --git a/cartridges/int_worldpay/cartridge/templates/default/worldpaypaymentmethods.isml b/cartridges/int_worldpay/cartridge/templates/default/worldpaypaymentmethods.isml
new file mode 100644
index 0000000..253d65b
--- /dev/null
+++ b/cartridges/int_worldpay/cartridge/templates/default/worldpaypaymentmethods.isml
@@ -0,0 +1,303 @@
+
+
+ Credit card block
+ --------------------------------------------------------------
+
+
+
+
+
+
+
+
+
+
+
+
+
display select box with stored credit cards if customer is authenticated
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ var help = {
+ label: Resource.msg('billing.linkcvn', 'checkout', null),
+ cid: 'checkout-security-code'
+ };
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Additional Code for IDEAL Payment Integration
+ --------------------------------------------------------------
+
+
+
+
+ Bill me later
+ --------------------------------------------------------------
+
+
+
+
+
${Resource.msg('billing.bmlhelp','checkout',null)}
+
+
•Date of Birth:
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ var help = {
+ label: Resource.msg('billing.linkcvn', 'checkout', null),
+ cid: 'checkout-security-code'
+ };
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ ${Resource.msg('worldpay.or','worldpay',null)}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ var siteCore = Site.getCurrent().getCustomPreferenceValue('siteCore');
+ var currentCountry = require(siteCore + '/cartridge/scripts/util/Countries').getCurrent(pdict);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ var elvMandateTypeList : dw.util.ArrayList = new dw.util.ArrayList();
+ elvMandateTypeList.add('ONE-OFF');
+ elvMandateTypeList.add('RECURRING');
+
+
+ var paymentMethod : dw.order.PaymentMethod = dw.order.PaymentMgr.getPaymentMethod('SEPA_DIRECT_DEBIT-SSL');
+
+ var elvMerchantNumber : String = '';
+
+ if(!empty(paymentMethod.custom.mandateNumber) && !empty(paymentMethod.custom.merchantID)){
+ elvMerchantNumber = paymentMethod.custom.mandateNumber;
+ }else{
+ elvMerchantNumber = dw.system.Site.getCurrent().getCustomPreferenceValue('WorldpayMerchantNumber');
+ }
+
+ var date : Date = dw.system.System.calendar.time;
+ var uniqueId = date.getFullYear().toString() + date.getMonth() + date.getDate() + date.getHours() + date.getMinutes() + date.getSeconds() + date.getMilliseconds();
+ var mandateID : String = 'M-'+ elvMerchantNumber +'-'+uniqueId;
+
+
+
+
+
+
\ No newline at end of file
diff --git a/cartridges/int_worldpay/cartridge/templates/default/worldpaysummary.isml b/cartridges/int_worldpay/cartridge/templates/default/worldpaysummary.isml
new file mode 100644
index 0000000..68fdee0
--- /dev/null
+++ b/cartridges/int_worldpay/cartridge/templates/default/worldpaysummary.isml
@@ -0,0 +1,28 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/cartridges/int_worldpay/package.json b/cartridges/int_worldpay/package.json
new file mode 100644
index 0000000..1be3d21
--- /dev/null
+++ b/cartridges/int_worldpay/package.json
@@ -0,0 +1,3 @@
+{
+ "hooks": "./cartridge/scripts/hooks.json"
+}
\ No newline at end of file
diff --git a/cartridges/int_worldpay_core/cartridge/scripts/common/createRequestHelper.js b/cartridges/int_worldpay_core/cartridge/scripts/common/createRequestHelper.js
index a4954fc..e229245 100644
--- a/cartridges/int_worldpay_core/cartridge/scripts/common/createRequestHelper.js
+++ b/cartridges/int_worldpay_core/cartridge/scripts/common/createRequestHelper.js
@@ -35,7 +35,7 @@ function createOrderContent(basket) {
* @param {dw.order.Basket} basket - The current basket
* @return {string} return CDATA
*/
-function sendPluginTrackerDetails(orderObj) {
+function sendPluginTrackerDetails(orderObj, worldpayAPMType) {
var system = require('dw/system/System');
var Resource = require('dw/web/Resource');
var PaymentMgr = require('dw/order/PaymentMgr');
@@ -55,18 +55,42 @@ function sendPluginTrackerDetails(orderObj) {
var SFRA_VERSION = Resource.msg('global.version.number', 'version', null);
var CURRENT_WORLDPAY_CARTRIDGE_VERSION = Resource.msg('Worldpay.version', 'version', null);
var WORLDPAY_CARTRIDGE_VERSION_USED_TILL_DATE; var UPGRADE_DATES;
+ var NODE_VERSION = Site.getCurrent().getCustomPreferenceValue('pluginTrackerNodeVersion');
if (previousCartridgeVersion) {
WORLDPAY_CARTRIDGE_VERSION_USED_TILL_DATE = previousCartridgeVersion.join(',');
}
if (upgradeDates) {
UPGRADE_DATES = upgradeDates.join(',');
}
+ var str = worldpayAPMType;
+ if (worldpayAPMType.equalsIgnoreCase(worldpayConstants.ELV)) {
+ str = 'SEPA_DIRECT_DEBIT-SSL';
+ } else if(worldpayAPMType.equals(worldpayConstants.KLARNA)) {
+ str = paymentIntrument.custom.wpKlarnaPaymentMethod;
+ } else if (paymentMthd && paymentMthd.ID === 'CREDIT_CARD' && Site.current.getCustomPreferenceValue('enableEFTPOS')) {
+ str = 'EFTPOS_AU-SSL';
+ }
var modeSupported = system.getCompatibilityMode();
var compMode = parseFloat(modeSupported) / 100;
var SFRA_COMPATIBILITY_VERSION = compMode.toString();
var rows = utils.dl(utils.dt('MERCHANT_ENTITY_REF') + utils.dt('MERCHANT_ID') + utils.dt('SFRA_VERSION') + utils.dt('SFRA_COMPATIBILITY_VERSION') + utils.dt('CURRENT_WORLDPAY_CARTRIDGE_VERSION') + utils.dt('UPGRADE_DATES') + utils.dt('WORLDPAY_CARTRIDGE_VERSION_USED_TILL_DATE'));
rows += utils.dl(utils.dd(MERCHANT_ENTITY_REF) + utils.dd(MERCHANT_ID) + utils.dd(SFRA_VERSION) + utils.dd(SFRA_COMPATIBILITY_VERSION) + utils.dd(CURRENT_WORLDPAY_CARTRIDGE_VERSION) + utils.dd(WORLDPAY_CARTRIDGE_VERSION_USED_TILL_DATE) + utils.dd(UPGRADE_DATES));
- return utils.convert2cdata(utils.dl(rows));
+ var upgradeDatesNewFormat = []
+ for( let i=0; i' + JSON.stringify(newPluginTrackerData) + '');
}
/**
@@ -223,10 +247,13 @@ function addBillingAddressDetailsFormat2(requestXml, billingAddress) {
* @return {XML} returns request xml
*/
function addShopperDetails(apmName, requestXml, orderObj, apmType, currentCustomer, includeShopperId) {
- if (apmName.equals(worldpayConstants.GIROPAY) || apmName.equals(worldpayConstants.GOOGLEPAY)) {
+ var Site = require('dw/system/Site');
+ if (apmName.equals(worldpayConstants.GOOGLEPAY)) {
var shopperXML = new XML('' + orderObj.getCustomerEmail() + '' +
request.getHttpHeaders().get(worldpayConstants.ACCEPT) + '' +
request.getHttpUserAgent() + '');
+ shopperXML.browser.browserScreenHeight = request.httpParameterMap.browserScreenHeight.value;
+ shopperXML.browser.browserScreenWidth = request.httpParameterMap.browserScreenWidth.value;
requestXml.submit.order.appendChild(shopperXML);
} else if (apmName.equals(worldpayConstants.WECHATPAY) && apmType.equalsIgnoreCase(worldpayConstants.DIRECT)) {
requestXml.submit.order.shopper.shopperEmailAddress = orderObj.getCustomerEmail();
@@ -243,7 +270,10 @@ function addShopperDetails(apmName, requestXml, orderObj, apmType, currentCustom
// The result of request.getSession().getSessionID() in Demandware is not NMTOKEN.
// use the createSessionID() function to cutomize the session ID
- if (apmType.equalsIgnoreCase(worldpayConstants.DIRECT) && !apmName.equals(worldpayConstants.KLARNA) && !apmName.equals(worldpayConstants.WECHATPAY)) {
+ if (apmType.equalsIgnoreCase(worldpayConstants.DIRECT) && !apmName.equals(worldpayConstants.KLARNA) && !apmName.equals(worldpayConstants.WECHATPAY) && Site.getCurrent().getCustomPreferenceValue("enableEFTPOSDebugging")) {
+ var sessionXML = new XML('');
+ requestXml.submit.order.shopper.appendChild(sessionXML);
+ } else if (apmType.equalsIgnoreCase(worldpayConstants.DIRECT) && !apmName.equals(worldpayConstants.KLARNA) && !apmName.equals(worldpayConstants.WECHATPAY)) {
var sessionXML = new XML('');
requestXml.submit.order.shopper.appendChild(sessionXML);
}
@@ -251,15 +281,32 @@ function addShopperDetails(apmName, requestXml, orderObj, apmType, currentCustom
}
/**
- * Hook function to add Installation details. This function is called during the xml order
- * creation. This is primarily required for all APM's and CC redirect .
- * @param {XML} requestXml - request Xml
- * @param {string} installationID - installationID
- * @return {XML} returns request xml
+ * Adds Worldpay installation ID to the request
+ * @param {Object} preferences - Worldpay preferences
+ * @param {Object} requestXml - request Object
+ * @param {string} apmName - APM name
+ * @param {Object} paymentMthd - Payment method object
+ * @param {dw.order.PaymentInstrument} paymentInstrument - Payment instrument associated with the order object
+ * @returns {XML} - request Object
*/
-function addInstallationDetails(requestXml, installationID) {
- requestXml.submit.order.@installationId = installationID;
- return requestXml;
+function addInstallationDetails(preferences, requestXml, apmName, paymentMthd, paymentInstrument) {
+ var createRequestHelper = require('*/cartridge/scripts/common/createRequestHelper');
+ var configurablePaymentMethods = preferences.configurablePaymentMethods;
+ var installationID = preferences.worldPayInstallationId;
+ var reqXml = requestXml;
+ if (installationID) {
+ configurablePaymentMethods.forEach(function (configurableAPM) {
+ if (configurableAPM.equalsIgnoreCase(apmName)) {
+ if (paymentMthd.ID === worldpayConstants.WORLDPAY && paymentInstrument.getCreditCardToken()) {
+ reqXml.submit.order.@installationId = installationID;
+ } else {
+ reqXml.submit.order.@installationId = installationID;
+ reqXml = addContactDetails(reqXml);
+ }
+ }
+ });
+ }
+ return reqXml;
}
/**
@@ -429,22 +476,21 @@ function addTokenDetails(requestXml, orderObj, tokenReason) {
*/
function getPaymentDetails(apmName, preferences, requestXml, orderObj, paymentInstrument) {
var URLUtils = require('dw/web/URLUtils');
+ var Site = require('dw/system/Site');
var str = '<' + apmName + '/>';
if (apmName.equalsIgnoreCase(worldpayConstants.ELV)) {
str = '';
} else if(apmName.equals(worldpayConstants.KLARNA)) {
- str = '<' + paymentInstrument.custom.wpKlarnaPaymentMethod + '/>';
+ str = '';
}
var orderNo = orderObj.orderNo;
var token = orderObj.orderToken;
var payment = new XML(str);
- if (apmName.equals(worldpayConstants.IDEAL)) {
- payment.@shopperBankCode = paymentInstrument.custom.bank;
- } else if (!apmName.equals(worldpayConstants.PAYPAL) && !apmName.equals(worldpayConstants.GOOGLEPAY) && !apmName.equals(worldpayConstants.GIROPAY) && !apmName.equalsIgnoreCase(worldpayConstants.ELV) && !apmName.equalsIgnoreCase(worldpayConstants.WECHATPAY)) {
+ if (!apmName.equals(worldpayConstants.IDEAL) && !apmName.equals(worldpayConstants.PAYPAL) && !apmName.equals(worldpayConstants.GOOGLEPAY) && !apmName.equalsIgnoreCase(worldpayConstants.ELV) && !apmName.equalsIgnoreCase(worldpayConstants.WECHATPAY)) {
payment.@shopperCountryCode = orderObj.getBillingAddress().countryCode.value.toString().toUpperCase();
}
- if (apmName.equals(worldpayConstants.KLARNASLICEIT) || apmName.equals(worldpayConstants.KLARNAPAYLATER) || apmName.equals(worldpayConstants.KLARNAPAYNOW)) {
+ if (apmName.equals(worldpayConstants.KLARNA) || apmName.equals(worldpayConstants.KLARNASLICEIT) || apmName.equals(worldpayConstants.KLARNAPAYLATER) || apmName.equals(worldpayConstants.KLARNAPAYNOW)) {
var klarnaCountries = require('*/cartridge/config/klarnaCountries.json');
payment.@locale = klarnaCountries[orderObj.getBillingAddress().countryCode.value.toString().toUpperCase()].shopperLocale;
}
@@ -453,7 +499,7 @@ function getPaymentDetails(apmName, preferences, requestXml, orderObj, paymentIn
payment.successURL = URLUtils.https('COPlaceOrder-Submit', worldpayConstants.ORDERID, orderNo, worldpayConstants.ORDERTOKEN, token, worldpayConstants.PAYMENTSTATUS,
worldpayConstants.AUTHORIZED).toString();
}
- if (apmName.equals(worldpayConstants.IDEAL) || apmName.equals(worldpayConstants.PAYPAL) || apmName.equals(worldpayConstants.GIROPAY)) {
+ if (apmName.equals(worldpayConstants.IDEAL) || apmName.equals(worldpayConstants.PAYPAL)) {
payment.successURL = URLUtils.https('COPlaceOrder-Submit', worldpayConstants.ORDERID, orderNo, worldpayConstants.ORDERTOKEN, token, worldpayConstants.PAYMENTSTATUS,
worldpayConstants.AUTHORIZED).toString();
payment.failureURL = URLUtils.https('COPlaceOrder-Submit', worldpayConstants.ORDERID, orderNo, worldpayConstants.ORDERTOKEN, token).toString();
@@ -461,16 +507,12 @@ function getPaymentDetails(apmName, preferences, requestXml, orderObj, paymentIn
if (!apmName.equalsIgnoreCase(worldpayConstants.ELV) && !apmName.equalsIgnoreCase(worldpayConstants.WECHATPAY) && !apmName.equals(worldpayConstants.GOOGLEPAY)) {
payment.cancelURL = URLUtils.https('COPlaceOrder-Submit', worldpayConstants.ORDERID, orderNo, worldpayConstants.ORDERTOKEN, token).toString();
}
- if (!apmName.equalsIgnoreCase(worldpayConstants.PAYPAL) && !apmName.equalsIgnoreCase(worldpayConstants.GIROPAY) && !apmName.equalsIgnoreCase(worldpayConstants.ELV) &&
+ if (!apmName.equalsIgnoreCase(worldpayConstants.PAYPAL) && !apmName.equalsIgnoreCase(worldpayConstants.ELV) &&
!apmName.equalsIgnoreCase(worldpayConstants.WECHATPAY) && !apmName.equals(worldpayConstants.GOOGLEPAY)) {
payment.pendingURL = URLUtils.https('COPlaceOrder-Submit', worldpayConstants.ORDERID, orderNo, worldpayConstants.ORDERTOKEN, token, worldpayConstants.PAYMENTSTATUS,
worldpayConstants.PENDING).toString();
}
- // CODE FOR GIROPAY
- if (apmName.equals(worldpayConstants.GIROPAY)) {
- payment.swiftCode = paymentInstrument.custom.bankCode;
- }
if (apmName.equals(worldpayConstants.GOOGLEPAY)) {
payment.protocolVersion = paymentInstrument.custom.gpayprotocolVersion;
payment.signature = paymentInstrument.custom.gpaySignature;
@@ -487,16 +529,21 @@ function getPaymentDetails(apmName, preferences, requestXml, orderObj, paymentIn
payment.bankAccountSEPA = bankAccountSEPA;
}
- if (apmName.equals(worldpayConstants.KLARNASLICEIT) || apmName.equals(worldpayConstants.KLARNAPAYLATER) || apmName.equals(worldpayConstants.KLARNAPAYNOW)) {
+ if (apmName.equals(worldpayConstants.KLARNA) || apmName.equals(worldpayConstants.KLARNASLICEIT) || apmName.equals(worldpayConstants.KLARNAPAYLATER) || apmName.equals(worldpayConstants.KLARNAPAYNOW)) {
payment.failureURL = URLUtils.https('COPlaceOrder-Submit', worldpayConstants.ORDERID, orderNo, worldpayConstants.ORDERTOKEN, token).toString();
}
var paymentDetails = new XML(worldpayConstants.XMLPAYMENTDETAILS);
paymentDetails.appendChild(payment);
- if (apmName.equals(worldpayConstants.GIROPAY) || (apmName.equals(worldpayConstants.GOOGLEPAY) && preferences.dstype && preferences.dstype.value ==='two3d')) {
+ if ((apmName.equals(worldpayConstants.GOOGLEPAY) && preferences.dstype && preferences.dstype.value ==='two3d')) {
var sessionXML = new XML('');
paymentDetails.appendChild(sessionXML);
+ if (preferences.enableEFTPOS) {
+ var routingMID = Site.getCurrent().getCustomPreferenceValue('EFTPOSRoutingMID');
+ var eftposRoutingMID = new XML('' + routingMID + '');
+ paymentDetails.appendChild(eftposRoutingMID);
+ }
}
requestXml.submit.order.appendChild(paymentDetails);
@@ -876,8 +923,14 @@ function createSRD(currentDate) {
return format;
}
}
-function createAmt() {
- var format= new XML('');
+function createAmt(orderObj) {
+ var format;
+ if(orderObj) {
+ var giftCertificateTotalPrice = orderObj.getGiftCertificateTotalPrice()
+ format= new XML('');
+ } else {
+ format= new XML('');
+ }
return format;
}
function getACHPaymentDetails(apmName, preferences, requestXml, orderObj, paymentInstrument) {
@@ -997,7 +1050,7 @@ function addTo3dsFexRequest(preferences, orderObj, order) {
shopperAccountRiskData.appendChild(shopperAccountModificationDate);
}
var transactionRiskDataGiftCardAmount = new XML(' ');
- transactionRiskDataGiftCardAmount.appendChild(createAmt());
+ transactionRiskDataGiftCardAmount.appendChild(createAmt(orderObj));
var transactionRiskData = new XML ('');
transactionRiskData.appendChild(transactionRiskDataGiftCardAmount);
riskdata.appendChild(authenticationRiskData);
@@ -1011,8 +1064,12 @@ function addTo3dsFexRequest(preferences, orderObj, order) {
if (preferences.challengeWindowSize.value != null && preferences.challengeWindowSize) {
var challengeWindowSize = preferences.challengeWindowSize.value;
}
+ var dfReferenceId = '';
+ if (orderObj.custom.dataSessionID) {
+ dfReferenceId = orderObj.custom.dataSessionID;
+ }
if ((orderObj.createdBy.equals(worldpayConstants.CUSTOMERORDER)) || orderObj.customerNo) {
- var additional3DSData = new XML('');
order.submit.order.appendChild(additional3DSData);
}
@@ -1419,6 +1476,136 @@ function addKonbiniDetails(reqXml, apmType, paymentInstrument, orderObj, current
return requestXml;
}
+/**
+ * Adds P24 details to the service request
+ * @param {Object} reqXml - Service request object
+ * @param {string} apmType - Type of APM
+ * @param {dw.order.PaymentInstrument} paymentInstrument - Payment instrument associated with the order object
+ * @param {string} apmName - APM name
+ * @param {dw.order.Order} orderObj - Current order object
+ * @param {dw.customer.Customer} currentCustomer - Current customer object
+ * @param {Object} preferences - Worldpay preferences
+ * @returns {XML} - Service request
+ */
+function addP24Details(reqXml, apmType, paymentInstrument, apmName, orderObj, currentCustomer, preferences) {
+ var createRequestHelper = require('*/cartridge/scripts/common/createRequestHelper');
+ var requestXml = reqXml;
+ if (apmType.equalsIgnoreCase(worldpayConstants.DIRECT)) {
+ requestXml = createRequestHelper.getPaymentDetails(apmName, preferences, requestXml, orderObj, paymentInstrument);
+ requestXml = createRequestHelper.addShopperDetails(apmName, requestXml, orderObj, apmType, currentCustomer, false);
+ createRequestHelper.addStatementNarrative(requestXml);
+ } else {
+ // Add code to support P24 REDIRECT method.
+ }
+ return requestXml;
+}
+
+/**
+ *This method creates and update request
+ * @param {Object} orderReq - current order request object
+ * @param {Object} orderObj - orderObj object
+ * @param {Object} paymentIntrument - paymentIntrument object
+ * @param {Object} preferences - preferences object
+ * @param {Object} echoData - echoData object
+ * @param {Object} payment - payment object
+ * @param {Object} shopperBrowser - shopperBrowser object
+ * @return {XML} returns an order in XML object
+ */
+ function getOrderObj(orderReq, orderObj, paymentIntrument, preferences, echoData, payment, shopperBrowser) {
+ var enableTokenizationPref = getTokenPref(preferences);
+ var order = orderReq;
+ order.submit.order.paymentDetails.appendChild(payment);
+ if (orderObj.getCustomerNo() != null && (enableTokenizationPref || paymentIntrument.creditCardToken) &&
+ ((preferences.tokenType == null) || (paymentIntrument.custom.tokenScope == null &&
+ !preferences.tokenType.toString().equals(worldpayConstants.merchanttokenType)) || (paymentIntrument.custom.tokenScope != null &&
+ !paymentIntrument.custom.tokenScope.equals(worldpayConstants.merchanttokenType)))) {
+ order.submit.order.shopper.appendChild(new XML('' + orderObj.getCustomerNo() + ''));
+ }
+ order.submit.order.shopper.appendChild(shopperBrowser);
+
+ if (echoData) {
+ var echoDataXML = new XML('' + echoData + '');
+ order.submit.order.appendChild(echoDataXML);
+ }
+ var installments;
+ addStatementNarrative(order);
+ installments = paymentIntrument.custom.installments;
+ if (installments) {
+ order.submit.order.thirdPartyData.instalments = installments;
+ }
+ return order;
+}
+
+function addELVDetails(requestXml, apmType, paymentInstrument, apmName, orderObj, currentCustomer, billingAddress, preferences) {
+ if (apmType.equalsIgnoreCase(worldpayConstants.DIRECT)) {
+ requestXml = getPaymentDetails(apmName, preferences, requestXml, orderObj, paymentInstrument);
+ requestXml = addShopperDetails(apmName, requestXml, orderObj, apmType, currentCustomer, false);
+ requestXml = addBillingAddressDetailsFormat2(requestXml, billingAddress);
+ addStatementNarrative(requestXml);
+ requestXml = appendMandateInfo(requestXml, paymentInstrument);
+ } else {
+ // Add code to support ELV REDIRECT method.
+ }
+ return requestXml;
+}
+
+function addNordEafiDetails(requestXml, apmType, apmName, orderObj, currentCustomer, shippingAddress) {
+ if (apmType.equalsIgnoreCase(worldpayConstants.REDIRECT)) {
+ payMethod = new ArrayList();
+ payMethod.push(worldpayConstants.NORDEAFI);
+ requestXml = createRequestHelper.addIncludedPaymentMethods(requestXml, payMethod);
+ requestXml = createRequestHelper.addShopperDetails(apmName, requestXml, orderObj, apmType, currentCustomer, false);
+ requestXml = createRequestHelper.addShippingAddressDetails(requestXml, shippingAddress);
+ } else {
+ // Add code to support SOLO-SSL DIRECT method.
+ Logger.getLogger('worldpay').error('ORDER XML REQUEST : Unsupported Payment Method');
+ return null;
+ }
+ return requestXml;
+}
+
+function addRiskData(preferences, customerObj, orderorder, orderObj) {
+ if (preferences.riskData != null && preferences.riskData) {
+ var riskdata = new XML(' ');
+ var authMethod = getAuthMethod(preferences);
+ var authenticationRiskData = new XML('');
+ var authenticationTimestamp = new XML(' ');
+ authenticationTimestamp.appendChild(createTimeStamp());
+ authenticationRiskData.appendChild(authenticationTimestamp);
+ var shopperAccountRiskData = new XML('');
+ if (customerObj.authenticated) {
+ var shopperAccountCreationDate = new XML(' ');
+ var shopperAccountModificationDate = new XML('');
+ shopperAccountCreationDate.appendChild(createSRD(customerObj.profile.getCreationDate()));
+ shopperAccountModificationDate.appendChild(createSRD(customerObj.profile.getLastModified()));
+ shopperAccountRiskData.appendChild(shopperAccountCreationDate);
+ shopperAccountRiskData.appendChild(shopperAccountModificationDate);
+ }
+ var transactionRiskDataGiftCardAmount = new XML(' ');
+ transactionRiskDataGiftCardAmount.appendChild(createAmt(orderObj));
+ var transactionRiskData = new XML('');
+ transactionRiskData.appendChild(transactionRiskDataGiftCardAmount);
+ riskdata.appendChild(authenticationRiskData);
+ riskdata.appendChild(shopperAccountRiskData);
+ riskdata.appendChild(transactionRiskData);
+ orderorder.appendChild(riskdata);
+ return orderorder;
+ }
+}
+
+function addPrimeRoutingRequest(enableSalesrequest, orderObj, order, primeRoutingRequest){
+ if (enableSalesrequest) {
+ if (orderObj.billingAddress.countryCode.value === 'US') {
+ order.submit.order.appendChild(primeRoutingRequest);
+ }
+ }
+ return order;
+}
+
+function isTwo3D(preferences) {
+ return preferences.dstype !== null && preferences.dstype.value === 'two3d';
+}
+
/** Exported functions **/
module.exports = {
createAmt:createAmt,
@@ -1469,5 +1656,12 @@ module.exports = {
addIdealDetails: addIdealDetails,
addChinaUnionPayDetails: addChinaUnionPayDetails,
addMisterCashDetails: addMisterCashDetails,
- addKonbiniDetails: addKonbiniDetails
+ addKonbiniDetails: addKonbiniDetails,
+ addP24Details: addP24Details,
+ addELVDetails: addELVDetails,
+ getOrderObj: getOrderObj,
+ addRiskData: addRiskData,
+ addPrimeRoutingRequest: addPrimeRoutingRequest,
+ isTwo3D: isTwo3D
+
};
diff --git a/cartridges/int_worldpay_core/cartridge/scripts/common/paymentInstrumentUtils.js b/cartridges/int_worldpay_core/cartridge/scripts/common/paymentInstrumentUtils.js
index bbb88ec..3598cfb 100644
--- a/cartridges/int_worldpay_core/cartridge/scripts/common/paymentInstrumentUtils.js
+++ b/cartridges/int_worldpay_core/cartridge/scripts/common/paymentInstrumentUtils.js
@@ -1,5 +1,12 @@
'use strict';
var PaymentMgr = require('dw/order/PaymentMgr');
+
+
+function isVisaSSL(cardType) {
+ const visaPattern = /^(VISA-SSL|VISA_CREDIT-SSL|VISA_DEBIT-SSL)$/;
+ return visaPattern.test(cardType);
+}
+
/**
* This Method returns the token ID & matched payment instrument from the saved payment cards for authenticated user.
* Match criteria - last 4 digit of card and card type must be same
@@ -27,8 +34,13 @@ function getTokenPaymentInstrument(customerPaymentInstruments, cardNumber, cardT
}
paymentCard = PaymentMgr.getPaymentCard(creditCardInstrument.creditCardType);
// card type match
- cardTypeMatch = paymentCard != null && cardType.equalsIgnoreCase(paymentCard.custom.worldPayCardType) ? true :
- cardType.equalsIgnoreCase(creditCardInstrument.creditCardType);
+ if (isVisaSSL(cardType) && isVisaSSL(paymentCard.custom.worldPayCardType)) {
+ cardTypeMatch = true;
+ }
+ else {
+ cardTypeMatch = paymentCard != null && cardType.equalsIgnoreCase(paymentCard.custom.worldPayCardType) ? true :
+ cardType.equalsIgnoreCase(creditCardInstrument.creditCardType);
+ }
// find token ID exists for matching payment card
if(cardTypeMatch && responseData && (responseData.tokenEvent.equals(worldpayConstants.CONFLICT) || responseData.tokenEvent.equals(worldpayConstants.MATCH))
&& responseData.paymentTokenID.equals(creditCardInstrument.creditCardToken)
@@ -89,14 +101,15 @@ function copyPaymentCardToInstrument(paymentInstr, ccNumber, ccType, ccExpiryMon
paymentInstr.setCreditCardExpirationYear(typeof (creditCardExpirationYear) === 'object' ? creditCardExpirationYear.valueOf() : creditCardExpirationYear);
}
if (!paymentInstr.getCreditCardType() && creditCardType) {
- var newCCType = creditCardType.toString().replace(/_DEBIT|_CREDIT|_ELECTRON/g ,"");
+ var newCCType = creditCardType.responseCardType.toString().replace(/_DEBIT|_CREDIT|_ELECTRON/g ,"");
+ var bmCCType = creditCardType.bMCardType;
var cardList = PaymentMgr.getPaymentMethod(paymentInstr.paymentMethod).getActivePaymentCards();
if (cardList) {
var cardItr = cardList.iterator();
var paymentCard;
while (cardItr.hasNext()) {
paymentCard = cardItr.next();
- if (paymentCard.custom.worldPayCardType !== null && paymentCard.custom.worldPayCardType.indexOf(newCCType) > -1) {
+ if (paymentCard.custom.worldPayCardType !== null && (paymentCard.custom.worldPayCardType.indexOf(newCCType) > -1 || paymentCard.cardType.indexOf(bmCCType) > -1)) {
paymentInstr.setCreditCardType(paymentCard.cardType);
break;
}
@@ -249,16 +262,17 @@ function getCardPaymentMethodToken(billingAddress, paymentInstrument, ccCVN) {
if (!disableCVV && ccCVN) {
payment.paymentInstrument.cardDetails.cvc = ccCVN;
}
- payment.paymentInstrument.cardDetails.cardAddress.address.firstName = billingAddress.firstName;
- payment.paymentInstrument.cardDetails.cardAddress.address.lastName = billingAddress.lastName;
- payment.paymentInstrument.cardDetails.cardAddress.address.address1 = billingAddress.address1;
- payment.paymentInstrument.cardDetails.cardAddress.address.address2 = (billingAddress.address2 != null) ? billingAddress.address2 : '';
- payment.paymentInstrument.cardDetails.cardAddress.address.postalCode = billingAddress.postalCode;
- payment.paymentInstrument.cardDetails.cardAddress.address.city = billingAddress.city;
- payment.paymentInstrument.cardDetails.cardAddress.address.state = billingAddress.stateCode;
- payment.paymentInstrument.cardDetails.cardAddress.address.countryCode = billingAddress.countryCode.value.toString().toUpperCase();
- payment.paymentInstrument.cardDetails.cardAddress.address.telephoneNumber = billingAddress.phone;
-
+ if (!Site.getCurrent().getCustomPreferenceValue('enableEFTPOSDebugging')) {
+ payment.paymentInstrument.cardDetails.cardAddress.address.firstName = billingAddress.firstName;
+ payment.paymentInstrument.cardDetails.cardAddress.address.lastName = billingAddress.lastName;
+ payment.paymentInstrument.cardDetails.cardAddress.address.address1 = billingAddress.address1;
+ payment.paymentInstrument.cardDetails.cardAddress.address.address2 = (billingAddress.address2 != null) ? billingAddress.address2 : '';
+ payment.paymentInstrument.cardDetails.cardAddress.address.postalCode = billingAddress.postalCode;
+ payment.paymentInstrument.cardDetails.cardAddress.address.city = billingAddress.city;
+ payment.paymentInstrument.cardDetails.cardAddress.address.state = billingAddress.stateCode;
+ payment.paymentInstrument.cardDetails.cardAddress.address.countryCode = billingAddress.countryCode.value.toString().toUpperCase();
+ payment.paymentInstrument.cardDetails.cardAddress.address.telephoneNumber = billingAddress.phone;
+ }
return payment;
}
diff --git a/cartridges/int_worldpay_core/cartridge/scripts/common/threeDFlexHelper.js b/cartridges/int_worldpay_core/cartridge/scripts/common/threeDFlexHelper.js
index 40eb098..df523a7 100644
--- a/cartridges/int_worldpay_core/cartridge/scripts/common/threeDFlexHelper.js
+++ b/cartridges/int_worldpay_core/cartridge/scripts/common/threeDFlexHelper.js
@@ -5,9 +5,14 @@
* @returns {string} - encoded string
*/
function base64url(source) {
- var Encoding = require('dw/crypto/Encoding');
- var encodedSource = Encoding.toBase64(source);
- encodedSource = encodedSource.replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
+ let Encoding = require('dw/crypto/Encoding');
+ let encodedSource = Encoding.toBase64(source);
+
+ // Remove trailing '=' characters efficiently
+ encodedSource = encodedSource.slice(0, encodedSource.indexOf('=') !== -1 ? encodedSource.indexOf('=') : encodedSource.length);
+
+ // Replace characters to make the string URL-safe
+ encodedSource = encodedSource.replace(/\+/g, '-').replace(/\//g, '_');
return encodedSource;
}
diff --git a/cartridges/int_worldpay_core/cartridge/scripts/common/tokenProcessUtils.js b/cartridges/int_worldpay_core/cartridge/scripts/common/tokenProcessUtils.js
index cc1d4d1..b431c60 100644
--- a/cartridges/int_worldpay_core/cartridge/scripts/common/tokenProcessUtils.js
+++ b/cartridges/int_worldpay_core/cartridge/scripts/common/tokenProcessUtils.js
@@ -21,8 +21,12 @@ function createNewPaymentInstrument(responseData, customerObj, paymentInstrument
} else {
cardNumberToSave = paymentInstrument.creditCardNumber;
}
+ var cardBrand = {
+ responseCardType: responseData.cardBrand.valueOf().toString(),
+ bMCardType: paymentInstrument.creditCardType
+ };
newPaymentInstrument = require('*/cartridge/scripts/common/paymentInstrumentUtils').copyPaymentCardToInstrument(newPaymentInstrument,
- cardNumberToSave, responseData.cardBrand.valueOf().toString(),
+ cardNumberToSave, cardBrand,
Number(responseData.cardExpiryMonth.valueOf()), Number(responseData.cardExpiryYear.valueOf()),
responseData.cardHolderName.valueOf().toString(), responseData.paymentTokenID.valueOf().toString(), responseData.bin.valueOf().toString());
if (!(newPaymentInstrument && newPaymentInstrument.getCreditCardNumber() && newPaymentInstrument.getCreditCardExpirationMonth() &&
@@ -60,12 +64,15 @@ function updatePaymentInstrument(responseData, customerObj, paymentInstrument, m
}
return updateTokenResult;
}
+ let cardBrand = {};
+ cardBrand.bmCCType = responseData.content.cardSubBrand.toString();
+ cardBrand.responseCardType = responseData.cardBrand.toString();
Transaction.wrap(function () {
wallet.removePaymentInstrument(matchedPaymentInstrument);
newPaymentInstrument = wallet.createPaymentInstrument(PaymentInstrument.METHOD_CREDIT_CARD);
newPaymentInstrument = require('*/cartridge/scripts/common/paymentInstrumentUtils').copyPaymentCardToInstrument(
newPaymentInstrument, responseData.cardNumber.valueOf().toString(),
- responseData.cardBrand.valueOf().toString(),
+ cardBrand,
Number(responseData.cardExpiryMonth.valueOf()),
Number(responseData.cardExpiryYear.valueOf()),
responseData.cardHolderName.valueOf().toString(),
@@ -226,3 +233,4 @@ exports.addOrUpdateIdentifier = addOrUpdateIdentifier;
exports.checkAuthorization = checkAuthorization;
exports.addOrUpdateToken = addOrUpdateToken;
exports.checkServiceResponse = checkServiceResponse;
+exports.updatePaymentInstrument = updatePaymentInstrument;
diff --git a/cartridges/int_worldpay_core/cartridge/scripts/common/utils.js b/cartridges/int_worldpay_core/cartridge/scripts/common/utils.js
index c4fc58d..7f7d006 100644
--- a/cartridges/int_worldpay_core/cartridge/scripts/common/utils.js
+++ b/cartridges/int_worldpay_core/cartridge/scripts/common/utils.js
@@ -245,7 +245,8 @@ function serviceCall(requestXML, requestHeader, preferences, merchantID, orderNo
{regex:/.*<\/iban>/, val: "******"},
{regex:/.*<\/checkNumber>/, val: "******"},
{regex:/.*<\/shopperEmailAddress>/, val:"******"},
- {regex:/.*<\/telephoneNumber>/, val:"*****"},
+ {regex:/\d*<\/telephoneNumber>/, val:"*****"},
+ {regex:/\d*<\/telephoneNumber>/, val:"*****"},
{regex:/.*<\/cvn>/, val:"***"},
{regex:/.*<\/swiftCode>/, val: "******"},
{regex:/.*<\/cpf>/, val:"******"}];
@@ -297,7 +298,8 @@ function getLoggableRequest (requestXML) {
{regex:/.*<\/iban>/, val: "******"},
{regex:/.*<\/checkNumber>/, val: "******"},
{regex:/.*<\/shopperEmailAddress>/, val:"******"},
- {regex:/.*<\/telephoneNumber>/, val:"*****"},
+ {regex:/\d*<\/telephoneNumber>/, val:"*****"},
+ {regex:/\d*<\/telephoneNumber>/, val:"*****"},
{regex:/.*<\/cvn>/, val:"***"},
{regex:/.*<\/swiftCode>/, val: "******"},
{regex:/.*<\/cpf>/, val:"******"}];
diff --git a/cartridges/int_worldpay_core/cartridge/scripts/common/worldpayConstants.js b/cartridges/int_worldpay_core/cartridge/scripts/common/worldpayConstants.js
index 75492cf..94abaf5 100644
--- a/cartridges/int_worldpay_core/cartridge/scripts/common/worldpayConstants.js
+++ b/cartridges/int_worldpay_core/cartridge/scripts/common/worldpayConstants.js
@@ -61,7 +61,6 @@ WorldpayConstants.IDEAL = 'IDEAL-SSL';
WorldpayConstants.PAYPAL = 'PAYPAL-EXPRESS';
WorldpayConstants.MISTERCASH = 'MISTERCASH-SSL';
WorldpayConstants.WORLDPAY = 'Worldpay';
-WorldpayConstants.GIROPAY = 'GIROPAY-SSL';
WorldpayConstants.CREDITCARD = 'CREDIT_CARD';
WorldpayConstants.GOOGLEPAY = 'PAYWITHGOOGLE-SSL';
WorldpayConstants.P24 = 'PRZELEWY-SSL';
diff --git a/cartridges/int_worldpay_core/cartridge/scripts/jobs/initiateCancelOrderJob.js b/cartridges/int_worldpay_core/cartridge/scripts/jobs/initiateCancelOrderJob.js
index ac3b67f..8de9090 100644
--- a/cartridges/int_worldpay_core/cartridge/scripts/jobs/initiateCancelOrderJob.js
+++ b/cartridges/int_worldpay_core/cartridge/scripts/jobs/initiateCancelOrderJob.js
@@ -94,7 +94,6 @@ function sendMail(errorCount, totalCount, errorString, errorList, scriptFailed)
}
throw new Error('Script Failed');
}
- return;
}
/**
* This script fetch orders, initiates the cancel order job
@@ -133,7 +132,6 @@ function initiateCancelOrder() {
if (Site.getCurrent().getCustomPreferenceValue('EnableJobMailerService')) {
sendMail(errorCount, totalCount, errorString, errorList, scriptFailed);
}
- return;
}
}
diff --git a/cartridges/int_worldpay_core/cartridge/scripts/jobs/worldpayJobs.js b/cartridges/int_worldpay_core/cartridge/scripts/jobs/worldpayJobs.js
index 28cec2d..2566979 100644
--- a/cartridges/int_worldpay_core/cartridge/scripts/jobs/worldpayJobs.js
+++ b/cartridges/int_worldpay_core/cartridge/scripts/jobs/worldpayJobs.js
@@ -117,6 +117,7 @@ function addOrUpdateToken(customerInformation, serviceResponse, cardNumber, card
var Site = require('dw/system/Site');
var worldpayConstants = require('*/cartridge/scripts/common/worldpayConstants');
var tokenType = Site.getCurrent().getCustomPreferenceValue('tokenType');
+ var tokenProcessUtil = require('*/cartridge/scripts/common/tokenProcessUtils.js')
var PaymentInstrument = require('dw/order/PaymentInstrument');
var currentCustomer = customerInformation;
var saveCustomerCreditCardResult;
@@ -126,21 +127,22 @@ function addOrUpdateToken(customerInformation, serviceResponse, cardNumber, card
var customerPaymentInstruments = currentCustomer.getProfile().getWallet().getPaymentInstruments(PaymentInstrument.METHOD_CREDIT_CARD);
// GetPaymentcardToken to fetch the saved card based on card details found in service response
var getPaymentCardTokenResult = require('*/cartridge/scripts/pipelets/getPaymentCardToken').getPaymentCardToken(
- customerPaymentInstruments, cardNumber, cardType, serviceResponse.cardExpiryMonth.valueOf(), serviceResponse.cardExpiryYear.valueOf());
+ customerPaymentInstruments, cardNumber, cardType, serviceResponse.cardExpiryMonth.valueOf(), serviceResponse.cardExpiryYear.valueOf(), serviceResponse);
if (!getPaymentCardTokenResult.success) {
return;
}
var paymentTokenID = getPaymentCardTokenResult.paymentTokenID;
var matchedCustomerPaymentInstrument = getPaymentCardTokenResult.matchedCustomerPaymentInstrument;
+ var paymentInstrument = {
+ creditCardHolder: serviceResponse.cardHolderName.toString(),
+ creditCardNumber: cardNumber,
+ creditCardType: cardType,
+ creditCardExpirationMonth: serviceResponse.cardExpiryMonth,
+ creditCardExpirationYear: serviceResponse.cardExpiryYear
+ };
// found matched saved card
if (matchedCustomerPaymentInstrument != null) {
- if (!paymentTokenID) {
- Transaction.wrap(function () {
- saveCustomerCreditCardResult = require('*/cartridge/scripts/pipelets/saveCustomerCreditCard').saveCustomerCreditCard(
- matchedCustomerPaymentInstrument, serviceResponse.paymentTokenID.valueOf().toString(), null, null, null, null, null);
- });
- return;
- }
+ result = tokenProcessUtil.updatePaymentInstrument(serviceResponse, customerInformation, paymentInstrument, matchedCustomerPaymentInstrument);
return;
}
// no matched payment card found in customer's account
diff --git a/cartridges/int_worldpay_core/cartridge/scripts/lib/libCreateRequest.js b/cartridges/int_worldpay_core/cartridge/scripts/lib/libCreateRequest.js
index 45322a9..0e0d445 100644
--- a/cartridges/int_worldpay_core/cartridge/scripts/lib/libCreateRequest.js
+++ b/cartridges/int_worldpay_core/cartridge/scripts/lib/libCreateRequest.js
@@ -82,6 +82,7 @@ function getOrderObj(orderReq, orderObj, paymentIntrument, preferences, echoData
* @return {XML} returns an order in XML object
*/
function createInitialRequest3D(orderObj, req, paymentIntrument, preferences, echoData, encryptedData, cardOrderObj) {
+ var Site = require('dw/system/Site');
var createRequestHelper = require('*/cartridge/scripts/common/createRequestHelper');
if (preferences.missingPreferences()) {
Logger.getLogger('worldpay').error('Request Creation : Worldpay preferences are not properly set.');
@@ -92,17 +93,28 @@ function createInitialRequest3D(orderObj, req, paymentIntrument, preferences, ec
var paymentInstrumentUtils = require('*/cartridge/scripts/common/paymentInstrumentUtils');
var payment;
var billingAddress = orderObj.billingAddress;
+ var paymentCard;
if (paymentIntrument.creditCardToken) {
payment = paymentInstrumentUtils.getCardPaymentMethodToken(billingAddress, paymentIntrument, cardOrderObj.cvn);
} else {
var PaymentMgr = require('dw/order/PaymentMgr');
- var paymentCard = PaymentMgr.getPaymentCard(paymentIntrument.creditCardType);
- payment = paymentInstrumentUtils.getCardPaymentMethod(orderObj, paymentCard.custom.worldPayCardType, billingAddress, paymentIntrument, cardOrderObj, encryptedData);
+ paymentCard = PaymentMgr.getPaymentCard(paymentIntrument.creditCardType);
+ if (preferences.enableEFTPOS) {
+ payment = paymentInstrumentUtils.getCardPaymentMethod(orderObj, 'CARD-SSL', billingAddress, paymentIntrument, cardOrderObj, encryptedData);
+ } else {
+ payment = paymentInstrumentUtils.getCardPaymentMethod(orderObj, paymentCard.custom.worldPayCardType, billingAddress, paymentIntrument, cardOrderObj, encryptedData);
+ }
}
let shopperBrowser = new XML('');
shopperBrowser.acceptHeader = req.httpHeaders.get(worldpayConstants.ACCEPT);
shopperBrowser.userAgentHeader = req.httpHeaders.get('user-agent');
+ if (req.httpParameterMap && req.httpParameterMap.browserScreenHeight) {
+ shopperBrowser.browserScreenHeight = req.httpParameterMap.browserScreenHeight.value;
+ }
+ if (req.httpParameterMap && req.httpParameterMap.browserScreenWidth) {
+ shopperBrowser.browserScreenWidth = req.httpParameterMap.browserScreenWidth.value;
+ }
// The result of request.getSession().getSessionID() in Demandware is not NMTOKEN.
// use the createSessionID() function to cutomize the session ID
@@ -115,9 +127,14 @@ function createInitialRequest3D(orderObj, req, paymentIntrument, preferences, ec
let shippingAddress = orderObj.defaultShipment.shippingAddress;
var transid = paymentIntrument.custom.transactionIdentifier;
var storedCredentials = createRequestHelper.getStoredCredentials(paymentIntrument, enableTokenizationPref, orderObj, transid);
-
- var sessionXML = new XML('');
+ } else {
+ sessionXML = new XML('');
+ }
+ var eftposRoutingMID = new XML('' + preferences.eftposRoutingMID + '');
var orderpaymentService = new XML('');
var ordersubmit = new XML('');
@@ -127,19 +144,32 @@ function createInitialRequest3D(orderObj, req, paymentIntrument, preferences, ec
var orderamount = new XML('');
var orderorderContent = new XML('');
- var Site = require('dw/system/Site');
var sendOrderContentProductDetails = Site.getCurrent().getCustomPreferenceValue('sendOrderContentProductDetails');
+ var orderContentProductDetail;
if (sendOrderContentProductDetails) {
- orderorderContent.appendChild(createRequestHelper.createOrderContent(orderObj).toString());
+ orderContentProductDetail = createRequestHelper.createOrderContent(orderObj).toString();
+ }
+ var worldpayAPMType;
+ if (paymentCard && paymentCard.custom.worldPayCardType) {
+ worldpayAPMType = paymentCard.custom.worldPayCardType;
+ } else {
+ worldpayAPMType = 'TOKEN-SSL';
+ }
+ var pluginTrackerDetail = createRequestHelper.sendPluginTrackerDetails(orderObj, worldpayAPMType).toString();
+ if (orderContentProductDetail) {
+ orderorderContent.appendChild('');
+ } else {
+ orderorderContent.appendChild('');
}
- orderorderContent.appendChild(createRequestHelper.sendPluginTrackerDetails(orderObj).toString());
var enableSalesrequest = preferences.enableSalesrequest;
var orderPaymentDetails = createRequestHelper.getOrderPayment(enableSalesrequest, orderObj);
let ordershopper = new XML('');
let ordershopperEmailAddress = new XML('');
ordershopperEmailAddress.appendChild(orderObj.getCustomerEmail());
+ // ordershopperPhone.appendChild(contact);
// associate respective conatiners inside shopper container
ordershopper.appendChild(ordershopperEmailAddress);
+ // ordershopper.appendChild(ordershopperPhone);
// prime routing
let primeRoutingRequest = new XML('');
let routingPreference = new XML('');
@@ -189,7 +219,9 @@ function createInitialRequest3D(orderObj, req, paymentIntrument, preferences, ec
orderorder.appendChild(orderorderContent);
orderorder.appendChild(orderPaymentDetails);
orderorder.appendChild(ordershopper);
- orderorder.appendChild(ordershippingAddress);
+ if (!Site.getCurrent().getCustomPreferenceValue('enableEFTPOSDebugging')) {
+ orderorder.appendChild(ordershippingAddress);
+ }
// associate respective conatiners inside submit container
ordersubmit.appendChild(orderorder);
@@ -198,7 +230,7 @@ function createInitialRequest3D(orderObj, req, paymentIntrument, preferences, ec
orderpaymentService.appendChild(ordersubmit);
var order = orderpaymentService;
- getOrderObj(order, orderObj, paymentIntrument, preferences, echoData, payment, shopperBrowser);
+ createRequestHelper.getOrderObj(order, orderObj, paymentIntrument, preferences, echoData, payment, shopperBrowser);
// Check if country code is Brazil(BR), then append CPF in request XML.
order = createRequestHelper.addCpfDetails(billingAddress, paymentIntrument, order, orderObj);
@@ -206,12 +238,12 @@ function createInitialRequest3D(orderObj, req, paymentIntrument, preferences, ec
order = createRequestHelper.addMotoAndStoredCredentialsDetails(order, orderObj, session, preferences, paymentIntrument, storedCredentials);
order.submit.order.paymentDetails.appendChild(sessionXML);
- if (enableSalesrequest != null && enableSalesrequest) {
- if (orderObj.billingAddress.countryCode.value === 'US') {
- order.submit.order.appendChild(primeRoutingRequest);
- }
+ if (preferences.enableEFTPOS) {
+ order.submit.order.paymentDetails.appendChild(eftposRoutingMID);
}
- if (preferences.dstype !== null && preferences.dstype.value === 'two3d') {
+ order = createRequestHelper.addPrimeRoutingRequest(enableSalesrequest, orderObj, order, primeRoutingRequest);
+
+ if (createRequestHelper.isTwo3D(preferences)) {
order = createRequestHelper.addTo3dsFexRequest(preferences, orderObj, order);
}
@@ -383,59 +415,6 @@ function createSaveCardAuthenticateRequest(paRes, md, preferences) {
return cardService;
}
-/**
- * Adds Worldpay installation ID to the request
- * @param {Object} preferences - Worldpay preferences
- * @param {Object} requestXml - request Object
- * @param {string} apmName - APM name
- * @param {Object} paymentMthd - Payment method object
- * @param {dw.order.PaymentInstrument} paymentInstrument - Payment instrument associated with the order object
- * @returns {XML} - request Object
- */
-function addInstallationDetails(preferences, requestXml, apmName, paymentMthd, paymentInstrument) {
- var createRequestHelper = require('*/cartridge/scripts/common/createRequestHelper');
- var configurablePaymentMethods = preferences.configurablePaymentMethods;
- var installationID = preferences.worldPayInstallationId;
- var reqXml = requestXml;
- if (installationID) {
- configurablePaymentMethods.forEach(function (configurableAPM) {
- if (configurableAPM.equalsIgnoreCase(apmName)) {
- if (paymentMthd.ID === worldpayConstants.WORLDPAY && paymentInstrument.getCreditCardToken()) {
- reqXml = createRequestHelper.addInstallationDetails(reqXml, installationID);
- } else {
- reqXml = createRequestHelper.addInstallationDetails(reqXml, installationID);
- reqXml = createRequestHelper.addContactDetails(reqXml);
- }
- }
- });
- }
- return reqXml;
-}
-
-/**
- * Adds P24 details to the service request
- * @param {Object} reqXml - Service request object
- * @param {string} apmType - Type of APM
- * @param {dw.order.PaymentInstrument} paymentInstrument - Payment instrument associated with the order object
- * @param {string} apmName - APM name
- * @param {dw.order.Order} orderObj - Current order object
- * @param {dw.customer.Customer} currentCustomer - Current customer object
- * @param {Object} preferences - Worldpay preferences
- * @returns {XML} - Service request
- */
-function addP24Details(reqXml, apmType, paymentInstrument, apmName, orderObj, currentCustomer, preferences) {
- var createRequestHelper = require('*/cartridge/scripts/common/createRequestHelper');
- var requestXml = reqXml;
- if (apmType.equalsIgnoreCase(worldpayConstants.DIRECT)) {
- requestXml = createRequestHelper.getPaymentDetails(apmName, preferences, requestXml, orderObj, paymentInstrument);
- requestXml = createRequestHelper.addShopperDetails(apmName, requestXml, orderObj, apmType, currentCustomer, false);
- createRequestHelper.addStatementNarrative(requestXml);
- } else {
- // Add code to support P24 REDIRECT method.
- }
- return requestXml;
-}
-
/**
* Creates the XML Order Request object.
* @param {dw.value.Money} paymentAmount - Payment amount
@@ -475,7 +454,7 @@ function createRequest(paymentAmount, orderObj, paymentInstrument, currentCustom
statementNarrative.appendChild(statementNarrativeText);
}
requestXml = createRequestHelper.addGeneralDetails(requestXml, orderObj, preferences, apmName);
- if (apmName.equals(worldpayConstants.KLARNASLICEIT) || apmName.equals(worldpayConstants.KLARNAPAYLATER) || apmName.equals(worldpayConstants.KLARNAPAYNOW)) {
+ if (apmName.equals(worldpayConstants.KLARNA) || apmName.equals(worldpayConstants.KLARNASLICEIT) || apmName.equals(worldpayConstants.KLARNAPAYLATER) || apmName.equals(worldpayConstants.KLARNAPAYNOW)) {
var klarnabillingCountry = orderObj.getBillingAddress().countryCode.value.toString().toUpperCase();
requestXml = createRequestHelper.addShipmentAmountDetailsForKlarna(klarnabillingCountry, requestXml, paymentAmount, preferences);
} else {
@@ -483,16 +462,22 @@ function createRequest(paymentAmount, orderObj, paymentInstrument, currentCustom
}
var Site = require('dw/system/Site');
var sendOrderContentProductDetails = Site.getCurrent().getCustomPreferenceValue('sendOrderContentProductDetails');
+ var orderContentProductDetail;
if (sendOrderContentProductDetails) {
- requestXml.submit.order.orderContent = createRequestHelper.createOrderContent(orderObj).toString();
+ orderContentProductDetail = createRequestHelper.createOrderContent(orderObj).toString();
+ }
+ var pluginTrackerDetail = createRequestHelper.sendPluginTrackerDetails(orderObj, apmName).toString();
+ if (orderContentProductDetail) {
+ requestXml.submit.order.orderContent = '';
+ } else {
+ requestXml.submit.order.orderContent = '';
}
- requestXml.submit.order.orderContent += createRequestHelper.sendPluginTrackerDetails(orderObj).toString();
if (!apmType) {
Logger.getLogger('worldpay').error('APM type is missing for this payment method. Please define APM(DIRECT/REDIRECT) in Payment methods in Business Manager)');
return null;
}
// Adding Installation Id for Hosted Payment Pages
- requestXml = addInstallationDetails(preferences, requestXml, apmName, paymentMthd, paymentInstrument);
+ requestXml = createRequestHelper.addInstallationDetails(preferences, requestXml, apmName, paymentMthd, paymentInstrument);
var ArrayList = require('dw/util/ArrayList');
// Add APM specfic details only. Custom logic can be implemented in this ection to add on details
@@ -505,11 +490,11 @@ function createRequest(paymentAmount, orderObj, paymentInstrument, currentCustom
case worldpayConstants.KLARNASLICEIT:
case worldpayConstants.KLARNAPAYNOW:
case worldpayConstants.KLARNAPAYLATER:
+ case worldpayConstants.KLARNA:
return createRequestHelper.addKlarnaDetails(requestXml, preferences, orderObj, paymentInstrument, currentCustomer, shippingAddress, billingAddress);
case worldpayConstants.SOFORT:
case worldpayConstants.SOFORT_SWITZERLAND:
case worldpayConstants.ALIPAYMOBILE:
- case worldpayConstants.GIROPAY:
case worldpayConstants.POLI:
case worldpayConstants.ALIPAY:
case worldpayConstants.WECHATPAY:
@@ -612,34 +597,12 @@ function createRequest(paymentAmount, orderObj, paymentInstrument, currentCustom
return createRequestHelper.addKonbiniDetails(requestXml, apmType, paymentInstrument, orderObj, currentCustomer, shippingAddress, preferences);
case worldpayConstants.P24:
- return addP24Details(requestXml, apmType, paymentInstrument, apmName, orderObj, currentCustomer, preferences);
+ return createRequestHelper.addP24Details(requestXml, apmType, paymentInstrument, apmName, orderObj, currentCustomer, preferences);
case worldpayConstants.ELV:
- if (apmType.equalsIgnoreCase(worldpayConstants.DIRECT)) {
- requestXml = createRequestHelper.getPaymentDetails(apmName, preferences, requestXml, orderObj, paymentInstrument);
- requestXml = createRequestHelper.addShopperDetails(apmName, requestXml, orderObj, apmType, currentCustomer, false);
- requestXml = createRequestHelper.addBillingAddressDetailsFormat2(requestXml, billingAddress);
- createRequestHelper.addStatementNarrative(requestXml);
- requestXml = createRequestHelper.appendMandateInfo(requestXml, paymentInstrument);
- } else {
- // Add code to support ELV REDIRECT method.
- }
- break;
-
+ return createRequestHelper.addELVDetails(requestXml, apmType, paymentInstrument, apmName, orderObj, currentCustomer, billingAddress, preferences);
case worldpayConstants.NORDEAFI:
- if (apmType.equalsIgnoreCase(worldpayConstants.REDIRECT)) {
- payMethod = new ArrayList();
- payMethod.push(worldpayConstants.NORDEAFI);
- requestXml = createRequestHelper.addIncludedPaymentMethods(requestXml, payMethod);
- requestXml = createRequestHelper.addShopperDetails(apmName, requestXml, orderObj, apmType, currentCustomer, false);
- requestXml = createRequestHelper.addShippingAddressDetails(requestXml, shippingAddress);
- } else {
- // Add code to support SOLO-SSL DIRECT method.
- Logger.getLogger('worldpay').error('ORDER XML REQUEST : Unsupported Payment Method');
- return null;
- }
- break;
-
+ return addNordEafiDetails(requestXml, apmType, apmName, orderObj, currentCustomer, shippingAddress);
case worldpayConstants.NORDEASE:
if (apmType.equalsIgnoreCase(worldpayConstants.REDIRECT)) {
payMethod = new ArrayList();
@@ -697,9 +660,14 @@ function createVoidRequest(orderObj, paymentMthd) {
function createPartialCaptureRequest(orderID, settleAmount, currency, shipmentNo) {
var OrderMgr = require('dw/order/OrderMgr');
var order = OrderMgr.getOrder(orderID);
+ var PaymentMgr = require('dw/order/PaymentMgr');
+ var paymentIntrument = order.getPaymentInstrument();
+ var apmName = paymentIntrument.getPaymentMethod();
+ // Fetch the APM Type from the Payment Method i.e. if the Payment Methoid is of DIRECT or REDIRECT type.
+ var paymentMthd = PaymentMgr.getPaymentMethod(apmName);
var WorldpayPreferences = require('*/cartridge/scripts/object/worldpayPreferences');
WorldpayPreferences = new WorldpayPreferences();
- var preferences = WorldpayPreferences.worldPayPreferencesInit(null, order);
+ var preferences = WorldpayPreferences.worldPayPreferencesInit(paymentMthd, order);
var capture;
var captureRequest = new XML('');
@@ -732,8 +700,13 @@ function createKlarnaCaptureRequest(orderID, settleAmount, currency, trackingID)
var createRequestHelper = require('*/cartridge/scripts/common/createRequestHelper');
var OrderMgr = require('dw/order/OrderMgr');
var order = OrderMgr.getOrder(orderID);
+ var PaymentMgr = require('dw/order/PaymentMgr');
+ var paymentIntrument = order.getPaymentInstrument();
+ var apmName = paymentIntrument.getPaymentMethod();
+ // Fetch the APM Type from the Payment Method i.e. if the Payment Methoid is of DIRECT or REDIRECT type.
+ var paymentMthd = PaymentMgr.getPaymentMethod(apmName);
WorldpayPreferences = new WorldpayPreferences();
- var preferences = WorldpayPreferences.worldPayPreferencesInit(null, order);
+ var preferences = WorldpayPreferences.worldPayPreferencesInit(paymentMthd, order);
var captureRequest = new XML('');
var modify = new XML('');
@@ -776,10 +749,15 @@ function createKlarnaCaptureRequest(orderID, settleAmount, currency, trackingID)
*/
function createPartialRefundRequest(orderID, settleAmount, currency, shipmentNo) {
var OrderMgr = require('dw/order/OrderMgr');
+ var PaymentMgr = require('dw/order/PaymentMgr');
var order = OrderMgr.getOrder(orderID);
+ var paymentIntrument = order.getPaymentInstrument();
+ var apmName = paymentIntrument.getPaymentMethod();
+ // Fetch the APM Type from the Payment Method i.e. if the Payment Methoid is of DIRECT or REDIRECT type.
+ var paymentMthd = PaymentMgr.getPaymentMethod(apmName);
var WorldpayPreferences = require('*/cartridge/scripts/object/worldpayPreferences');
WorldpayPreferences = new WorldpayPreferences();
- var preferences = WorldpayPreferences.worldPayPreferencesInit(null, order);
+ var preferences = WorldpayPreferences.worldPayPreferencesInit(paymentMthd, order);
var refund;
var refundRequest = new XML('');
var modify = new XML('');
@@ -806,11 +784,16 @@ function createPartialRefundRequest(orderID, settleAmount, currency, shipmentNo)
*/
function createKlarnaRefundRequest(orderID, settleAmount, currency) {
var WorldpayPreferences = require('*/cartridge/scripts/object/worldpayPreferences');
+ var PaymentMgr = require('dw/order/PaymentMgr');
var createRequestHelper = require('*/cartridge/scripts/common/createRequestHelper');
var OrderMgr = require('dw/order/OrderMgr');
var order = OrderMgr.getOrder(orderID);
+ var paymentIntrument = order.getPaymentInstrument();
+ var apmName = paymentIntrument.getPaymentMethod();
+ // Fetch the APM Type from the Payment Method i.e. if the Payment Methoid is of DIRECT or REDIRECT type.
+ var paymentMthd = PaymentMgr.getPaymentMethod(apmName);
WorldpayPreferences = new WorldpayPreferences();
- var preferences = WorldpayPreferences.worldPayPreferencesInit(null, order);
+ var preferences = WorldpayPreferences.worldPayPreferencesInit(paymentMthd, order);
var refundRequest = new XML('');
var modify = new XML('');
var ordermodification = new XML('');
@@ -834,10 +817,15 @@ function createKlarnaRefundRequest(orderID, settleAmount, currency) {
*/
function createCancelRequest(orderID) {
var OrderMgr = require('dw/order/OrderMgr');
+ var PaymentMgr = require('dw/order/PaymentMgr');
+ var order = OrderMgr.getOrder(orderID);
+ var paymentIntrument = order.getPaymentInstrument();
+ var apmName = paymentIntrument.getPaymentMethod();
+ // Fetch the APM Type from the Payment Method i.e. if the Payment Methoid is of DIRECT or REDIRECT type.
+ var paymentMthd = PaymentMgr.getPaymentMethod(apmName);
var WorldpayPreferences = require('*/cartridge/scripts/object/worldpayPreferences');
WorldpayPreferences = new WorldpayPreferences();
- var order = OrderMgr.getOrder(orderID);
- var preferences = WorldpayPreferences.worldPayPreferencesInit(null, order);
+ var preferences = WorldpayPreferences.worldPayPreferencesInit(paymentMthd, order);
var cancelRequest = new XML('');
var modify = new XML('');
var ordermodification = new XML('');
@@ -932,21 +920,60 @@ function createTokenRequestWOP(customerObj, paymentInstrument, preferences, card
cardtype.appendChild(cardno);
cardtype.appendChild(expiryDate);
cardtype.appendChild(cardholdername);
+ var preferredAddress = customerObj.addressBook.preferredAddress;
+ if (preferredAddress) {
+ var cardAddress = new XML('');
+ if (cardAddress.address.firstName) {
+ cardAddress.address.firstName = preferredAddress.firstName;
+ }
+ if (cardAddress.address.lastName) {
+ cardAddress.address.lastName = preferredAddress.lastName;
+ }
+ if (cardAddress.address.address1) {
+ cardAddress.address.address1 = preferredAddress.address1;
+ }
+ if (cardAddress.address.address2) {
+ cardAddress.address.address2 = preferredAddress.address2;
+ }
+ if (cardAddress.address.postalCode) {
+ cardAddress.address.postalCode = preferredAddress.postalCode;
+ }
+ if (cardAddress.address.city) {
+ cardAddress.address.city = preferredAddress.city;
+ }
+ if (cardAddress.address.countryCode) {
+ cardAddress.address.countryCode = preferredAddress.countryCode;
+ }
+ if (cardAddress.address.telephoneNumber) {
+ cardAddress.address.telephoneNumber = preferredAddress.phone;
+ }
+ cardtype.appendChild(cardAddress);
+ }
var storedCredentials = new XML('');
orderPaymentDetails.appendChild(cardtype);
if (preferences.enableStoredCredentials && preferences.enableStoredCredentials != null) {
orderPaymentDetails.appendChild(storedCredentials);
}
- var sessionXML = new XML('');
+ var sessionXML;
+ if (Site.getCurrent().getCustomPreferenceValue('enableEFTPOSDebugging')) {
+ sessionXML = new XML('');
+ } else {
+ sessionXML = new XML('');
+ }
orderPaymentDetails.appendChild(sessionXML);
var ordershopper = new XML('');
var authenticatedShopperID = new XML('');
authenticatedShopperID.appendChild(customerObj.profile.customerNo);
+ var shopperEmailAddress = new XML('');
+ shopperEmailAddress.appendChild(customerObj.profile.email);
var shopperBrowser = new XML('');
shopperBrowser.acceptHeader = requestObject.httpHeaders.get(worldpayConstants.ACCEPT);
shopperBrowser.userAgentHeader = requestObject.httpHeaders.get('user-agent');
+ shopperBrowser.browserScreenHeight = requestObject.httpParameterMap.browserScreenHeight.value;
+ shopperBrowser.browserScreenWidth = requestObject.httpParameterMap.browserScreenWidth.value;
if (customerObj.profile.customerNo != null && (enableTokenizationPref) &&
((preferences.tokenType == null) || !preferences.tokenType.toString().equals(worldpayConstants.merchanttokenType))) {
+ ordershopper.appendChild(shopperEmailAddress);
ordershopper.appendChild(authenticatedShopperID);
}
ordershopper.appendChild(shopperBrowser);
@@ -965,31 +992,7 @@ function createTokenRequestWOP(customerObj, paymentInstrument, preferences, card
orderorder.appendChild(token);
}
if (preferences.dstype !== null && preferences.dstype.value === 'two3d') {
- if (preferences.riskData != null && preferences.riskData) {
- var riskdata = new XML(' ');
- var authMethod = createRequestHelper.getAuthMethod(preferences);
- var authenticationRiskData = new XML('');
- var authenticationTimestamp = new XML(' ');
- authenticationTimestamp.appendChild(createRequestHelper.createTimeStamp());
- authenticationRiskData.appendChild(authenticationTimestamp);
- var shopperAccountRiskData = new XML('');
- if (customerObj.authenticated) {
- var shopperAccountCreationDate = new XML(' ');
- var shopperAccountModificationDate = new XML('');
- shopperAccountCreationDate.appendChild(createRequestHelper.createSRD(customerObj.profile.getCreationDate()));
- shopperAccountModificationDate.appendChild(createRequestHelper.createSRD(customerObj.profile.getLastModified()));
- shopperAccountRiskData.appendChild(shopperAccountCreationDate);
- shopperAccountRiskData.appendChild(shopperAccountModificationDate);
- }
- var transactionRiskDataGiftCardAmount = new XML(' ');
- transactionRiskDataGiftCardAmount.appendChild(createRequestHelper.createAmt());
- var transactionRiskData = new XML('');
- transactionRiskData.appendChild(transactionRiskDataGiftCardAmount);
- riskdata.appendChild(authenticationRiskData);
- riskdata.appendChild(shopperAccountRiskData);
- riskdata.appendChild(transactionRiskData);
- orderorder.appendChild(riskdata);
- }
+ orderorder = createRequestHelper.addRiskData(preferences, customerObj, orderorder);
var additional3DSData = createRequestHelper.creatAddional3DSData(preferences, requestObject);
orderorder.appendChild(additional3DSData);
}
@@ -1016,9 +1019,11 @@ function updateTokenRequestWOP(customerObj, preferences, responseData, expiratio
address = null;
}
var modify = new XML('');
- var paymentTokenUpdate = new XML('');
+ var paymentTokenUpdate = new XML('');
paymentTokenUpdate.paymentTokenID = responseData.paymentTokenID;
- paymentTokenUpdate.authenticatedShopperID = responseData.authenticatedShopperID;
+ if ((preferences.tokenType == null) || !preferences.tokenType.toString().equals(worldpayConstants.merchanttokenType)) {
+ paymentTokenUpdate.authenticatedShopperID = responseData.authenticatedShopperID;
+ }
paymentTokenUpdate.paymentInstrument.cardDetails = createRequestHelper.addCardDetails(expirationMonth,
expirationYear, responseData.cardHolderName.valueOf().toString(), address);
paymentTokenUpdate.tokenEventReference = responseData.tokenEventReference;
@@ -1080,8 +1085,12 @@ function createSavedCardAuthRequest(orderObj, req, paymentIntrument, preferences
if (paymentMthd.ID === worldpayConstants.WORLDPAY && paymentIntrument.creditCardToken) {
isSavedRedirectCard = true;
}
-
- var sessionXML = new XML('');
+ var sessionXML;
+ if (Site.getCurrent().getCustomPreferenceValue('enableEFTPOSDebugging')) {
+ sessionXML = new XML('');
+ } else {
+ sessionXML = new XML('');
+ }
var orderpaymentService = new XML('');
// sumbit container
@@ -1108,6 +1117,7 @@ function createSavedCardAuthRequest(orderObj, req, paymentIntrument, preferences
// shopper container
var ordershopper = new XML('');
// shopper email address contaioner
+
var ordershopperEmailAddress = new XML('');
ordershopperEmailAddress.appendChild(orderObj.getCustomerEmail());
// associate respective conatiners inside shopper container
@@ -1184,7 +1194,9 @@ function createSavedCardAuthRequest(orderObj, req, paymentIntrument, preferences
orderorder.appendChild(orderamount);
orderorder.appendChild(orderPaymentDetails);
orderorder.appendChild(ordershopper);
- orderorder.appendChild(ordershippingAddress);
+ if (!Site.getCurrent().getCustomPreferenceValue('enableEFTPOSDebugging')) {
+ orderorder.appendChild(ordershippingAddress);
+ }
// associate respective conatiners inside submit container
ordersubmit.appendChild(orderorder);
@@ -1250,7 +1262,7 @@ function createSavedCardAuthRequest(orderObj, req, paymentIntrument, preferences
shopperAccountRiskData.appendChild(shopperAccountModificationDate);
}
var transactionRiskDataGiftCardAmount = new XML(' ');
- transactionRiskDataGiftCardAmount.appendChild(createRequestHelper.createAmt());
+ transactionRiskDataGiftCardAmount.appendChild(createRequestHelper.createAmt(orderObj));
var transactionRiskData = new XML('');
transactionRiskData.appendChild(transactionRiskDataGiftCardAmount);
riskdata.appendChild(authenticationRiskData);
@@ -1266,7 +1278,11 @@ function createSavedCardAuthRequest(orderObj, req, paymentIntrument, preferences
if (preferences.challengeWindowSize.value != null && preferences.challengeWindowSize) {
challengeWindowSize = preferences.challengeWindowSize.value;
}
- var additional3DSData = new XML('');
order.submit.order.appendChild(additional3DSData);
}
@@ -1294,11 +1310,19 @@ function addExemptionAttributes(order, preferences) {
*/
function createApplePayAuthRequest(order, event) {
var utils = require('*/cartridge/scripts/common/utils');
+ var createRequestHelper = require('*/cartridge/scripts/common/createRequestHelper');
var language = utils.getLanguage();
+ var PaymentMgr = require('dw/order/PaymentMgr');
+ // Fetch the APM Name from the Payment isntrument.
+ var paymentIntrument = order.getPaymentInstrument();
+ var apmName = paymentIntrument.getPaymentMethod();
+ // Fetch the APM Type from the Payment Method i.e. if the Payment Methoid is of DIRECT or REDIRECT type.
+ var paymentMthd = PaymentMgr.getPaymentMethod(apmName);
var WorldpayPreferences = require('*/cartridge/scripts/object/worldpayPreferences');
var worldPayPreferences = new WorldpayPreferences();
- var preferences = worldPayPreferences.worldPayPreferencesInit(null, order);
+ var preferences = worldPayPreferences.worldPayPreferencesInit(paymentMthd, order);
var orderNo = order.orderNo;
+ var pluginTrackerDetail = createRequestHelper.sendPluginTrackerDetails(order, apmName).toString();
var requestXML = new XML('');
var submit = new XML('');
var orderData = new XML('');
@@ -1311,7 +1335,8 @@ function createApplePayAuthRequest(order, event) {
var amountXml = new XML('');
submit.order.appendChild(amountXml);
var orderContent = new XML('');
- orderContent.appendChild(order.orderNo);
+ var orderContentDetail = '';
+ orderContent.appendChild(orderContentDetail);
submit.order.appendChild(orderContent);
var paymentDetails = new XML('');
submit.order.appendChild(paymentDetails);
@@ -1340,7 +1365,6 @@ function createApplePayAuthRequest(order, event) {
applePayDetails.appendChild(version);
applePayDetails.appendChild(data);
submit.order.paymentDetails.appendChild(applePayDetails);
-
var ordershopper = new XML('');
var ordershopperEmailAddress = new XML('');
ordershopperEmailAddress.appendChild(order.getCustomerEmail());
diff --git a/cartridges/int_worldpay_core/cartridge/scripts/object/worldpayPreferences.js b/cartridges/int_worldpay_core/cartridge/scripts/object/worldpayPreferences.js
index 9156596..10bc54c 100644
--- a/cartridges/int_worldpay_core/cartridge/scripts/object/worldpayPreferences.js
+++ b/cartridges/int_worldpay_core/cartridge/scripts/object/worldpayPreferences.js
@@ -10,7 +10,8 @@
var URLUtils = require('dw/web/URLUtils');
var Site = require('dw/system/Site');
var isMultiMerchantSupportEnabled = Site.current.getCustomPreferenceValue('enableMultiMerchantSupport');
-
+var Order = require('dw/order/Order');
+var Basket = require('dw/order/Basket');
/**
* an Empty function for prototype
@@ -46,9 +47,15 @@ WorldpayPreferences.prototype = {
if (Site.current.getCustomPreferenceValue('multiMerchantType')) {
multiMerchantType = Site.current.getCustomPreferenceValue('multiMerchantType').value;
}
+ this.enableEFTPOS = getSitePeference('enableEFTPOS');
this.googlePayMerchantID = getSitePeference('googlePayMerchantID');
this.gatewayMerchantID = getSitePeference('gatewayMerchantId');
- if (paymentMthd && paymentMthd.custom.merchantID) {
+ if (paymentMthd && (paymentMthd.ID === 'CREDIT_CARD' || paymentMthd.ID === 'PAYWITHGOOGLE-SSL') && getSitePeference('enableEFTPOS')) {
+ this.merchantCode = getSitePeference('eftposMerchantCode');
+ this.userName = getSitePeference('eftposUserName');
+ this.XMLPassword = getSitePeference('EFTPOSPassword');
+ this.eftposRoutingMID = getSitePeference('EFTPOSRoutingMID');
+ } else if (paymentMthd && paymentMthd.custom.merchantID) {
this.merchantCode = paymentMthd.custom.merchantID;
this.userName = paymentMthd.custom.userName;
this.XMLPassword = paymentMthd.custom.password;
@@ -75,9 +82,9 @@ WorldpayPreferences.prototype = {
this.country = this.getLocale().getCountry();
this.language = this.getLocale().getLanguage();
this.enableWorldPayElvRecurringMandate = getSitePeference('enableSepaRecurringMandate');
- this.worldPayIdealBankList = getSitePeference('WorldpayIdealBankList');
this.worldPayEnableCardSelection = getSitePeference('WorldpayEnableCardSelection');
this.worldPayPaymentMethodMaskIncludes = getSitePeference('WorldpayPaymentMethodMaskIncludes');
+ this.addHppPaymentMethodMaskDetails(order);
if (!isMultiMerchantSupportEnabled || (isMultiMerchantSupportEnabled && multiMerchantType !== 'channel' && multiMerchantType !== 'paymentMethod')) {
this.worldPayMerchantNumber = getSitePeference('WorldpayMerchantNumber');
}
@@ -193,8 +200,6 @@ WorldpayPreferences.prototype = {
},
addMultiMerchantPreferences: function (paymentMthd, multiMerchantType, order) {
- var Order = require('dw/order/Order');
- var Basket = require('dw/order/Basket');
var globalHelper = require('*/cartridge/scripts/multimerchant/globalMultiMerchantHelper');
var config = globalHelper.getMultiMerchantConfiguration(paymentMthd);
if (order && order instanceof Order && order.custom.isPayByLinkOrder && Site.current.getCustomPreferenceValue('enablePayByLinkMultiMerchant')) {
@@ -222,6 +227,23 @@ WorldpayPreferences.prototype = {
} else {
this.addMultiMerchantEdgeCase(paymentMthd);
}
+ },
+
+ addHppPaymentMethodMaskDetails: function (order) {
+ if (order &&
+ (((order instanceof Basket || order instanceof Order) && order.getShipments().length > 1) ||
+ (!(order instanceof Basket || order instanceof Order) && (order.shipping.length > 1)))) {
+ let paymentMethodsIncludes = [];
+ for (let i = 0; i < this.paymentMethodsIncludes.length; i++) {
+ if (this.paymentMethodsIncludes[i] === 'PAYWITHGOOGLE-SSL' ||
+ this.paymentMethodsIncludes[i] === 'PAYPAL-EXPRESS' ||
+ this.paymentMethodsIncludes[i] === 'ONLINE') {
+ paymentMethodsIncludes.push(this.paymentMethodsIncludes[i]);
+ }
+ }
+ this.paymentMethodsIncludes = paymentMethodsIncludes;
+ this.worldPayPaymentMethodMaskIncludes = paymentMethodsIncludes;
+ }
}
};
module.exports = WorldpayPreferences;
diff --git a/cartridges/int_worldpay_core/cartridge/scripts/order/worldpayPayment.js b/cartridges/int_worldpay_core/cartridge/scripts/order/worldpayPayment.js
index 6df1c77..566f5b1 100644
--- a/cartridges/int_worldpay_core/cartridge/scripts/order/worldpayPayment.js
+++ b/cartridges/int_worldpay_core/cartridge/scripts/order/worldpayPayment.js
@@ -206,8 +206,6 @@ function handleAPM(basket, paymentInformation) {
paymentInstrument.custom.gpaySignature = paramMap.signature;
paymentInstrument.custom.gpayprotocolVersion = paramMap.protocolVersion;
paymentInstrument.custom.gpaysignedMessage = paramMap.signedMessage;
- } else if (paymentMethod.equals(worldpayConstants.GIROPAY)) {
- paymentInstrument.custom.bankCode = paymentInformation.giropayFields.bankCode.value;
} else if (paymentMethod.equals(worldpayConstants.ELV)) {
paymentInstrument.custom.elvMandateType = paymentInformation.elvFields.elvMandateType.value;
paymentInstrument.custom.elvMandateID = paymentInformation.elvFields.elvMandateID.value;
@@ -218,7 +216,7 @@ function handleAPM(basket, paymentInformation) {
paymentInstrument.setBankAccountNumber(paymentInformation.achFields.achAccountNumber.value);
paymentInstrument.setBankRoutingNumber(paymentInformation.achFields.achRoutingNumber.value);
paymentInstrument.custom.achCheckNumber = paymentInformation.achFields.achCheckNumber.value;
- } else if (paymentMethod.equals(worldpayConstants.KLARNASLICEIT) || paymentMethod.equals(worldpayConstants.KLARNAPAYLATER) ||
+ } else if (paymentMethod.equals(worldpayConstants.KLARNA) || paymentMethod.equals(worldpayConstants.KLARNASLICEIT) || paymentMethod.equals(worldpayConstants.KLARNAPAYLATER) ||
paymentMethod.equals(worldpayConstants.KLARNAPAYNOW)) {
paymentInstrument.custom.wpKlarnaPaymentMethod = paymentMethod;
}
@@ -452,11 +450,11 @@ function createURL(responsePaymentMethod, redirectUrl, paymentInstrument, apmTyp
var apmName = pi.getPaymentMethod();
var redirectURL = redirectUrl;
if (responsePaymentMethod && !responsePaymentMethod.equals(worldpayConstants.KLARNAPAYLATER) && !responsePaymentMethod.equals(worldpayConstants.KLARNASLICEIT) &&
- !responsePaymentMethod.equals(worldpayConstants.KLARNAPAYNOW) && redirectURL.includes('&') > 0) {
+ !responsePaymentMethod.equals(worldpayConstants.KLARNAPAYNOW) && !responsePaymentMethod.equals(worldpayConstants.KLARNA) && redirectURL.includes('&') > 0) {
redirectURL = redirectURL.replace('&', '&');
}
if (undefined === responsePaymentMethod || !responsePaymentMethod.equals(worldpayConstants.KLARNASLICEIT) ||
- !responsePaymentMethod.equals(worldpayConstants.KLARNAPAYLATER) || !responsePaymentMethod.equals(worldpayConstants.KLARNAPAYNOW)) {
+ !responsePaymentMethod.equals(worldpayConstants.KLARNAPAYLATER) || !responsePaymentMethod.equals(worldpayConstants.KLARNAPAYNOW) || !responsePaymentMethod.equals(worldpayConstants.KLARNA)) {
if (!isValidCustomOptionsHPP) {
if (apmType.equalsIgnoreCase(worldpayConstants.DIRECT)) {
redirectURL = utils.createDirectURL(redirectURL, order.orderNo, countryCode);
@@ -550,7 +548,7 @@ function authorize(orderNumber, cardNumber, encryptedData, cvn) {
var orderamount = utils.calculateNonGiftCertificateAmount(order);
// if Klarna then adjustedMerchandizeTotalPrice
- if (apmName.equals(worldpayConstants.KLARNASLICEIT) || apmName.equals(worldpayConstants.KLARNAPAYLATER) || apmName.equals(worldpayConstants.KLARNAPAYNOW)) {
+ if (apmName.equals(worldpayConstants.KLARNA) || apmName.equals(worldpayConstants.KLARNASLICEIT) || apmName.equals(worldpayConstants.KLARNAPAYLATER) || apmName.equals(worldpayConstants.KLARNAPAYNOW)) {
orderamount = order.adjustedMerchandizeTotalGrossPrice.add(order.adjustedShippingTotalGrossPrice);
}
var authorizeOrderResult = serviceFacade.authorizeOrderService(orderamount, order, pi, order.customer, paymentMthd);
@@ -653,7 +651,7 @@ function authorize(orderNumber, cardNumber, encryptedData, cvn) {
returnToPage: true,
customOptionsHPPJSON: utils.getCustomOptionsHPP(paymentMthd, redirectURL, order.orderNo, order.getOrderToken(), null)
};
- } else if (responsePaymentMethod && (responsePaymentMethod.equals(worldpayConstants.KLARNASLICEIT) || responsePaymentMethod.equals(worldpayConstants.KLARNAPAYLATER) ||
+ } else if (responsePaymentMethod && (responsePaymentMethod.equals(worldpayConstants.KLARNA) || responsePaymentMethod.equals(worldpayConstants.KLARNASLICEIT) || responsePaymentMethod.equals(worldpayConstants.KLARNAPAYLATER) ||
responsePaymentMethod.equals(worldpayConstants.KLARNAPAYNOW))) {
redirectURL = StringUtils.decodeString(StringUtils.decodeBase64(redirectURL), StringUtils.ENCODE_TYPE_HTML);
redirectURL = redirectURL.replace('window.location.href', 'window.top.location.href');
@@ -833,6 +831,83 @@ function updateToken(paymentInstrument, customer) {
return serviceResponses;
}
+/**
+ * Returns True if payment method is applicable else false
+ * @param {Object} item -
+ * @param {Object} APMLookupServicePmtMtds -
+ * @param {Object} preferences -
+ * @param {boolean} showKlarna -
+ * @returns {boolean} -
+ */
+function isApplicablePaymentMethod(item, APMLookupServicePmtMtds, preferences) {
+ var itemId = item.ID;
+ return (item.paymentProcessor && !worldpayConstants.WORLDPAY.equals(item.paymentProcessor.ID))
+ || (item.custom.merchantID && !item.custom.merchantID.equalsIgnoreCase(preferences.merchantCode))
+ || (APMLookupServicePmtMtds.contains(itemId) && itemId.equalsIgnoreCase(worldpayConstants.IDEAL))
+ || (APMLookupServicePmtMtds.contains(itemId) && itemId.equalsIgnoreCase(worldpayConstants.KLARNA))
+ || (APMLookupServicePmtMtds.contains(itemId) && ((itemId.equalsIgnoreCase(worldpayConstants.WECHATPAY)
+ || (itemId.equalsIgnoreCase(worldpayConstants.ALIPAY))) && (utils.isDesktopDevice())))
+ || (APMLookupServicePmtMtds.contains(itemId) && (itemId.equalsIgnoreCase(worldpayConstants.ALIPAYMOBILE) && !(utils.isDesktopDevice())))
+ || (APMLookupServicePmtMtds.contains(itemId) && !itemId.equalsIgnoreCase(worldpayConstants.NORDEAFI) &&
+ !itemId.equalsIgnoreCase(worldpayConstants.NORDEASE) && !itemId.equalsIgnoreCase(worldpayConstants.IDEAL) &&
+ !itemId.equalsIgnoreCase(worldpayConstants.WECHATPAY) &&
+ !itemId.equalsIgnoreCase(worldpayConstants.ALIPAY) && !itemId.equalsIgnoreCase(worldpayConstants.ALIPAYMOBILE));
+}
+
+/**
+ * Returns True if payment method is Klarna
+ * @param {Object} itemId -
+ * @param {Object} siteCountry -
+ * @param {Object} countryCode -
+ * @returns {boolean} -
+ */
+function isKlarnaPaymentMethod(itemId, siteCountry, countryCode) {
+ return (itemId.equalsIgnoreCase(worldpayConstants.KLARNA)) && siteCountry.equalsIgnoreCase(countryCode.toUpperCase());
+}
+
+/**
+ * Returns True if payment method is active
+ * @param {Object} paymentMethod -
+ * @returns {boolean} -
+ */
+function isPaymentMethodActive(paymentMethod) {
+ return paymentMethod != null && paymentMethod.active && paymentMethod.paymentProcessor && worldpayConstants.WORLDPAY.equals(paymentMethod.paymentProcessor.ID);
+}
+
+/**
+ * returns page action
+ * @param {Object} requestPath -
+ * @returns {Object} -
+ */
+function getPageAction(requestPath) {
+ if (requestPath) {
+ var action = requestPath.split('/');
+ return action[action.length - 1];
+ }
+ return null;
+}
+
+
+/**
+ * Adds applicable APMs to applicableAPMs array
+ * @param {Object} iterator -
+ * @param {Object} applicableAPMs -
+ * @param {Object} APMLookupServicePmtMtds -
+ * @param {Object} preferences -
+ * @param {sting} countryCode -
+ */
+function pushApplicableAPM(iterator, applicableAPMs, APMLookupServicePmtMtds, preferences, countryCode) {
+ while (iterator.hasNext()) {
+ let item = iterator.next();
+ if (isApplicablePaymentMethod(item, APMLookupServicePmtMtds, preferences)) {
+ applicableAPMs.push(item);
+ }
+ if (isKlarnaPaymentMethod(item.ID, request.locale.toUpperCase().substr(3, 2), countryCode)) {
+ applicableAPMs.push(item);
+ }
+ }
+}
+
/**
* Creates an array of objects containing applicable payment methods
* @param {dw.util.ArrayList} paymentMethods - An ArrayList of
@@ -847,62 +922,26 @@ function applicablePaymentMethods(paymentMethods, countryCode, preferences) {
var enableAPMLookUpService = preferences.enableAPMLookUpService;
var applicableAPMs = new ArrayList();
var APMLookupServicePmtMtds;
- // get page url action
- var pageaction;
- var req = request;
- var requestpath = req.getHttpPath();
- if (requestpath) {
- var action = requestpath.split('/');
- pageaction = action[action.length - 1];
- }
+ var pageaction = getPageAction(request.getHttpPath());
+
if (enableAPMLookUpService && pageaction !== 'Order-History') {
- var showKlarna = false;
- var siteCountry = req.locale.toUpperCase().substr(3, 2);
- if (siteCountry.equalsIgnoreCase(countryCode.toUpperCase())) {
- showKlarna = true;
- }
APMLookupServiceResult = serviceFacade.apmLookupService(countryCode);
APMLookupServicePmtMtds = (undefined !== APMLookupServiceResult && undefined !== APMLookupServiceResult.apmList) ? APMLookupServiceResult.apmList : new ArrayList();
+
var iterator = paymentMethods.iterator();
- var item = null;
- while (iterator.hasNext()) {
- item = iterator.next();
- var itemId = item.ID;
- if ((item.paymentProcessor && !worldpayConstants.WORLDPAY.equals(item.paymentProcessor.ID))
- || (item.custom.merchantID && !item.custom.merchantID.equalsIgnoreCase(preferences.merchantCode))
- || (APMLookupServicePmtMtds.contains(itemId) && itemId.equalsIgnoreCase(worldpayConstants.IDEAL) && preferences.worldPayIdealBankList)
- || (APMLookupServicePmtMtds.contains(itemId) && itemId.equalsIgnoreCase(worldpayConstants.KLARNA) && showKlarna)
- || (APMLookupServicePmtMtds.contains(itemId) && ((itemId.equalsIgnoreCase(worldpayConstants.WECHATPAY)
- || (itemId.equalsIgnoreCase(worldpayConstants.ALIPAY))) && (utils.isDesktopDevice())))
- || (APMLookupServicePmtMtds.contains(itemId) && (itemId.equalsIgnoreCase(worldpayConstants.ALIPAYMOBILE) && !(utils.isDesktopDevice())))
- || (APMLookupServicePmtMtds.contains(itemId) && !itemId.equalsIgnoreCase(worldpayConstants.NORDEAFI) && !itemId.equalsIgnoreCase(worldpayConstants.KLARNA) &&
- !itemId.equalsIgnoreCase(worldpayConstants.NORDEASE) && !itemId.equalsIgnoreCase(worldpayConstants.IDEAL) &&
- !itemId.equalsIgnoreCase(worldpayConstants.WECHATPAY) &&
- !itemId.equalsIgnoreCase(worldpayConstants.ALIPAY) && !itemId.equalsIgnoreCase(worldpayConstants.ALIPAYMOBILE))) {
- applicableAPMs.push(item);
- }
- if ((itemId.equalsIgnoreCase(worldpayConstants.KLARNASLICEIT) || itemId.equalsIgnoreCase(worldpayConstants.KLARNAPAYLATER) ||
- itemId.equalsIgnoreCase(worldpayConstants.KLARNAPAYNOW)) && siteCountry.equalsIgnoreCase(countryCode.toUpperCase())) {
- applicableAPMs.push(item);
- }
- }
+ pushApplicableAPM(iterator, applicableAPMs, APMLookupServicePmtMtds, preferences, countryCode);
- var creditCardPmtMtd = PaymentMgr.getPaymentMethod(worldpayConstants.CREDITCARD);
- if (creditCardPmtMtd != null && creditCardPmtMtd.active && creditCardPmtMtd.paymentProcessor && worldpayConstants.WORLDPAY.equals(creditCardPmtMtd.paymentProcessor.ID)) {
- applicableAPMs.push(creditCardPmtMtd);
+ if (isPaymentMethodActive(PaymentMgr.getPaymentMethod(worldpayConstants.CREDITCARD))) {
+ applicableAPMs.push(PaymentMgr.getPaymentMethod(worldpayConstants.CREDITCARD));
}
- var googlepay = PaymentMgr.getPaymentMethod(worldpayConstants.GOOGLEPAY);
- if (googlepay != null && googlepay.active && googlepay.paymentProcessor && worldpayConstants.WORLDPAY.equals(googlepay.paymentProcessor.ID)) {
- applicableAPMs.push(googlepay);
+ if (isPaymentMethodActive(PaymentMgr.getPaymentMethod(worldpayConstants.GOOGLEPAY))) {
+ applicableAPMs.push(PaymentMgr.getPaymentMethod(worldpayConstants.GOOGLEPAY));
}
- var creditCardPmtMtdWorldpay = PaymentMgr.getPaymentMethod(worldpayConstants.WORLDPAY);
- if (creditCardPmtMtdWorldpay != null && creditCardPmtMtdWorldpay.active && creditCardPmtMtdWorldpay.paymentProcessor &&
- worldpayConstants.WORLDPAY.equals(creditCardPmtMtdWorldpay.paymentProcessor.ID)) {
- applicableAPMs.push(creditCardPmtMtdWorldpay);
+ if (isPaymentMethodActive(PaymentMgr.getPaymentMethod(worldpayConstants.WORLDPAY))) {
+ applicableAPMs.push(PaymentMgr.getPaymentMethod(worldpayConstants.WORLDPAY));
}
- var applePayWorldPay = PaymentMgr.getPaymentMethod(worldpayConstants.APPLEPAY);
- if (applePayWorldPay != null && applePayWorldPay.active && applePayWorldPay.paymentProcessor && worldpayConstants.WORLDPAY.equals(applePayWorldPay.paymentProcessor.ID)) {
- applicableAPMs.push(applePayWorldPay);
+ if (isPaymentMethodActive(PaymentMgr.getPaymentMethod(worldpayConstants.APPLEPAY))) {
+ applicableAPMs.push(PaymentMgr.getPaymentMethod(worldpayConstants.APPLEPAY));
}
}
return {
diff --git a/cartridges/int_worldpay_core/cartridge/scripts/pipelets/getPaymentCardToken.js b/cartridges/int_worldpay_core/cartridge/scripts/pipelets/getPaymentCardToken.js
index 97080df..e667374 100644
--- a/cartridges/int_worldpay_core/cartridge/scripts/pipelets/getPaymentCardToken.js
+++ b/cartridges/int_worldpay_core/cartridge/scripts/pipelets/getPaymentCardToken.js
@@ -8,9 +8,10 @@
* @param {string} cardType - cardType.
* @param {string} expirationMonth - expirationMonth.
* @param {string} expirationYear - expirationYear.
+ * @param {Object} serviceResponse - response data for token service call
* @return {Object} returns an json object having MatchedCustomerPaymentInstrument.
*/
-function getPaymentCardToken(customerPaymentInstruments, cardNumber, cardType, expirationMonth, expirationYear) {
+function getPaymentCardToken(customerPaymentInstruments, cardNumber, cardType, expirationMonth, expirationYear, serviceResponse) {
var Logger = require('dw/system/Logger');
var paymentTokenID = null;
var matchedCustomerPaymentInstrument = null;
@@ -18,7 +19,7 @@ function getPaymentCardToken(customerPaymentInstruments, cardNumber, cardType, e
try {
// find credit card in payment instruments
creditCardInstrument = require('*/cartridge/scripts/common/paymentInstrumentUtils').getTokenPaymentInstrument(
- customerPaymentInstruments, cardNumber, cardType, expirationMonth, expirationYear);
+ customerPaymentInstruments, cardNumber, cardType, expirationMonth, expirationYear, serviceResponse);
if (creditCardInstrument) {
matchedCustomerPaymentInstrument = creditCardInstrument;
if (creditCardInstrument.getCreditCardToken()) {
diff --git a/cartridges/int_worldpay_core/cartridge/scripts/pipelets/readNotifyCustomObject.js b/cartridges/int_worldpay_core/cartridge/scripts/pipelets/readNotifyCustomObject.js
index 4d26c16..fe3d3e5 100644
--- a/cartridges/int_worldpay_core/cartridge/scripts/pipelets/readNotifyCustomObject.js
+++ b/cartridges/int_worldpay_core/cartridge/scripts/pipelets/readNotifyCustomObject.js
@@ -14,6 +14,70 @@ var Logger = require('dw/system/Logger');
var utils = require('*/cartridge/scripts/common/utils');
var worldpayConstants = require('*/cartridge/scripts/common/worldpayConstants');
+/**
+ * Handles change of status for PostAuthCancelled scenario
+ * @param {Object} temp - XmlBody
+ * @returns {string} - changedStatus
+ */
+function handlePostAuthCancelledStatus(temp) {
+ var changedStatus;
+ changedStatus = temp.notify.orderStatusEvent.payment.lastEvent;
+ var cvcId = temp.notify.orderStatusEvent.payment.CVCResultCode.attribute('description').toString();
+ var avsId = temp.notify.orderStatusEvent.payment.AVSResultCode.attribute('description').toString();
+ var riskScore = 0;
+ if (temp.notify.orderStatusEvent.payment.riskScore.attribute('finalScore')) {
+ var riskFinalScoreString = temp.notify.orderStatusEvent.payment.riskScore.attribute('finalScore').toString();
+ riskScore = Number(riskFinalScoreString);
+ } else if (temp.notify.orderStatusEvent.payment.riskScore.attribute('value')) {
+ var riskScoreString = temp.notify.orderStatusEvent.payment.riskScore.attribute('value').toString();
+ riskScore = Number(riskScoreString);
+ }
+ if (changedStatus.equalsIgnoreCase(worldpayConstants.CANCELLEDSTATUS)) {
+ if ((cvcId.equalsIgnoreCase(worldpayConstants.FAILEDSTATUS) && avsId.equalsIgnoreCase(worldpayConstants.FAILEDSTATUS)) ||
+ (cvcId.equalsIgnoreCase('D') && avsId.equalsIgnoreCase('J')) || (riskScore > 100)) {
+ changedStatus = 'POST_AUTH_CANCELLED';
+ }
+ }
+ return changedStatus;
+}
+
+/**
+ * Helper function for readNotifyCustomObject
+ * @param {string} xmlString - Order Notification Updates XML
+ * @param {string} content - service response content
+ * @returns {Object} - success or error object
+ */
+function readNotifyCustomObjectHelper(xmlString, content) {
+ var orderCode;
+ var errorCode;
+ var errorMessage;
+ var changedStatus;
+ if (content.localName().equalsIgnoreCase(worldpayConstants.XMLPAYMENTSERVICE)) {
+ var temp = content;
+ if (worldpayConstants.XMLORDERSTATUSEVENT in temp.notify) {
+ orderCode = temp.notify.orderStatusEvent.attribute('orderCode').toString();
+ } else {
+ errorCode = worldpayConstants.NOTIFYERRORCODE112;
+ errorMessage = utils.getErrorMessage(errorCode);
+ Logger.getLogger('worldpay').error('Order Notification : Read Custom Object : ' + errorCode + ' : ' + errorMessage + ' : ' + xmlString);
+ }
+ if (worldpayConstants.XMLLASTEVENT in temp.notify.orderStatusEvent.payment) {
+ changedStatus = handlePostAuthCancelledStatus(temp);
+ } else {
+ errorCode = worldpayConstants.NOTIFYERRORCODE112;
+ errorMessage = utils.getErrorMessage(errorCode);
+ Logger.getLogger('worldpay').error('Order Notification : Read Custom Object : ' + errorCode + ' : ' + errorMessage + ' : ' + xmlString);
+ return { success: false, changedStatus: changedStatus, xmlString: xmlString, response: response };
+ }
+ } else {
+ errorCode = worldpayConstants.NOTIFYERRORCODE112;
+ errorMessage = utils.getErrorMessage(errorCode);
+ Logger.getLogger('worldpay').error('Order Notification : Read Custom Object : ' + errorCode + ' : ' + errorMessage + ' : ' + xmlString);
+ return { success: false, changedStatus: changedStatus, xmlString: xmlString, response: response };
+ }
+ return { success: true, changedStatus: changedStatus, xmlString: xmlString, response: response, orderCode: orderCode };
+}
+
/**
* Reads OrderNotifyUpdates custom object
* @param {number} customObjectID - Custom Object ID
@@ -55,45 +119,12 @@ function readNotifyCustomObject(customObjectID) {
}
var orderCode;
try {
- if (this.content.localName().equalsIgnoreCase(worldpayConstants.XMLPAYMENTSERVICE)) {
- var temp = this.content;
- if (worldpayConstants.XMLORDERSTATUSEVENT in temp.notify) {
- orderCode = temp.notify.orderStatusEvent.attribute('orderCode').toString();
- } else {
- errorCode = worldpayConstants.NOTIFYERRORCODE112;
- errorMessage = utils.getErrorMessage(errorCode);
- Logger.getLogger('worldpay').error('Order Notification : Read Custom Object : ' + errorCode + ' : ' + errorMessage + ' : ' + xmlString);
- }
- if (worldpayConstants.XMLLASTEVENT in temp.notify.orderStatusEvent.payment) {
- changedStatus = temp.notify.orderStatusEvent.payment.lastEvent;
- var cvcId = temp.notify.orderStatusEvent.payment.CVCResultCode.attribute('description').toString();
- var avsId = temp.notify.orderStatusEvent.payment.AVSResultCode.attribute('description').toString();
- var riskScore = 0;
- if (temp.notify.orderStatusEvent.payment.riskScore.attribute('finalScore')) {
- var riskFinalScoreString = temp.notify.orderStatusEvent.payment.riskScore.attribute('finalScore').toString();
- riskScore = Number(riskFinalScoreString);
- } else if (temp.notify.orderStatusEvent.payment.riskScore.attribute('value')) {
- var riskScoreString = temp.notify.orderStatusEvent.payment.riskScore.attribute('value').toString();
- riskScore = Number(riskScoreString);
- }
- if (changedStatus.equalsIgnoreCase(worldpayConstants.CANCELLEDSTATUS)) {
- if ((cvcId.equalsIgnoreCase(worldpayConstants.FAILEDSTATUS) && avsId.equalsIgnoreCase(worldpayConstants.FAILEDSTATUS)) ||
- (cvcId.equalsIgnoreCase('D') && avsId.equalsIgnoreCase('J')) || (riskScore > 100)) {
- changedStatus = 'POST_AUTH_CANCELLED';
- }
- }
- } else {
- errorCode = worldpayConstants.NOTIFYERRORCODE112;
- errorMessage = utils.getErrorMessage(errorCode);
- Logger.getLogger('worldpay').error('Order Notification : Read Custom Object : ' + errorCode + ' : ' + errorMessage + ' : ' + xmlString);
- return { success: false, changedStatus: changedStatus, xmlString: xmlString, response: response };
- }
- } else {
- errorCode = worldpayConstants.NOTIFYERRORCODE112;
- errorMessage = utils.getErrorMessage(errorCode);
- Logger.getLogger('worldpay').error('Order Notification : Read Custom Object : ' + errorCode + ' : ' + errorMessage + ' : ' + xmlString);
- return { success: false, changedStatus: changedStatus, xmlString: xmlString, response: response };
+ var result = readNotifyCustomObjectHelper(xmlString, this.content);
+ if (!result.success) {
+ return result;
}
+ orderCode = result.orderCode;
+ changedStatus = result.changedStatus;
} catch (ex) {
errorCode = worldpayConstants.NOTIFYERRORCODE117;
errorMessage = utils.getErrorMessage(errorCode);
diff --git a/cartridges/int_worldpay_core/cartridge/scripts/service/serviceFacade.js b/cartridges/int_worldpay_core/cartridge/scripts/service/serviceFacade.js
index f4beb87..9af39ce 100644
--- a/cartridges/int_worldpay_core/cartridge/scripts/service/serviceFacade.js
+++ b/cartridges/int_worldpay_core/cartridge/scripts/service/serviceFacade.js
@@ -572,7 +572,7 @@ function cscPartialCapture(orderID, settleAmount, partialSettleAmount, currency,
var order = OrderMgr.getOrder(orderID);
var paymentMethod = order.paymentInstrument.getPaymentMethod();
var partialCaptureRequest;
- if ((paymentMethod === worldpayConstants.KLARNASLICEIT || paymentMethod === worldpayConstants.KLARNAPAYLATER || paymentMethod === worldpayConstants.KLARNAPAYNOW)) {
+ if ((paymentMethod === worldpayConstants.KLARNA || paymentMethod === worldpayConstants.KLARNASLICEIT || paymentMethod === worldpayConstants.KLARNAPAYLATER || paymentMethod === worldpayConstants.KLARNAPAYNOW)) {
partialCaptureRequest = libCreateRequest.createKlarnaCaptureRequest(orderID, settleAmount, currency, trackingID);
} else {
partialCaptureRequest = libCreateRequest.createPartialCaptureRequest(orderID, settleAmount, currency, shipmentNo);
@@ -582,8 +582,13 @@ function cscPartialCapture(orderID, settleAmount, partialSettleAmount, currency,
errorMessage = 'Inavlid XML Request ';
return { error: true, errorCode: errorCode, errorMessage: errorMessage };
}
+ var PaymentMgr = require('dw/order/PaymentMgr');
+ var paymentIntrument = order.getPaymentInstrument();
+ var apmName = paymentIntrument.getPaymentMethod();
+ // Fetch the APM Type from the Payment Method i.e. if the Payment Methoid is of DIRECT or REDIRECT type.
+ var paymentMthd = PaymentMgr.getPaymentMethod(apmName);
WorldpayPreferences = new WorldpayPreferences();
- var preferences = WorldpayPreferences.worldPayPreferencesInit(null, order);
+ var preferences = WorldpayPreferences.worldPayPreferencesInit(paymentMthd, order);
var responseObject = utils.serviceCall(partialCaptureRequest, null, preferences, null); // Making Service Call and Getting Response
let responseResult = validateResponse(responseObject);
@@ -619,8 +624,14 @@ function cscPartialRefund(orderID, settleAmount, currency, shipmentNo) {
var OrderMgr = require('dw/order/OrderMgr');
var order = OrderMgr.getOrder(orderID);
var paymentMethod = order.paymentInstrument.getPaymentMethod();
+ var PaymentMgr = require('dw/order/PaymentMgr');
+ // Fetch the APM Name from the Payment isntrument.
+ var paymentIntrument = order.getPaymentInstrument();
+ var apmName = paymentIntrument.getPaymentMethod();
+ // Fetch the APM Type from the Payment Method i.e. if the Payment Methoid is of DIRECT or REDIRECT type.
+ var paymentMthd = PaymentMgr.getPaymentMethod(apmName);
var partialRefundRequest;
- if ((paymentMethod === worldpayConstants.KLARNASLICEIT || paymentMethod === worldpayConstants.KLARNAPAYLATER || paymentMethod === worldpayConstants.KLARNAPAYNOW)) {
+ if ((paymentMethod === worldpayConstants.KLARNA || paymentMethod === worldpayConstants.KLARNASLICEIT || paymentMethod === worldpayConstants.KLARNAPAYLATER || paymentMethod === worldpayConstants.KLARNAPAYNOW)) {
partialRefundRequest = libCreateRequest.createKlarnaRefundRequest(orderID, settleAmount, currency);
} else {
partialRefundRequest = libCreateRequest.createPartialRefundRequest(orderID, settleAmount, currency, shipmentNo);
@@ -631,7 +642,7 @@ function cscPartialRefund(orderID, settleAmount, currency, shipmentNo) {
return { error: true, errorCode: errorCode, errorMessage: errorMessage };
}
WorldpayPreferences = new WorldpayPreferences();
- var preferences = WorldpayPreferences.worldPayPreferencesInit(null, order);
+ var preferences = WorldpayPreferences.worldPayPreferencesInit(paymentMthd, order);
var responseObject = utils.serviceCall(partialRefundRequest, null, preferences, null); // Making Service Call and Getting Response
let responseResult = validateResponse(responseObject);
@@ -669,8 +680,13 @@ function cscCancel(orderID) {
errorMessage = 'Inavlid XML Request ';
return { error: true, errorCode: errorCode, errorMessage: errorMessage };
}
+ var PaymentMgr = require('dw/order/PaymentMgr');
+ var paymentIntrument = order.getPaymentInstrument();
+ var apmName = paymentIntrument.getPaymentMethod();
+ // Fetch the APM Type from the Payment Method i.e. if the Payment Methoid is of DIRECT or REDIRECT type.
+ var paymentMthd = PaymentMgr.getPaymentMethod(apmName);
WorldpayPreferences = new WorldpayPreferences();
- var preferences = WorldpayPreferences.worldPayPreferencesInit(null, order);
+ var preferences = WorldpayPreferences.worldPayPreferencesInit(paymentMthd, order);
var responseObject = utils.serviceCall(cancelRequest, null, preferences, null); // Making Service Call and Getting Response
let responseResult = validateResponse(responseObject);
diff --git a/cartridges/int_worldpay_core/cartridge/static/default/images/KONBINI-SSL.png b/cartridges/int_worldpay_core/cartridge/static/default/images/KONBINI-SSL.png
new file mode 100644
index 0000000..9a30538
Binary files /dev/null and b/cartridges/int_worldpay_core/cartridge/static/default/images/KONBINI-SSL.png differ
diff --git a/cartridges/int_worldpay_core/cartridge/static/default/images/POLI-SSL.png b/cartridges/int_worldpay_core/cartridge/static/default/images/POLI-SSL.png
new file mode 100644
index 0000000..130ed80
Binary files /dev/null and b/cartridges/int_worldpay_core/cartridge/static/default/images/POLI-SSL.png differ
diff --git a/cartridges/int_worldpay_core/cartridge/static/default/images/worldpay_logo.png b/cartridges/int_worldpay_core/cartridge/static/default/images/worldpay_logo.png
index a63a304..1a89a6d 100644
Binary files a/cartridges/int_worldpay_core/cartridge/static/default/images/worldpay_logo.png and b/cartridges/int_worldpay_core/cartridge/static/default/images/worldpay_logo.png differ
diff --git a/cartridges/int_worldpay_core/cartridge/static/default/images/worldpay_logo_old.png b/cartridges/int_worldpay_core/cartridge/static/default/images/worldpay_logo_old.png
new file mode 100644
index 0000000..a63a304
Binary files /dev/null and b/cartridges/int_worldpay_core/cartridge/static/default/images/worldpay_logo_old.png differ
diff --git a/cartridges/int_worldpay_core/cartridge/templates/resources/worldpay.properties b/cartridges/int_worldpay_core/cartridge/templates/resources/worldpay.properties
index 18d6f3b..4d44e57 100644
--- a/cartridges/int_worldpay_core/cartridge/templates/resources/worldpay.properties
+++ b/cartridges/int_worldpay_core/cartridge/templates/resources/worldpay.properties
@@ -61,7 +61,6 @@ WorldpayConstants.IDEAL=IDEAL-SSL
WorldpayConstants.PAYPAL=PAYPAL-EXPRESS
WorldpayConstants.MISTERCASH=MISTERCASH-SSL
WorldpayConstants.WORLDPAY=Worldpay
-WorldpayConstants.GIROPAY=GIROPAY-SSL
WorldpayConstants.CREDITCARD=CREDIT_CARD
WorldpayConstants.P24=PRZELEWY-SSL
WorldpayConstants.KONBINI=KONBINI-SSL
diff --git a/cartridges/int_worldpay_csc/cartridge/controllers/CscWorldpay.js b/cartridges/int_worldpay_csc/cartridge/controllers/CscWorldpay.js
index 3c1ca2f..23c4375 100644
--- a/cartridges/int_worldpay_csc/cartridge/controllers/CscWorldpay.js
+++ b/cartridges/int_worldpay_csc/cartridge/controllers/CscWorldpay.js
@@ -244,6 +244,7 @@ server.get('RefundAction', function (req, res, next) {
case worldpayConstants.KLARNASLICEIT:
case worldpayConstants.KLARNAPAYLATER:
case worldpayConstants.KLARNAPAYNOW:
+ case worldpayConstants.KLARNA:
settleamount = amount;
break;
default:
@@ -393,7 +394,7 @@ server.get('PartialSettleOrderAction', function (req, res, next) {
} else {
partialSettleAmount = 0;
}
- if ((paymentMethod === worldpayConstants.KLARNASLICEIT || paymentMethod === worldpayConstants.KLARNAPAYLATER || paymentMethod === worldpayConstants.KLARNAPAYNOW)) {
+ if ((paymentMethod === worldpayConstants.KLARNA || paymentMethod === worldpayConstants.KLARNASLICEIT || paymentMethod === worldpayConstants.KLARNAPAYLATER || paymentMethod === worldpayConstants.KLARNAPAYNOW)) {
settleamount = amount;
}
if (isPartialCaptureAllowed) {
diff --git a/cartridges/int_worldpay_csc/cartridge/scripts/helpers/worldpayCscOrderHelper.js b/cartridges/int_worldpay_csc/cartridge/scripts/helpers/worldpayCscOrderHelper.js
index 2a5c054..7f8b0c6 100644
--- a/cartridges/int_worldpay_csc/cartridge/scripts/helpers/worldpayCscOrderHelper.js
+++ b/cartridges/int_worldpay_csc/cartridge/scripts/helpers/worldpayCscOrderHelper.js
@@ -146,7 +146,6 @@ function isCaptureAllowed(paymentMethod) {
function isRefundAllowed(paymentMethod) {
switch (paymentMethod) {
case 'KONBINI-SSL':
- case 'GIROPAY-SSL':
case 'MISTERCASH-SSL':
return false;
default:
diff --git a/cartridges/int_worldpay_sfra/cartridge/client/default/js/checkout/checkout.js b/cartridges/int_worldpay_sfra/cartridge/client/default/js/checkout/checkout.js
index b492745..40b1999 100644
--- a/cartridges/int_worldpay_sfra/cartridge/client/default/js/checkout/checkout.js
+++ b/cartridges/int_worldpay_sfra/cartridge/client/default/js/checkout/checkout.js
@@ -82,6 +82,105 @@ var scrollAnimate = require('base/components/scrollAnimate');
// initialize the currentStage variable for the first time
currentStage: 0,
+ updateCustomerStage: function (defer) {
+ var customerFormSelector = customerHelpers.methods.isGuestFormActive() ? customerHelpers.vars.GUEST_FORM : customerHelpers.vars.REGISTERED_FORM;
+ var customerForm = $(customerFormSelector);
+ $.ajax({
+ url: customerForm.attr('action'),
+ type: 'post',
+ data: customerForm.serialize(),
+ success: function (data) {
+ if (data.redirectUrl) {
+ window.location.href = data.redirectUrl;
+ } else {
+ customerHelpers.methods.customerFormResponse(defer, data);
+ }
+ },
+ error: function (err) {
+ if (err.responseJSON && err.responseJSON.redirectUrl) {
+ window.location.href = err.responseJSON.redirectUrl;
+ }
+ // Server error submitting form
+ defer.reject(err.responseJSON);
+ }
+ });
+ return defer;
+ },
+ updateShippingStage: function (defer) {
+ var isMultiShip = $('#checkout-main').hasClass('multi-ship');
+ var formSelector = isMultiShip ?
+ '.multi-shipping .active form' : '.single-shipping .shipping-form';
+ var form = $(formSelector);
+ if (isMultiShip && form.length === 0) {
+ // disable the next:Payment button here
+ $('body').trigger('checkout:disableButton', '.next-step-button button');
+ // in case the multi ship form is already submitted
+ var url = $('#checkout-main').attr('data-checkout-get-url');
+ $.ajax({
+ url: url,
+ method: 'GET',
+ success: function (data) {
+ // enable the next:Payment button here
+ $('body').trigger('checkout:enableButton', '.next-step-button button');
+ if (!data.error) {
+ $('body').trigger('checkout:updateCheckoutView',
+ { order: data.order, customer: data.customer });
+ defer.resolve();
+ } else if (data.message && $('.shipping-error .alert-danger').length < 1) {
+ var errorMsg = data.message;
+ var errorHtml = '' +
+ '' + errorMsg + '
';
+ $('.shipping-error').append(errorHtml);
+ scrollAnimate($('.shipping-error'));
+ defer.reject();
+ } else if (data.redirectUrl) {
+ window.location.href = data.redirectUrl;
+ }
+ },
+ error: function () {
+ // enable the next:Payment button here
+ $('body').trigger('checkout:enableButton', '.next-step-button button');
+ // Server error submitting form
+ defer.reject();
+ }
+ });
+ } else {
+ var shippingFormData = form.serialize();
+
+ $('body').trigger('checkout:serializeShipping', {
+ form: form,
+ data: shippingFormData,
+ callback: function (data) {
+ shippingFormData = data;
+ }
+ });
+ // disable the next:Payment button here
+ $('body').trigger('checkout:disableButton', '.next-step-button button');
+ $.ajax({
+ url: form.attr('action'),
+ type: 'post',
+ data: shippingFormData,
+ success: function (data) {
+ // enable the next:Payment button here
+ $('body').trigger('checkout:enableButton', '.next-step-button button');
+ shippingHelpers.methods.shippingFormResponse(defer, data);
+ },
+ error: function (err) {
+ // enable the next:Payment button here
+ $('body').trigger('checkout:enableButton', '.next-step-button button');
+ if (err.responseJSON && err.responseJSON.redirectUrl) {
+ window.location.href = err.responseJSON.redirectUrl;
+ }
+ // Server error submitting form
+ defer.reject(err.responseJSON);
+ }
+ });
+ }
+ return defer;
+ },
/**
* Set or update the checkout stage (AKA the shipping, billing, payment, etc... steps)
* @returns {Object} a promise
@@ -98,28 +197,7 @@ var scrollAnimate = require('base/components/scrollAnimate');
//
// Submit the Customer Form
//
- var customerFormSelector = customerHelpers.methods.isGuestFormActive() ? customerHelpers.vars.GUEST_FORM : customerHelpers.vars.REGISTERED_FORM;
- var customerForm = $(customerFormSelector);
- $.ajax({
- url: customerForm.attr('action'),
- type: 'post',
- data: customerForm.serialize(),
- success: function (data) {
- if (data.redirectUrl) {
- window.location.href = data.redirectUrl;
- } else {
- customerHelpers.methods.customerFormResponse(defer, data);
- }
- },
- error: function (err) {
- if (err.responseJSON && err.responseJSON.redirectUrl) {
- window.location.href = err.responseJSON.redirectUrl;
- }
- // Server error submitting form
- defer.reject(err.responseJSON);
- }
- });
- return defer;
+ return this.updateCustomerStage(defer);
} else if (stage === 'shipping') {
//
// Clear Previous Errors
@@ -128,80 +206,7 @@ var scrollAnimate = require('base/components/scrollAnimate');
//
// Submit the Shipping Address Form
//
- var isMultiShip = $('#checkout-main').hasClass('multi-ship');
- var formSelector = isMultiShip ?
- '.multi-shipping .active form' : '.single-shipping .shipping-form';
- var form = $(formSelector);
-
- if (isMultiShip && form.length === 0) {
- // disable the next:Payment button here
- $('body').trigger('checkout:disableButton', '.next-step-button button');
- // in case the multi ship form is already submitted
- var url = $('#checkout-main').attr('data-checkout-get-url');
- $.ajax({
- url: url,
- method: 'GET',
- success: function (data) {
- // enable the next:Payment button here
- $('body').trigger('checkout:enableButton', '.next-step-button button');
- if (!data.error) {
- $('body').trigger('checkout:updateCheckoutView',
- { order: data.order, customer: data.customer });
- defer.resolve();
- } else if (data.message && $('.shipping-error .alert-danger').length < 1) {
- var errorMsg = data.message;
- var errorHtml = '' +
- '' + errorMsg + '
';
- $('.shipping-error').append(errorHtml);
- scrollAnimate($('.shipping-error'));
- defer.reject();
- } else if (data.redirectUrl) {
- window.location.href = data.redirectUrl;
- }
- },
- error: function () {
- // enable the next:Payment button here
- $('body').trigger('checkout:enableButton', '.next-step-button button');
- // Server error submitting form
- defer.reject();
- }
- });
- } else {
- var shippingFormData = form.serialize();
-
- $('body').trigger('checkout:serializeShipping', {
- form: form,
- data: shippingFormData,
- callback: function (data) {
- shippingFormData = data;
- }
- });
- // disable the next:Payment button here
- $('body').trigger('checkout:disableButton', '.next-step-button button');
- $.ajax({
- url: form.attr('action'),
- type: 'post',
- data: shippingFormData,
- success: function (data) {
- // enable the next:Payment button here
- $('body').trigger('checkout:enableButton', '.next-step-button button');
- shippingHelpers.methods.shippingFormResponse(defer, data);
- },
- error: function (err) {
- // enable the next:Payment button here
- $('body').trigger('checkout:enableButton', '.next-step-button button');
- if (err.responseJSON && err.responseJSON.redirectUrl) {
- window.location.href = err.responseJSON.redirectUrl;
- }
- // Server error submitting form
- defer.reject(err.responseJSON);
- }
- });
- }
- return defer;
+ this.updateShippingStage(defer);
} else if (stage === 'payment') {
//
// Submit the Billing Address Form
@@ -364,6 +369,10 @@ var scrollAnimate = require('base/components/scrollAnimate');
$.ajax({
url: $('.place-order').data('action'),
method: 'POST',
+ data: {
+ browserScreenHeight: screen.height,
+ browserScreenWidth: screen.width
+ },
success: function (data) {
// enable the placeOrder button here
$('body').trigger('checkout:enableButton', '.next-step-button button');
diff --git a/cartridges/int_worldpay_sfra/cartridge/client/default/js/chromepay/chromepay.js b/cartridges/int_worldpay_sfra/cartridge/client/default/js/chromepay/chromepay.js
index ed26b15..4b6ed28 100644
--- a/cartridges/int_worldpay_sfra/cartridge/client/default/js/chromepay/chromepay.js
+++ b/cartridges/int_worldpay_sfra/cartridge/client/default/js/chromepay/chromepay.js
@@ -31,10 +31,10 @@ function encryption(details) {
// eslint-disable-next-line require-jsdoc
function base64url(source) {
// Encode in classical base64
- var encodedSource = CryptoJS.enc.Base64.stringify(source);
+ let encodedSource = CryptoJS.enc.Base64.stringify(source);
// Remove padding equal characters
- encodedSource = encodedSource.replace(/=+$/, '');
+ encodedSource = encodedSource.slice(0, encodedSource.indexOf('=') !== -1 ? encodedSource.indexOf('=') : encodedSource.length);
// Replace characters according to base64url specifications
encodedSource = encodedSource.replace(/\+/g, '-');
@@ -82,6 +82,25 @@ function createJWT() {
signature = base64url(signature);
return encodedHeader + '.' + encodedData + '.' + signature;
}
+
+// eslint-disable-next-line require-jsdoc
+function extractSessionId(ddcResponseStr) {
+ var startIndex = ddcResponseStr.indexOf('sendNotification(');
+ if (startIndex !== -1) {
+ var endIndex = ddcResponseStr.indexOf(');', startIndex);
+ if (endIndex !== -1) {
+ var functionCall = ddcResponseStr.substring(startIndex, endIndex + 2);
+ var parts = functionCall.split('"');
+
+ if (parts.length >= 2) {
+ var sessionId = parts[1].trim(); // The session ID should be the second part
+ return sessionId;
+ }
+ }
+ }
+ return new Error('Session ID not found');
+}
+
/**
* Converts the payment instrument into a JSON string.
*
@@ -114,16 +133,20 @@ function instrumentToJsonString(instrument) {
if (response.responseObject) {
var ddcResponse = response.responseObject;
var ddcResponseStr = ddcResponse.toString();
- var ddcResponseSubStr = ddcResponseStr.match(/sendNotification\\*.*?\);/g);
- var sessionId = ddcResponseSubStr[0].split('"');
- dataSessionId = sessionId[1].toString();
+ dataSessionId = extractSessionId(ddcResponseStr);
}
}
})).then($.ajax({
url: placeorderURL,
dataType: 'json',
- data: { dataSessionId: dataSessionId, encryptedData: encryptedData, instrumentString: instrumentString, cardTypeString: cardTypeString },
+ data: { dataSessionId: dataSessionId,
+ encryptedData: encryptedData,
+ instrumentString: instrumentString,
+ cardTypeString: cardTypeString,
+ browserScreenHeight: screen.height,
+ browserScreenWidth: screen.width
+ },
type: 'POST',
success: function (response) {
if (response.error && response.errorMessage) {
@@ -225,7 +248,8 @@ function onShippingMethodChange(paymentData, shippingOption, resolve, reject) {
})).then(function (data) {
// eslint-disable-next-line no-param-reassign
paymentData = data.chromePayment;
- paymentData.details.shippingOptions.forEach((option) => {
+ const initialPaymentData = paymentData;
+ initialPaymentData.details.shippingOptions.forEach((option) => {
// eslint-disable-next-line no-param-reassign
option.selected = option.id === shippingOption;
});
diff --git a/cartridges/int_worldpay_sfra/cartridge/client/default/js/instantCheckout/instantCheckout.js b/cartridges/int_worldpay_sfra/cartridge/client/default/js/instantCheckout/instantCheckout.js
index 8994712..256d09f 100644
--- a/cartridges/int_worldpay_sfra/cartridge/client/default/js/instantCheckout/instantCheckout.js
+++ b/cartridges/int_worldpay_sfra/cartridge/client/default/js/instantCheckout/instantCheckout.js
@@ -259,7 +259,11 @@ module.exports = {
$.ajax({
url: placeOrderUrl,
type: 'post',
- dataType: 'json'
+ dataType: 'json',
+ data: {
+ browserScreenHeight: screen.height,
+ browserScreenWidth: screen.width
+ }
}).done(function (resp) {
handlePlaceOrderResponse(resp);
}).fail(function () {
diff --git a/cartridges/int_worldpay_sfra/cartridge/client/default/js/paymentInstruments/paymentInstruments.js b/cartridges/int_worldpay_sfra/cartridge/client/default/js/paymentInstruments/paymentInstruments.js
index a442d44..e2802f6 100644
--- a/cartridges/int_worldpay_sfra/cartridge/client/default/js/paymentInstruments/paymentInstruments.js
+++ b/cartridges/int_worldpay_sfra/cartridge/client/default/js/paymentInstruments/paymentInstruments.js
@@ -10,6 +10,8 @@ base.submitPayment = function () {
var url = $form.attr('action');
$form.spinner().start();
$('form.payment-form').trigger('payment:submit', e);
+ $form[0][0].value = screen.height;
+ $form[0][1].value = screen.width;
var formData = cleave.serializeData($form);
$.ajax({
url: url,
diff --git a/cartridges/int_worldpay_sfra/cartridge/client/default/scss/checkoutTheme.scss b/cartridges/int_worldpay_sfra/cartridge/client/default/scss/checkoutTheme.scss
index dc21cb0..f148c86 100644
--- a/cartridges/int_worldpay_sfra/cartridge/client/default/scss/checkoutTheme.scss
+++ b/cartridges/int_worldpay_sfra/cartridge/client/default/scss/checkoutTheme.scss
@@ -55,6 +55,7 @@
}
}
.payment-method-title {
+ overflow:hidden;
padding: 0 0.938rem;
.label {
margin: 0.938rem 0.625rem;
@@ -407,6 +408,17 @@
margin-bottom: 0;
}
+@media (max-width: 61.938rem){
+ .paymentoptions-icons-wrapper {
+ display: none;
+ }
+ .form-caption-text.cc-ccv-info-text {
+ float: left;
+ }
+ .alternative-payment-listitem {
+ min-width: 38%;
+ }
+}
@media (max-width: 48rem){
.paymentoptions-icons-wrapper {
diff --git a/cartridges/int_worldpay_sfra/cartridge/controllers/COPlaceOrder.js b/cartridges/int_worldpay_sfra/cartridge/controllers/COPlaceOrder.js
index bd3dcac..da676cb 100644
--- a/cartridges/int_worldpay_sfra/cartridge/controllers/COPlaceOrder.js
+++ b/cartridges/int_worldpay_sfra/cartridge/controllers/COPlaceOrder.js
@@ -75,7 +75,8 @@ function authStatusOrderPlacement(paymentMethod, paymentStatus, paymentInstrumen
var currentSite = Site.getCurrent();
var order = orderObj;
var error;
- if (!paymentMethod.equals(worldpayConstants.KLARNASLICEIT) &&
+ if (!paymentMethod.equals(worldpayConstants.KLARNA) &&
+ !paymentMethod.equals(worldpayConstants.KLARNASLICEIT) &&
!paymentMethod.equals(worldpayConstants.KLARNAPAYLATER) &&
!paymentMethod.equals(worldpayConstants.KLARNAPAYNOW) &&
!paymentMethod.equals(worldpayConstants.IDEAL) &&
@@ -372,7 +373,8 @@ server.get('Submit',
order.custom.WorldpayLastEvent = worldpayConstants.REFUSED;
});
- if (!paymentMethod.equals(worldpayConstants.KLARNASLICEIT) &&
+ if (!paymentMethod.equals(worldpayConstants.KLARNA) &&
+ !paymentMethod.equals(worldpayConstants.KLARNASLICEIT) &&
!paymentMethod.equals(worldpayConstants.KLARNAPAYLATER) &&
!paymentMethod.equals(worldpayConstants.KLARNAPAYNOW) &&
!paymentMethod.equals(worldpayConstants.IDEAL) &&
@@ -423,7 +425,8 @@ server.get('Submit',
var orderModel = new OrderModel(order, { config: config });
if (paymentMethod.equals(worldpayConstants.KLARNASLICEIT) ||
paymentMethod.equals(worldpayConstants.KLARNAPAYLATER) ||
- paymentMethod.equals(worldpayConstants.KLARNAPAYNOW)) {
+ paymentMethod.equals(worldpayConstants.KLARNAPAYNOW) ||
+ paymentMethod.equals(worldpayConstants.KLARNA)) {
if (authResult) {
authResult.reference = StringUtils.decodeString(StringUtils.decodeBase64(authResult.reference), StringUtils.ENCODE_TYPE_HTML);
authResult.reference = authResult.reference.replace('window.location.href', 'window.top.location.href');
@@ -448,7 +451,8 @@ server.get('Submit',
order: orderModel,
returningCustomer: false,
passwordForm: passwordForm,
- klarnaConfirmationSnippet: ((paymentMethod.equals(worldpayConstants.KLARNASLICEIT) ||
+ klarnaConfirmationSnippet: ((paymentMethod.equals(worldpayConstants.KLARNA) ||
+ paymentMethod.equals(worldpayConstants.KLARNASLICEIT) ||
paymentMethod.equals(worldpayConstants.KLARNAPAYLATER) ||
paymentMethod.equals(worldpayConstants.KLARNAPAYNOW)) && authResult) ? authResult.reference : '',
orderUUID: order.getUUID()
@@ -457,7 +461,8 @@ server.get('Submit',
res.render('checkout/confirmation/confirmation', {
order: orderModel,
returningCustomer: true,
- klarnaConfirmationSnippet: ((paymentMethod.equals(worldpayConstants.KLARNASLICEIT) ||
+ klarnaConfirmationSnippet: ((paymentMethod.equals(worldpayConstants.KLARNA) ||
+ paymentMethod.equals(worldpayConstants.KLARNASLICEIT) ||
paymentMethod.equals(worldpayConstants.KLARNAPAYLATER) ||
paymentMethod.equals(worldpayConstants.KLARNAPAYNOW)) && authResult) ? authResult.reference : '',
orderUUID: order.getUUID()
diff --git a/cartridges/int_worldpay_sfra/cartridge/controllers/CheckoutServices.js b/cartridges/int_worldpay_sfra/cartridge/controllers/CheckoutServices.js
index 8bc7775..34fde48 100644
--- a/cartridges/int_worldpay_sfra/cartridge/controllers/CheckoutServices.js
+++ b/cartridges/int_worldpay_sfra/cartridge/controllers/CheckoutServices.js
@@ -67,12 +67,6 @@ function getPaymentInformationObject(paymentForm, paramMap) {
htmlName: paymentForm.idealFields.bank.htmlName
}
},
- giropayFields: {
- bankCode: {
- value: paymentForm.giropayFields.bankCode.value,
- htmlName: paymentForm.giropayFields.bankCode.htmlName
- }
- },
brazilFields: {
cpf: {
value: paymentForm.creditCardFields.cpf.value,
@@ -287,8 +281,6 @@ server.prepend(
}
} else if (paymentForm.paymentMethod.value.equals(worldpayConstants.IDEAL)) {
paymentFieldErrors = COHelpers.validateFields(paymentForm.idealFields);
- } else if (paymentForm.paymentMethod.value.equals(worldpayConstants.GIROPAY)) {
- paymentFieldErrors = COHelpers.validateFields(paymentForm.giropayFields);
} else if (paymentForm.paymentMethod.value.equals(worldpayConstants.ELV)) {
paymentFieldErrors = COHelpers.validateFields(paymentForm.elvFields);
if (!paymentForm.elvFields.elvConsent.value) {
diff --git a/cartridges/int_worldpay_sfra/cartridge/controllers/ChromePay.js b/cartridges/int_worldpay_sfra/cartridge/controllers/ChromePay.js
index 03cf4ea..55872e8 100644
--- a/cartridges/int_worldpay_sfra/cartridge/controllers/ChromePay.js
+++ b/cartridges/int_worldpay_sfra/cartridge/controllers/ChromePay.js
@@ -483,6 +483,15 @@ server.post('Handle3ds', server.middleware.https, function (req, res, next) {
return next();
});
+server.get('GetPaymentManifest', server.middleware.https, function (req, res, next) {
+ var URLUtils = require('dw/web/URLUtils');
+ res.setHttpHeader('Link', '<' + URLUtils.https('ChromePay-PaymentManifest').toString() + '>; rel="payment-method-manifest"');
+ res.json({
+ success: true
+ });
+ return next();
+});
+
server.get('PaymentManifest', server.middleware.https, function (req, res, next) {
var URLUtils = require('dw/web/URLUtils');
res.json({
diff --git a/cartridges/int_worldpay_sfra/cartridge/controllers/Worldpay.js b/cartridges/int_worldpay_sfra/cartridge/controllers/Worldpay.js
index 5c4ffa3..19bdf64 100644
--- a/cartridges/int_worldpay_sfra/cartridge/controllers/Worldpay.js
+++ b/cartridges/int_worldpay_sfra/cartridge/controllers/Worldpay.js
@@ -180,6 +180,184 @@ server.get('APMLookupService', function (req, res, next) {
return next();
});
+/**
+ * This controller is responsible for Handling authentication response
+ */
+server.post('HandleAuthenticationResponse', server.middleware.https, function (req, res, next) {
+ var utils = require('*/cartridge/scripts/common/utils');
+ var worldpayConstants = require('*/cartridge/scripts/common/worldpayConstants');
+ var URLUtils = require('dw/web/URLUtils');
+ var OrderManager = require('dw/order/OrderMgr');
+ var PaymentMgr = require('dw/order/PaymentMgr');
+ var Order = require('dw/order/Order');
+ var Resource = require('dw/web/Resource');
+ var Site = require('dw/system/Site');
+ var enableErrorMailService = Site.getCurrent().getCustomPreferenceValue('enableErrorMailService');
+ let error = null;
+ let orderObj;
+
+ //md - merchant supplied data contains the OrderNo
+ var md = req.form.MD ? req.form.MD : null;
+ var orderNo = md;
+
+ if (!orderNo) {
+ Logger.getLogger('worldpay').error('Worldpay.js HandleAuthenticationResponse : Order no. not present in parameters');
+ res.redirect(URLUtils.url('Cart-Show', 'placeerror', utils.worldpayErrorMessage()));
+ return next();
+ }
+
+ try {
+ orderObj = OrderManager.getOrder(orderNo);
+ } catch (ex) {
+ Logger.getLogger('worldpay').error('Worldpay.js HandleAuthenticationResponse : Invalid Order ');
+ res.redirect(URLUtils.url('Cart-Show', 'placeerror', utils.worldpayErrorMessage()));
+ return next();
+ }
+
+ // Fetch the APM Name from the Payment isntrument.
+ var paymentIntrument = utils.getPaymentInstrument(orderObj);
+ var apmName = paymentIntrument.getPaymentMethod();
+ // Fetch the APM Type from the Payment Method i.e. if the Payment Methoid is of DIRECT or REDIRECT type.
+ var paymentMthd = PaymentMgr.getPaymentMethod(apmName);
+ WorldpayPreferences = new WorldpayPreferences();
+ var preferences = WorldpayPreferences.worldPayPreferencesInit(paymentMthd, orderObj);
+
+ if (preferences.missingPreferences()) {
+ Logger.getLogger('worldpay').error('Worldpay.js HandleAuthenticationResponse : Worldpay preferences are not properly set.');
+ error = utils.worldpayErrorMessage();
+ if (enableErrorMailService) {
+ utils.sendErrorNotification(orderNo, worldpayConstants.AUTHENTICATION_FAILED, paymentMthd);
+ }
+ utils.failImpl(orderObj, error.errorMessage);
+ return {
+ error: true,
+ success: false,
+ errorMessage: error.errorMessage,
+ orderNo: orderObj.orderNo,
+ orderToken: orderObj.orderToken
+ };
+ }
+
+ var paRes = req.form.PaRes;
+ // Checks if paRes is exist in error codes (Issuer Response for 3D check)
+ if (paRes === null || paRes === worldpayConstants.UNKNOWN_ENTITY || paRes === worldpayConstants.CANCELLEDBYSHOPPER
+ || paRes === worldpayConstants.THREEDERROR || paRes === worldpayConstants.THREEDSINVALIDERROR || paRes === worldpayConstants.NOT_IDENTIFIED_NOID) {
+ var errorMessage = utils.getErrorMessage(paRes);
+ Logger.getLogger('worldpay').error('Worldpay.js HandleAuthenticationResponse : issuerResponse Error Message : ' + errorMessage);
+ var failRes = utils.failImpl(orderObj, errorMessage);
+ if (enableErrorMailService) {
+ utils.sendErrorNotification(orderNo, worldpayConstants.AUTHENTICATION_FAILED, paymentMthd);
+ }
+ if (failRes.error) {
+ res.redirect(URLUtils.url('Checkout-Begin', 'stage', 'placeOrder', 'placeerror', failRes.errorMessage));
+ return next();
+ }
+ res.redirect(URLUtils.url('Checkout-Begin', 'stage', 'payment', 'placeerror', errorMessage));
+ return next();
+ }
+ // Capturing Issuer Response
+ var paymentforms = server.forms.getForm('billing').creditCardFields;
+ var echoData = req.session.privacyCache.get('echoData');
+ req.session.privacyCache.set('echoData', null);
+ var cardNumber = paymentforms.cardNumber ? paymentforms.cardNumber.value : '';
+ var encryptedData = paymentforms.encryptedData ? paymentforms.encryptedData.value : '';
+ var cvn = paymentforms.securityCode ? paymentforms.securityCode.value : '';
+ var cardOrderObj = {
+ cvn: cvn,
+ cardNumber: cardNumber,
+ md: md,
+ paRes: paRes
+ };
+ var SecondAuthorizeRequestResult = require('*/cartridge/scripts/service/serviceFacade').secondAuthorizeRequestService(orderObj,
+ req,
+ paymentIntrument,
+ preferences,
+ echoData,
+ encryptedData,
+ cardOrderObj
+ );
+
+ if (SecondAuthorizeRequestResult.error && orderObj.custom.isInstantPurchaseOrder) {
+ delete session.privacy.isInstantPurchaseBasket;
+ Logger.getLogger('worldpay').error('Worldpay.js HandleAuthenticationResponse : isInstantPurchaseBasket deleted.');
+ if (enableErrorMailService) {
+ utils.sendErrorNotification(orderNo, worldpayConstants.AUTHENTICATION_FAILED, paymentMthd);
+ }
+ utils.failImpl(orderObj, SecondAuthorizeRequestResult.errorMessage);
+ res.redirect(URLUtils.url('Cart-Show', 'placeerror', SecondAuthorizeRequestResult.errorMessage));
+ return next();
+ }
+
+ if (SecondAuthorizeRequestResult.error) {
+ Logger.getLogger('worldpay').error('Worldpay.js HandleAuthenticationResponse : ErrorCode : ' +
+ SecondAuthorizeRequestResult.errorCode + ' : Error Message : ' + SecondAuthorizeRequestResult.errorMessage);
+ if (enableErrorMailService) {
+ utils.sendErrorNotification(orderNo, worldpayConstants.AUTHENTICATION_FAILED, paymentMthd);
+ }
+ utils.failImpl(orderObj, SecondAuthorizeRequestResult.errorMessage);
+ Logger.getLogger('worldpay').error('Worldpay.js HandleAuthenticationResponse : failing on order');
+ res.redirect(URLUtils.url('Checkout-Begin', 'stage', 'placeOrder', 'placeerror', SecondAuthorizeRequestResult.errorMessage));
+ return next();
+ }
+
+ // success handling
+ if (orderObj === null) {
+ res.redirect(URLUtils.url('Cart-Show'));
+ return next();
+ }
+ if (orderObj.getStatus().value === Order.ORDER_STATUS_FAILED) {
+ Transaction.wrap(function () {
+ orderObj.custom.worldpayMACMissingVal = true;
+ });
+ Logger.getLogger('worldpay').error('Worldpay.js HandleAuthenticationResponse : worldpayMACMissingVal sets');
+ error = utils.worldpayErrorMessage();
+ if (enableErrorMailService) {
+ utils.sendErrorNotification(orderNo, worldpayConstants.WORLDPAY_MAC_MISSING_VAL, paymentMthd);
+ }
+ res.redirect(URLUtils.url('Checkout-Begin', 'stage', 'payment', 'placeerror', error.errorMessage));
+ return next();
+ }
+
+ var customerObj = orderObj.customer.authenticated ? orderObj.customer : null;
+ var tokenProcessUtils = require('*/cartridge/scripts/common/tokenProcessUtils');
+ var resultCheckAuthorization = tokenProcessUtils.checkAuthorization(SecondAuthorizeRequestResult.response, paymentIntrument, customerObj);
+ if (resultCheckAuthorization.error) {
+ if (utils.failImpl(orderObj, resultCheckAuthorization.errorMessage).error) {
+ Logger.getLogger('worldpay').error('Worldpay.js HandleAuthenticationResponse : failing on order');
+ res.redirect(URLUtils.url('Cart-Show', 'placeerror', resultCheckAuthorization.errorMessage));
+ return next();
+ }
+ res.redirect(URLUtils.url('Checkout-Begin', 'stage', 'payment', 'placeerror', resultCheckAuthorization.errorMessage));
+ return next();
+ }
+
+ // Places the order
+ let placedOrderResult = COHelpers.placeOrder(orderObj);
+ if (placedOrderResult.error) {
+ res.redirect(URLUtils.url('Checkout-Begin', 'stage', 'payment', 'placeerror', Resource.msg('error.technical', 'checkout', null)));
+ return next();
+ }
+ Transaction.wrap(function () {
+ orderObj.custom.WorldpayLastEvent = worldpayConstants.AUTHORIZED;
+ });
+
+ if (!empty(session.privacy.currentOrderNo)) {
+ delete session.privacy.currentOrderNo;
+ Logger.getLogger('worldpay').error('Worldpay.js HandleAuthenticationResponse : deleting current order number');
+ }
+ COHelpers.sendConfirmationEmail(orderObj, req.locale.id);
+
+ // Reset usingMultiShip after successful Order placement
+ req.session.privacyCache.set('usingMultiShipping', false);
+ res.render('/checkout/orderConfirmForm', {
+ error: false,
+ orderID: orderObj.orderNo,
+ orderToken: orderObj.orderToken,
+ continueUrl: URLUtils.url('Order-Confirm').toString()
+ });
+ return next();
+});
+
function processSecondAuthorizeRequest(SecondAuthorizeRequestResult , enableErrorMailService ,res) {
var utils = require('*/cartridge/scripts/common/utils');
var worldpayConstants = require('*/cartridge/scripts/common/worldpayConstants');
diff --git a/cartridges/int_worldpay_sfra/cartridge/forms/default/billing.xml b/cartridges/int_worldpay_sfra/cartridge/forms/default/billing.xml
index dc9d59c..b7f3ec3 100644
--- a/cartridges/int_worldpay_sfra/cartridge/forms/default/billing.xml
+++ b/cartridges/int_worldpay_sfra/cartridge/forms/default/billing.xml
@@ -16,8 +16,6 @@
-
-
diff --git a/cartridges/int_worldpay_sfra/cartridge/models/chromepayment.js b/cartridges/int_worldpay_sfra/cartridge/models/chromepayment.js
index 63aa736..c2be13b 100644
--- a/cartridges/int_worldpay_sfra/cartridge/models/chromepayment.js
+++ b/cartridges/int_worldpay_sfra/cartridge/models/chromepayment.js
@@ -20,7 +20,7 @@ function getSupportedInstruments(req) {
});
var types = ['debit', 'credit']; // Prepaid not supported in SFCC
- var supportedMethods = URLUtils.https('ChromePay-PaymentManifest').toString();
+ var supportedMethods = URLUtils.https('ChromePay-GetPaymentManifest').toString();
return [{
supportedMethods: supportedMethods,
data: { supportedNetworks: result, supportedTypes: types }
diff --git a/cartridges/int_worldpay_sfra/cartridge/models/payment.js b/cartridges/int_worldpay_sfra/cartridge/models/payment.js
index 0d96888..886d762 100644
--- a/cartridges/int_worldpay_sfra/cartridge/models/payment.js
+++ b/cartridges/int_worldpay_sfra/cartridge/models/payment.js
@@ -81,24 +81,6 @@ function applicablePaymentCards(paymentCards) {
});
}
-/**
- * Provide Ideal bank key value pairs.
- * @param {dw.util.Collection} worldPayIdealBankList - An ArrayList of bank enumValue in custom preference.
- * @returns {Array} Array of objects that contain information about ideal bank.
- */
-function getIdealBankList(worldPayIdealBankList) {
- var bankArray = worldPayIdealBankList;
- if (bankArray && bankArray.length > 0) {
- return bankArray.map(function (bank) {
- return {
- value: bank.value,
- displayValue: bank.displayValue
- };
- });
- }
- return null;
-}
-
/**
* Provide Preferred Cards list.
* @param {Object} preferences - the associated worldpay preferences
@@ -265,9 +247,6 @@ function getSelectedPaymentInstruments(selectedPaymentInstruments, countryCode,
case worldpayConstants.WECHATPAY:
results.wechatQRCode = paymentInstrument.custom.wpWechatQRCode;
break;
- case worldpayConstants.GIROPAY:
- results.bankCode = paymentInstrument.custom.bankCode;
- break;
case worldpayConstants.IDEAL:
results.bank = paymentInstrument.custom.bank;
break;
@@ -443,8 +422,6 @@ function Payment(currentBasket, currentCustomer, countryCode) {
var worldPayPreferences = new WorldpayPreferences();
var preferences = worldPayPreferences.worldPayPreferencesInit(null, currentBasket);
- this.worldPayIdealBankList = getIdealBankList(preferences.worldPayIdealBankList);
-
this.applicablePaymentMethods =
paymentMethods ? applicablePaymentMethods(paymentMethods, paymentCountryCode, preferences) : null;
diff --git a/cartridges/int_worldpay_sfra/cartridge/scripts/hooks/applepay/applePayAuth.js b/cartridges/int_worldpay_sfra/cartridge/scripts/hooks/applepay/applePayAuth.js
index 10dff8b..f60bac5 100644
--- a/cartridges/int_worldpay_sfra/cartridge/scripts/hooks/applepay/applePayAuth.js
+++ b/cartridges/int_worldpay_sfra/cartridge/scripts/hooks/applepay/applePayAuth.js
@@ -6,6 +6,7 @@ var Transaction = require('dw/system/Transaction');
var applePayHelpers = require('*/cartridge/scripts/checkout/applePayHelpers');
exports.authorizeOrderPayment = function (order, responseData) {
+ var PaymentMgr = require('dw/order/PaymentMgr');
var libCreateRequest = require('*/cartridge/scripts/lib/libCreateRequest');
var ApplePayHookResult = require('dw/extensions/applepay/ApplePayHookResult');
var utils = require('*/cartridge/scripts/common/utils');
@@ -13,8 +14,13 @@ exports.authorizeOrderPayment = function (order, responseData) {
var Site = require('dw/system/Site');
var skipStateCodeValidation = Site.getCurrent().getCustomPreferenceValue('skipStateCodeAddressValidation');
var paymentMethodID = 'DW_APPLE_PAY';
+ // Fetch the APM Name from the Payment isntrument.
+ var paymentIntrument = order.getPaymentInstrument();
+ var apmName = paymentIntrument.getPaymentMethod();
+ // Fetch the APM Type from the Payment Method i.e. if the Payment Methoid is of DIRECT or REDIRECT type.
+ var paymentMthd = PaymentMgr.getPaymentMethod(apmName);
var worldPayPreferences = new WorldpayPreferences();
- var preferences = worldPayPreferences.worldPayPreferencesInit(null, order);
+ var preferences = worldPayPreferences.worldPayPreferencesInit(paymentMthd, order);
// validate the billing address
var error = new Status(Status.ERROR);
diff --git a/cartridges/int_worldpay_sfra/cartridge/scripts/multimerchant/channel/userAgentHelper.js b/cartridges/int_worldpay_sfra/cartridge/scripts/multimerchant/channel/userAgentHelper.js
index 9eca993..4d3bad7 100644
--- a/cartridges/int_worldpay_sfra/cartridge/scripts/multimerchant/channel/userAgentHelper.js
+++ b/cartridges/int_worldpay_sfra/cartridge/scripts/multimerchant/channel/userAgentHelper.js
@@ -96,13 +96,13 @@ var UserAgent = function () {
this._Versions = {
Edge: /(?:edge|edga|edgios|edg)\/([\d\w\.\-]+)/i,
Firefox: /(?:firefox|fxios)\/([\d\w\.\-]+)/i,
- IE: /msie\s([\d\.]+[\d])|trident\/\d+\.\d+;.*[rv:]+(\d+\.\d)/i,
+ IE: /msie\s(\d+\.\d+)|trident\/\d+\.\d+;[^\r\n]*rv:(\d+\.\d+)/i,
Chrome: /(?:chrome|crios)\/([\d\w\.\-]+)/i,
Chromium: /chromium\/([\d\w\.\-]+)/i,
Safari: /(version|safari)\/([\d\w\.\-]+)/i,
Opera: /version\/([\d\w\.\-]+)|OPR\/([\d\w\.\-]+)/i,
- Ps3: /([\d\w\.\-]+)\)\s*$/i,
- Psp: /([\d\w\.\-]+)\)?\s*$/i,
+ Ps3: /([\w.-]+)\s*\)$/i,
+ Psp: /([A-Za-z0-9.\-]+)\s*\)?\s*$/i,
Amaya: /amaya\/([\d\w\.\-]+)/i,
SeaMonkey: /seamonkey\/([\d\w\.\-]+)/i,
OmniWeb: /omniweb\/v([\d\w\.\-]+)/i,
@@ -179,7 +179,7 @@ var UserAgent = function () {
iOS: /ios/i,
Bada: /Bada\/(\d+)\.(\d+)/i,
Curl: /curl\/(\d+)\.(\d+)\.(\d+)/i,
- Electron: /Electron\/(\d+)\.(\d+)\.(\d+)/i,
+ Electron: /Electron\/(\d+)\.(\d+)\.(\d+)/i
};
this._Platform = {
Windows: /windows nt/i,
@@ -244,8 +244,8 @@ var UserAgent = function () {
isSilk: false,
isCaptive: false,
isSmartTV: false,
- isUC : false,
- isFacebook : false,
+ isUC: false,
+ isFacebook: false,
isAlamoFire: false,
isElectron: false,
silkAccelerated: false,
@@ -255,7 +255,7 @@ var UserAgent = function () {
platform: 'unknown',
geoIp: {},
source: '',
- isWechat: false,
+ isWechat: false
};
this.Agent = {};
@@ -367,7 +367,7 @@ var UserAgent = function () {
break;
case 'Opera':
if (this._Versions.Opera.test(string)) {
- return RegExp.$1 ? RegExp.$1: RegExp.$2;
+ return RegExp.$1 ? RegExp.$1 : RegExp.$2;
}
break;
case 'Firefox':
@@ -666,7 +666,7 @@ var UserAgent = function () {
if (/Silk-Accelerated=true/gi.test(ua.Agent.source)) {
this.Agent.SilkAccelerated = true;
}
- return this.Agent.isSilk ? 'Silk' : false;
+ return this.Agent.isSilk ? 'Silk' : 'false';
};
this.testKindleFire = function () {
@@ -700,7 +700,7 @@ var UserAgent = function () {
this.Agent.isKindleFire = true;
return 'Kindle Fire HDX 8.9 4G';
default:
- return false;
+ return 'false';
}
};
@@ -713,7 +713,7 @@ var UserAgent = function () {
ua.Agent.platform = 'Apple Mac';
return 'CaptiveNetwork';
}
- return false;
+ return 'false';
};
this.reset = function reset() {
@@ -803,7 +803,7 @@ var UserAgent = function () {
this.testSmartTV = function testBot() {
var ua = this;
- ua.Agent.isSmartTV = new RegExp('smart-tv|smarttv|googletv|appletv|hbbtv|pov_tv|netcast.tv','gi').test(ua.Agent.source.toLowerCase());
+ ua.Agent.isSmartTV = new RegExp('smart-tv|smarttv|googletv|appletv|hbbtv|pov_tv|netcast.tv', 'gi').test(ua.Agent.source.toLowerCase());
};
this.testAndroidTablet = function testAndroidTablet() {
@@ -824,7 +824,7 @@ var UserAgent = function () {
this.testWechat = function testWechat() {
var ua = this;
- if(/micromessenger/i.test(ua.Agent.source)) {
+ if (/micromessenger/i.test(ua.Agent.source)) {
ua.Agent.isWechat = true;
ua.Agent.version = this.getWechatVersion(ua.Agent.source);
}
@@ -832,7 +832,7 @@ var UserAgent = function () {
this.parse = function parse(source) {
var ua = new UserAgent();
- ua.Agent.source = source.replace(/^\s*/, '').replace(/\s*$/, '');
+ ua.Agent.source = source.trim();
ua.Agent.os = ua.getOS(ua.Agent.source);
ua.Agent.platform = ua.getPlatform(ua.Agent.source);
ua.Agent.browser = ua.getBrowser(ua.Agent.source);
diff --git a/cartridges/int_worldpay_sfra/cartridge/static/default/js/checkout/wallet/googlePay.js b/cartridges/int_worldpay_sfra/cartridge/static/default/js/checkout/wallet/googlePay.js
index d0ab75b..f05daa2 100644
--- a/cartridges/int_worldpay_sfra/cartridge/static/default/js/checkout/wallet/googlePay.js
+++ b/cartridges/int_worldpay_sfra/cartridge/static/default/js/checkout/wallet/googlePay.js
@@ -306,6 +306,8 @@ function onPaymentAuthorized(paymentData) {
url: url,
type: 'post',
data: {
+ browserScreenHeight: screen.height,
+ browserScreenWidth: screen.width
},
success: function (response) {
if (response.redirectUrl) {
diff --git a/cartridges/int_worldpay_sfra/cartridge/templates/default/account/payment/paymentForm.isml b/cartridges/int_worldpay_sfra/cartridge/templates/default/account/payment/paymentForm.isml
index 8d00acb..832f0f2 100644
--- a/cartridges/int_worldpay_sfra/cartridge/templates/default/account/payment/paymentForm.isml
+++ b/cartridges/int_worldpay_sfra/cartridge/templates/default/account/payment/paymentForm.isml
@@ -7,6 +7,8 @@
class="payment-form"
method="POST"
name="payment-form" ${pdict.paymentForm.attributes}>
+
+
${Resource.msg('worldpay.error.code5','worldpayerror',null)}
diff --git a/cartridges/int_worldpay_sfra/cartridge/templates/default/checkout/billing/paymentOptions/idealContent.isml b/cartridges/int_worldpay_sfra/cartridge/templates/default/checkout/billing/paymentOptions/idealContent.isml
index 94eaa47..03bbc6a 100644
--- a/cartridges/int_worldpay_sfra/cartridge/templates/default/checkout/billing/paymentOptions/idealContent.isml
+++ b/cartridges/int_worldpay_sfra/cartridge/templates/default/checkout/billing/paymentOptions/idealContent.isml
@@ -1,27 +1,5 @@
-fade
+
diff --git a/cartridges/int_worldpay_sfra/cartridge/templates/default/checkout/billing/paymentOptions/klarnaContent.isml b/cartridges/int_worldpay_sfra/cartridge/templates/default/checkout/billing/paymentOptions/klarnaContent.isml
index 3ac684c..b2ee453 100644
--- a/cartridges/int_worldpay_sfra/cartridge/templates/default/checkout/billing/paymentOptions/klarnaContent.isml
+++ b/cartridges/int_worldpay_sfra/cartridge/templates/default/checkout/billing/paymentOptions/klarnaContent.isml
@@ -4,20 +4,7 @@
diff --git a/cartridges/int_worldpay_sfra/cartridge/templates/default/checkout/billing/paymentOptions/paymentOptionsContent.isml b/cartridges/int_worldpay_sfra/cartridge/templates/default/checkout/billing/paymentOptions/paymentOptionsContent.isml
index 9ef7b1c..0f818ba 100644
--- a/cartridges/int_worldpay_sfra/cartridge/templates/default/checkout/billing/paymentOptions/paymentOptionsContent.isml
+++ b/cartridges/int_worldpay_sfra/cartridge/templates/default/checkout/billing/paymentOptions/paymentOptionsContent.isml
@@ -40,15 +40,11 @@
assets.addJs('/js/checkout.js');
-
-
-
-
diff --git a/cartridges/int_worldpay_sfra/cartridge/templates/default/checkout/billing/paymentOptions/redirectTab.isml b/cartridges/int_worldpay_sfra/cartridge/templates/default/checkout/billing/paymentOptions/redirectTab.isml
index 682af2e..914d22b 100644
--- a/cartridges/int_worldpay_sfra/cartridge/templates/default/checkout/billing/paymentOptions/redirectTab.isml
+++ b/cartridges/int_worldpay_sfra/cartridge/templates/default/checkout/billing/paymentOptions/redirectTab.isml
@@ -1,24 +1,5 @@
-
- active" data-toggle="tab" href="#giropay-content" role="tab">
-
-
-
-
-
-
-
-
+
active" data-toggle="tab" href="#ideal-content" role="tab">
-
+
active" data-toggle="tab" href="#applepay-content" role="tab">
-
+
active" data-toggle="tab" href="#redirect-content" role="tab">
-
-
diff --git a/cartridges/worldpay_sfra_changes/cartridge/templates/default/checkout/billing/paymentOptions/paymentOptionsContent.isml b/cartridges/worldpay_sfra_changes/cartridge/templates/default/checkout/billing/paymentOptions/paymentOptionsContent.isml
index 106e096..376f6a8 100644
--- a/cartridges/worldpay_sfra_changes/cartridge/templates/default/checkout/billing/paymentOptions/paymentOptionsContent.isml
+++ b/cartridges/worldpay_sfra_changes/cartridge/templates/default/checkout/billing/paymentOptions/paymentOptionsContent.isml
@@ -1,10 +1,6 @@
-
-
-
+
-
-
diff --git a/cartridges/worldpay_sfra_changes/cartridge/templates/default/checkout/billing/paymentOptions/redirectTab_APM.isml b/cartridges/worldpay_sfra_changes/cartridge/templates/default/checkout/billing/paymentOptions/redirectTab_APM.isml
index 7eee57e..e189501 100644
--- a/cartridges/worldpay_sfra_changes/cartridge/templates/default/checkout/billing/paymentOptions/redirectTab_APM.isml
+++ b/cartridges/worldpay_sfra_changes/cartridge/templates/default/checkout/billing/paymentOptions/redirectTab_APM.isml
@@ -1,27 +1,6 @@
+
+
+
+
+
+
+
@@ -158,5 +168,6 @@
+
\ No newline at end of file
diff --git a/documentation/worldpay-sfra-installation-and-overview-guide.pdf b/documentation/worldpay-sfra-installation-and-overview-guide.pdf
index b5f88d7..2d4b1e2 100644
Binary files a/documentation/worldpay-sfra-installation-and-overview-guide.pdf and b/documentation/worldpay-sfra-installation-and-overview-guide.pdf differ
diff --git a/documentation/worldpay-technical-guide.pdf b/documentation/worldpay-technical-guide.pdf
index af2ecb7..ace3b62 100644
Binary files a/documentation/worldpay-technical-guide.pdf and b/documentation/worldpay-technical-guide.pdf differ
diff --git a/documentation/worldpay-testing-guide.pdf b/documentation/worldpay-testing-guide.pdf
index 84e36da..ade1e6d 100644
Binary files a/documentation/worldpay-testing-guide.pdf and b/documentation/worldpay-testing-guide.pdf differ
diff --git a/metadata/jobs.xml b/metadata/jobs.xml
index c92abfe..33d9acf 100644
--- a/metadata/jobs.xml
+++ b/metadata/jobs.xml
@@ -115,6 +115,33 @@
+
+
+
+
+
+
+
+
+ int_worldpay_core/cartridge/scripts/jobs/payByLinkFailOrderJob.js
+ failOrder
+ false
+
+
+
+
+
+
+
+
+
+
+ 2023-02-13Z
+
+
+
+
+
Job that notifies the list of fraud sight risk orders
diff --git a/metadata/meta/custom-objecttype-definitions.xml b/metadata/meta/custom-objecttype-definitions.xml
index f5db097..04015f8 100644
--- a/metadata/meta/custom-objecttype-definitions.xml
+++ b/metadata/meta/custom-objecttype-definitions.xml
@@ -174,6 +174,14 @@
false
0
+
+ Gateway Merchant ID for Google Pay
+ string
+ false
+ false
+ false
+ 0
+
Worldpay Merchant Number
Worldpay Merchant Number
@@ -206,6 +214,7 @@
+
@@ -257,6 +266,14 @@
false
0
+
+ Gateway Merchant ID for Google Pay
+ string
+ false
+ false
+ false
+ 0
+
SEPA Mandate Number
SEPA Mandate Number
@@ -276,6 +293,7 @@
+
diff --git a/metadata/meta/system-objecttype-extensions.xml b/metadata/meta/system-objecttype-extensions.xml
index 9457d21..5ff5e76 100644
--- a/metadata/meta/system-objecttype-extensions.xml
+++ b/metadata/meta/system-objecttype-extensions.xml
@@ -282,6 +282,18 @@
false
false
+
+ boolean
+ false
+ false
+
+
+ Pay By Link Reminder Email Sent
+ If pay by link reminder email is sent then this is set to true
+ boolean
+ false
+ false
+
Fraud Sight Risk Message
String value that holds the fraudSight risk decision.
@@ -528,23 +540,6 @@
false
0
-
- iDEAL Bank
- Banks to be captured incase of iDEAL
- string
- false
- false
- 0
- 0
-
-
- GiroPay Bank Code
- string
- false
- false
- 0
- 0
-
binToken
string
@@ -750,7 +745,6 @@
-
@@ -1046,6 +1040,23 @@ Direct or Redirect
false
true
+
+ Pay By Link Expiry Time
+ Once expiry time is exceeded, the order will be failed and inventory will be restored. Expiry time is given in hours
+ double
+ false
+ false
+ Hours
+ 24.0
+ 24.0
+
+
+ Resend email after link expired
+ boolean
+ false
+ false
+ false
+
Previous Plugin Upgrade Dates
Previous Plugin Upgrade Dates
@@ -1175,6 +1186,12 @@ Direct or Redirect
+
+ boolean
+ false
+ false
+ true
+
Enable Card Selection
Enable card selection for Credit redirect model
@@ -1220,55 +1237,6 @@ Direct or Redirect
false
false
-
- Worldpay iDEAL Bank List
- enum-of-string
- false
- false
- true
-
-
- ING
- ING
-
-
- ABN AMRO
- ABN_AMRO
-
-
- ASN
- ASN
-
-
- Rabobank
- RABOBANK
-
-
- SNS
- SNS
-
-
- SNS Regio
- SNS_REGIO
-
-
- Triodos
- TRIODOS
-
-
- Van Lanschot
- VAN_LANSCHOT
-
-
- Knab
- KNAB
-
-
- Test
- Test
-
-
-
Worldpay Installation Id
int
@@ -1486,6 +1454,14 @@ Direct or Redirect
false
false
+
+ Enable Pay By Link
+ If set to true, the Pay By Link button will appear on checkout screen. If set to false then button will disappear
+ boolean
+ false
+ false
+ false
+
Enable Sales request
boolean
@@ -1846,6 +1822,91 @@ Direct or Redirect
+
+ Enable Multi Shipping Multi Merchant
+ When set to true, all multi shipping orders will use merchant code specified in MultiMerchantByMultiShipping custom object
+ boolean
+ false
+ false
+ false
+
+
+ Multi Shipping SEPA Mandate Number
+ string
+ false
+ false
+ 0
+
+
+ Multi Shipping Merchant ID
+ When enableMultiShippingMultiMerchant is set to true, this Merchant Code will be used for multi shipping orders
+ string
+ false
+ false
+ 0
+
+
+ Multi Shipping XML Password
+ password
+ false
+ false
+
+
+ Multi Shipping XML User Name
+ string
+ false
+ false
+ 0
+
+
+ Gateway Merchant ID for Multishipping
+ string
+ false
+ false
+ 0
+
+
+ Google Merchant ID For Multishipping
+ string
+ false
+ false
+ 0
+
+
+ Enable Pay By Link Multi Merchant
+ boolean
+ false
+ false
+ false
+
+
+ Pay By Link Merchant ID
+ string
+ false
+ false
+ 0
+
+
+ Pay By Link XML User Name
+ string
+ false
+ false
+ 0
+
+
+ Pay By Link XML Password
+ password
+ false
+ false
+
+
+ Node Version For Plugin Tracker
+ Enter the Node version for Plugin Tracker
+ string
+ true
+ false
+ 0
+
List of spoofed country
set-of-string
@@ -1889,6 +1950,48 @@ Direct or Redirect
false
false
+
+ Enable ETFPOS for Australia
+ Enables ETFPOS for Australia
+ boolean
+ false
+ false
+ true
+
+
+ EFTPOS Specific Merchant Code
+ Merchant Code used for EFTPOS
+ string
+ false
+ false
+ 0
+
+
+ EFTPOS UserName
+ string
+ false
+ false
+ 0
+
+
+ password
+ false
+ false
+
+
+ string
+ false
+ false
+ 0
+
+
+ Enable Debugging for EFTPOS Testing
+ Enable Debugging for EFTPOS Testing. Should be disabled in PRODUCTION
+ boolean
+ false
+ false
+ false
+
Enable Installments For LatAm Countries
boolean
@@ -2155,12 +2258,19 @@ Direct or Redirect
+
Payment method configurations
+
+
+
+
+
+
Card specific configurations
@@ -2178,13 +2288,16 @@ Direct or Redirect
Alternate payment methods configurations
-
+
+
+
+
Mobile wallets configurations
@@ -2237,6 +2350,17 @@ Direct or Redirect
+
+
+
+
+
+
+
+
+
+
+
Checkout feature configurations
diff --git a/metadata/sites/RefArch/custom-objects/ConfiguredLabels.xml b/metadata/sites/RefArch/custom-objects/ConfiguredLabels.xml
index e872b75..5dc40ad 100644
--- a/metadata/sites/RefArch/custom-objects/ConfiguredLabels.xml
+++ b/metadata/sites/RefArch/custom-objects/ConfiguredLabels.xml
@@ -449,7 +449,22 @@
- Share Order
-
+ Pay By Link
+
+
+
+ Order has expired, place another
+ order
+
+
+
+ Your order has been created, payment URL is sent
+ to your email
+
+
+
+ Unable to send email to given address, please check
+ your email or try again later.
+
diff --git a/metadata/sites/RefArch/custom-objects/MultiMerchantByPaymentMethod.xml b/metadata/sites/RefArch/custom-objects/MultiMerchantByPaymentMethod.xml
index 8a0022b..8986c75 100644
--- a/metadata/sites/RefArch/custom-objects/MultiMerchantByPaymentMethod.xml
+++ b/metadata/sites/RefArch/custom-objects/MultiMerchantByPaymentMethod.xml
@@ -72,12 +72,6 @@
S@pient^9090
XU5UIXKPP30S30WTY3FP
-
- 32e04907d379490
- SAPIENTNITROECOM
- S@pient^9090
- XU5UIXKPP30S30WTY3FP
-
55b2510eaa3f910
SAPIENTNITROECOM1
diff --git a/metadata/sites/RefArch/payment-methods.xml b/metadata/sites/RefArch/payment-methods.xml
index 98973be..0dfa5dc 100644
--- a/metadata/sites/RefArch/payment-methods.xml
+++ b/metadata/sites/RefArch/payment-methods.xml
@@ -240,25 +240,6 @@
-
-
- GiroPay
- true
- Worldpay
-
-
-
-
- DIRECT
-
-
-
- 0.1
- 50000
-
-
-
-
Przelewy24
true
diff --git a/metadata/sites/RefArch/payment-processors.xml b/metadata/sites/RefArch/payment-processors.xml
index 22a6379..a739220 100644
--- a/metadata/sites/RefArch/payment-processors.xml
+++ b/metadata/sites/RefArch/payment-processors.xml
@@ -17,7 +17,6 @@
COPlaceOrder-Submit
COPlaceOrder-Submit
Worldpay-HandleAuthenticationResponse
- ING ABN_AMRO ASN
true
false
diff --git a/metadata/sites/RefArch/preferences.xml b/metadata/sites/RefArch/preferences.xml
index 1c357a7..e82fd98 100644
--- a/metadata/sites/RefArch/preferences.xml
+++ b/metadata/sites/RefArch/preferences.xml
@@ -37,11 +37,6 @@
1#10001#9054b62f59775755d937226ac89d2fc8e3040b674e939c803840892f27e3c7d44909da41a8476e29ff0f214e6fbaee3dac9aeb62d041c81c5922156c43271aa4d0d59f15398364950e7ea7953566951dbb07512163aa8fa6ca5de2aad70244aed11ece6d04a94e4383f5c83eff8b38964e00d21918b908d76baaa0c89bb90b273c1fb956bbf7fc8d4e2649eed8fa5919878bb795ea207e231ef5bb3ef14b11480696e9131865177ac4a651113476d5e8f084ca8f0832ec759b7ccceeb238c9244d0774e86803f37eb1e1fa04fd60a553827cc235158e859b6e92a981e263f414828abc4a52bb64fd5e370718a928145d44a00ed5b08f40d249e9df773c4584b7
ONE-OFF
true
-
- ING
- ABN_AMRO
- ASN
-
/C0kv+c7DfOM0Fy3vJNl0hoHUfHTqaxusEvyuri4OgbbWUhRa6WhmJQwS8bRCYsnmkcAOLb2CgkbArqC/Nv8Zw==
ALL
diff --git a/package.json b/package.json
index 71175f1..568f214 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "int_worldpay_sfra",
- "version": "q1-23-v23.1.0",
+ "version": "q3-24-v24.1.0",
"description": "WorldPay Link Cartridge",
"main": "index.js",
"scripts": {
diff --git a/test/acceptance/features/steps/wpPaymentRegisteredApm.steps.js b/test/acceptance/features/steps/wpPaymentRegisteredApm.steps.js
index 8ff165a..7016b6a 100644
--- a/test/acceptance/features/steps/wpPaymentRegisteredApm.steps.js
+++ b/test/acceptance/features/steps/wpPaymentRegisteredApm.steps.js
@@ -395,26 +395,6 @@ When('Apm Shopper fills email and phone number and status for chinaunionpay', (t
}
});
-When('Apm Shopper fills email and phone number and status for giropay', (table) => {
- for (const id in table.rows) {
- console.log(table.rows);
- if (id < 1) {
- continue; // skip a header of a table
- }
-
- // go by row cells
- const cells = table.rows[id].cells;
-
- // take values
- const email = cells[0].value;
- const phone = cells[1].value;
- const bankcode = cells[2].value;
- const status = cells[3].value;
- const country = cells[4].value;
- worldpayPaymentTestRegistered.giropayRegistered(email, phone, bankcode, status, country);
- }
-});
-
When('Apm Shopper fills email and phone number for konbini', (table) => {
for (const id in table.rows) {
console.log(table.rows);
@@ -782,26 +762,6 @@ When('Apm Shopper fills new ui email and phone number and status for enets', (ta
}
});
-When('Apm Shopper fills new ui email and phone number and status for giropay', (table) => {
- for (const id in table.rows) {
- console.log(table.rows);
- if (id < 1) {
- continue; // skip a header of a table
- }
-
- // go by row cells
- const cells = table.rows[id].cells;
-
- // take values
- const email = cells[0].value;
- const phone = cells[1].value;
- const bankcode = cells[2].value;
- const status = cells[3].value;
- const country = cells[4].value;
- worldpayPaymentTestRegistered.giropayRegisteredNUI(email, phone, bankcode, status, country);
- }
-});
-
When('Apm Shopper fills new ui email and phone number for konbini', (table) => {
for (const id in table.rows) {
console.log(table.rows);
@@ -994,26 +954,6 @@ When('Apm Shopper fills phone number and status for chinaunionpay', (table) => {
}
});
-When('Apm Shopper fills phone number and status for giropay', (table) => {
- for (const id in table.rows) {
- console.log(table.rows);
- if (id < 1) {
- continue; // skip a header of a table
- }
-
- // go by row cells
- const cells = table.rows[id].cells;
-
- // take values
-
- const phone = cells[0].value;
- const bankcode = cells[1].value;
- const status = cells[2].value;
- const country = cells[3].value;
- worldpayPaymentTestRegistered.giropayRegistered(phone, bankcode, status, country);
- }
-});
-
When('Apm Shopper fills phone number and status for alipay', (table) => {
for (const id in table.rows) {
console.log(table.rows);
@@ -1304,25 +1244,6 @@ When('Apm Shopper fills new ui phone number and status for chinaunionpay', (tabl
}
});
-When('Apm Shopper fills new ui phone number and status for giropay', (table) => {
- for (const id in table.rows) {
- console.log(table.rows);
- if (id < 1) {
- continue; // skip a header of a table
- }
-
- // go by row cells
- const cells = table.rows[id].cells;
-
- // take values
- const phone = cells[0].value;
- const bankcode = cells[1].value;
- const status = cells[2].value;
- const country = cells[3].value;
- worldpayPaymentTestRegistered.giropayRegisteredNUI(phone, bankcode, status, country);
- }
-});
-
When('Apm Shopper fills new ui phone number and status for alipay', (table) => {
for (const id in table.rows) {
console.log(table.rows);
diff --git a/test/acceptance/pages/worldpayPaymentTestRegistered.js b/test/acceptance/pages/worldpayPaymentTestRegistered.js
index 88eab04..d1fd73e 100644
--- a/test/acceptance/pages/worldpayPaymentTestRegistered.js
+++ b/test/acceptance/pages/worldpayPaymentTestRegistered.js
@@ -409,39 +409,6 @@ module.exports = {
},
-
- giropayRegistered(email, phone, bankcode, status, country) {
- I.waitForElement({ xpath: '//*[@id="dwfrm_billing"]/fieldset/fieldset[1]/div/div[2]/a[1]' });
- I.click({ xpath: '//*[@id="dwfrm_billing"]/fieldset/fieldset[1]/div/div[2]/a[1]' });
- I.wait(2);
- I.selectOption('#billingCountry', country);
- I.waitForEnabled('.payment-form');
- I.waitForEnabled('#GIROPAY-SSL');
- I.waitForElement(locate('a').inside(locate('li').withAttr({ id: 'GIROPAY-SSL' })));
- I.wait(5);
- I.click(locate('a').inside(locate('li').withAttr({ id: 'GIROPAY-SSL' })));
- I.waitForEnabled('.form-control.email');
- I.waitForEnabled('.form-control.phone');
- I.waitForEnabled('.form-control.bankCode');
- I.fillField('.form-control.email', email);
- I.fillField('.form-control.phone', phone);
- I.fillField('.form-control.bankCode', bankcode);
- I.waitForEnabled('.submit-payment');
- I.click('.submit-payment');
- I.wait(2);
- I.waitForEnabled('.btn.btn-primary.btn-block.place-order');
- I.wait(2);
- I.click('.btn.btn-primary.btn-block.place-order');
- I.waitForEnabled('.container');
- I.selectOption('status', status);
- I.waitForElement('#jsEnabled');
- I.wait(2);
- I.click('#jsEnabled');
- I.wait(2);
-
- },
-
-
mistercashRegistered(email, phone, status, country) {
I.waitForElement({ xpath: '//*[@id="dwfrm_billing"]/fieldset/fieldset[1]/div/div[2]/a[1]' });
I.click({ xpath: '//*[@id="dwfrm_billing"]/fieldset/fieldset[1]/div/div[2]/a[1]' });
@@ -866,38 +833,6 @@ module.exports = {
},
-
- giropayRegisteredNUI(email, phone, bankcode, status, country) {
- I.waitForElement({ xpath: '//*[@id="dwfrm_billing"]/fieldset/fieldset[1]/div/div[2]/a[1]' });
- I.click({ xpath: '//*[@id="dwfrm_billing"]/fieldset/fieldset[1]/div/div[2]/a[1]' });
- I.wait(2);
- I.selectOption('#billingCountry', country);
- I.wait(1);
- I.click('Alternative Payment');
- I.wait(1);
- I.click({ xpath: '//*[@id="GIROPAY-SSL"]/div/label' });
- I.wait(1);
- I.waitForEnabled('.form-control.email');
- I.waitForEnabled('.form-control.phone');
- I.waitForEnabled('.form-control.bankCode');
- I.fillField('.form-control.email', email);
- I.fillField('.form-control.phone', phone);
- I.fillField('.form-control.bankCode', bankcode);
- I.waitForEnabled('.submit-payment');
- I.click('.submit-payment');
- I.wait(2);
- I.waitForEnabled('.btn.btn-primary.btn-block.place-order');
- I.wait(2);
- I.click('.btn.btn-primary.btn-block.place-order');
- I.waitForEnabled('.container');
- I.selectOption('status', status);
- I.waitForElement('#jsEnabled');
- I.wait(2);
- I.click('#jsEnabled');
- I.wait(2);
-
- },
-
konbiniRegisteredNUI(email, phone) {
I.wait(1);
I.click('Alternative Payment');
@@ -1240,35 +1175,6 @@ module.exports = {
},
- giropayRegistered(phone, bankcode, status, country) {
- I.waitForElement({ xpath: '//*[@id="dwfrm_billing"]/fieldset/fieldset[1]/div/div[2]/a[1]' });
- I.click({ xpath: '//*[@id="dwfrm_billing"]/fieldset/fieldset[1]/div/div[2]/a[1]' });
- I.wait(2);
- I.selectOption('#billingCountry', country);
- I.waitForEnabled('.payment-form');
- I.waitForEnabled('#GIROPAY-SSL');
- I.waitForElement(locate('a').inside(locate('li').withAttr({ id: 'GIROPAY-SSL' })));
- I.wait(5);
- I.click(locate('a').inside(locate('li').withAttr({ id: 'GIROPAY-SSL' })));
- I.waitForEnabled('.form-control.phone');
- I.waitForEnabled('.form-control.bankCode');
- I.fillField('.form-control.phone', phone);
- I.fillField('.form-control.bankCode', bankcode);
- I.waitForEnabled('.submit-payment');
- I.click('.submit-payment');
- I.wait(2);
- I.waitForEnabled('.btn.btn-primary.btn-block.place-order');
- I.wait(2);
- I.click('.btn.btn-primary.btn-block.place-order');
- I.waitForEnabled('.container');
- I.selectOption('status', status);
- I.waitForElement('#jsEnabled');
- I.wait(2);
- I.click('#jsEnabled');
- I.wait(2);
-
- },
-
alipayRegistered(phone, status, country) {
I.waitForElement({ xpath: '//*[@id="dwfrm_billing"]/fieldset/fieldset[1]/div/div[2]/a[1]' });
I.click({ xpath: '//*[@id="dwfrm_billing"]/fieldset/fieldset[1]/div/div[2]/a[1]' });
@@ -1682,35 +1588,6 @@ module.exports = {
},
- giropayRegisteredNUI(phone, bankcode, status, country) {
- I.waitForElement({ xpath: '//*[@id="dwfrm_billing"]/fieldset/fieldset[1]/div/div[2]/a[1]' });
- I.click({ xpath: '//*[@id="dwfrm_billing"]/fieldset/fieldset[1]/div/div[2]/a[1]' });
- I.wait(2);
- I.selectOption('#billingCountry', country);
- I.wait(1);
- I.click('Alternative Payment');
- I.wait(1);
- I.click({ xpath: '//*[@id="GIROPAY-SSL"]/div/label' });
- I.wait(1);
- I.waitForEnabled('.form-control.phone');
- I.waitForEnabled('.form-control.bankCode');
- I.fillField('.form-control.phone', phone);
- I.fillField('.form-control.bankCode', bankcode);
- I.waitForEnabled('.submit-payment');
- I.click('.submit-payment');
- I.wait(2);
- I.waitForEnabled('.btn.btn-primary.btn-block.place-order');
- I.wait(2);
- I.click('.btn.btn-primary.btn-block.place-order');
- I.waitForEnabled('.container');
- I.selectOption('status', status);
- I.waitForElement('#jsEnabled');
- I.wait(2);
- I.click('#jsEnabled');
- I.wait(2);
-
- },
-
alipayRegisteredNUI(phone, status, country) {
I.waitForElement({ xpath: '//*[@id="dwfrm_billing"]/fieldset/fieldset[1]/div/div[2]/a[1]' });
I.click({ xpath: '//*[@id="dwfrm_billing"]/fieldset/fieldset[1]/div/div[2]/a[1]' });
diff --git a/test/mocks/models/chromepayment.js b/test/mocks/models/chromepayment.js
index b3368bf..0320c2a 100644
--- a/test/mocks/models/chromepayment.js
+++ b/test/mocks/models/chromepayment.js
@@ -55,7 +55,12 @@ function proxyModel() {
},
'dw/util/ArrayList': ArrayList,
'*/cartridge/scripts/util/array': collections,
- 'dw/order/PaymentInstrument': {}
+ 'dw/order/PaymentInstrument': {},
+ 'dw/web/URLUtils': {
+ https: function(){
+ return 'some url';
+ }
+ },
});
}
diff --git a/test/unit/link_worldpay/scripts/checkout/checkoutHelpers.js b/test/unit/link_worldpay/scripts/checkout/checkoutHelpers.js
index 9cd76ce..bb2da86 100644
--- a/test/unit/link_worldpay/scripts/checkout/checkoutHelpers.js
+++ b/test/unit/link_worldpay/scripts/checkout/checkoutHelpers.js
@@ -28,6 +28,53 @@ describe('checkoutHelpers', function () {
return { order: 'failed order' };
}
};
+ var PaymentMgr = {
+ getApplicablePaymentMethods: function () {
+ return [
+ {
+ ID: 'GIFT_CERTIFICATE',
+ name: 'Gift Certificate'
+ },
+ {
+ ID: 'CREDIT_CARD',
+ name: 'Credit Card'
+ }
+ ];
+ },
+ getPaymentMethod: function () {
+ return {
+ getApplicablePaymentCards: function () {
+ return new ArrayList ([
+ {
+ cardType: 'Visa',
+ custom: { worldPayCardType: 'Visa' },
+ name: 'Visa',
+ UUID: 'some UUID'
+ },
+ {
+ cardType: 'Amex',
+ custom: { worldPayCardType: 'Amex' },
+ name: 'American Express',
+ UUID: 'some UUID'
+ },
+ {
+ cardType: 'Master Card',
+ custom: { worldPayCardType: 'Master Card' },
+ name: 'MasterCard'
+ },
+ {
+ cardType: 'Discover',
+ custom: { worldPayCardType: 'Discover' },
+ name: 'Discover'
+ }
+ ]);
+ }
+ };
+ },
+ getApplicablePaymentCards: function () {
+ return ['applicable payment cards'];
+ }
+ };
var order = {
setConfirmationStatus: setConfirmationStatusStub,
setExportStatus: setExportStatusStub
@@ -42,6 +89,7 @@ describe('checkoutHelpers', function () {
begin: function () {},
commit: function () {}
},
+ 'dw/order/PaymentMgr': PaymentMgr,
'dw/order/OrderMgr': orderMgr,
'dw/order/Order': order,
'dw/system/Status': status,