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 125 - Add woocommerce checkout blocks support #808

Merged
merged 5 commits into from
Sep 13, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"fzaninotto/faker": "^1.9@dev",
"inpsyde/php-coding-standards": "^1.0.0",
"php-stubs/wordpress-stubs": "^5.0@stable",
"php-stubs/woocommerce-stubs": "^5.0@stable",
"php-stubs/woocommerce-stubs": "7.9.0",
"vimeo/psalm": "^4.8 || ^5.13.0"
},
"autoload": {
Expand Down
21 changes: 10 additions & 11 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions psalm.xml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
<file name=".psalm/stubs.php"/>
<file name="vendor/php-stubs/wordpress-stubs/wordpress-stubs.php"/>
<file name="vendor/php-stubs/woocommerce-stubs/woocommerce-stubs.php"/>
<file name="vendor/php-stubs/woocommerce-stubs/woocommerce-packages-stubs.php"/>
</stubs>
<issueHandlers>
<MixedAssignment errorLevel="suppress" />
Expand Down
9 changes: 5 additions & 4 deletions resources/js/mollieBlockIndex.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ import molliePaymentMethod from './blocks/molliePaymentMethod'
const { ajaxUrl, filters, gatewayData, availableGateways } = mollieBlockData.gatewayData;
const {useEffect} = wp.element;
const isAppleSession = typeof window.ApplePaySession === "function"
function getCompanyField()
{
const isBlockEditor = !!wp?.blockEditor;

function getCompanyField() {
let shippingCompany = document.getElementById('shipping-company');
let billingCompany = document.getElementById('billing-company');
return shippingCompany ? shippingCompany : billingCompany;
Expand Down Expand Up @@ -39,8 +40,8 @@ import molliePaymentMethod from './blocks/molliePaymentMethod'
}
gatewayData.forEach(item => {
let register = () => registerPaymentMethod(molliePaymentMethod(useEffect, ajaxUrl, filters, gatewayData, availableGateways, item, jQuery, requiredFields, isCompanyFieldVisible, isPhoneFieldVisible));
if (item.name === 'mollie_wc_gateway_applepay' ) {
if (isAppleSession && window.ApplePaySession.canMakePayments()) {
if (item.name === 'mollie_wc_gateway_applepay' && !isBlockEditor) {
if ((isAppleSession && window.ApplePaySession.canMakePayments())) {
register();
}
return;
Expand Down
141 changes: 27 additions & 114 deletions src/Assets/AssetsModule.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,13 @@

namespace Mollie\WooCommerce\Assets;

use Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry;
use Inpsyde\Modularity\Module\ExecutableModule;
use Inpsyde\Modularity\Module\ModuleClassNameIdTrait;
use Mollie\Api\Exceptions\ApiException;
use Mollie\WooCommerce\Buttons\ApplePayButton\DataToAppleButtonScripts;
use Mollie\WooCommerce\Buttons\PayPalButton\DataToPayPal;
use Mollie\WooCommerce\Components\AcceptedLocaleValuesDictionary;
use Mollie\WooCommerce\Gateway\MolliePaymentGateway;
use Mollie\WooCommerce\Gateway\MolliePaymentGatewayI;
use Mollie\WooCommerce\PaymentMethods\PaymentMethodI;
use Mollie\WooCommerce\Settings\Settings;
use Mollie\WooCommerce\Shared\Data;
use Psr\Container\ContainerInterface;
Expand All @@ -34,15 +32,7 @@ public function enqueueBlockCheckoutScripts(Data $dataService, array $gatewayIns
if (!has_block('woocommerce/checkout')) {
return;
}
wp_enqueue_script('mollie_block_index');
wp_enqueue_style('mollie-gateway-icons');
wp_localize_script(
'mollie_block_index',
'mollieBlockData',
[
'gatewayData' => $this->gatewayDataForWCBlocks($dataService, $gatewayInstances),
]
);
}

public function registerButtonsBlockScripts(string $pluginUrl, string $pluginPath): void
Expand Down Expand Up @@ -431,102 +421,6 @@ public function enqueueComponentsAssets(Settings $settingsHelper): void
);
}

protected function gatewayDataForWCBlocks(Data $dataService, array $gatewayInstances): array
{
$filters = $dataService->wooCommerceFiltersForCheckout();
$availableGateways = WC()->payment_gateways()->get_available_payment_gateways();
$availablePaymentMethods = [];
/**
* @var MolliePaymentGatewayI $gateway
* psalm-suppress UnusedForeachValue
*/
foreach ($availableGateways as $key => $gateway) {
if (strpos($key, 'mollie_wc_gateway_') === false) {
unset($availableGateways[$key]);
}
}
if (
isset($filters['amount']['currency'])
&& isset($filters['locale'])
&& isset($filters['billingCountry'])
) {
$filterKey = "{$filters['amount']['currency']}-{$filters['locale']}-{$filters['billingCountry']}";
foreach ($availableGateways as $key => $gateway) {
$availablePaymentMethods[$filterKey][$key] = $gateway->paymentMethod()->getProperty('id');
}
}

$dataToScript = [
'ajaxUrl' => admin_url('admin-ajax.php'),
'filters' => [
'currency' => isset($filters['amount']['currency']) ? $filters['amount']['currency'] : false,
'cartTotal' => isset($filters['amount']['value']) ? $filters['amount']['value'] : false,
'paymentLocale' => isset($filters['locale']) ? $filters['locale'] : false,
'billingCountry' => isset($filters['billingCountry']) ? $filters['billingCountry'] : false,
],
];
$gatewayData = [];
$isSepaEnabled = isset($gatewayInstances['mollie_wc_gateway_directdebit']) && $gatewayInstances['mollie_wc_gateway_directdebit']->enabled === 'yes';
/** @var MolliePaymentGateway $gateway */
foreach ($gatewayInstances as $gatewayKey => $gateway) {
/** @var string $gatewayId */
$gatewayId = is_string($gateway->paymentMethod()->getProperty('id')) ? $gateway->paymentMethod()->getProperty('id') : "";

if ($gateway->enabled !== 'yes' || $gatewayId === 'directdebit') {
continue;
}
$content = $gateway->paymentMethod()->getProcessedDescriptionForBlock();
$issuers = false;
if ($gateway->paymentMethod()->getProperty('paymentFields') === true) {
$paymentFieldsService = $gateway->paymentMethod()->paymentFieldsService();
$paymentFieldsService->setStrategy($gateway->paymentMethod());
$issuers = $gateway->paymentMethod()->paymentFieldsService()->getStrategyMarkup($gateway);
}
if ($gatewayId === 'creditcard') {
$content .= $issuers;
$issuers = false;
}
$title = $gateway->paymentMethod()->title();
$labelMarkup = "<span style='margin-right: 1em'>{$title}</span>{$gateway->icon}";
$hasSurcharge = $gateway->paymentMethod()->hasSurcharge();
$gatewayData[] = [
'name' => $gatewayKey,
'label' => $labelMarkup,
'content' => $content,
'issuers' => $issuers,
'hasSurcharge' => $hasSurcharge,
'title' => $title,
'contentFallback' => __('Please choose a billing country to see the available payment methods', 'mollie-payments-for-woocommerce'),
'edit' => $content,
'paymentMethodId' => $gatewayKey,
'allowedCountries' => is_array(
$gateway->paymentMethod()->getProperty('allowed_countries')
) ? $gateway->paymentMethod()->getProperty('allowed_countries') : [],
'ariaLabel' => $gateway->paymentMethod()->getProperty('defaultDescription'),
'supports' => $this->gatewaySupportsFeatures($gateway->paymentMethod(), $isSepaEnabled),
'errorMessage' => $gateway->paymentMethod()->getProperty('errorMessage'),
'companyPlaceholder' => $gateway->paymentMethod()->getProperty('companyPlaceholder'),
'phonePlaceholder' => $gateway->paymentMethod()->getProperty('phonePlaceholder'),
'birthdatePlaceholder' => $gateway->paymentMethod()->getProperty('birthdatePlaceholder'),
];
}
$dataToScript['gatewayData'] = $gatewayData;
$dataToScript['availableGateways'] = $availablePaymentMethods;

return $dataToScript;
}

public function gatewaySupportsFeatures(PaymentMethodI $paymentMethod, bool $isSepaEnabled): array
{
$supports = (array) $paymentMethod->getProperty('supports');
$isSepaPaymentMethod = (bool) $paymentMethod->getProperty('SEPA');
if ($isSepaEnabled && $isSepaPaymentMethod) {
array_push($supports, 'subscriptions');
}

return $supports;
}

protected function getPluginUrl(string $pluginUrl, string $path = ''): string
{
return $pluginUrl . ltrim($path, '/');
Expand Down Expand Up @@ -633,9 +527,34 @@ protected function setupModuleActions(ContainerInterface $container): void
$pluginPath = $container->get('shared.plugin_path');
/** @var Settings */
$settingsHelper = $container->get('settings.settings_helper');
$gatewayInstances = $container->get('gateway.instances');

/** 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
add_action(
'woocommerce_blocks_loaded',
function () use ($dataService, $gatewayInstances, $pluginUrl, $pluginPath, $hasBlocksEnabled) {
if ($hasBlocksEnabled && class_exists('Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType')) {
add_action(
'woocommerce_blocks_payment_method_type_registration',
function (PaymentMethodRegistry $paymentMethodRegistry) use ($dataService, $gatewayInstances, $pluginUrl, $pluginPath) {
$paymentMethodRegistry->register(
new MollieCheckoutBlocksSupport(
$dataService,
$gatewayInstances,
$this->getPluginUrl($pluginUrl, '/public/js/mollieBlockIndex.min.js'),
(string) filemtime($this->getPluginPath($pluginPath, '/public/js/mollieBlockIndex.min.js'))
)
);
}
);
}
}
);

add_action(
'init',
function () use ($container, $hasBlocksEnabled, $settingsHelper, $pluginUrl, $pluginPath, $dataService) {
function () use ($hasBlocksEnabled, $settingsHelper, $pluginUrl, $pluginPath) {
self::registerFrontendScripts($pluginUrl, $pluginPath);

// Enqueue Scripts
Expand All @@ -649,12 +568,6 @@ function () use ($container, $hasBlocksEnabled, $settingsHelper, $pluginUrl, $pl
});

if ($hasBlocksEnabled) {
/** @var array */
$gatewayInstances = $container->get('gateway.instances');
self::registerBlockScripts($pluginUrl, $pluginPath);
add_action('wp_enqueue_scripts', function () use ($dataService, $gatewayInstances) {
$this->enqueueBlockCheckoutScripts($dataService, $gatewayInstances);
});
$this->registerButtonsBlockScripts($pluginUrl, $pluginPath);
}
}
Expand Down
Loading