Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Express methods loader [SFRA] #844

Merged
merged 5 commits into from
Mar 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
const { checkIfExpressMethodsAreReady, updateLoadedExpressMethods } = require('./commons');

const AMAZON_PAY = 'amazonpay';

async function mountAmazonPayComponent() {
/**
* Makes an ajax call to the controller function GetPaymentMethods
Expand All @@ -9,8 +13,13 @@ async function mountAmazonPayComponent() {
success(data) {
paymentMethods(data);
},
error() {
updateLoadedExpressMethods(AMAZON_PAY);
checkIfExpressMethodsAreReady();
},
});
}

getPaymentMethods(async (data) => {
const paymentMethodsResponse = data.AdyenPaymentMethods;

Expand All @@ -21,7 +30,7 @@ async function mountAmazonPayComponent() {
});

const amazonPayConfig = paymentMethodsResponse.find(
(pm) => pm.type === 'amazonpay',
(pm) => pm.type === AMAZON_PAY,
)?.configuration;
if (!amazonPayConfig) return;

Expand All @@ -32,8 +41,10 @@ async function mountAmazonPayComponent() {
returnUrl: window.returnUrl,
};

const amazonPayButton = checkout.create('amazonpay', amazonPayButtonConfig);
const amazonPayButton = checkout.create(AMAZON_PAY, amazonPayButtonConfig);
amazonPayButton.mount('#amazonpay-container');
updateLoadedExpressMethods(AMAZON_PAY);
checkIfExpressMethodsAreReady();
});
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
const helpers = require('./adyen_checkout/helpers');
const { checkIfExpressMethodsAreReady } = require('./commons/index');
const { updateLoadedExpressMethods } = require('./commons');

const APPLE_PAY = 'applepay';
const isSafari = /^((?!chrome|android|ios).)*safari/i.test(navigator.userAgent);
Expand Down Expand Up @@ -112,9 +114,8 @@ function callPaymentFromComponent(data, resolveApplePay, rejectApplePay) {
success(response) {
helpers.createShowConfirmationForm(window.showConfirmationAction);
helpers.setOrderFormData(response);
document.querySelector('#additionalDetailsHidden').value = JSON.stringify(
data,
);
document.querySelector('#additionalDetailsHidden').value =
JSON.stringify(data);
handleApplePayResponse(response, resolveApplePay, rejectApplePay);
},
}).fail(() => {
Expand All @@ -123,174 +124,185 @@ function callPaymentFromComponent(data, resolveApplePay, rejectApplePay) {
}

if (isSafari) {
initializeCheckout().then(() => {
const applePayPaymentMethod = checkout.paymentMethodsResponse.paymentMethods.find(
(pm) => pm.type === APPLE_PAY,
);

if (!applePayPaymentMethod) {
return;
}
initializeCheckout()
.then(() => {
const applePayPaymentMethod =
checkout.paymentMethodsResponse.paymentMethods.find(
(pm) => pm.type === APPLE_PAY,
);

const applePayConfig = applePayPaymentMethod.configuration;
if (!applePayPaymentMethod) {
updateLoadedExpressMethods(APPLE_PAY);
checkIfExpressMethodsAreReady();
return;
}

const applePayButtonConfig = {
showPayButton: true,
configuration: applePayConfig,
amount: checkout.options.amount,
requiredShippingContactFields: ['postalAddress', 'email', 'phone'],
requiredBillingContactFields: ['postalAddress', 'phone'],
shippingMethods: shippingMethodsData.shippingMethods.map((sm) => ({
label: sm.displayName,
detail: sm.description,
identifier: sm.ID,
amount: `${sm.shippingCost.value}`,
})),
onAuthorized: async (resolve, reject, event) => {
try {
const customerData = event.payment.shippingContact;
const billingData = event.payment.billingContact;
const customer = formatCustomerObject(customerData, billingData);
const stateData = {
paymentMethod: {
type: APPLE_PAY,
applePayToken: event.payment.token.paymentData,
},
paymentType: 'express',
};
const applePayConfig = applePayPaymentMethod.configuration;

const resolveApplePay = () => {
const finalPriceUpdate = {
newTotal: {
type: 'final',
label: applePayConfig.merchantName,
amount: `${applePayButtonConfig.amount.value / 100}`,
const applePayButtonConfig = {
showPayButton: true,
configuration: applePayConfig,
amount: checkout.options.amount,
requiredShippingContactFields: ['postalAddress', 'email', 'phone'],
requiredBillingContactFields: ['postalAddress', 'phone'],
shippingMethods: shippingMethodsData.shippingMethods.map((sm) => ({
label: sm.displayName,
detail: sm.description,
identifier: sm.ID,
amount: `${sm.shippingCost.value}`,
})),
onAuthorized: async (resolve, reject, event) => {
try {
const customerData = event.payment.shippingContact;
const billingData = event.payment.billingContact;
const customer = formatCustomerObject(customerData, billingData);
const stateData = {
paymentMethod: {
type: APPLE_PAY,
applePayToken: event.payment.token.paymentData,
},
paymentType: 'express',
};
resolve(finalPriceUpdate);
};

await callPaymentFromComponent(
{ ...stateData, customer },
resolveApplePay,
reject,
);
} catch (error) {
reject(error);
}
},
onSubmit: () => {
// This handler is empty to prevent sending a second payment request
// We already do the payment in paymentFromComponent
},
onShippingMethodSelected: async (resolve, reject, event) => {
const { shippingMethod } = event;
const matchingShippingMethod = shippingMethodsData.shippingMethods.find(
(sm) => sm.ID === shippingMethod.identifier,
);
const calculationResponse = await fetch(
`${window.calculateAmountUrl}?${new URLSearchParams({
shipmentUUID: matchingShippingMethod.shipmentUUID,
methodID: matchingShippingMethod.ID,
})}`,
{
method: 'POST',
},
);
if (calculationResponse.ok) {
const newCalculation = await calculationResponse.json();
applePayButtonConfig.amount = {
value: newCalculation.grandTotalAmount.value,
currency: newCalculation.grandTotalAmount.currency,
};
const applePayShippingMethodUpdate = {
newTotal: {
type: 'final',
label: applePayConfig.merchantName,
amount: newCalculation.grandTotalAmount.value,
},
};
resolve(applePayShippingMethodUpdate);
} else {
reject();
}
},
onShippingContactSelected: async (resolve, reject, event) => {
const { shippingContact } = event;
const shippingMethods = await fetch(
`${window.shippingMethodsUrl}?${new URLSearchParams({
city: shippingContact.locality,
country: shippingContact.country,
countryCode: shippingContact.countryCode,
stateCode: shippingContact.administrativeArea,
})}`,
);
if (shippingMethods.ok) {
shippingMethodsData = await shippingMethods.json();
if (shippingMethodsData.shippingMethods?.length) {
const selectedShippingMethod =
shippingMethodsData.shippingMethods[0];
const calculationResponse = await fetch(
`${window.calculateAmountUrl}?${new URLSearchParams({
shipmentUUID: selectedShippingMethod.shipmentUUID,
methodID: selectedShippingMethod.ID,
})}`,
{
method: 'POST',
},
);
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,
const resolveApplePay = () => {
const finalPriceUpdate = {
newTotal: {
type: 'final',
label: applePayConfig.merchantName,
amount: newCalculation.grandTotalAmount.value,
amount: `${applePayButtonConfig.amount.value / 100}`,
},
};
resolve(applePayShippingContactUpdate);
resolve(finalPriceUpdate);
};

await callPaymentFromComponent(
{ ...stateData, customer },
resolveApplePay,
reject,
);
} catch (error) {
reject(error);
}
},
onSubmit: () => {
// This handler is empty to prevent sending a second payment request
// We already do the payment in paymentFromComponent
},
onShippingMethodSelected: async (resolve, reject, event) => {
const { shippingMethod } = event;
const matchingShippingMethod =
shippingMethodsData.shippingMethods.find(
(sm) => sm.ID === shippingMethod.identifier,
);
const calculationResponse = await fetch(
`${window.calculateAmountUrl}?${new URLSearchParams({
shipmentUUID: matchingShippingMethod.shipmentUUID,
methodID: matchingShippingMethod.ID,
})}`,
{
method: 'POST',
},
);
if (calculationResponse.ok) {
const newCalculation = await calculationResponse.json();
applePayButtonConfig.amount = {
value: newCalculation.grandTotalAmount.value,
currency: newCalculation.grandTotalAmount.currency,
};
const applePayShippingMethodUpdate = {
newTotal: {
type: 'final',
label: applePayConfig.merchantName,
amount: newCalculation.grandTotalAmount.value,
},
};
resolve(applePayShippingMethodUpdate);
} else {
reject();
}
},
onShippingContactSelected: async (resolve, reject, event) => {
const { shippingContact } = event;
const shippingMethods = await fetch(
`${window.shippingMethodsUrl}?${new URLSearchParams({
city: shippingContact.locality,
country: shippingContact.country,
countryCode: shippingContact.countryCode,
stateCode: shippingContact.administrativeArea,
})}`,
);
if (shippingMethods.ok) {
shippingMethodsData = await shippingMethods.json();
if (shippingMethodsData.shippingMethods?.length) {
const selectedShippingMethod =
shippingMethodsData.shippingMethods[0];
const calculationResponse = await fetch(
`${window.calculateAmountUrl}?${new URLSearchParams({
shipmentUUID: selectedShippingMethod.shipmentUUID,
methodID: selectedShippingMethod.ID,
})}`,
{
method: 'POST',
},
);
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: applePayConfig.merchantName,
amount: newCalculation.grandTotalAmount.value,
},
};
resolve(applePayShippingContactUpdate);
} else {
reject();
}
} else {
reject();
}
} else {
reject();
}
} else {
reject();
}
},
};
},
};

const cartContainer = document.getElementsByClassName('applepay');
for (
let expressCheckoutNodesIndex = 0;
expressCheckoutNodesIndex < cartContainer.length;
expressCheckoutNodesIndex += 1
) {
createApplePayButton(applePayButtonConfig).then((applePayButton) => {
const isApplePayButtonAvailable = applePayButton.isAvailable();
if (isApplePayButtonAvailable) {
applePayButton.mount(cartContainer[expressCheckoutNodesIndex]);
}
});
}
});
const cartContainer = document.getElementsByClassName(APPLE_PAY);
for (
let expressCheckoutNodesIndex = 0;
expressCheckoutNodesIndex < cartContainer.length;
expressCheckoutNodesIndex += 1
) {
createApplePayButton(applePayButtonConfig).then((applePayButton) => {
const isApplePayButtonAvailable = applePayButton.isAvailable();
if (isApplePayButtonAvailable) {
applePayButton.mount(cartContainer[expressCheckoutNodesIndex]);
}
});
}
updateLoadedExpressMethods(APPLE_PAY);
checkIfExpressMethodsAreReady();
})
.catch(() => {
updateLoadedExpressMethods(APPLE_PAY);
checkIfExpressMethodsAreReady();
});
} else {
updateLoadedExpressMethods(APPLE_PAY);
checkIfExpressMethodsAreReady();
}

module.exports = {
createApplePayButton,
formatCustomerObject,
handleAuthorised,
handleError,
handleApplePayResponse,
callPaymentFromComponent,
}
};
Loading