woocommerce-paypal-payments/modules/ppcp-blocks/resources/js/checkout-block.js

409 lines
14 KiB
JavaScript
Raw Normal View History

2022-12-20 16:04:11 +02:00
import {useEffect, useState} from '@wordpress/element';
2023-04-07 15:58:59 +03:00
import {registerExpressPaymentMethod, registerPaymentMethod} from '@woocommerce/blocks-registry';
2023-10-27 09:59:55 +03:00
import {mergeWcAddress, paypalAddressToWc, paypalOrderToWcAddresses} from "./Helper/Address";
import {
loadPaypalScriptPromise
} from '../../../ppcp-button/resources/js/modules/Helper/ScriptLoading'
import {
normalizeStyleForFundingSource
} from '../../../ppcp-button/resources/js/modules/Helper/Style'
2023-08-28 17:19:07 +01:00
import buttonModuleWatcher from "../../../ppcp-button/resources/js/modules/ButtonModuleWatcher";
import BlockCheckoutMessagesBootstrap from "./Bootstrap/BlockCheckoutMessagesBootstrap";
2022-12-20 16:04:11 +02:00
const config = wc.wcSettings.getSetting('ppcp-gateway_data');
2023-04-21 11:12:32 +03:00
window.ppcpFundingSource = config.fundingSource;
let registeredContext = false;
let paypalScriptPromise = null;
2022-12-20 16:04:11 +02:00
const PayPalComponent = ({
onClick,
onClose,
onSubmit,
onError,
2022-12-20 16:04:11 +02:00
eventRegistration,
emitResponse,
2023-03-27 10:59:08 +03:00
activePaymentMethod,
shippingData,
2023-07-11 09:15:36 +03:00
isEditing,
fundingSource,
2022-12-20 16:04:11 +02:00
}) => {
2023-10-19 15:55:57 +03:00
const {onPaymentSetup, onCheckoutFail, onCheckoutValidation} = eventRegistration;
2022-12-20 16:04:11 +02:00
const {responseTypes} = emitResponse;
const [paypalOrder, setPaypalOrder] = useState(null);
2023-12-14 09:39:02 +00:00
const [gotoContinuationOnError, setGotoContinuationOnError] = useState(false);
2022-12-20 16:04:11 +02:00
const [paypalScriptLoaded, setPaypalScriptLoaded] = useState(false);
if (!paypalScriptLoaded) {
if (!paypalScriptPromise) {
// for editor, since canMakePayment was not called
paypalScriptPromise = loadPaypalScriptPromise(config.scriptData)
}
paypalScriptPromise.then(() => setPaypalScriptLoaded(true));
}
2023-11-23 08:46:48 +02:00
const methodId = fundingSource ? `${config.id}-${fundingSource}` : config.id;
2023-10-23 20:59:49 +03:00
useEffect(() => {
// fill the form if in continuation (for product or mini-cart buttons)
if (!config.scriptData.continuation || !config.scriptData.continuation.order || window.ppcpContinuationFilled) {
return;
}
try {
const paypalAddresses = paypalOrderToWcAddresses(config.scriptData.continuation.order);
const wcAddresses = wp.data.select('wc/store/cart').getCustomerData();
const addresses = mergeWcAddress(wcAddresses, paypalAddresses);
wp.data.dispatch('wc/store/cart').setBillingAddress(addresses.billingAddress);
if (shippingData.needsShipping) {
wp.data.dispatch('wc/store/cart').setShippingAddress(addresses.shippingAddress);
}
} catch (err) {
// sometimes the PayPal address is missing, skip in this case.
console.log(err);
2023-10-23 20:59:49 +03:00
}
// this useEffect should run only once, but adding this in case of some kind of full re-rendering
window.ppcpContinuationFilled = true;
}, [])
2022-12-20 16:04:11 +02:00
const createOrder = async () => {
try {
const res = await fetch(config.scriptData.ajax.create_order.endpoint, {
method: 'POST',
credentials: 'same-origin',
body: JSON.stringify({
nonce: config.scriptData.ajax.create_order.nonce,
bn_code: '',
2023-04-22 13:16:42 +03:00
context: config.scriptData.context,
2022-12-20 16:04:11 +02:00
payment_method: 'ppcp-gateway',
createaccount: false
}),
});
const json = await res.json();
if (!json.success) {
if (json.data?.details?.length > 0) {
throw new Error(json.data.details.map(d => `${d.issue} ${d.description}`).join('<br/>'));
} else if (json.data?.message) {
throw new Error(json.data.message);
}
throw new Error(config.scriptData.labels.error.generic);
}
return json.data.id;
} catch (err) {
console.error(err);
onError(err.message);
2022-12-20 16:04:11 +02:00
onClose();
throw err;
}
};
const getCheckoutRedirectUrl = () => {
const checkoutUrl = new URL(config.scriptData.redirect);
// sometimes some browsers may load some kind of cached version of the page,
// so adding a parameter to avoid that
checkoutUrl.searchParams.append('ppcp-continuation-redirect', (new Date()).getTime().toString());
return checkoutUrl.toString();
}
2022-12-20 16:04:11 +02:00
const handleApprove = async (data, actions) => {
try {
const order = await actions.order.get();
if (order) {
const addresses = paypalOrderToWcAddresses(order);
let promises = [
// save address on server
wp.data.dispatch('wc/store/cart').updateCustomerData({
billing_address: addresses.billingAddress,
shipping_address: addresses.shippingAddress,
}),
];
if (!config.finalReviewEnabled) {
// set address in UI
promises.push(wp.data.dispatch('wc/store/cart').setBillingAddress(addresses.billingAddress));
if (shippingData.needsShipping) {
promises.push(wp.data.dispatch('wc/store/cart').setShippingAddress(addresses.shippingAddress))
}
}
await Promise.all(promises);
}
setPaypalOrder(order);
2022-12-20 16:04:11 +02:00
const res = await fetch(config.scriptData.ajax.approve_order.endpoint, {
method: 'POST',
credentials: 'same-origin',
body: JSON.stringify({
nonce: config.scriptData.ajax.approve_order.nonce,
order_id: data.orderID,
2023-04-21 11:12:32 +03:00
funding_source: window.ppcpFundingSource ?? 'paypal',
2022-12-20 16:04:11 +02:00
})
});
const json = await res.json();
if (!json.success) {
if (typeof actions !== 'undefined' && typeof actions.restart !== 'undefined') {
return actions.restart();
}
if (json.data?.message) {
throw new Error(json.data.message);
}
throw new Error(config.scriptData.labels.error.generic)
}
2023-04-24 08:12:48 +03:00
if (config.finalReviewEnabled) {
location.href = getCheckoutRedirectUrl();
2023-04-24 08:12:48 +03:00
} else {
2023-12-14 09:39:02 +00:00
setGotoContinuationOnError(true);
2023-04-24 08:12:48 +03:00
onSubmit();
2023-04-17 10:23:52 +03:00
}
2022-12-20 16:04:11 +02:00
} catch (err) {
console.error(err);
onError(err.message);
2022-12-20 16:04:11 +02:00
onClose();
throw err;
}
};
useEffect(() => {
const unsubscribe = onCheckoutValidation(() => {
if (config.scriptData.continuation) {
return true;
}
2023-12-14 09:39:02 +00:00
if (gotoContinuationOnError && wp.data.select('wc/store/validation').hasValidationErrors()) {
location.href = getCheckoutRedirectUrl();
return { type: responseTypes.ERROR };
}
return true;
});
return unsubscribe;
2023-12-14 09:39:02 +00:00
}, [onCheckoutValidation, gotoContinuationOnError] );
2023-04-21 11:12:32 +03:00
const handleClick = (data, actions) => {
2023-07-11 09:15:36 +03:00
if (isEditing) {
return actions.reject();
}
2023-04-21 11:12:32 +03:00
window.ppcpFundingSource = data.fundingSource;
2022-12-20 16:04:11 +02:00
onClick();
};
let handleShippingChange = null;
if (shippingData.needsShipping && !config.finalReviewEnabled) {
2023-04-27 09:06:38 +03:00
handleShippingChange = async (data, actions) => {
try {
const shippingOptionId = data.selected_shipping_option?.id;
if (shippingOptionId) {
await shippingData.setSelectedRates(shippingOptionId);
}
const address = paypalAddressToWc(data.shipping_address);
await wp.data.dispatch('wc/store/cart').updateCustomerData({
shipping_address: address,
});
await shippingData.setShippingAddress(address);
2023-04-27 09:06:38 +03:00
const res = await fetch(config.ajax.update_shipping.endpoint, {
method: 'POST',
credentials: 'same-origin',
body: JSON.stringify({
nonce: config.ajax.update_shipping.nonce,
order_id: data.orderID,
})
});
const json = await res.json();
if (!json.success) {
throw new Error(json.data.message);
}
} catch (e) {
console.error(e);
actions.reject();
}
};
}
2022-12-20 16:04:11 +02:00
useEffect(() => {
2023-11-23 08:46:48 +02:00
if (activePaymentMethod !== methodId) {
2023-03-27 10:59:08 +03:00
return;
}
2023-03-23 11:59:15 +02:00
const unsubscribeProcessing = onPaymentSetup(() => {
2023-04-07 15:58:59 +03:00
if (config.scriptData.continuation) {
return {
type: responseTypes.SUCCESS,
meta: {
paymentMethodData: {
'paypal_order_id': config.scriptData.continuation.order_id,
2023-04-21 11:12:32 +03:00
'funding_source': window.ppcpFundingSource ?? 'paypal',
2023-04-24 08:12:48 +03:00
}
2023-04-07 15:58:59 +03:00
},
};
}
2023-04-24 08:12:48 +03:00
const addresses = paypalOrderToWcAddresses(paypalOrder);
return {
type: responseTypes.SUCCESS,
meta: {
paymentMethodData: {
'paypal_order_id': paypalOrder.id,
'funding_source': window.ppcpFundingSource ?? 'paypal',
},
...addresses,
},
};
2022-12-20 16:04:11 +02:00
});
return () => {
unsubscribeProcessing();
};
2023-03-27 10:59:08 +03:00
}, [onPaymentSetup, paypalOrder, activePaymentMethod]);
2022-12-20 16:04:11 +02:00
2023-05-22 10:38:31 +03:00
useEffect(() => {
2023-11-23 08:46:48 +02:00
if (activePaymentMethod !== methodId) {
return;
}
2023-10-19 15:55:57 +03:00
const unsubscribe = onCheckoutFail(({ processingResponse }) => {
console.error(processingResponse)
2023-05-22 10:38:31 +03:00
if (onClose) {
onClose();
}
if (config.scriptData.continuation) {
return true;
}
if (!config.finalReviewEnabled) {
location.href = getCheckoutRedirectUrl();
2023-05-22 10:38:31 +03:00
}
return true;
});
return unsubscribe;
}, [onCheckoutFail, onClose, activePaymentMethod]);
2023-05-22 10:38:31 +03:00
2023-04-07 15:58:59 +03:00
if (config.scriptData.continuation) {
return (
<div dangerouslySetInnerHTML={{__html: config.scriptData.continuation.cancel.html}}>
</div>
)
}
if (!registeredContext) {
buttonModuleWatcher.registerContextBootstrap(config.scriptData.context, {
createOrder: () => {
return createOrder();
},
onApprove: (data, actions) => {
return handleApprove(data, actions);
},
});
registeredContext = true;
}
const style = normalizeStyleForFundingSource(config.scriptData.button.style, fundingSource);
if (!paypalScriptLoaded) {
return null;
}
const PayPalButton = paypal.Buttons.driver("react", { React, ReactDOM });
2022-12-20 16:04:11 +02:00
return (
<PayPalButton
fundingSource={fundingSource}
style={style}
onClick={handleClick}
onCancel={onClose}
onError={onClose}
createOrder={createOrder}
onApprove={handleApprove}
onShippingChange={handleShippingChange}
/>
2022-12-20 16:04:11 +02:00
);
}
2023-04-07 15:58:59 +03:00
const features = ['products'];
if ((config.addPlaceOrderMethod || config.usePlaceOrder) && !config.scriptData.continuation) {
let descriptionElement = <div dangerouslySetInnerHTML={{__html: config.description}}></div>;
if (config.placeOrderButtonDescription) {
descriptionElement = <div>
<p dangerouslySetInnerHTML={{__html: config.description}}></p>
<p style={{textAlign: 'center'}} className={'ppcp-place-order-description'} dangerouslySetInnerHTML={{__html: config.placeOrderButtonDescription}}></p>
</div>;
}
registerPaymentMethod({
name: config.id,
label: <div dangerouslySetInnerHTML={{__html: config.title}}/>,
content: descriptionElement,
edit: descriptionElement,
2023-11-16 16:01:32 +02:00
placeOrderButtonLabel: config.placeOrderButtonText,
ariaLabel: config.title,
canMakePayment: () => config.enabled,
supports: {
features: features,
},
});
}
if (config.scriptData.continuation) {
registerPaymentMethod({
name: config.id,
label: <div dangerouslySetInnerHTML={{__html: config.title}}/>,
content: <PayPalComponent isEditing={false}/>,
edit: <PayPalComponent isEditing={true}/>,
ariaLabel: config.title,
canMakePayment: () => true,
supports: {
features: [...features, 'ppcp_continuation'],
},
});
} else if (!config.usePlaceOrder) {
for (const fundingSource of ['paypal', ...config.enabledFundingSources]) {
registerExpressPaymentMethod({
name: `${config.id}-${fundingSource}`,
paymentMethodId: config.id,
label: <div dangerouslySetInnerHTML={{__html: config.title}}/>,
content: <PayPalComponent isEditing={false} fundingSource={fundingSource}/>,
2023-11-24 09:56:52 +02:00
edit: <PayPalComponent isEditing={true} fundingSource={fundingSource}/>,
ariaLabel: config.title,
canMakePayment: async () => {
if (!paypalScriptPromise) {
paypalScriptPromise = loadPaypalScriptPromise(config.scriptData);
paypalScriptPromise.then(() => {
const messagesBootstrap = new BlockCheckoutMessagesBootstrap(config.scriptData);
messagesBootstrap.init();
});
}
await paypalScriptPromise;
return paypal.Buttons({fundingSource}).isEligible();
},
supports: {
features: features,
},
});
}
}