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

Fix/piwoo 579 load payments in blocks #968

Merged
merged 9 commits into from
Jan 13, 2025
Merged
41 changes: 41 additions & 0 deletions resources/js/blocks/availableGatewaysStore.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const DEFAULT_STATE = {
cachedAvailableGateways: {},
};

const actions = {
setAvailableGateways(country, currency, gateways) {
return {
type: 'SET_AVAILABLE_GATEWAYS',
country,
currency,
gateways,
};
},
};

const reducer = (state = DEFAULT_STATE, action) => {
switch (action.type) {
case 'SET_AVAILABLE_GATEWAYS':
return {
...state,
cachedAvailableGateways: {
...state.cachedAvailableGateways,
[`${action.currency}-${action.country}`]: action.gateways,
},
};
default:
return state;
}
};

const selectors = {
getAvailableGateways(state) {
return state.cachedAvailableGateways || {};
},
};

wp.data.registerStore('mollie/available-gateways', {
reducer,
actions,
selectors,
});
185 changes: 131 additions & 54 deletions resources/js/blocks/molliePaymentMethod.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,86 @@
let cachedAvailableGateways = {};

function loadCachedAvailableGateways() {
const storedData = localStorage.getItem('cachedAvailableGateways');
if (storedData) {
try {
cachedAvailableGateways = JSON.parse(storedData);
} catch (e) {
console.warn('Error parsing cachedAvailableGateways from localStorage:', e);
cachedAvailableGateways = {};
}
}
}

function saveCachedAvailableGateways() {
localStorage.setItem('cachedAvailableGateways', JSON.stringify(cachedAvailableGateways));
}

loadCachedAvailableGateways();
function setAvailableGateways(country, currencyCode, data) {
cachedAvailableGateways = {
...cachedAvailableGateways,
...data
};
saveCachedAvailableGateways();
}
function useMollieAvailableGateways(billing, currencyCode, cartTotal, filters, ajaxUrl, jQuery, item) {
const country = billing.country;
const code = currencyCode;
const value = cartTotal;


wp.element.useEffect(() => {
if (!country || !item) return;
const currencyCode = code;
const cartTotal = value;
const currentFilterKey = currencyCode + "-" + country;
if (cachedAvailableGateways.hasOwnProperty(currentFilterKey)) {
return;
}
jQuery.ajax({
url: ajaxUrl,
method: 'POST',
data: {
action: 'mollie_checkout_blocks_canmakepayment',
currentGateway: item,
currency: currencyCode,
billingCountry: country,
cartTotal,
paymentLocale: filters.paymentLocale
},
success: (response) => {
setAvailableGateways(country, currencyCode, response.data);
const cartTotals = wp.data.select('wc/store/cart').getCartTotals();
// Dispatch them again to trigger a re-render:
wp.data.dispatch('wc/store/cart').setCartData({...cartTotals});
},
error: (jqXHR, textStatus, errorThrown) => {
console.warn('Failed to fetch available gateways:', textStatus, errorThrown);
},
});
}, [billing, currencyCode, filters.paymentLocale, ajaxUrl, jQuery, item]);

return cachedAvailableGateways;
}

// Component that runs the hook but does not render anything.
function MollieGatewayUpdater({ billing, currencyCode, cartTotal, filters, ajaxUrl, jQuery, item }) {

useMollieAvailableGateways(billing, currencyCode, cartTotal, filters, ajaxUrl, jQuery, item);
return null;
}

let onSubmitLocal
let activePaymentMethodLocal
let cachedAvailableGateways
let creditCardSelected = new Event("mollie_creditcard_component_selected", {bubbles: true});
const MollieComponent = (props) => {
let {onSubmit, activePaymentMethod, billing, item, useEffect, ajaxUrl, jQuery, emitResponse, eventRegistration, requiredFields, shippingData, isPhoneFieldVisible} = props
const { responseTypes } = emitResponse;
const {onPaymentSetup, onCheckoutValidation} = eventRegistration;
if (!item || !item.name) {
return <div>Loading payment methods...</div>;
}
const [ selectedIssuer, selectIssuer ] = wp.element.useState('');
const [ inputPhone, selectPhone ] = wp.element.useState('');
const [ inputBirthdate, selectBirthdate ] = wp.element.useState('');
Expand Down Expand Up @@ -277,18 +351,60 @@ const MollieComponent = (props) => {
return <div><p>{item.content}</p></div>
}

const molliePaymentMethod = (useEffect, ajaxUrl, filters, gatewayData, availableGateways, item, jQuery, requiredFields, isPhoneFieldVisible) =>{
let billingCountry = filters.billingCountry
let cartTotal = filters.cartTotal
cachedAvailableGateways = availableGateways
let changedBillingCountry = filters.billingCountry
const Label = ({ item, filters, ajaxUrl, jQuery }) => {
const cartData = wp.data.useSelect((select) =>
select('wc/store/cart').getCartData(),
[]
);
const cartTotals = wp.data.useSelect( (select) => select('wc/store/cart').getCartTotals(), [ ] );
const cartTotal = cartTotals?.total_price || 0;
return (
<>
<div dangerouslySetInnerHTML={{ __html: item.label }}/>
<MollieGatewayUpdater
billing={cartData.billingAddress}
currencyCode={wcSettings.currency.code}
filters={filters}
ajaxUrl={ajaxUrl}
jQuery={jQuery}
item={item}
cartTotal={cartTotal}
/>
</>
);
};

const molliePaymentMethod = (useEffect, ajaxUrl, filters, gatewayData, availableGateways, item, jQuery, requiredFields, isCompanyFieldVisible, isPhoneFieldVisible) =>{

document.addEventListener('mollie_components_ready_to_submit', function () {
onSubmitLocal()
})
function creditcardSelectedEvent() {
if (item.name === "mollie_wc_gateway_creditcard") {
document.documentElement.dispatchEvent(creditCardSelected);
}
}

// On first load, if availableGateways is not empty, store it
if (_.isEmpty(cachedAvailableGateways) && !_.isEmpty(availableGateways)) {
cachedAvailableGateways = availableGateways;
saveCachedAvailableGateways();
}
return {
name: item.name,
label: <div dangerouslySetInnerHTML={{__html: item.label}}/>,
content: <MollieComponent item={item} useEffect={useEffect} ajaxUrl={ajaxUrl} jQuery={jQuery} requiredFields={requiredFields} isPhoneFieldVisible={isPhoneFieldVisible}/>,
label:<Label
item={item}
ajaxUrl={ajaxUrl}
jQuery={jQuery}
filters={filters}
/>,
content: <MollieComponent
item={item}
useEffect={useEffect}
ajaxUrl={ajaxUrl}
jQuery={jQuery}
requiredFields={requiredFields}
isPhoneFieldVisible={isPhoneFieldVisible}/>,
edit: <div>{item.edit}</div>,
paymentMethodId: item.paymentMethodId,
canMakePayment: ({cartTotals, billingData}) => {
Expand All @@ -298,56 +414,17 @@ const molliePaymentMethod = (useEffect, ajaxUrl, filters, gatewayData, available
if (cartTotals <= 0) {
return true
}
loadCachedAvailableGateways();
const currencyCode = cartTotals?.currency_code;
const country = billingData?.country;
const currentFilterKey = currencyCode + "-" + country;

cartTotal = cartTotals?.total_price
if(billingData?.country && billingData.country !== ''){
billingCountry = billingData?.country
}
let currencyCode = cartTotals?.currency_code
let currentFilterKey = currencyCode + "-" + filters.paymentLocale + "-" + billingCountry

function creditcardSelectedEvent() {
if (item.name === "mollie_wc_gateway_creditcard") {
document.documentElement.dispatchEvent(creditCardSelected);
}
}

if (billingCountry !== changedBillingCountry) {
changedBillingCountry = billingCountry
if (!cachedAvailableGateways.hasOwnProperty(currentFilterKey)) {
jQuery.ajax({
url: ajaxUrl,
method: 'POST',
data: {
action: 'mollie_checkout_blocks_canmakepayment',
currentGateway: item,
currency: currencyCode,
billingCountry: billingCountry,
cartTotal: cartTotal,
paymentLocale: filters.paymentLocale
},
complete: (jqXHR, textStatus) => {
},
success: (response, textStatus, jqXHR) => {
cachedAvailableGateways = {...cachedAvailableGateways, ...response.data}
if (!cachedAvailableGateways.hasOwnProperty(currentFilterKey)) {
return false
}
return cachedAvailableGateways[currentFilterKey].hasOwnProperty(item.name)
},
error: (jqXHR, textStatus, errorThrown) => {
console.warn(textStatus, errorThrown)
},
})
}
}

creditcardSelectedEvent();
if (!cachedAvailableGateways.hasOwnProperty(currentFilterKey)) {
return false
return false;
}
creditcardSelectedEvent();

return cachedAvailableGateways[currentFilterKey].hasOwnProperty(item.name)
return cachedAvailableGateways[currentFilterKey].hasOwnProperty(item.name);
},
ariaLabel: item.ariaLabel,
supports: {
Expand Down
100 changes: 49 additions & 51 deletions resources/js/mollieBlockIndex.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,64 +3,62 @@ import ApplePayButtonComponent from './blocks/ApplePayButtonComponent'
import ApplePayButtonEditorComponent from './blocks/ApplePayButtonEditorComponent'

(
function ({ mollieBlockData, wc, _, jQuery}) {
function ({mollieBlockData, wc, _, jQuery}) {
if (_.isEmpty(mollieBlockData)) {
return;
}

window.onload = (event) => {
const { registerPaymentMethod } = wc.wcBlocksRegistry;
const { defaultFields } = wc.wcSettings.allSettings;
const { ajaxUrl, filters, gatewayData, availableGateways } = mollieBlockData.gatewayData;
const {useEffect} = wp.element;
const isAppleSession = typeof window.ApplePaySession === "function"
function getPhoneField()
{
const phoneFieldDataset = document.querySelector('[data-show-phone-field]');
if (!phoneFieldDataset) {
return true;
}
return phoneFieldDataset.dataset.showPhoneField !== "false"
}
const {registerPaymentMethod} = wc.wcBlocksRegistry;
const {defaultFields} = wc.wcSettings.allSettings;
const {ajaxUrl, filters, gatewayData, availableGateways} = mollieBlockData.gatewayData;
const {useEffect} = wp.element;
const isAppleSession = typeof window.ApplePaySession === "function"
localStorage.removeItem('cachedAvailableGateways');

const companyNameString = defaultFields.company.label
const isPhoneFieldVisible = getPhoneField();
const phoneString = defaultFields.phone.label
let requiredFields = {
'companyNameString': companyNameString,
'phoneString': phoneString,
function getPhoneField() {
const phoneFieldDataset = document.querySelector('[data-show-phone-field]');
if (!phoneFieldDataset) {
return true;
}
gatewayData.forEach(item => {
let register = () => registerPaymentMethod(molliePaymentMethod(useEffect, ajaxUrl, filters, gatewayData, availableGateways, item, jQuery, requiredFields, isPhoneFieldVisible));
if (item.name === 'mollie_wc_gateway_applepay') {
const {isExpressEnabled} = item;
if ((isAppleSession && window.ApplePaySession.canMakePayments())) {
register();
if (isExpressEnabled !== true) {
return;
}
const {registerExpressPaymentMethod} = wc.wcBlocksRegistry;
registerExpressPaymentMethod({
name: 'mollie_wc_gateway_applepay_express',
title: 'Apple Pay Express button',
description: 'Apple Pay Express button',
content: <ApplePayButtonComponent />,
edit: <ApplePayButtonEditorComponent />,
ariaLabel: 'Apple Pay',
canMakePayment: () => true,
paymentMethodId: 'mollie_wc_gateway_applepay',
gatewayId: 'mollie_wc_gateway_applepay',
supports: {
features: ['products'],
style: ['height', 'borderRadius']
},
})
return phoneFieldDataset.dataset.showPhoneField !== "false"
}

const companyNameString = defaultFields.company.label
const isPhoneFieldVisible = getPhoneField();
const phoneString = defaultFields.phone.label
let requiredFields = {
'companyNameString': companyNameString,
'phoneString': phoneString,
}
gatewayData.forEach(item => {
let register = () => registerPaymentMethod(molliePaymentMethod(useEffect, ajaxUrl, filters, gatewayData, availableGateways, item, jQuery, requiredFields, isPhoneFieldVisible));
if (item.name === 'mollie_wc_gateway_applepay') {
const {isExpressEnabled} = item;
if ((isAppleSession && window.ApplePaySession.canMakePayments())) {
register();
if (isExpressEnabled !== true) {
return;
}
return;
const {registerExpressPaymentMethod} = wc.wcBlocksRegistry;
registerExpressPaymentMethod({
name: 'mollie_wc_gateway_applepay_express',
title: 'Apple Pay Express button',
description: 'Apple Pay Express button',
content: <ApplePayButtonComponent/>,
edit: <ApplePayButtonEditorComponent/>,
ariaLabel: 'Apple Pay',
canMakePayment: () => true,
paymentMethodId: 'mollie_wc_gateway_applepay',
gatewayId: 'mollie_wc_gateway_applepay',
supports: {
features: ['products'],
style: ['height', 'borderRadius']
},
})
}
register();
});
};

return;
}
register();
});
}
)(window, wc)
10 changes: 10 additions & 0 deletions src/Assets/AssetsModule.php
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,16 @@ protected function setupModuleActions(ContainerInterface $container): void
/** @var Settings */
$settingsHelper = $container->get('settings.settings_helper');
$gatewayInstances = $container->get('gateway.instances');
add_action('woocommerce_blocks_loaded', function () {
woocommerce_store_api_register_update_callback(
[
'namespace' => 'mollie-payments-for-woocommerce',
'callback' => function () {
// Do nothing
},
]
);
});

/** Add support to Mollie blocks for WooCommerce checkout blocks functionality */
//https://github.com/woocommerce/woocommerce-blocks/blob/trunk/docs/third-party-developers/extensibility/checkout-payment-methods/payment-method-integration.md#putting-it-all-together
Expand Down
Loading
Loading