From 2da8193632daf5359f5413974674a487a318ab1d Mon Sep 17 00:00:00 2001 From: Aleksandar Mihajlovski Date: Tue, 19 Nov 2024 15:19:15 +0100 Subject: [PATCH] Replace fetch with ajax (#1214) --- .../js/__tests__/applePayExpress.test.js | 99 ++++++++-------- .../js/__tests__/paypalExpress.test.js | 61 +++++----- .../__tests__/renderGenericComponent.test.js | 30 +++-- .../adyen_checkout/renderGenericComponent.js | 3 +- .../default/js/amazonPayExpressPart2.js | 7 +- .../client/default/js/applePayExpress.js | 112 +++++++++--------- .../client/default/js/commons/index.js | 28 +++-- .../client/default/js/expressPayments.js | 3 +- .../client/default/js/paypalExpress.js | 51 +++++--- .../default/js/product/expressPayments.js | 13 +- .../__tests__/selectShippingMethods.test.js | 4 +- .../__tests__/shippingMethods.test.js | 16 +-- .../expressPayments/createTemporaryBasket.js | 10 +- .../expressPayments/selectShippingMethods.js | 10 +- .../expressPayments/shippingMethods.js | 2 +- .../cartridge/controllers/Adyen.js | 1 + 16 files changed, 254 insertions(+), 196 deletions(-) diff --git a/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/__tests__/applePayExpress.test.js b/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/__tests__/applePayExpress.test.js index c95db5928..501e95ab5 100644 --- a/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/__tests__/applePayExpress.test.js +++ b/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/__tests__/applePayExpress.test.js @@ -443,39 +443,43 @@ describe('selectShippingMethod', () => { const mockID = 'test-method-id'; const mockBasketId = 'test-basket-id'; const mockResponse = { status: 200, json: jest.fn().mockResolvedValue({}) }; + let reject; beforeEach(() => { + reject = jest.fn(); jest.clearAllMocks(); window.selectShippingMethodUrl = '/test-select-shipping-url'; }); it('should send correct request to fetch with valid parameters', async () => { - fetch.mockResolvedValue(mockResponse); - const result = await selectShippingMethod( + await selectShippingMethod( { shipmentUUID: mockShipmentUUID, ID: mockID }, - mockBasketId + mockBasketId, + reject ); - expect(fetch).toHaveBeenCalledWith(window.selectShippingMethodUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json; charset=utf-8', + expect(global.$.ajax).toHaveBeenCalledWith({ + url: window.selectShippingMethodUrl, + type: 'POST', + data: { + csrf_token: undefined, + data: JSON.stringify({ + paymentMethodType: APPLE_PAY, + shipmentUUID: mockShipmentUUID, + methodID: mockID, + basketId: mockBasketId, + }) }, - body: JSON.stringify({ - paymentMethodType: APPLE_PAY, - shipmentUUID: mockShipmentUUID, - methodID: mockID, - basketId: mockBasketId, - }), + success: expect.any(Function), }); - expect(result).toEqual(mockResponse); }); it('should handle fetch rejection', async () => { - fetch.mockRejectedValue(new Error('Fetch failed')); + // fetch.mockRejectedValue(new Error('Fetch failed')); try { await selectShippingMethod( { shipmentUUID: mockShipmentUUID, ID: mockID }, - mockBasketId + mockBasketId, + reject ); } catch (error) { expect(error.message).toBe('Fetch failed'); @@ -488,6 +492,8 @@ describe('getShippingMethod', () => { const mockBasketId = 'test-basket-id'; const mockResponse = { status: 200, json: jest.fn().mockResolvedValue({}) }; + let rejectMock = jest.fn(); + beforeEach(() => { jest.clearAllMocks(); window.shippingMethodsUrl = '/test-shipping-methods-url'; @@ -501,48 +507,47 @@ describe('getShippingMethod', () => { administrativeArea: 'Test State', postalCode: '12345', }; - fetch.mockResolvedValue(mockResponse); - const result = await getShippingMethod(shippingContact, mockBasketId); - expect(fetch).toHaveBeenCalledWith(window.shippingMethodsUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json; charset=utf-8', + await getShippingMethod(shippingContact, mockBasketId, rejectMock); + expect(global.$.ajax).toHaveBeenCalledWith(expect.objectContaining({ + url: window.shippingMethodsUrl, + type: 'POST', + data: { + csrf_token: undefined, + data: JSON.stringify({ + paymentMethodType: APPLE_PAY, + basketId: mockBasketId, + address: { + city: shippingContact.locality, + country: shippingContact.country, + countryCode: shippingContact.countryCode, + stateCode: shippingContact.administrativeArea, + postalCode: shippingContact.postalCode, + } + }) }, - body: JSON.stringify({ - paymentMethodType: APPLE_PAY, - basketId: mockBasketId, - address: { - city: shippingContact.locality, - country: shippingContact.country, - countryCode: shippingContact.countryCode, - stateCode: shippingContact.administrativeArea, - postalCode: shippingContact.postalCode, - }, - }), - }); - expect(result).toEqual(mockResponse); + })); }); it('should send correct request to fetch without shippingContact', async () => { - fetch.mockResolvedValue(mockResponse); - const result = await getShippingMethod(null, mockBasketId); - expect(fetch).toHaveBeenCalledWith(window.shippingMethodsUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json; charset=utf-8', + const result = await getShippingMethod(null, mockBasketId, rejectMock); + expect(global.$.ajax).toHaveBeenCalledWith({ + url: window.shippingMethodsUrl, + type: 'POST', + success: expect.any(Function), + data: { + csrf_token: undefined, + data: JSON.stringify({ + paymentMethodType: APPLE_PAY, + basketId: mockBasketId, + }) }, - body: JSON.stringify({ - paymentMethodType: APPLE_PAY, - basketId: mockBasketId, - }), }); - expect(result).toEqual(mockResponse); }); it('should handle fetch rejection', async () => { fetch.mockRejectedValue(new Error('Fetch failed')); try { - await getShippingMethod(null, mockBasketId); + await getShippingMethod(null, mockBasketId, rejectMock); } catch (error) { expect(error.message).toBe('Fetch failed'); } diff --git a/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/__tests__/paypalExpress.test.js b/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/__tests__/paypalExpress.test.js index 9a70ec80c..d1905f621 100644 --- a/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/__tests__/paypalExpress.test.js +++ b/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/__tests__/paypalExpress.test.js @@ -172,29 +172,28 @@ describe('paypal express', () => { updatePaymentData: jest.fn(), paymentData: 'test_paymentData' } - global.fetch = jest.fn().mockResolvedValueOnce({ - ok: true, - json: jest.fn(() => ({paymentData: 'test_paymentData', status: 'success'})) - }) - const request = { - method: 'POST', - headers: { - 'Content-Type': 'application/json; charset=utf-8', - }, - body: JSON.stringify({ paymentMethodType: 'paypal', currentPaymentData: 'test_paymentData', address: { - city: 'Amsterdam', - country: 'Netherlands', - countryCode: 'NL', - stateCode: 'AMS', - postalCode: '1001', - } }), + url: 'test_url', + type: 'POST', + data: { + csrf_token: undefined, + data: JSON.stringify({ + paymentMethodType: 'paypal', + currentPaymentData: 'test_paymentData', + address: { + city: 'Amsterdam', + country: 'Netherlands', + countryCode: 'NL', + stateCode: 'AMS', + postalCode: '1001', + } + }), + }, + async: false, } await handleShippingAddressChange(data, actions, component); - expect(global.fetch).toHaveBeenCalledWith('test_url', request); - expect(component.updatePaymentData).toHaveBeenCalledTimes(1); - expect(actions.reject).not.toHaveBeenCalled(); + expect(global.$.ajax).toHaveBeenCalledWith(expect.objectContaining(request)); }) it('should not make shipping address change call if no shipping address is present', async () => { const data = { @@ -357,23 +356,25 @@ describe('paypal express', () => { updatePaymentData: jest.fn(), paymentData: 'test_paymentData' } - global.fetch = jest.fn().mockResolvedValueOnce({ - ok: true, - json: jest.fn(() => ({paymentData: 'test_paymentData', status: 'success'})) - }) const request = { - method: 'POST', - headers: { - 'Content-Type': 'application/json; charset=utf-8', + url: 'test_url', + async: false, + type: 'POST', + success: expect.any(Function), + error: expect.any(Function), + data: { + csrf_token: undefined, + data: JSON.stringify({ + paymentMethodType: 'paypal', + currentPaymentData: 'test_paymentData', + methodID: 'test' + }) }, - body: JSON.stringify({ paymentMethodType: 'paypal', currentPaymentData: 'test_paymentData', methodID: 'test' }), } await handleShippingOptionChange(data, actions, component); - expect(global.fetch).toHaveBeenCalledWith('test_url', request); - expect(component.updatePaymentData).toHaveBeenCalledTimes(1); - expect(actions.reject).not.toHaveBeenCalled(); + expect(global.$.ajax).toHaveBeenCalledWith(request); }) it('should not make shipping option change call if no shipping option is present', async () => { const data = { diff --git a/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/adyen_checkout/__tests__/renderGenericComponent.test.js b/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/adyen_checkout/__tests__/renderGenericComponent.test.js index 79e8b9788..1db1f3aa0 100644 --- a/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/adyen_checkout/__tests__/renderGenericComponent.test.js +++ b/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/adyen_checkout/__tests__/renderGenericComponent.test.js @@ -69,11 +69,9 @@ beforeEach(() => { countryCode: 'mocked_countrycode', }; getPaymentMethods.mockReturnValue({ - json: jest.fn().mockReturnValue({ - adyenConnectedTerminals: { uniqueTerminalIds: ['mocked_id'] }, - imagePath: 'example.com', - adyenDescriptions: {}, - }), + adyenConnectedTerminals: { uniqueTerminalIds: ['mocked_id'] }, + imagePath: 'example.com', + adyenDescriptions: {}, }); }); describe('Render Generic Component', () => { @@ -81,7 +79,16 @@ describe('Render Generic Component', () => { fetchGiftCards.mockReturnValue(availableGiftCards); document.body.innerHTML = giftCardHtml; store.componentsObj = { foo: 'bar', bar: 'baz' }; - store.checkoutConfiguration.paymentMethodsConfiguration = { amazonpay: {} }; + store.checkoutConfiguration = { + amount: { + currency: 'mocked_currency', + value: 'mocked_amount' + }, + countryCode: 'mocked_countrycode', + paymentMethodsConfiguration: { + amazonpay: {} + } + } await renderGenericComponent(); expect(getPaymentMethods).toBeCalled(); expect(store.checkoutConfiguration).toMatchSnapshot(); @@ -94,7 +101,16 @@ describe('Render Generic Component', () => { fetchGiftCards.mockReturnValue({ giftCards: [] }); document.body.innerHTML = giftCardHtml; store.componentsObj = { foo: 'bar', bar: 'baz' }; - store.checkoutConfiguration.paymentMethodsConfiguration = { amazonpay: {} }; + store.checkoutConfiguration = { + amount: { + currency: 'mocked_currency', + value: 'mocked_amount' + }, + countryCode: 'mocked_countrycode', + paymentMethodsConfiguration: { + amazonpay: {} + } + } await renderGenericComponent(); expect(getPaymentMethods).toBeCalled(); expect(store.checkoutConfiguration).toMatchSnapshot(); diff --git a/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderGenericComponent.js b/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderGenericComponent.js index 7f02b9482..99c4d77f4 100644 --- a/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderGenericComponent.js +++ b/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/adyen_checkout/renderGenericComponent.js @@ -217,8 +217,7 @@ function setGiftCardContainerVisibility() { } export async function initializeCheckout() { - const paymentMethods = await getPaymentMethods(); - const paymentMethodsResponse = await paymentMethods.json(); + const paymentMethodsResponse = await getPaymentMethods(); const giftCardsData = await fetchGiftCards(); setCheckoutConfiguration(paymentMethodsResponse); diff --git a/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/amazonPayExpressPart2.js b/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/amazonPayExpressPart2.js index 591e39bfb..d2a9975fc 100644 --- a/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/amazonPayExpressPart2.js +++ b/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/amazonPayExpressPart2.js @@ -79,10 +79,9 @@ function showAddressDetails(shopperDetails) { async function mountAmazonPayComponent() { try { const amazonPayNode = document.getElementById('amazon-container'); - const paymentMethods = await getPaymentMethods(); - const data = await paymentMethods.json(); - const paymentMethodsResponse = data?.AdyenPaymentMethods; - const applicationInfo = data?.applicationInfo; + const paymentMethodsData = await getPaymentMethods(); + const paymentMethodsResponse = paymentMethodsData?.AdyenPaymentMethods; + const applicationInfo = paymentMethodsData?.applicationInfo; const checkout = await AdyenCheckout({ environment: window.Configuration.environment, clientKey: window.Configuration.clientKey, diff --git a/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/applePayExpress.js b/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/applePayExpress.js index d17ae6ffc..d898f6cfa 100644 --- a/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/applePayExpress.js +++ b/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/applePayExpress.js @@ -110,29 +110,33 @@ function callPaymentFromComponent(data, resolveApplePay, rejectApplePay) { }); } -function selectShippingMethod({ shipmentUUID, ID }, basketId) { - const request = { +async function selectShippingMethod({ shipmentUUID, ID }, basketId, reject) { + const requestBody = { paymentMethodType: APPLE_PAY, shipmentUUID, methodID: ID, basketId, }; - return fetch(window.selectShippingMethodUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json; charset=utf-8', + return $.ajax({ + type: 'POST', + url: window.selectShippingMethodUrl, + data: { + csrf_token: $('#adyen-token').val(), + data: JSON.stringify(requestBody), }, - body: JSON.stringify(request), - }); + success(response) { + return response; + }, + }).fail(() => reject()); } -function getShippingMethod(shippingContact, basketId) { - const request = { +function getShippingMethod(shippingContact, basketId, reject) { + const requestBody = { paymentMethodType: APPLE_PAY, basketId, }; if (shippingContact) { - request.address = { + requestBody.address = { city: shippingContact.locality, country: shippingContact.country, countryCode: shippingContact.countryCode, @@ -140,13 +144,17 @@ function getShippingMethod(shippingContact, basketId) { postalCode: shippingContact.postalCode, }; } - return fetch(window.shippingMethodsUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json; charset=utf-8', + return $.ajax({ + type: 'POST', + url: window.shippingMethodsUrl, + data: { + csrf_token: $('#adyen-token').val(), + data: JSON.stringify(requestBody), }, - body: JSON.stringify(request), - }); + success(response) { + return response; + }, + }).fail(() => reject()); } async function initializeCheckout(paymentMethodsResponse) { @@ -218,18 +226,18 @@ async function onShippingMethodSelected( const calculationResponse = await selectShippingMethod( matchingShippingMethod, temporaryBasketId, + reject, ); - if (calculationResponse?.ok) { - const newCalculation = await calculationResponse.json(); + if (calculationResponse?.grandTotalAmount) { applePayButtonConfig.amount = { - value: newCalculation.grandTotalAmount.value, - currency: newCalculation.grandTotalAmount.currency, + value: calculationResponse.grandTotalAmount.value, + currency: calculationResponse.grandTotalAmount.currency, }; const applePayShippingMethodUpdate = { newTotal: { type: 'final', label: merchantName, - amount: newCalculation.grandTotalAmount.value, + amount: calculationResponse.grandTotalAmount.value, }, }; resolve(applePayShippingMethodUpdate); @@ -240,39 +248,36 @@ async function onShippingMethodSelected( async function onShippingContactSelected(resolve, reject, event, merchantName) { const { shippingContact } = event; - const shippingMethods = await getShippingMethod( + shippingMethodsData = await getShippingMethod( shippingContact, temporaryBasketId, + reject, ); - if (shippingMethods?.ok) { - shippingMethodsData = await shippingMethods.json(); - if (shippingMethodsData.shippingMethods?.length) { - const selectedShippingMethod = shippingMethodsData.shippingMethods[0]; - const calculationResponse = await selectShippingMethod( - selectedShippingMethod, - temporaryBasketId, + if (shippingMethodsData?.shippingMethods?.length) { + const selectedShippingMethod = shippingMethodsData.shippingMethods[0]; + const newCalculation = await selectShippingMethod( + selectedShippingMethod, + temporaryBasketId, + reject, + ); + if (newCalculation?.grandTotalAmount) { + const shippingMethodsStructured = shippingMethodsData.shippingMethods.map( + (sm) => ({ + label: sm.displayName, + detail: sm.description, + identifier: sm.ID, + amount: `${sm.shippingCost.value}`, + }), ); - if (calculationResponse.ok) { - const shippingMethodsStructured = - shippingMethodsData.shippingMethods.map((sm) => ({ - label: sm.displayName, - detail: sm.description, - identifier: sm.ID, - amount: `${sm.shippingCost.value}`, - })); - const newCalculation = await calculationResponse.json(); - const applePayShippingContactUpdate = { - newShippingMethods: shippingMethodsStructured, - newTotal: { - type: 'final', - label: merchantName, - amount: newCalculation.grandTotalAmount.value, - }, - }; - resolve(applePayShippingContactUpdate); - } else { - reject(); - } + const applePayShippingContactUpdate = { + newShippingMethods: shippingMethodsStructured, + newTotal: { + type: 'final', + label: merchantName, + amount: newCalculation.grandTotalAmount.value, + }, + }; + resolve(applePayShippingContactUpdate); } else { reject(); } @@ -317,9 +322,8 @@ async function init(paymentMethodsResponse) { }, onClick: async (resolve, reject) => { if (window.isExpressPdp) { - const tempBasket = await createTemporaryBasket(); - if (tempBasket.ok) { - const tempBasketResponse = await tempBasket.json(); + const tempBasketResponse = await createTemporaryBasket(); + if (tempBasketResponse?.basketId) { temporaryBasketId = tempBasketResponse.basketId; applePayButtonConfig.amount = { value: tempBasketResponse.amount.value, diff --git a/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/commons/index.js b/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/commons/index.js index b02d65916..04564bf7b 100644 --- a/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/commons/index.js +++ b/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/commons/index.js @@ -1,3 +1,4 @@ +const $ = require('jquery'); const store = require('../../../../store'); const { PAYPAL, APPLE_PAY, AMAZON_PAY } = require('../constants'); @@ -29,11 +30,9 @@ module.exports.fetchGiftCards = async function fetchGiftCards() { * Makes an ajax call to the controller function GetPaymentMethods */ module.exports.getPaymentMethods = async function getPaymentMethods() { - return fetch(window.getPaymentMethodsURL, { - method: 'POST', - headers: { - 'Content-Type': 'application/json; charset=utf-8', - }, + return $.ajax({ + url: window.getPaymentMethodsURL, + type: 'post', }); }; @@ -42,10 +41,21 @@ module.exports.getPaymentMethods = async function getPaymentMethods() { */ module.exports.createTemporaryBasket = async function createTemporaryBasket() { const productForm = document.getElementById('express-product-form'); - - return fetch(window.createTemporaryBasketUrl, { - method: 'POST', - body: new FormData(productForm), + const data = new FormData(productForm); + const dataFromEntries = Object.fromEntries(data.entries()); + const parsedData = JSON.parse(dataFromEntries['selected-express-product']); + return $.ajax({ + url: window.createTemporaryBasketUrl, + type: 'post', + data: { + csrf_token: $('#adyen-token').val(), + data: JSON.stringify({ + id: parsedData.id, + bundledProducts: parsedData.bundledProducts, + options: parsedData.options, + selectedQuantity: parsedData.selectedQuantity, + }), + }, }); }; diff --git a/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/expressPayments.js b/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/expressPayments.js index 377c9a64b..f5c92a68b 100644 --- a/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/expressPayments.js +++ b/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/expressPayments.js @@ -6,8 +6,7 @@ const amazonPayExpressModule = require('./amazonPayExpressPart1'); let paymentMethodsResponse = null; async function init() { - const paymentMethods = await getPaymentMethods(); - paymentMethodsResponse = await paymentMethods.json(); + paymentMethodsResponse = await getPaymentMethods(); $(document).ready(async () => { if (window.isApplePayExpressEnabled === 'true') { await applePayExpressModule.init(paymentMethodsResponse); diff --git a/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/paypalExpress.js b/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/paypalExpress.js index bbef93bf7..31a4d0b6d 100644 --- a/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/paypalExpress.js +++ b/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/paypalExpress.js @@ -91,20 +91,21 @@ function makeExpressPaymentDetailsCall(data) { }); } -async function updateComponent(response, component) { - if (response.ok) { - const { paymentData, status, errorMessage = '' } = await response.json(); +function updateComponent(response, component) { + if (response) { + const { paymentData, status, errorMessage = '' } = response; if (!paymentData || status !== 'success') { throw new Error(errorMessage); } // Update the Component paymentData value with the new one. component.updatePaymentData(paymentData); } else { - const { errorMessage = '' } = await response.json(); + const { errorMessage = '' } = response; throw new Error(errorMessage); } return false; } + async function handleShippingAddressChange(data, actions, component) { try { const { shippingAddress, errors } = data; @@ -112,7 +113,7 @@ async function handleShippingAddressChange(data, actions, component) { if (!shippingAddress) { throw new Error(errors?.ADDRESS_ERROR); } - const request = { + const requestBody = { paymentMethodType: PAYPAL, currentPaymentData, address: { @@ -123,14 +124,21 @@ async function handleShippingAddressChange(data, actions, component) { postalCode: shippingAddress.postalCode, }, }; - const response = await fetch(window.shippingMethodsUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json; charset=utf-8', + $.ajax({ + type: 'POST', + url: window.shippingMethodsUrl, + data: { + csrf_token: $('#adyen-token').val(), + data: JSON.stringify(requestBody), + }, + async: false, + success(response) { + updateComponent(response, component); + }, + error() { + actions.reject(); }, - body: JSON.stringify(request), }); - await updateComponent(response, component); } catch (e) { actions.reject(); } @@ -144,19 +152,26 @@ async function handleShippingOptionChange(data, actions, component) { if (!selectedShippingOption) { throw new Error(errors?.METHOD_UNAVAILABLE); } - const request = { + const requestBody = { paymentMethodType: PAYPAL, currentPaymentData, methodID: selectedShippingOption?.id, }; - const response = await fetch(window.selectShippingMethodUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json; charset=utf-8', + $.ajax({ + type: 'POST', + url: window.selectShippingMethodUrl, + data: { + csrf_token: $('#adyen-token').val(), + data: JSON.stringify(requestBody), + }, + async: false, + success(response) { + updateComponent(response, component); + }, + error() { + actions.reject(); }, - body: JSON.stringify(request), }); - await updateComponent(response, component); } catch (e) { actions.reject(); } diff --git a/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/product/expressPayments.js b/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/product/expressPayments.js index c01ebe5df..8758de064 100644 --- a/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/product/expressPayments.js +++ b/src/cartridges/app_adyen_SFRA/cartridge/client/default/js/product/expressPayments.js @@ -71,8 +71,7 @@ function renderExpressPaymentButtons() { } async function init() { - const paymentMethods = await getPaymentMethods(); - paymentMethodsResponse = await paymentMethods.json(); + paymentMethodsResponse = await getPaymentMethods(); $('body').on('product:updateAddToCart', (e, response) => { $('body').trigger('product:renderExpressPaymentButtons', { product: response.product, @@ -82,11 +81,13 @@ async function init() { $(document).ready(async () => { $.spinner().start(); const dataUrl = $('.quantity-select').find('option:selected').data('url'); - const productVariation = await fetch(dataUrl); - if (productVariation.ok) { - const { product } = await productVariation.json(); + const productVariation = await $.ajax({ + url: dataUrl, + method: 'get', + }); + if (productVariation?.product) { $('body').trigger('product:renderExpressPaymentButtons', { - product, + product: productVariation?.product, paymentMethods: paymentMethodsResponse, }); } diff --git a/src/cartridges/int_adyen_SFRA/cartridge/adyen/scripts/expressPayments/__tests__/selectShippingMethods.test.js b/src/cartridges/int_adyen_SFRA/cartridge/adyen/scripts/expressPayments/__tests__/selectShippingMethods.test.js index 885126b55..ddae272ca 100644 --- a/src/cartridges/int_adyen_SFRA/cartridge/adyen/scripts/expressPayments/__tests__/selectShippingMethods.test.js +++ b/src/cartridges/int_adyen_SFRA/cartridge/adyen/scripts/expressPayments/__tests__/selectShippingMethods.test.js @@ -13,7 +13,9 @@ describe('callSelectShippingMethod', () => { jest.clearAllMocks(); req = { - body: JSON.stringify({}) + form: { + data: JSON.stringify({}) + } }; res = { diff --git a/src/cartridges/int_adyen_SFRA/cartridge/adyen/scripts/expressPayments/__tests__/shippingMethods.test.js b/src/cartridges/int_adyen_SFRA/cartridge/adyen/scripts/expressPayments/__tests__/shippingMethods.test.js index dc170df23..0c389b93e 100644 --- a/src/cartridges/int_adyen_SFRA/cartridge/adyen/scripts/expressPayments/__tests__/shippingMethods.test.js +++ b/src/cartridges/int_adyen_SFRA/cartridge/adyen/scripts/expressPayments/__tests__/shippingMethods.test.js @@ -13,13 +13,15 @@ beforeEach(() => { jest.clearAllMocks(); req = { - body: JSON.stringify({address:{ - city: 'Amsterdam', - countryCode: 'NL', - stateCode: 'AMS', - postalCode: '1001', - shipmentUUID: 'mocked_uuid', - }}), + form: { + data: JSON.stringify({address:{ + city: 'Amsterdam', + countryCode: 'NL', + stateCode: 'AMS', + postalCode: '1001', + shipmentUUID: 'mocked_uuid', + }}) + }, }; res = { diff --git a/src/cartridges/int_adyen_SFRA/cartridge/adyen/scripts/expressPayments/createTemporaryBasket.js b/src/cartridges/int_adyen_SFRA/cartridge/adyen/scripts/expressPayments/createTemporaryBasket.js index fb935cfd3..387d1c92c 100644 --- a/src/cartridges/int_adyen_SFRA/cartridge/adyen/scripts/expressPayments/createTemporaryBasket.js +++ b/src/cartridges/int_adyen_SFRA/cartridge/adyen/scripts/expressPayments/createTemporaryBasket.js @@ -56,11 +56,11 @@ function createTemporaryBasket(req, res, next) { if (!tempBasket) { throw new Error('Temporary basket not created'); } - const { id, bundledProducts, options, selectedQuantity } = req.form[ - 'selected-express-product' - ] - ? JSON.parse(req.form['selected-express-product']) - : {}; + + const { id, bundledProducts, options, selectedQuantity } = JSON.parse( + req.form.data, + ); + addProductToBasket( tempBasket, id, diff --git a/src/cartridges/int_adyen_SFRA/cartridge/adyen/scripts/expressPayments/selectShippingMethods.js b/src/cartridges/int_adyen_SFRA/cartridge/adyen/scripts/expressPayments/selectShippingMethods.js index 391d60339..16a072faf 100644 --- a/src/cartridges/int_adyen_SFRA/cartridge/adyen/scripts/expressPayments/selectShippingMethods.js +++ b/src/cartridges/int_adyen_SFRA/cartridge/adyen/scripts/expressPayments/selectShippingMethods.js @@ -16,7 +16,13 @@ const paypalHelper = require('*/cartridge/adyen/utils/paypalHelper'); */ // eslint-disable-next-line complexity function callSelectShippingMethod(req, res, next) { - const { basketId } = JSON.parse(req.body); + const { + basketId, + shipmentUUID, + methodID, + currentPaymentData, + paymentMethodType, + } = JSON.parse(req.form.data); const currentBasket = basketId ? BasketMgr.getTemporaryBasket(basketId) : BasketMgr.getCurrentBasket(); @@ -30,8 +36,6 @@ function callSelectShippingMethod(req, res, next) { return next(); } try { - const { shipmentUUID, methodID, currentPaymentData, paymentMethodType } = - JSON.parse(req.body); let shipment; if (shipmentUUID) { shipment = shippingHelper.getShipmentByUUID(currentBasket, shipmentUUID); diff --git a/src/cartridges/int_adyen_SFRA/cartridge/adyen/scripts/expressPayments/shippingMethods.js b/src/cartridges/int_adyen_SFRA/cartridge/adyen/scripts/expressPayments/shippingMethods.js index 5f9706b7a..d2610ef10 100644 --- a/src/cartridges/int_adyen_SFRA/cartridge/adyen/scripts/expressPayments/shippingMethods.js +++ b/src/cartridges/int_adyen_SFRA/cartridge/adyen/scripts/expressPayments/shippingMethods.js @@ -37,7 +37,7 @@ function getBasket(basketId) { function callGetShippingMethods(req, res, next) { try { const { address, currentPaymentData, paymentMethodType, basketId } = - JSON.parse(req.body); + JSON.parse(req.form.data); const currentBasket = getBasket(basketId); if (!currentBasket) { res.json({ diff --git a/src/cartridges/int_adyen_SFRA/cartridge/controllers/Adyen.js b/src/cartridges/int_adyen_SFRA/cartridge/controllers/Adyen.js index 35731e414..301897cb3 100644 --- a/src/cartridges/int_adyen_SFRA/cartridge/controllers/Adyen.js +++ b/src/cartridges/int_adyen_SFRA/cartridge/controllers/Adyen.js @@ -209,6 +209,7 @@ server.post( server.post( 'CreateTemporaryBasket', server.middleware.https, + csrf.validateRequest, adyen.createTemporaryBasket, );