diff --git a/inc/settings/mollie_applepay_settings.php b/inc/settings/mollie_applepay_settings.php index 2ef1c3fa0..92e0b305a 100644 --- a/inc/settings/mollie_applepay_settings.php +++ b/inc/settings/mollie_applepay_settings.php @@ -115,6 +115,14 @@ 'value' => isset($applePayOption['mollie_apple_pay_button_enabled_product']) ? $applePayOption['mollie_apple_pay_button_enabled_product'] : 'no', ], + [ + 'id' => 'mollie_apple_pay_button_enabled_express_checkout', + 'title' => __('Enable Apple Pay Express Button on Checkout page', 'mollie-payments-for-woocommerce'), + 'desc' => __('Enable the Apple Pay direct buy button on the Express Buttons section of the Checkout page', 'mollie-payments-for-woocommerce'), + 'type' => 'checkbox', + 'default' => 'no', + 'value' => isset($applePayOption['mollie_apple_pay_button_enabled_express_checkout']) ? $applePayOption['mollie_apple_pay_button_enabled_express_checkout'] : 'no', + ], [ 'id' => $pluginName . '_' . 'sectionend', 'type' => 'sectionend', diff --git a/package.json b/package.json index d5429a333..a97339a4a 100644 --- a/package.json +++ b/package.json @@ -53,7 +53,7 @@ "webpack": "^5.89.0" }, "scripts": { - "watch": "webpack --watch", + "watch": "BASE_PATH=. node_modules/.bin/encore dev --watch", "build": "BASE_PATH=. node_modules/.bin/encore dev", "setup": "gulp setup", "e2e-activation": "npx playwright test --project=activation", diff --git a/resources/js/applepayButtonBlock.js b/resources/js/applepayButtonBlock.js new file mode 100644 index 000000000..058da50c7 --- /dev/null +++ b/resources/js/applepayButtonBlock.js @@ -0,0 +1,30 @@ +import {ApplePayButtonComponent} from "./blocks/ApplePayButtonComponent"; + +( + function ({mollieApplePayBlockDataCart}) { + if (mollieApplePayBlockDataCart.length === 0) { + return + } + const {ApplePaySession} = window; + if (!(ApplePaySession && ApplePaySession.canMakePayments())) { + return null; + } + + const {registerExpressPaymentMethod} = wc.wcBlocksRegistry; + + registerExpressPaymentMethod({ + name: 'mollie_wc_gateway_applepay_express', + content: < ApplePayButtonComponent/>, + edit: < ApplePayButtonComponent/>, + ariaLabel: 'Apple Pay', + canMakePayment: () => true, + paymentMethodId: 'mollie_wc_gateway_applepay', + supports: { + features: ['products'], + }, + }); + } +) +( + window +) diff --git a/resources/js/applepayButtonBlockComponent.js b/resources/js/applepayButtonBlockComponent.js deleted file mode 100644 index 7c0215c6e..000000000 --- a/resources/js/applepayButtonBlockComponent.js +++ /dev/null @@ -1,194 +0,0 @@ -import {maybeShowButton} from './maybeShowApplePayButton.js'; -import {request} from "./applePayRequest"; -import {createAppleErrors} from "./applePayError"; - -( - function ({mollieApplePayBlockDataCart}) - { - if (mollieApplePayBlockDataCart.length === 0 ) { - return - } - const {product: {needShipping = true, subtotal}, shop: {countryCode, currencyCode = 'EUR', totalLabel = ''}, buttonMarkup, ajaxUrl} = mollieApplePayBlockDataCart - - const { registerPlugin } = wp.plugins; - const { ExperimentalOrderMeta } = wc.blocksCheckout; - const ApplePayButtonComponent = ( { cart, extensions } ) => { - return
- } - const MollieApplePayButtonCart = () => { - return - - - }; - - registerPlugin( 'mollie-applepay-block-button', { - render: () => { - return ; - }, - scope: 'woocommerce-checkout' - } ); - - setTimeout(function(){ - if(!maybeShowButton()){ - return - } - const nonce = document.getElementById("woocommerce-process-checkout-nonce").value - let updatedContactInfo = [] - let selectedShippingMethod = [] - let redirectionUrl = '' - let applePaySession = () => { - const session = new ApplePaySession(3, request(countryCode, currencyCode, totalLabel, subtotal)) - session.begin() - session.onshippingmethodselected = function (event) { - jQuery.ajax({ - url: ajaxUrl, - method: 'POST', - data: { - action: 'mollie_apple_pay_update_shipping_method', - shippingMethod: event.shippingMethod, - callerPage: 'cart', - simplifiedContact: updatedContactInfo, - 'woocommerce-process-checkout-nonce': nonce, - }, - complete: (jqXHR, textStatus) => { - }, - success: (applePayShippingMethodUpdate, textStatus, jqXHR) => { - let response = applePayShippingMethodUpdate.data - selectedShippingMethod = event.shippingMethod - if (applePayShippingMethodUpdate.success === false) { - response.errors = createAppleErrors(response.errors) - } - this.completeShippingMethodSelection(response) - }, - error: (jqXHR, textStatus, errorThrown) => { - console.warn(textStatus, errorThrown) - session.abort() - }, - }) - } - session.onshippingcontactselected = function (event) { - jQuery.ajax({ - url: ajaxUrl, - method: 'POST', - data: { - action: 'mollie_apple_pay_update_shipping_contact', - simplifiedContact: event.shippingContact, - callerPage: 'cart', - needShipping: needShipping, - 'woocommerce-process-checkout-nonce': nonce, - }, - complete: (jqXHR, textStatus) => { - }, - success: (applePayShippingContactUpdate, textStatus, jqXHR) => { - let response = applePayShippingContactUpdate.data - updatedContactInfo = event.shippingContact - if (applePayShippingContactUpdate.success === false) { - response.errors = createAppleErrors(response.errors) - } - if (response.newShippingMethods) { - selectedShippingMethod = response.newShippingMethods[0] - } - this.completeShippingContactSelection(response) - }, - error: (jqXHR, textStatus, errorThrown) => { - console.warn(textStatus, errorThrown) - session.abort() - }, - }) - } - session.onvalidatemerchant = (applePayValidateMerchantEvent) => { - jQuery.ajax({ - url: ajaxUrl, - method: 'POST', - data: { - action: 'mollie_apple_pay_validation', - validationUrl: applePayValidateMerchantEvent.validationURL, - 'woocommerce-process-checkout-nonce': nonce, - }, - complete: (jqXHR, textStatus) => { - }, - success: (merchantSession, textStatus, jqXHR) => { - if (merchantSession.success === true) { - session.completeMerchantValidation(JSON.parse(merchantSession.data)) - } else { - console.warn(merchantSession.data) - session.abort() - } - }, - error: (jqXHR, textStatus, errorThrown) => { - console.warn(textStatus, errorThrown) - session.abort() - }, - }) - } - session.onpaymentauthorized = (ApplePayPayment) => { - const {billingContact, shippingContact } = ApplePayPayment.payment - - jQuery.ajax({ - url: ajaxUrl, - method: 'POST', - data: { - action: 'mollie_apple_pay_create_order_cart', - shippingContact: ApplePayPayment.payment.shippingContact, - billingContact: ApplePayPayment.payment.billingContact, - token: ApplePayPayment.payment.token, - shippingMethod: selectedShippingMethod, - 'mollie-payments-for-woocommerce_issuer_applepay': 'applepay', - 'woocommerce-process-checkout-nonce': nonce, - 'billing_first_name': billingContact.givenName || '', - 'billing_last_name': billingContact.familyName || '', - 'billing_company': '', - 'billing_country': billingContact.countryCode || '', - 'billing_address_1': billingContact.addressLines[0] || '', - 'billing_address_2': billingContact.addressLines[1] || '', - 'billing_postcode': billingContact.postalCode || '', - 'billing_city': billingContact.locality || '', - 'billing_state': billingContact.administrativeArea || '', - 'billing_phone': billingContact.phoneNumber || '000000000000', - 'billing_email': shippingContact.emailAddress || '', - 'shipping_first_name': shippingContact.givenName || '', - 'shipping_last_name': shippingContact.familyName || '', - 'shipping_company': '', - 'shipping_country': shippingContact.countryCode || '', - 'shipping_address_1': shippingContact.addressLines[0] || '', - 'shipping_address_2': shippingContact.addressLines[1] || '', - 'shipping_postcode': shippingContact.postalCode || '', - 'shipping_city': shippingContact.locality || '', - 'shipping_state': shippingContact.administrativeArea || '', - 'shipping_phone': shippingContact.phoneNumber || '000000000000', - 'shipping_email': shippingContact.emailAddress || '', - 'order_comments' : '', - 'payment_method' : 'mollie_wc_gateway_applepay', - '_wp_http_referer' : '/?wc-ajax=update_order_review' - }, - complete: (jqXHR, textStatus) => { - - }, - success: (authorizationResult, textStatus, jqXHR) => { - let result = authorizationResult.data - if (authorizationResult.success === true) { - redirectionUrl = result['returnUrl']; - session.completePayment(result['responseToApple']) - window.location.href = redirectionUrl - } else { - result.errors = createAppleErrors(result.errors) - session.completePayment(result) - } - }, - error: (jqXHR, textStatus, errorThrown) => { - console.warn(textStatus, errorThrown) - session.abort() - }, - }) - } - } - document.querySelector('#mollie_applepay_button').addEventListener('click', (evt) => { - applePaySession() - }) - },2000); - - } -) -( - window -) diff --git a/resources/js/blocks/ApplePayButtonComponent.js b/resources/js/blocks/ApplePayButtonComponent.js new file mode 100644 index 000000000..d712477cf --- /dev/null +++ b/resources/js/blocks/ApplePayButtonComponent.js @@ -0,0 +1,185 @@ +import {request} from "../applePayRequest"; +import {createAppleErrors} from "../applePayError"; + +export const ApplePayButtonComponent = ({cart, extensions}) => { + const mollieApplePayBlockDataCart = window.mollieApplePayBlockDataCart || window.mollieBlockData.mollieApplePayBlockDataCart + const nonce = document.getElementById("woocommerce-process-checkout-nonce").value + let updatedContactInfo = [] + let redirectionUrl = '' + const { + product: {needShipping = true, subtotal}, + shop: {countryCode, currencyCode = 'EUR', totalLabel = ''}, + ajaxUrl, + } = mollieApplePayBlockDataCart + + const findSelectedShippingMethod = (shippingRates) => { + let shippingRate = shippingRates.find((shippingMethod) => shippingMethod.selected === true) + const appleFormattedRate = { + amount: '', + detail: '', + label: shippingRate.name, + identifier: shippingRate.rate_id, + selected: shippingRate.selected, + } + return shippingRate ? appleFormattedRate : '' + } + + let applePaySession = () => { + const session = new ApplePaySession(3, request(countryCode, currencyCode, totalLabel, subtotal)) + const store = wp.data.select('wc/store/cart') + const shippingRates = store.getShippingRates()?.[0]?.shipping_rates; + let selectedShippingMethod = ''; + if (shippingRates && shippingRates.length > 0) { + selectedShippingMethod = findSelectedShippingMethod(shippingRates, selectedShippingMethod); + } + session.onshippingmethodselected = function (event) { + jQuery.ajax({ + url: ajaxUrl, + method: 'POST', + data: { + action: 'mollie_apple_pay_update_shipping_method', + shippingMethod: event.shippingMethod, + callerPage: 'cart', + simplifiedContact: updatedContactInfo, + 'woocommerce-process-checkout-nonce': nonce, + }, + success: (applePayShippingMethodUpdate, textStatus, jqXHR) => { + let response = applePayShippingMethodUpdate.data + selectedShippingMethod = event.shippingMethod + if (applePayShippingMethodUpdate.success === false) { + response.errors = createAppleErrors(response.errors) + } + this.completeShippingMethodSelection(response) + }, + error: (jqXHR, textStatus, errorThrown) => { + console.warn(textStatus, errorThrown) + session.abort() + }, + }) + } + session.onshippingcontactselected = function (event) { + jQuery.ajax({ + url: ajaxUrl, + method: 'POST', + data: { + action: 'mollie_apple_pay_update_shipping_contact', + simplifiedContact: event.shippingContact, + callerPage: 'cart', + needShipping: needShipping, + 'woocommerce-process-checkout-nonce': nonce, + shippingMethod: selectedShippingMethod, + }, + success: (applePayShippingContactUpdate, textStatus, jqXHR) => { + let response = applePayShippingContactUpdate.data + updatedContactInfo = event.shippingContact + if (applePayShippingContactUpdate.success === false) { + response.errors = createAppleErrors(response.errors) + } + if (response.newShippingMethods) { + selectedShippingMethod = response.newShippingMethods[0] + } + this.completeShippingContactSelection(response) + }, + error: (jqXHR, textStatus, errorThrown) => { + console.warn(textStatus, errorThrown) + session.abort() + }, + }) + } + session.onvalidatemerchant = (applePayValidateMerchantEvent) => { + jQuery.ajax({ + url: ajaxUrl, + method: 'POST', + data: { + action: 'mollie_apple_pay_validation', + validationUrl: applePayValidateMerchantEvent.validationURL, + 'woocommerce-process-checkout-nonce': nonce, + }, + success: (merchantSession, textStatus, jqXHR) => { + if (merchantSession.success === true) { + session.completeMerchantValidation(JSON.parse(merchantSession.data)) + } else { + console.warn(merchantSession.data) + session.abort() + } + }, + error: (jqXHR, textStatus, errorThrown) => { + console.warn(textStatus, errorThrown) + session.abort() + }, + }) + } + session.onpaymentauthorized = (ApplePayPayment) => { + const {billingContact, shippingContact} = ApplePayPayment.payment + + jQuery.ajax({ + url: ajaxUrl, + method: 'POST', + data: { + action: 'mollie_apple_pay_create_order_cart', + shippingContact: ApplePayPayment.payment.shippingContact, + billingContact: ApplePayPayment.payment.billingContact, + token: ApplePayPayment.payment.token, + shippingMethod: selectedShippingMethod, + 'mollie-payments-for-woocommerce_issuer_applepay': 'applepay', + 'woocommerce-process-checkout-nonce': nonce, + 'billing_first_name': billingContact.givenName || '', + 'billing_last_name': billingContact.familyName || '', + 'billing_company': '', + 'billing_country': billingContact.countryCode || '', + 'billing_address_1': billingContact.addressLines[0] || '', + 'billing_address_2': billingContact.addressLines[1] || '', + 'billing_postcode': billingContact.postalCode || '', + 'billing_city': billingContact.locality || '', + 'billing_state': billingContact.administrativeArea || '', + 'billing_phone': billingContact.phoneNumber || '000000000000', + 'billing_email': shippingContact.emailAddress || '', + 'shipping_first_name': shippingContact.givenName || '', + 'shipping_last_name': shippingContact.familyName || '', + 'shipping_company': '', + 'shipping_country': shippingContact.countryCode || '', + 'shipping_address_1': shippingContact.addressLines[0] || '', + 'shipping_address_2': shippingContact.addressLines[1] || '', + 'shipping_postcode': shippingContact.postalCode || '', + 'shipping_city': shippingContact.locality || '', + 'shipping_state': shippingContact.administrativeArea || '', + 'shipping_phone': shippingContact.phoneNumber || '000000000000', + 'shipping_email': shippingContact.emailAddress || '', + 'order_comments': '', + 'payment_method': 'mollie_wc_gateway_applepay', + '_wp_http_referer': '/?wc-ajax=update_order_review' + }, + success: (authorizationResult, textStatus, jqXHR) => { + let result = authorizationResult.data + if (authorizationResult.success === true) { + redirectionUrl = result['returnUrl']; + session.completePayment(result['responseToApple']) + window.location.href = redirectionUrl + } else { + result.errors = createAppleErrors(result.errors) + session.completePayment(result) + } + }, + error: (jqXHR, textStatus, errorThrown) => { + console.warn(textStatus, errorThrown) + session.abort() + }, + }) + } + session.begin() + } + + return ( + + ); +} + +export default ApplePayButtonComponent; diff --git a/resources/js/mollieBlockIndex.js b/resources/js/mollieBlockIndex.js index 04c6d367b..fdfaa0141 100644 --- a/resources/js/mollieBlockIndex.js +++ b/resources/js/mollieBlockIndex.js @@ -1,10 +1,12 @@ import molliePaymentMethod from './blocks/molliePaymentMethod' +import ApplePayButtonComponent from './blocks/ApplePayButtonComponent' ( function ({ mollieBlockData, wc, _, jQuery}) { if (_.isEmpty(mollieBlockData)) { return; } + window.onload = (event) => { const { registerPaymentMethod } = wc.wcBlocksRegistry; const { checkoutData, defaultFields } = wc.wcSettings.allSettings; @@ -47,8 +49,24 @@ 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' && !isBlockEditor) { + const {isExpressEnabled} = item; if ((isAppleSession && window.ApplePaySession.canMakePayments())) { register(); + if (isExpressEnabled !== true) { + return; + } + const {registerExpressPaymentMethod} = wc.wcBlocksRegistry; + registerExpressPaymentMethod({ + name: 'mollie_wc_gateway_applepay_express', + content: , + edit: , + ariaLabel: 'Apple Pay', + canMakePayment: () => true, + paymentMethodId: 'mollie_wc_gateway_applepay', + supports: { + features: ['products'], + }, + }) } return; } diff --git a/resources/scss/mollie-applepaydirect.scss b/resources/scss/mollie-applepaydirect.scss index 0cb757d88..07e9ae8fd 100644 --- a/resources/scss/mollie-applepaydirect.scss +++ b/resources/scss/mollie-applepaydirect.scss @@ -3,10 +3,35 @@ } .apple-pay-button { display: inline-block; + width: 100%; -webkit-appearance: -apple-pay-button; -apple-pay-button-type: checkout; /* also: check-out, book, or subscribe */ } +@media (max-width: 480px) { + .apple-pay-button { + height: 41px; + min-height: 40px; + max-height: 47px; + } +} + +@media (min-width: 481px) and (max-width: 1024px) { + .apple-pay-button { + height: 48px; + min-height: 48px; + max-height: 55px; + } +} + +@media (min-width: 1025px) { + .apple-pay-button { + height: 56px; + min-height: 56px; + max-height: 64px; + } +} + .apple-pay-button-black { -apple-pay-button-style: black; } diff --git a/src/Assets/AssetsModule.php b/src/Assets/AssetsModule.php index eeb8cd882..7ef945631 100644 --- a/src/Assets/AssetsModule.php +++ b/src/Assets/AssetsModule.php @@ -74,13 +74,13 @@ public function registerButtonsBlockScripts(string $pluginUrl, string $pluginPat 'mollie_applepayButtonBlock', $this->getPluginUrl( $pluginUrl, - '/public/js/applepayButtonBlockComponent.min.js' + '/public/js/applepayButtonBlock.min.js' ), [], (string) filemtime( $this->getPluginPath( $pluginPath, - '/public/js/applepayButtonBlockComponent.min.js' + '/public/js/applepayButtonBlock.min.js' ) ), true diff --git a/src/Assets/MollieCheckoutBlocksSupport.php b/src/Assets/MollieCheckoutBlocksSupport.php index 450f6b76f..16d2d7481 100644 --- a/src/Assets/MollieCheckoutBlocksSupport.php +++ b/src/Assets/MollieCheckoutBlocksSupport.php @@ -64,12 +64,13 @@ public function get_payment_method_script_handles(): array public static function localizeWCBlocksData($dataService, $gatewayInstances) { - + wp_enqueue_style('mollie-applepaydirect'); wp_localize_script( self::$scriptHandle, 'mollieBlockData', [ 'gatewayData' => self::gatewayDataForWCBlocks($dataService, $gatewayInstances), + 'mollieApplePayBlockDataCart' => $dataService->mollieApplePayBlockDataCart(), ] ); } @@ -112,26 +113,26 @@ public static function gatewayDataForWCBlocks(Data $dataService, array $gatewayI $isSepaEnabled = isset($gatewayInstances['mollie_wc_gateway_directdebit']) && $gatewayInstances['mollie_wc_gateway_directdebit']->enabled === 'yes'; /** @var MolliePaymentGateway $gateway */ foreach ($gatewayInstances as $gatewayKey => $gateway) { - $gatewayId = is_string($gateway->paymentMethod()->getProperty('id')) ? $gateway->paymentMethod( - )->getProperty('id') : ""; + $method = $gateway->paymentMethod(); + $gatewayId = is_string($method->getProperty('id')) ? $method->getProperty('id') : ""; if ($gateway->enabled !== 'yes' || ($gatewayId === 'directdebit' && !is_admin())) { continue; } - $content = $gateway->paymentMethod()->getProcessedDescriptionForBlock(); + $content = $method->getProcessedDescriptionForBlock(); $issuers = false; - if ($gateway->paymentMethod()->getProperty('paymentFields') === true) { - $paymentFieldsService = $gateway->paymentMethod()->paymentFieldsService(); - $paymentFieldsService->setStrategy($gateway->paymentMethod()); - $issuers = $gateway->paymentMethod()->paymentFieldsService()->getStrategyMarkup($gateway); + if ($method->getProperty('paymentFields') === true) { + $paymentFieldsService = $method->paymentFieldsService(); + $paymentFieldsService->setStrategy($method); + $issuers = $method->paymentFieldsService()->getStrategyMarkup($gateway); } if ($gatewayId === 'creditcard') { $content .= $issuers; $issuers = false; } - $title = $gateway->paymentMethod()->title(); + $title = $method->title(); $labelMarkup = "{$title}{$gateway->icon}"; - $hasSurcharge = $gateway->paymentMethod()->hasSurcharge(); + $hasSurcharge = $method->hasSurcharge(); $countryCodes = [ 'BE' => '+32xxxxxxxxx', 'NL' => '+316xxxxxxxx', @@ -154,15 +155,16 @@ public static function gatewayDataForWCBlocks(Data $dataService, array $gatewayI 'edit' => $content, 'paymentMethodId' => $gatewayKey, 'allowedCountries' => is_array( - $gateway->paymentMethod()->getProperty('allowed_countries') - ) ? $gateway->paymentMethod()->getProperty('allowed_countries') : [], - 'ariaLabel' => $gateway->paymentMethod()->getProperty('defaultDescription'), - 'supports' => self::gatewaySupportsFeatures($gateway->paymentMethod(), $isSepaEnabled), - 'errorMessage' => $gateway->paymentMethod()->getProperty('errorMessage'), - 'companyPlaceholder' => $gateway->paymentMethod()->getProperty('companyPlaceholder'), - 'phoneLabel' => $gateway->paymentMethod()->getProperty('phoneLabel'), + $method->getProperty('allowed_countries') + ) ? $method->getProperty('allowed_countries') : [], + 'ariaLabel' => $method->getProperty('defaultDescription'), + 'supports' => self::gatewaySupportsFeatures($method, $isSepaEnabled), + 'errorMessage' => $method->getProperty('errorMessage'), + 'companyPlaceholder' => $method->getProperty('companyPlaceholder'), + 'phoneLabel' => $method->getProperty('phoneLabel'), 'phonePlaceholder' => $phonePlaceholder, - 'birthdatePlaceholder' => $gateway->paymentMethod()->getProperty('birthdatePlaceholder'), + 'birthdatePlaceholder' => $method->getProperty('birthdatePlaceholder'), + 'isExpressEnabled' => $gatewayId === 'applepay' && $method->getProperty('mollie_apple_pay_button_enabled_express_checkout') === 'yes', ]; } $dataToScript['gatewayData'] = $gatewayData; diff --git a/src/Buttons/ApplePayButton/AppleAjaxRequests.php b/src/Buttons/ApplePayButton/AppleAjaxRequests.php index 59a82fb98..ec1b28b1a 100644 --- a/src/Buttons/ApplePayButton/AppleAjaxRequests.php +++ b/src/Buttons/ApplePayButton/AppleAjaxRequests.php @@ -191,7 +191,7 @@ public function updateShippingContact() } $paymentDetails = $this->whichCalculateTotals($applePayRequestDataObject); - $response = $this->responseTemplates->appleFormattedResponse($paymentDetails); + $response = $this->responseTemplates->appleFormattedResponse($paymentDetails, $applePayRequestDataObject); $this->responseTemplates->responseSuccess($response); } @@ -212,7 +212,7 @@ public function updateShippingMethod() $this->responseTemplates->responseWithDataErrors($applePayRequestDataObject->errors()); } $paymentDetails = $this->whichCalculateTotals($applePayRequestDataObject); - $response = $this->responseTemplates->appleFormattedResponse($paymentDetails); + $response = $this->responseTemplates->appleFormattedResponse($paymentDetails, $applePayRequestDataObject); $this->responseTemplates->responseSuccess($response); } diff --git a/src/Buttons/ApplePayButton/DataToAppleButtonScripts.php b/src/Buttons/ApplePayButton/DataToAppleButtonScripts.php index b6e551b25..d3e37ab1c 100644 --- a/src/Buttons/ApplePayButton/DataToAppleButtonScripts.php +++ b/src/Buttons/ApplePayButton/DataToAppleButtonScripts.php @@ -14,6 +14,9 @@ class DataToAppleButtonScripts */ public function applePayScriptData(bool $isBlock = false): array { + if (is_admin()) { + return []; + } $base_location = wc_get_base_location(); $shopCountryCode = $base_location['country']; $currencyCode = get_woocommerce_currency(); diff --git a/src/Buttons/ApplePayButton/ResponsesToApple.php b/src/Buttons/ApplePayButton/ResponsesToApple.php index b4b580c2b..2f9f34cde 100644 --- a/src/Buttons/ApplePayButton/ResponsesToApple.php +++ b/src/Buttons/ApplePayButton/ResponsesToApple.php @@ -84,11 +84,15 @@ public function responseWithDataErrors($errorList) * * @return array */ - public function appleFormattedResponse(array $paymentDetails) + public function appleFormattedResponse(array $paymentDetails, $applePayRequestDataObject) { $response = []; if ($paymentDetails['shippingMethods']) { - $response['newShippingMethods'] = $paymentDetails['shippingMethods']; + $selectedShippingMethod = $applePayRequestDataObject->shippingMethod(); + $response['newShippingMethods'] = $this->reorderShippingMethods( + $paymentDetails['shippingMethods'], + $selectedShippingMethod + ); } $response['newLineItems'] = $this->appleNewLineItemsResponse( @@ -101,6 +105,28 @@ public function appleFormattedResponse(array $paymentDetails) return $response; } + /** + * Reorders the shipping methods to have the selected shipping method on top so we see it as selected + * @param array $methods + * @param array $selectedShippingMethod + * @return array + */ + private function reorderShippingMethods(array $methods, array $selectedShippingMethod): array + { + $reordered_methods = []; + + foreach ($methods as $key => $method) { + if ($method['identifier'] === $selectedShippingMethod['identifier']) { + $reordered_methods[] = $method; + unset($methods[$key]); + break; + } + } + + return array_merge($reordered_methods, array_values($methods)); + } + + /** * Returns a success response to be handled by the script */ diff --git a/src/PaymentMethods/Applepay.php b/src/PaymentMethods/Applepay.php index 63a32c9ab..0ef6f13a6 100644 --- a/src/PaymentMethods/Applepay.php +++ b/src/PaymentMethods/Applepay.php @@ -32,7 +32,6 @@ public function getFormFields($generalFormFields): array $paymentMethodFormFieds = [ 'mollie_apple_pay_button_enabled_cart' => [ 'title' => __('Enable Apple Pay Button on Cart page', 'mollie-payments-for-woocommerce'), - /* translators: Placeholder 1: enabled or disabled */ 'desc' => __( 'Enable the Apple Pay direct buy button on the Cart page', 'mollie-payments-for-woocommerce' @@ -42,7 +41,6 @@ public function getFormFields($generalFormFields): array ], 'mollie_apple_pay_button_enabled_product' => [ 'title' => __('Enable Apple Pay Button on Product page', 'mollie-payments-for-woocommerce'), - /* translators: Placeholder 1: enabled or disabled */ 'desc' => __( 'Enable the Apple Pay direct buy button on the Product page', 'mollie-payments-for-woocommerce' @@ -50,6 +48,12 @@ public function getFormFields($generalFormFields): array 'type' => 'checkbox', 'default' => 'no', ], + 'mollie_apple_pay_button_enabled_express_checkout' => [ + 'title' => __('Enable Apple Pay Express Button on Checkout page', 'mollie-payments-for-woocommerce'), + 'desc' => __('Enable the Apple Pay direct buy button on the Express Buttons section of the Checkout page', 'mollie-payments-for-woocommerce'), + 'type' => 'checkbox', + 'default' => 'no', + ], ]; return array_merge($generalFormFields, $paymentMethodFormFieds); } diff --git a/src/Shared/Data.php b/src/Shared/Data.php index 54230c6db..cf38fd51f 100644 --- a/src/Shared/Data.php +++ b/src/Shared/Data.php @@ -7,6 +7,7 @@ use Exception; use InvalidArgumentException; use Mollie\Api\Resources\Method; +use Mollie\WooCommerce\Buttons\ApplePayButton\DataToAppleButtonScripts; use Mollie\WooCommerce\SDK\Api; use Mollie\WooCommerce\Settings\Settings; use Psr\Log\LoggerInterface as Logger; @@ -786,4 +787,10 @@ protected function addRecurringPaymentMethods($apiKey, bool $testMode, bool $use } return $result; } + + public function mollieApplePayBlockDataCart() + { + $dataToScripts = new DataToAppleButtonScripts(); + return $dataToScripts->applePayScriptData(true); + } } diff --git a/tests/php/Functional/ApplePayButton/DataToAppleButtonScriptsTest.php b/tests/php/Functional/ApplePayButton/DataToAppleButtonScriptsTest.php index 1d4c79cea..40fe4bbda 100644 --- a/tests/php/Functional/ApplePayButton/DataToAppleButtonScriptsTest.php +++ b/tests/php/Functional/ApplePayButton/DataToAppleButtonScriptsTest.php @@ -52,6 +52,7 @@ public function testApplePayScriptDataOnProduct() 'wc_get_product' => $this->wcProduct(), 'admin_url' => 'admin-ajax.php', 'get_option' => false, + 'is_admin' => false, ] ); @@ -97,6 +98,7 @@ public function testApplePayScriptDataOnCart() 'admin_url' => 'admin-ajax.php', 'WC' => $this->wooCommerce($subtotal), 'wp_nonce_field'=> 'testNonce', + 'is_admin' => false, ] ); diff --git a/tests/php/Functional/ApplePayButton/ResponsesToAppleTest.php b/tests/php/Functional/ApplePayButton/ResponsesToAppleTest.php index 5f5c793e3..59908b6b0 100644 --- a/tests/php/Functional/ApplePayButton/ResponsesToAppleTest.php +++ b/tests/php/Functional/ApplePayButton/ResponsesToAppleTest.php @@ -71,7 +71,8 @@ public function testAppleFormattedResponseWithoutShippingMethod() ] ]; - + //shippingMethods is null this is not going to run + $applePayRequestDataObject = []; expect('get_bloginfo') ->once() ->with('name') @@ -82,7 +83,7 @@ public function testAppleFormattedResponseWithoutShippingMethod() $logger = $this->helperMocks->loggerMock(); $appleGateway = $this->mollieGateway('applepay', false, true); $responsesTemplate = new ResponsesToApple($logger, $appleGateway); - $response = $responsesTemplate->appleFormattedResponse($paymentDetails); + $response = $responsesTemplate->appleFormattedResponse($paymentDetails, $applePayRequestDataObject); self::assertEquals($response, $expectedResponse); } @@ -107,6 +108,8 @@ public function testAppleFormattedResponseWithShippingMethod() 'taxes' => $taxes, 'total' => $total ]; + //shippingMethods is null this is not going to run + $applePayRequestDataObject = []; $expectedResponse = [ 'newLineItems'=>[ [ @@ -143,7 +146,7 @@ public function testAppleFormattedResponseWithShippingMethod() $logger = $this->helperMocks->loggerMock(); $appleGateway = $this->mollieGateway('applepay', false, true); $responsesTemplate = new ResponsesToApple($logger, $appleGateway); - $response = $responsesTemplate->appleFormattedResponse($paymentDetails); + $response = $responsesTemplate->appleFormattedResponse($paymentDetails, $applePayRequestDataObject); self::assertEquals($response, $expectedResponse); } diff --git a/webpack.config.js b/webpack.config.js index fbd545086..08b7b5714 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -29,7 +29,7 @@ function configJavaScript ({ basePath }) .addEntry('mollie-components-blocks.min', './resources/js/mollie-components-blocks.js') .addEntry('mollieBlockIndex.min', './resources/js/mollieBlockIndex.js') .addEntry('paypalButtonBlockComponent.min', './resources/js/paypalButtonBlockComponent.js') - .addEntry('applepayButtonBlockComponent.min', './resources/js/applepayButtonBlockComponent.js') + .addEntry('applepayButtonBlock.min', './resources/js/applepayButtonBlock.js') .addEntry('rivertyCountryPlaceholder.min', './resources/js/rivertyCountryPlaceholder.js') .enableSourceMaps(!Encore.isProduction())