From 7429b73174de539ec1efef40a971fa19fce05c8c Mon Sep 17 00:00:00 2001 From: "v.carkaxhija" Date: Fri, 1 Nov 2024 12:57:57 +0100 Subject: [PATCH 1/7] update applepay --- Block/Catalog/Product/View/Applepay.php | 3 +- .../catalog/product/view/applepay.phtml | 69 ++++++++----------- .../templates/checkout/cart/applepay.phtml | 2 +- .../view/checkout/applepay/checkout-cart.js | 4 +- 4 files changed, 34 insertions(+), 44 deletions(-) diff --git a/Block/Catalog/Product/View/Applepay.php b/Block/Catalog/Product/View/Applepay.php index 9870b9d79..5c7bbae2c 100644 --- a/Block/Catalog/Product/View/Applepay.php +++ b/Block/Catalog/Product/View/Applepay.php @@ -62,8 +62,7 @@ public function __construct( */ public function canShowButton($page) { - return $this->cart->getSummaryQty() && - $this->isModuleActive() && + return $this->isModuleActive() && in_array($page, $this->applepayConfigProvider->getAvailableButtons()) && $this->applepayConfigProvider->isApplePayEnabled($this->_storeManager->getStore()); } diff --git a/view/frontend/templates/catalog/product/view/applepay.phtml b/view/frontend/templates/catalog/product/view/applepay.phtml index 8be785333..5d8a149f1 100644 --- a/view/frontend/templates/catalog/product/view/applepay.phtml +++ b/view/frontend/templates/catalog/product/view/applepay.phtml @@ -1,50 +1,41 @@ canShowButton('Product')): ?> -
- +
+
+
+
+
+
+
- - -
diff --git a/view/frontend/templates/checkout/cart/applepay.phtml b/view/frontend/templates/checkout/cart/applepay.phtml index d0e95936d..d9cdbe7ee 100644 --- a/view/frontend/templates/checkout/cart/applepay.phtml +++ b/view/frontend/templates/checkout/cart/applepay.phtml @@ -34,7 +34,7 @@ } showPayButton = function() { require(['jquery', 'buckaroo/applepay/checkout-cart'], function (jQuery, applepayPay) { - applepayPay.showPayButton(); + applepayPay.showPayButton('cart'); }); } diff --git a/view/frontend/web/js/view/checkout/applepay/checkout-cart.js b/view/frontend/web/js/view/checkout/applepay/checkout-cart.js index 42e026c20..8823a1989 100644 --- a/view/frontend/web/js/view/checkout/applepay/checkout-cart.js +++ b/view/frontend/web/js/view/checkout/applepay/checkout-cart.js @@ -32,9 +32,9 @@ define( 'use strict'; return { - showPayButton: function () { + showPayButton: function ($page) { applepayPay.setQuote(quote); - applepayPay.showPayButton('cart'); + applepayPay.showPayButton($page); applepayPay.transactionResult.subscribe( function () { From 679abeb2a58b09279f267bd10cb1a09c7231d027 Mon Sep 17 00:00:00 2001 From: "v.carkaxhija" Date: Fri, 1 Nov 2024 14:40:06 +0100 Subject: [PATCH 2/7] update applepay --- .../catalog/product/view/applepay.phtml | 68 +++++++++---------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/view/frontend/templates/catalog/product/view/applepay.phtml b/view/frontend/templates/catalog/product/view/applepay.phtml index 5d8a149f1..9fa8631b0 100644 --- a/view/frontend/templates/catalog/product/view/applepay.phtml +++ b/view/frontend/templates/catalog/product/view/applepay.phtml @@ -1,41 +1,41 @@ canShowButton('Product')): ?> -
-
-
-
-
+
+
+
+
+
- + From 2f5b1eeba563c2c269709ccde0d5f487cc9bd988 Mon Sep 17 00:00:00 2001 From: "v.carkaxhija" Date: Fri, 1 Nov 2024 15:00:25 +0100 Subject: [PATCH 3/7] update applepay --- view/frontend/templates/catalog/product/view/applepay.phtml | 1 + 1 file changed, 1 insertion(+) diff --git a/view/frontend/templates/catalog/product/view/applepay.phtml b/view/frontend/templates/catalog/product/view/applepay.phtml index 9fa8631b0..120a45323 100644 --- a/view/frontend/templates/catalog/product/view/applepay.phtml +++ b/view/frontend/templates/catalog/product/view/applepay.phtml @@ -38,4 +38,5 @@ }); } + From f67f99a3f1fa77527e6855e3b40f831590bf7627 Mon Sep 17 00:00:00 2001 From: "v.carkaxhija" Date: Fri, 1 Nov 2024 15:18:50 +0100 Subject: [PATCH 4/7] update applepay --- view/frontend/templates/catalog/product/view/applepay.phtml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/view/frontend/templates/catalog/product/view/applepay.phtml b/view/frontend/templates/catalog/product/view/applepay.phtml index 120a45323..639d8aad4 100644 --- a/view/frontend/templates/catalog/product/view/applepay.phtml +++ b/view/frontend/templates/catalog/product/view/applepay.phtml @@ -29,8 +29,11 @@ + + +
diff --git a/view/frontend/web/js/view/checkout/applepay/pay.js b/view/frontend/web/js/view/checkout/applepay/pay.js index 700db28ca..6bbd2789c 100644 --- a/view/frontend/web/js/view/checkout/applepay/pay.js +++ b/view/frontend/web/js/view/checkout/applepay/pay.js @@ -16,639 +16,525 @@ * @copyright Copyright (c) Buckaroo B.V. * @license https://tldrlegal.com/license/mit-license */ -define( - [ - 'jquery', - 'ko', - 'mage/url', - 'Magento_Checkout/js/model/resource-url-manager', - 'buckaroo/applepay/shipping-handler', - 'Magento_Checkout/js/model/payment/additional-validators', - 'underscore', - 'Magento_Checkout/js/model/shipping-rate-service', - 'mage/translate', - 'BuckarooSDK' - ], - function ( - $, - ko, - urlBuilder, - resourceUrlManager, - shippingHandler, - additionalValidators, - _ - ) { - 'use strict'; - - var transactionResult = ko.observable(null); - - return { - transactionResult : transactionResult, - canShowMethod: ko.observable(null), - applepayOptions : null, - isOnCheckout : false, - quote : null, - shippingGroups: {}, - payment: null, - - showPayButton: function (payMode) { - this.devLog('==============applepaydebug/6', payMode); - this.payMode = payMode; - this.productSelected = {}; - - if (typeof window.checkoutConfig === 'undefined') { - return; - } +define([ + 'jquery', + 'ko', + 'mage/url', + 'Magento_Checkout/js/model/resource-url-manager', + 'buckaroo/applepay/shipping-handler', + 'Magento_Checkout/js/model/payment/additional-validators', + 'underscore', + 'Magento_Checkout/js/model/shipping-rate-service', + 'mage/translate', + 'BuckarooSDK' +], function ( + $, + ko, + urlBuilder, + resourceUrlManager, + shippingHandler, + additionalValidators, + _ +) { + 'use strict'; + + var transactionResult = ko.observable(null); + + return { + transactionResult: transactionResult, + canShowMethod: ko.observable(null), + applepayOptions: null, + isOnCheckout: false, + quote: null, + shippingGroups: {}, + payment: null, + productSelected: {}, + + showPayButton: function (payMode) { + this.devLog('applepaydebug/6', payMode); + this.payMode = payMode; + + if (typeof window.checkoutConfig === 'undefined') { + return; + } - if ((this.payMode == 'product') || (this.payMode == 'cart')) { - this.setIsOnCheckout(false); - } else { - this.setIsOnCheckout(true); - } + this.setIsOnCheckout(!(this.payMode === 'product' || this.payMode === 'cart')); - BuckarooSdk.ApplePay.checkApplePaySupport(window.checkoutConfig.payment.buckaroo.applepay.guid).then( - function (applePaySupported) { - this.devLog('==============applepaydebug/8',[ - applePaySupported, - this.isOnCheckout, - window.checkoutConfig.payment.buckaroo.applepay - ]); - - //move to inner block - if (this.payMode == 'product') { - this.initProductViewWatchers(); - } + if (this.payMode === 'product') { + this.initProductViewWatchers(); + } - if (applePaySupported) { - this.generateApplepayOptions(); - - this.payment = new BuckarooSdk.ApplePay.ApplePayPayment('#apple-pay-wrapper', this.applepayOptions); - this.payment.showPayButton( - window.checkoutConfig.payment.buckaroo.applepay.buttonStyle ? - window.checkoutConfig.payment.buckaroo.applepay.buttonStyle : 'black', - 'buy'); - if (this.payMode == 'product') { - this.payment.button.off("click"); - var self = this; - this.payment.button.on("click", function (e) { - self.devLog('==============applepaydebug/24'); - var dataForm = $('#product_addtocart_form'); - dataForm.validation('isValid'); - setTimeout(function () { - if ($('.mage-error:visible').length == 0) { - self.payment.beginPayment(e); - } - }, 100); - }); - } - } - }.bind(this) - ); - }, + BuckarooSdk.ApplePay.checkApplePaySupport(window.checkoutConfig.payment.buckaroo.applepay.guid) + .then(function (applePaySupported) { + this.devLog('applepaydebug/8', [ + applePaySupported, + this.isOnCheckout, + window.checkoutConfig.payment.buckaroo.applepay + ]); - updateOptions: function () { - if (this.payment === null) { - return; - } + if (!applePaySupported) { + return; + } - this.generateApplepayOptions(); - this.payment.options = this.applepayOptions; - }, - - canShowApplePay:function () { - //ZAK - //return true; - BuckarooSdk.ApplePay.checkApplePaySupport(window.checkoutConfig.payment.buckaroo.applepay.guid).then( - function (applePaySupported) { - this.canShowMethod(applePaySupported); - }.bind(this) - ); - - return this.canShowMethod(); - }, - - /** - * @param newQuote - */ - setQuote: function (newQuote) { - this.quote = newQuote; - }, - - /** - * @param isOnCheckout - */ - setIsOnCheckout: function (isOnCheckout) { - this.isOnCheckout = isOnCheckout; - }, - - generateApplepayOptions: function () { - var self = this; - var lineItemsType = 'pending'; - var shippingMethods = self.availableShippingMethodInformation(); - var shippingContactCallback = self.onSelectedShippingContact.bind(this); - var shipmentMethodCallback = self.onSelectedShipmentMethod.bind(this); - var requiredBillingContactFields = ["name", "postalAddress", "phone"]; - var requiredShippingContactFields = ["name", "postalAddress", "phone"]; - - var country = window.checkoutConfig.payment.buckaroo.applepay.country; - this.devLog('==============applepaydebug/11', this.quote); - if (this.quote && (null !== this.quote.shippingAddress())) { - country = this.quote.shippingAddress().countryId; - } + this.generateApplepayOptions(); - if (!this.isOnCheckout && !window.isCustomerLoggedIn) { - requiredBillingContactFields.push("email"); - requiredShippingContactFields.push("email"); - } + this.payment = new BuckarooSdk.ApplePay.ApplePayPayment('#apple-pay-wrapper', this.applepayOptions); + this.payment.showPayButton( + window.checkoutConfig.payment.buckaroo.applepay.buttonStyle || 'black', + 'buy' + ); + + if (this.payMode === 'product') { + this.payment.button.off('click'); + this.payment.button.on('click', function (e) { + this.devLog('applepaydebug/24'); + var dataForm = $('#product_addtocart_form'); + dataForm.validation('isValid'); - if (this.isOnCheckout) { - lineItemsType = 'final'; - shippingMethods = []; - shippingContactCallback = null; - shipmentMethodCallback = null; - requiredBillingContactFields = ["postalAddress"]; - requiredShippingContactFields = []; - if (window.checkoutConfig.payment.buckaroo.applepay.dontAskBillingInfoInCheckout) { - requiredBillingContactFields = []; + setTimeout(function () { + if ($('.mage-error:visible').length === 0) { + this.payment.beginPayment(e); + } + }.bind(this), 100); + }.bind(this)); } - } + }.bind(this)) + .catch(function (error) { + this.devLog('Apple Pay support check failed:', error); + }.bind(this)); + }, - this.devLog('==============applepaydebug/13', [country, requiredBillingContactFields, requiredShippingContactFields]); - - this.applepayOptions = new BuckarooSdk.ApplePay.ApplePayOptions( - window.checkoutConfig.payment.buckaroo.applepay.storeName, - country, - window.checkoutConfig.payment.buckaroo.applepay.currency, - window.checkoutConfig.payment.buckaroo.applepay.cultureCode, - window.checkoutConfig.payment.buckaroo.applepay.guid, - self.processLineItems(lineItemsType), - self.processTotalLineItems(lineItemsType), - "shipping", - shippingMethods, - self.captureFunds.bind(this), - shipmentMethodCallback, - shippingContactCallback, - requiredBillingContactFields, - requiredShippingContactFields - ); - }, - - /** - * @param type - * - * @returns {{amount: string, label, type: string}[]} - */ - processLineItems: function (type = 'final', directTotals = false) { - var subTotal = '0.00'; - var shippingInclTax = '0.00'; - var totals = directTotals ? directTotals : this.getQuoteTotals(); - - if ('subtotal' in totals && 'shipping' in totals) { - subTotal = parseFloat(totals['subtotal']).toFixed(2); - shippingInclTax = parseFloat(totals['shipping']).toFixed(2); - } + updateOptions: function () { + if (!this.payment) { + return; + } - var lineItems = [ - {label: $.mage.__('Subtotal'), amount: subTotal, type: type}, - {label: $.mage.__('Delivery costs'), amount: shippingInclTax, type: type} - ]; + this.generateApplepayOptions(); + this.payment.options = this.applepayOptions; + }, + + canShowApplePay: function () { + BuckarooSdk.ApplePay.checkApplePaySupport(window.checkoutConfig.payment.buckaroo.applepay.guid) + .then(function (applePaySupported) { + this.canShowMethod(applePaySupported); + }.bind(this)) + .catch(function () { + this.canShowMethod(false); + }.bind(this)); - if ('discount' in totals && totals['discount'] < 0) { - var discountTotal = parseFloat(totals['discount']).toFixed(2); - lineItems.push({label: $.mage.__('Discount'), amount: discountTotal, type: type}); - } + return this.canShowMethod(); + }, - return lineItems; - }, - - /** - * @param type - * - * @returns {{amount: string, label: *, type: string}} - */ - processTotalLineItems: function (type = 'final', directTotals = false) { - var grandTotal = '0.00'; - var storeName = window.checkoutConfig.payment.buckaroo.applepay.storeName; - var totals = directTotals ? directTotals : this.getQuoteTotals(); - - if ('grand_total' in totals) { - grandTotal = parseFloat(totals['grand_total']).toFixed(2); - } - if (isNaN(grandTotal)) grandTotal = 0; - return {label: storeName, amount: grandTotal, type: type}; - }, - - /** - * @returns {Array} - */ - getQuoteTotals: function () { - var totals = {}; - - if (!this.quote || typeof this.quote.totals() === 'undefined') { - return totals; - } + setQuote: function (newQuote) { + this.quote = newQuote; + }, - totals['subtotal'] = this.quote.totals().subtotal_incl_tax; - totals['discount'] = this.quote.totals().discount_amount; - totals['shipping'] = this.quote.totals().shipping_incl_tax; - totals['grand_total'] = this.quote.totals().grand_total; + setIsOnCheckout: function (isOnCheckout) { + this.isOnCheckout = isOnCheckout; + }, - var customGrandTotal = this.quote.totals().custom_grand_total; + generateApplepayOptions: function () { + var lineItemsType = this.isOnCheckout ? 'final' : 'pending'; + var shippingMethods = this.isOnCheckout ? [] : this.availableShippingMethodInformation(); + var shippingContactCallback = this.isOnCheckout ? null : this.onSelectedShippingContact.bind(this); + var shipmentMethodCallback = this.isOnCheckout ? null : this.onSelectedShipmentMethod.bind(this); + var requiredBillingContactFields = this.isOnCheckout ? ['postalAddress'] : ['name', 'postalAddress', 'phone']; + var requiredShippingContactFields = this.isOnCheckout ? [] : ['name', 'postalAddress', 'phone']; - if (customGrandTotal !== undefined && customGrandTotal) { - return totals; - } + if (!this.isOnCheckout && !window.isCustomerLoggedIn) { + requiredBillingContactFields.push('email'); + requiredShippingContactFields.push('email'); + } - var segments = this.quote.totals().total_segments; + if (this.isOnCheckout && window.checkoutConfig.payment.buckaroo.applepay.dontAskBillingInfoInCheckout) { + requiredBillingContactFields = []; + } - for (let i in segments) { - if (segments[i]['code'] === 'grand_total') { - totals['grand_total'] = segments[i]['value']; - } - } + var country = window.checkoutConfig.payment.buckaroo.applepay.country; + if (this.quote && this.quote.shippingAddress()) { + country = this.quote.shippingAddress().countryId || country; + } - return totals; - }, + this.devLog('applepaydebug/13', [country, requiredBillingContactFields, requiredShippingContactFields]); + + this.applepayOptions = new BuckarooSdk.ApplePay.ApplePayOptions( + window.checkoutConfig.payment.buckaroo.applepay.storeName, + country, + window.checkoutConfig.payment.buckaroo.applepay.currency, + window.checkoutConfig.payment.buckaroo.applepay.cultureCode, + window.checkoutConfig.payment.buckaroo.applepay.guid, + this.processLineItems(lineItemsType), + this.processTotalLineItems(lineItemsType), + 'shipping', + shippingMethods, + this.captureFunds.bind(this), + shipmentMethodCallback, + shippingContactCallback, + requiredBillingContactFields, + requiredShippingContactFields + ); + }, + + processLineItems: function (type = 'final', directTotals = false) { + var totals = directTotals || this.getQuoteTotals(); + var subTotal = parseFloat(totals.subtotal || '0.00').toFixed(2); + var shippingInclTax = parseFloat(totals.shipping || '0.00').toFixed(2); + + var lineItems = [ + { label: $.mage.__('Subtotal'), amount: subTotal, type: type }, + { label: $.mage.__('Delivery costs'), amount: shippingInclTax, type: type } + ]; + + if (totals.discount && totals.discount < 0) { + var discountTotal = parseFloat(totals.discount).toFixed(2); + lineItems.push({ label: $.mage.__('Discount'), amount: discountTotal, type: type }); + } - availableShippingMethodInformation: function () { - var shippingMethods = []; + return lineItems; + }, - $.each(this.shippingGroups, function (index, rate) { - var shippingInclTax = parseFloat(rate['price_incl_tax']).toFixed(2); + processTotalLineItems: function (type = 'final', directTotals = false) { + var totals = directTotals || this.getQuoteTotals(); + var grandTotal = parseFloat(totals.grand_total || '0.00').toFixed(2); + if (isNaN(grandTotal)) { + grandTotal = '0.00'; + } + var storeName = window.checkoutConfig.payment.buckaroo.applepay.storeName; - shippingMethods.push({ - label: rate['carrier_title'], - amount: shippingInclTax, - identifier: rate['method_code'], - detail: rate['method_title'] - }); - }); + return { label: storeName, amount: grandTotal, type: type }; + }, - return shippingMethods; - }, + getQuoteTotals: function () { + if (!this.quote || typeof this.quote.totals() === 'undefined') { + return {}; + } - timeoutRedirect: function (url = false) { - this.devLog('==============applepaydebug/38', url); - /** Set Timeout to prevent Safari from crashing and reload window to show error in Magento. */ - setTimeout( - function() { - if (url) { - window.location.href = url; - } else { - window.location.reload(); - } - }, 1500 - ) - }, - - onSelectedShipmentMethod: function (event) { - this.devLog('==============applepaydebug/27'); - - if ((this.payMode == 'product') || (this.payMode == 'cart')) { - var update = $.ajax({ - url: urlBuilder.build('buckaroo/applepay/updateShippingMethods'), - type: 'POST', - data: { - wallet: { - identifier: event.identifier - } - }, - global: false, - dataType: 'json', - async: false, - dataFilter: function(data, type) { - var result = JSON.parse(data); - if (result.success == 'true') { - - var authorizationResult = { - newTotal: this.processTotalLineItems('final', result.data.totals), - newLineItems: this.processLineItems('final', result.data.totals) - }; - - this.devLog('==============applepaydebug/37'); - - return JSON.stringify(authorizationResult); - } else { - this.timeoutRedirect(); - } - }.bind(this), - }) - .fail(function() { - this.timeoutRedirect(); - }.bind(this)); + var totals = { + subtotal: this.quote.totals().subtotal_incl_tax, + discount: this.quote.totals().discount_amount, + shipping: this.quote.totals().shipping_incl_tax, + grand_total: this.quote.totals().grand_total + }; - return update; + if (this.quote.totals().custom_grand_total) { + return totals; + } - } else { + var segments = this.quote.totals().total_segments || []; + segments.forEach(function (segment) { + if (segment.code === 'grand_total') { + totals.grand_total = segment.value; + } + }); - var newShippingMethod = this.shippingGroups[event.identifier]; - this.updateQuoteRate(newShippingMethod); + return totals; + }, - var authorizationResult = { - newTotal: this.processTotalLineItems(), - newLineItems: this.processLineItems() - }; + availableShippingMethodInformation: function () { + var shippingMethods = []; - return Promise.resolve(authorizationResult); - } - }, - - onSelectedShippingContact: function (event) { - this.devLog('==============applepaydebug/28'); - - if (this.payMode == 'product') { - - var update = $.ajax({ - url: urlBuilder.build('buckaroo/applepay/add'), - type: 'POST', - data: { - product: this.productSelected, - wallet: event - }, - global: false, - dataType: 'json', - async: false, - dataFilter: function(data, type) { - var result = JSON.parse(data); - if (result.success == 'true') { - - this.shippingGroups = {}; - $.each(result.data.shipping_methods, function (index, rate) { - this.shippingGroups[rate['method_code']] = rate; - }.bind(this)); - - var authorizationResult = { - errors: [], - newShippingMethods: this.availableShippingMethodInformation(), - newTotal: this.processTotalLineItems('final', result.data.totals), - newLineItems: this.processLineItems('final', result.data.totals) - }; - - this.devLog('==============applepaydebug/30'); - - return JSON.stringify(authorizationResult); - } else { - this.timeoutRedirect(); - } - }.bind(this), - }) - .fail(function() { - this.timeoutRedirect(); - }.bind(this)); - - return update; - } else if (this.payMode == 'cart') { - - var update = $.ajax({ - url: urlBuilder.build('buckaroo/applepay/getShippingMethods'), - type: 'POST', - data: { - wallet: event - }, - global: false, - dataType: 'json', - async: false, - dataFilter: function(data, type) { - var result = JSON.parse(data); - if (result.success == 'true') { - - this.shippingGroups = {}; - $.each(result.data.shipping_methods, function (index, rate) { - this.shippingGroups[rate['method_code']] = rate; - }.bind(this)); - - var authorizationResult = { - errors: [], - newShippingMethods: this.availableShippingMethodInformation(), - newTotal: this.processTotalLineItems('final', result.data.totals), - newLineItems: this.processLineItems('final', result.data.totals) - }; - - this.devLog('==============applepaydebug/53'); - - return JSON.stringify(authorizationResult); - } else { - this.timeoutRedirect(); - } - }.bind(this), - }) - .fail(function() { - this.timeoutRedirect(); - }.bind(this)); + $.each(this.shippingGroups, function (index, rate) { + var shippingInclTax = parseFloat(rate.price_incl_tax).toFixed(2); + + shippingMethods.push({ + label: rate.carrier_title, + amount: shippingInclTax, + identifier: rate.method_code, + detail: rate.method_title + }); + }); - return update; + return shippingMethods; + }, + + timeoutRedirect: function (url) { + this.devLog('applepaydebug/38', url); + setTimeout(function () { + if (url) { + window.location.href = url; } else { - var newShippingAddress = shippingHandler.setShippingAddress(event); - this.updateShippingMethods(newShippingAddress); + window.location.reload(); } + }, 1500); + }, + + onSelectedShipmentMethod: function (event) { + this.devLog('applepaydebug/27'); + + if (this.payMode === 'product' || this.payMode === 'cart') { + return $.ajax({ + url: urlBuilder.build('buckaroo/applepay/updateShippingMethods'), + type: 'POST', + data: { + wallet: { + identifier: event.identifier + } + }, + global: false, + dataType: 'json' + }).then(function (result) { + if (result.success === 'true') { + var authorizationResult = { + newTotal: this.processTotalLineItems('final', result.data.totals), + newLineItems: this.processLineItems('final', result.data.totals) + }; + + this.devLog('applepaydebug/37'); + + return authorizationResult; + } else { + this.timeoutRedirect(); + return $.Deferred().reject(); + } + }.bind(this)).fail(function () { + this.timeoutRedirect(); + return $.Deferred().reject(); + }.bind(this)); + } else { + var newShippingMethod = this.shippingGroups[event.identifier]; + this.updateQuoteRate(newShippingMethod); var authorizationResult = { - errors: [], - newShippingMethods: this.availableShippingMethodInformation(), newTotal: this.processTotalLineItems(), newLineItems: this.processLineItems() }; return Promise.resolve(authorizationResult); - }, - - updateShippingMethods: function (address) { - this.devLog('==============applepaydebug/16'); - var serviceUrl = resourceUrlManager.getUrlForEstimationShippingMethodsForNewAddress(this.quote); - var payload = JSON.stringify({ - address: { - 'street': address.street, - 'city': address.city, - 'region_id': address.regionId, - 'region': address.region, - 'country_id': address.countryId, - 'postcode': address.postcode, - 'firstname': address.firstname, - 'lastname': address.lastname, - 'company': address.company, - 'telephone': address.telephone, - 'custom_attributes': address.customAttributes, - 'save_in_address_book': address.saveInAddressBook - } - }); - - $.ajax({ - url: urlBuilder.build(serviceUrl), - type: 'POST', - data: payload, - global: false, - contentType: 'application/json', - async: false - }).done(function (result) { - this.shippingGroups = {}; - var firstLoop = true; - - $.each(result, function (index, rate) { - this.shippingGroups[rate['method_code']] = rate; - - if (firstLoop) { - this.updateQuoteRate(rate); - firstLoop = false; - } - }.bind(this)); - }.bind(this)); - }, + } + }, - updateQuoteRate: function (newRate) { - shippingHandler.selectShippingMethod(newRate); + onSelectedShippingContact: function (event) { + this.devLog('applepaydebug/28'); - var subtotal = this.quote.totals().subtotal_incl_tax; - this.quote.totals().shipping_incl_tax = newRate['price_incl_tax']; - this.quote.totals().grand_total = subtotal + newRate['price_incl_tax']; - this.quote.totals().custom_grand_total = true; - }, + if (this.payMode === 'product' || this.payMode === 'cart') { + var urlEndpoint = this.payMode === 'product' ? 'buckaroo/applepay/add' : 'buckaroo/applepay/getShippingMethods'; + var requestData = this.payMode === 'product' ? { product: this.productSelected, wallet: event } : { wallet: event }; - /** - * @param payment - * @returns {Promise<{errors: Array, status: *}>} - */ - captureFunds: function (payment) { - this.devLog('==========applepaydebug/12',payment); + return $.ajax({ + url: urlBuilder.build(urlEndpoint), + type: 'POST', + data: requestData, + global: false, + dataType: 'json' + }).then(function (result) { + if (result.success === 'true') { + this.shippingGroups = {}; + $.each(result.data.shipping_methods, function (index, rate) { + this.shippingGroups[rate.method_code] = rate; + }.bind(this)); - var authorizationResult = { - status: ApplePaySession.STATUS_SUCCESS, - errors: [] - }; + var authorizationResult = { + errors: [], + newShippingMethods: this.availableShippingMethodInformation(), + newTotal: this.processTotalLineItems('final', result.data.totals), + newLineItems: this.processLineItems('final', result.data.totals) + }; - if ((this.payMode == 'product') || (this.payMode == 'cart')) { + this.devLog('applepaydebug/30'); - var authorizationFailedResult = { + return authorizationResult; + } else { + this.timeoutRedirect(); + return $.Deferred().reject(); + } + }.bind(this)).fail(function () { + this.timeoutRedirect(); + return $.Deferred().reject(); + }.bind(this)); + } else { + var newShippingAddress = shippingHandler.setShippingAddress(event); + return this.updateShippingMethods(newShippingAddress).then(function () { + var authorizationResult = { + errors: [], + newShippingMethods: this.availableShippingMethodInformation(), + newTotal: this.processTotalLineItems(), + newLineItems: this.processLineItems() + }; + return authorizationResult; + }.bind(this)); + } + }, + + updateShippingMethods: function (address) { + this.devLog('applepaydebug/16'); + var serviceUrl = resourceUrlManager.getUrlForEstimationShippingMethodsForNewAddress(this.quote); + var payload = JSON.stringify({ + address: { + street: address.street, + city: address.city, + region_id: address.regionId, + region: address.region, + country_id: address.countryId, + postcode: address.postcode, + firstname: address.firstname, + lastname: address.lastname, + company: address.company, + telephone: address.telephone, + custom_attributes: address.customAttributes, + save_in_address_book: address.saveInAddressBook + } + }); + + return $.ajax({ + url: urlBuilder.build(serviceUrl), + type: 'POST', + data: payload, + global: false, + contentType: 'application/json', + dataType: 'json' + }).done(function (result) { + this.shippingGroups = {}; + var firstLoop = true; + + $.each(result, function (index, rate) { + this.shippingGroups[rate.method_code] = rate; + + if (firstLoop) { + this.updateQuoteRate(rate); + firstLoop = false; + } + }.bind(this)); + }.bind(this)).fail(function () { + this.devLog('Failed to update shipping methods'); + }.bind(this)); + }, + + updateQuoteRate: function (newRate) { + shippingHandler.selectShippingMethod(newRate); + + var subtotal = parseFloat(this.quote.totals().subtotal_incl_tax || 0); + var shipping = parseFloat(newRate.price_incl_tax || 0); + this.quote.totals().shipping_incl_tax = shipping; + this.quote.totals().grand_total = subtotal + shipping; + this.quote.totals().custom_grand_total = true; + }, + + captureFunds: function (payment) { + this.devLog('applepaydebug/12', payment); + + var authorizationResult = { + status: ApplePaySession.STATUS_SUCCESS, + errors: [] + }; + + if (this.payMode === 'product' || this.payMode === 'cart') { + return $.ajax({ + url: urlBuilder.build('buckaroo/applepay/saveOrder'), + type: 'POST', + data: { + payment: payment, + extra: this.getData(payment) + }, + global: false, + dataType: 'json' + }).then(function (result) { + if (result.success === 'true') { + if (result.data && result.data.RequiredAction && result.data.RequiredAction.RedirectURL) { + this.timeoutRedirect(result.data.RequiredAction.RedirectURL); + } else { + this.timeoutRedirect(); + } + this.payMode = ''; + return authorizationResult; + } else { + this.timeoutRedirect(); + return { + status: ApplePaySession.STATUS_FAILURE, + errors: [] + }; + } + }.bind(this)).fail(function () { + this.timeoutRedirect(); + return { status: ApplePaySession.STATUS_FAILURE, errors: [] }; + }.bind(this)); + } else { + this.transactionResult(payment); + return Promise.resolve(authorizationResult); + } + }, + + getData: function (payment) { + var transactionData = this.formatTransactionResponse(payment); + + return { + method: 'buckaroo_magento2_applepay', + po_number: null, + additional_data: { + applepayTransaction: transactionData, + billingContact: payment && payment.billingContact + ? JSON.stringify(payment.billingContact) + : '' + } + }; + }, + formatTransactionResponse: function (response) { + if (!response || !response.token || !response.token.paymentData) { + return null; + } - var update = $.ajax({ - url: urlBuilder.build('buckaroo/applepay/saveOrder'), - type: 'POST', - data: { - payment: payment, - extra: this.getData(payment) - }, - global: false, - dataType: 'json', - async: false, - dataFilter: function(data, type) { - var result = JSON.parse(data); - if (result.success == 'true') { - if (result.data && result.data.RequiredAction !== undefined && result.data.RequiredAction.RedirectURL !== undefined) { - this.timeoutRedirect(result.data.RequiredAction.RedirectURL); - } else { - this.timeoutRedirect(); - } - this.payMode = ''; - return JSON.stringify(authorizationResult); - } else { - this.timeoutRedirect(); - } - }.bind(this), - }) - .fail(function() { - this.timeoutRedirect(); - }.bind(this)); + var paymentData = response.token.paymentData; - return update; + var formattedData = { + paymentData: { + version: paymentData.version, + data: paymentData.data, + signature: paymentData.signature, + header: paymentData.header + } + }; - } else { + return JSON.stringify(formattedData); + }, - this.transactionResult(payment); + initProductViewWatchers: function () { + this.devLog('applepaydebug/initProductViewWatchers'); - return Promise.resolve(authorizationResult); - } - }, - - getData: function (payment) { - var transactionResult = payment; - var transactionData = this.formatTransactionResponse(transactionResult); - - return { - "method": 'buckaroo_magento2_applepay', - "po_number": null, - "additional_data": { - "applepayTransaction" : transactionData, - "billingContact" : transactionResult && transactionResult.billingContact ? - JSON.stringify(transactionResult.billingContact) : '' - } - }; - }, - - /** - * @param response - * @returns {string|null} - */ - formatTransactionResponse: function (response) { - if (null === response || 'undefined' === response) { - return null; - } + var productId = $('.price-box').attr('data-product-id'); + var productQty = $('#qty').val() || '1'; - var paymentData = response.token.paymentData; - - var formattedData = { - "paymentData": { - "version": paymentData.version, - "data": paymentData.data, - "signature": paymentData.signature, - "header": { - "ephemeralPublicKey": paymentData.header.ephemeralPublicKey, - "publicKeyHash": paymentData.header.publicKeyHash, - "transactionId": paymentData.header.transactionId, - } - } - }; + if (!productId) { + console.error('Product ID not found on the page.'); + return; + } - return JSON.stringify(formattedData); - }, + this.productSelected.id = productId; + this.productSelected.qty = productQty; - initProductViewWatchers: function () { - this.devLog('==============applepaydebug/initProductViewWatchers'); + $('#qty').on('change', function () { + this.productSelected.qty = $(this).val(); + }.bind(this)); - this.productSelected.id = $('.price-box').attr('data-product-id'); - this.productSelected.qty = $('#qty').val(); - var self = this; + $('.product-options-wrapper').on('click', 'div', function () { + var selectedOptions = {}; + $('div.swatch-attribute').each(function () { + var attributeId = $(this).attr('attribute-id') || $(this).attr('data-attribute-id'); + var optionSelected = $(this).attr('option-selected') || $(this).attr('data-option-selected'); - $('#qty').change(function() { - self.productSelected.qty = $(this).val(); + if (attributeId && optionSelected) { + selectedOptions[attributeId] = optionSelected; + } }); - $('.product-options-wrapper div').click(function() { - var selected_options = {}; - $('div.swatch-attribute').each(function(k,v){ - var attribute_id = $(v).attr('attribute-id'); - var option_selected = $(v).attr('option-selected'); - if(!attribute_id || !option_selected) { - attribute_id = $(v).attr('data-attribute-id'); - option_selected = $(v).attr('data-option-selected'); - if(!attribute_id || !option_selected) { - return; - } - } - selected_options[attribute_id] = option_selected; - }); + this.productSelected.selected_options = selectedOptions; + }.bind(this)); + }, - self.productSelected.selected_options = selected_options; - }); - }, + isOsc: function () { + return !!this.getOscButton(); + }, - isOsc: function () { - return this.getOscButton(); - }, + getOscButton: function () { + return document.querySelector('.action.primary.checkout.iosc-place-order-button'); + }, - getOscButton: function () { - return document.querySelector('.action.primary.checkout.iosc-place-order-button'); - }, - - devLog: function (msg, params) { - //window.buckarooDebug = 1; - if (window.buckarooDebug) { - console.log(msg, params); - } + devLog: function (msg, params) { + if (window.buckarooDebug) { + console.log(msg, params); } - - }; - } -); + } + }; +}); From 5e0c0650f79368bc05113ba1b5b6d73c46afa64b Mon Sep 17 00:00:00 2001 From: "v.carkaxhija" Date: Tue, 5 Nov 2024 14:15:29 +0100 Subject: [PATCH 6/7] update applepay --- .../web/js/view/checkout/applepay/pay.js | 1038 +++++++++-------- 1 file changed, 582 insertions(+), 456 deletions(-) diff --git a/view/frontend/web/js/view/checkout/applepay/pay.js b/view/frontend/web/js/view/checkout/applepay/pay.js index 6bbd2789c..ae4efa01f 100644 --- a/view/frontend/web/js/view/checkout/applepay/pay.js +++ b/view/frontend/web/js/view/checkout/applepay/pay.js @@ -16,525 +16,651 @@ * @copyright Copyright (c) Buckaroo B.V. * @license https://tldrlegal.com/license/mit-license */ -define([ - 'jquery', - 'ko', - 'mage/url', - 'Magento_Checkout/js/model/resource-url-manager', - 'buckaroo/applepay/shipping-handler', - 'Magento_Checkout/js/model/payment/additional-validators', - 'underscore', - 'Magento_Checkout/js/model/shipping-rate-service', - 'mage/translate', - 'BuckarooSDK' -], function ( - $, - ko, - urlBuilder, - resourceUrlManager, - shippingHandler, - additionalValidators, - _ -) { - 'use strict'; - - var transactionResult = ko.observable(null); - - return { - transactionResult: transactionResult, - canShowMethod: ko.observable(null), - applepayOptions: null, - isOnCheckout: false, - quote: null, - shippingGroups: {}, - payment: null, - productSelected: {}, - - showPayButton: function (payMode) { - this.devLog('applepaydebug/6', payMode); - this.payMode = payMode; - - if (typeof window.checkoutConfig === 'undefined') { - return; - } - - this.setIsOnCheckout(!(this.payMode === 'product' || this.payMode === 'cart')); +define( + [ + 'jquery', + 'ko', + 'mage/url', + 'Magento_Checkout/js/model/resource-url-manager', + 'buckaroo/applepay/shipping-handler', + 'Magento_Checkout/js/model/payment/additional-validators', + 'underscore', + 'Magento_Checkout/js/model/shipping-rate-service', + 'mage/translate', + 'BuckarooSDK' + ], + function ( + $, + ko, + urlBuilder, + resourceUrlManager, + shippingHandler, + additionalValidators, + _ + ) { + 'use strict'; + + var transactionResult = ko.observable(null); + + return { + transactionResult : transactionResult, + canShowMethod: ko.observable(null), + applepayOptions : null, + isOnCheckout : false, + quote : null, + shippingGroups: {}, + payment: null, + + showPayButton: function (payMode) { + this.devLog('==============applepaydebug/6', payMode); + this.payMode = payMode; + this.productSelected = {}; + + if (typeof window.checkoutConfig === 'undefined') { + return; + } - if (this.payMode === 'product') { - this.initProductViewWatchers(); - } + if ((this.payMode == 'product') || (this.payMode == 'cart')) { + this.setIsOnCheckout(false); + } else { + this.setIsOnCheckout(true); + } - BuckarooSdk.ApplePay.checkApplePaySupport(window.checkoutConfig.payment.buckaroo.applepay.guid) - .then(function (applePaySupported) { - this.devLog('applepaydebug/8', [ - applePaySupported, - this.isOnCheckout, - window.checkoutConfig.payment.buckaroo.applepay - ]); + BuckarooSdk.ApplePay.checkApplePaySupport(window.checkoutConfig.payment.buckaroo.applepay.guid).then( + function (applePaySupported) { + this.devLog('==============applepaydebug/8',[ + applePaySupported, + this.isOnCheckout, + window.checkoutConfig.payment.buckaroo.applepay + ]); + + //move to inner block + if (this.payMode == 'product') { + this.initProductViewWatchers(); + } - if (!applePaySupported) { - return; - } + if (applePaySupported) { + this.generateApplepayOptions(); + + this.payment = new BuckarooSdk.ApplePay.ApplePayPayment('#apple-pay-wrapper', this.applepayOptions); + this.payment.showPayButton( + window.checkoutConfig.payment.buckaroo.applepay.buttonStyle ? + window.checkoutConfig.payment.buckaroo.applepay.buttonStyle : 'black', + 'buy'); + if (this.payMode == 'product') { + this.payment.button.off("click"); + var self = this; + this.payment.button.on("click", function (e) { + self.devLog('==============applepaydebug/24'); + var dataForm = $('#product_addtocart_form'); + dataForm.validation('isValid'); + setTimeout(function () { + if ($('.mage-error:visible').length == 0) { + self.payment.beginPayment(e); + } + }, 100); + }); + } + } + }.bind(this) + ); + }, - this.generateApplepayOptions(); + updateOptions: function () { + if (this.payment === null) { + return; + } - this.payment = new BuckarooSdk.ApplePay.ApplePayPayment('#apple-pay-wrapper', this.applepayOptions); - this.payment.showPayButton( - window.checkoutConfig.payment.buckaroo.applepay.buttonStyle || 'black', - 'buy' - ); + this.generateApplepayOptions(); + this.payment.options = this.applepayOptions; + }, + + canShowApplePay:function () { + //ZAK + //return true; + BuckarooSdk.ApplePay.checkApplePaySupport(window.checkoutConfig.payment.buckaroo.applepay.guid).then( + function (applePaySupported) { + this.canShowMethod(applePaySupported); + }.bind(this) + ); + + return this.canShowMethod(); + }, + + /** + * @param newQuote + */ + setQuote: function (newQuote) { + this.quote = newQuote; + }, + + /** + * @param isOnCheckout + */ + setIsOnCheckout: function (isOnCheckout) { + this.isOnCheckout = isOnCheckout; + }, + + generateApplepayOptions: function () { + var self = this; + var lineItemsType = 'pending'; + var shippingMethods = self.availableShippingMethodInformation(); + var shippingContactCallback = self.onSelectedShippingContact.bind(this); + var shipmentMethodCallback = self.onSelectedShipmentMethod.bind(this); + var requiredBillingContactFields = ["name", "postalAddress", "phone"]; + var requiredShippingContactFields = ["name", "postalAddress", "phone"]; + + var country = window.checkoutConfig.payment.buckaroo.applepay.country; + this.devLog('==============applepaydebug/11', this.quote); + if (this.quote && (null !== this.quote.shippingAddress())) { + country = this.quote.shippingAddress().countryId; + } - if (this.payMode === 'product') { - this.payment.button.off('click'); - this.payment.button.on('click', function (e) { - this.devLog('applepaydebug/24'); - var dataForm = $('#product_addtocart_form'); - dataForm.validation('isValid'); + if (!this.isOnCheckout && !window.isCustomerLoggedIn) { + requiredBillingContactFields.push("email"); + requiredShippingContactFields.push("email"); + } - setTimeout(function () { - if ($('.mage-error:visible').length === 0) { - this.payment.beginPayment(e); - } - }.bind(this), 100); - }.bind(this)); + if (this.isOnCheckout) { + lineItemsType = 'final'; + shippingMethods = []; + shippingContactCallback = null; + shipmentMethodCallback = null; + requiredBillingContactFields = ["postalAddress"]; + requiredShippingContactFields = []; + if (window.checkoutConfig.payment.buckaroo.applepay.dontAskBillingInfoInCheckout) { + requiredBillingContactFields = []; } - }.bind(this)) - .catch(function (error) { - this.devLog('Apple Pay support check failed:', error); - }.bind(this)); - }, - - updateOptions: function () { - if (!this.payment) { - return; - } + } - this.generateApplepayOptions(); - this.payment.options = this.applepayOptions; - }, - - canShowApplePay: function () { - BuckarooSdk.ApplePay.checkApplePaySupport(window.checkoutConfig.payment.buckaroo.applepay.guid) - .then(function (applePaySupported) { - this.canShowMethod(applePaySupported); - }.bind(this)) - .catch(function () { - this.canShowMethod(false); - }.bind(this)); + this.devLog('==============applepaydebug/13', [country, requiredBillingContactFields, requiredShippingContactFields]); + + this.applepayOptions = new BuckarooSdk.ApplePay.ApplePayOptions( + window.checkoutConfig.payment.buckaroo.applepay.storeName, + country, + window.checkoutConfig.payment.buckaroo.applepay.currency, + window.checkoutConfig.payment.buckaroo.applepay.cultureCode, + window.checkoutConfig.payment.buckaroo.applepay.guid, + self.processLineItems(lineItemsType), + self.processTotalLineItems(lineItemsType), + "shipping", + shippingMethods, + self.captureFunds.bind(this), + shipmentMethodCallback, + shippingContactCallback, + requiredBillingContactFields, + requiredShippingContactFields + ); + }, + + /** + * @param type + * + * @returns {{amount: string, label, type: string}[]} + */ + processLineItems: function (type = 'final', directTotals = false) { + var subTotal = '0.00'; + var shippingInclTax = '0.00'; + var totals = directTotals ? directTotals : this.getQuoteTotals(); + + if ('subtotal' in totals && 'shipping' in totals) { + subTotal = parseFloat(totals['subtotal']).toFixed(2); + shippingInclTax = parseFloat(totals['shipping']).toFixed(2); + } - return this.canShowMethod(); - }, + var lineItems = [ + {label: $.mage.__('Subtotal'), amount: subTotal, type: type}, + {label: $.mage.__('Delivery costs'), amount: shippingInclTax, type: type} + ]; - setQuote: function (newQuote) { - this.quote = newQuote; - }, + if ('discount' in totals && totals['discount'] < 0) { + var discountTotal = parseFloat(totals['discount']).toFixed(2); + lineItems.push({label: $.mage.__('Discount'), amount: discountTotal, type: type}); + } - setIsOnCheckout: function (isOnCheckout) { - this.isOnCheckout = isOnCheckout; - }, + return lineItems; + }, + + /** + * @param type + * + * @returns {{amount: string, label: *, type: string}} + */ + processTotalLineItems: function (type = 'final', directTotals = false) { + var grandTotal = '0.00'; + var storeName = window.checkoutConfig.payment.buckaroo.applepay.storeName; + var totals = directTotals ? directTotals : this.getQuoteTotals(); + + if ('grand_total' in totals) { + grandTotal = parseFloat(totals['grand_total']).toFixed(2); + } + if (isNaN(grandTotal)) grandTotal = 0; + return {label: storeName, amount: grandTotal, type: type}; + }, + + /** + * @returns {Array} + */ + getQuoteTotals: function () { + var totals = {}; + + if (!this.quote || typeof this.quote.totals() === 'undefined') { + return totals; + } - generateApplepayOptions: function () { - var lineItemsType = this.isOnCheckout ? 'final' : 'pending'; - var shippingMethods = this.isOnCheckout ? [] : this.availableShippingMethodInformation(); - var shippingContactCallback = this.isOnCheckout ? null : this.onSelectedShippingContact.bind(this); - var shipmentMethodCallback = this.isOnCheckout ? null : this.onSelectedShipmentMethod.bind(this); - var requiredBillingContactFields = this.isOnCheckout ? ['postalAddress'] : ['name', 'postalAddress', 'phone']; - var requiredShippingContactFields = this.isOnCheckout ? [] : ['name', 'postalAddress', 'phone']; + totals['subtotal'] = this.quote.totals().subtotal_incl_tax; + totals['discount'] = this.quote.totals().discount_amount; + totals['shipping'] = this.quote.totals().shipping_incl_tax; + totals['grand_total'] = this.quote.totals().grand_total; - if (!this.isOnCheckout && !window.isCustomerLoggedIn) { - requiredBillingContactFields.push('email'); - requiredShippingContactFields.push('email'); - } + var customGrandTotal = this.quote.totals().custom_grand_total; - if (this.isOnCheckout && window.checkoutConfig.payment.buckaroo.applepay.dontAskBillingInfoInCheckout) { - requiredBillingContactFields = []; - } + if (customGrandTotal !== undefined && customGrandTotal) { + return totals; + } - var country = window.checkoutConfig.payment.buckaroo.applepay.country; - if (this.quote && this.quote.shippingAddress()) { - country = this.quote.shippingAddress().countryId || country; - } + var segments = this.quote.totals().total_segments; - this.devLog('applepaydebug/13', [country, requiredBillingContactFields, requiredShippingContactFields]); - - this.applepayOptions = new BuckarooSdk.ApplePay.ApplePayOptions( - window.checkoutConfig.payment.buckaroo.applepay.storeName, - country, - window.checkoutConfig.payment.buckaroo.applepay.currency, - window.checkoutConfig.payment.buckaroo.applepay.cultureCode, - window.checkoutConfig.payment.buckaroo.applepay.guid, - this.processLineItems(lineItemsType), - this.processTotalLineItems(lineItemsType), - 'shipping', - shippingMethods, - this.captureFunds.bind(this), - shipmentMethodCallback, - shippingContactCallback, - requiredBillingContactFields, - requiredShippingContactFields - ); - }, - - processLineItems: function (type = 'final', directTotals = false) { - var totals = directTotals || this.getQuoteTotals(); - var subTotal = parseFloat(totals.subtotal || '0.00').toFixed(2); - var shippingInclTax = parseFloat(totals.shipping || '0.00').toFixed(2); - - var lineItems = [ - { label: $.mage.__('Subtotal'), amount: subTotal, type: type }, - { label: $.mage.__('Delivery costs'), amount: shippingInclTax, type: type } - ]; - - if (totals.discount && totals.discount < 0) { - var discountTotal = parseFloat(totals.discount).toFixed(2); - lineItems.push({ label: $.mage.__('Discount'), amount: discountTotal, type: type }); - } + for (let i in segments) { + if (segments[i]['code'] === 'grand_total') { + totals['grand_total'] = segments[i]['value']; + } + } - return lineItems; - }, + return totals; + }, - processTotalLineItems: function (type = 'final', directTotals = false) { - var totals = directTotals || this.getQuoteTotals(); - var grandTotal = parseFloat(totals.grand_total || '0.00').toFixed(2); - if (isNaN(grandTotal)) { - grandTotal = '0.00'; - } - var storeName = window.checkoutConfig.payment.buckaroo.applepay.storeName; + availableShippingMethodInformation: function () { + var shippingMethods = []; - return { label: storeName, amount: grandTotal, type: type }; - }, + $.each(this.shippingGroups, function (index, rate) { + var shippingInclTax = parseFloat(rate['price_incl_tax']).toFixed(2); - getQuoteTotals: function () { - if (!this.quote || typeof this.quote.totals() === 'undefined') { - return {}; - } + shippingMethods.push({ + label: rate['carrier_title'], + amount: shippingInclTax, + identifier: rate['method_code'], + detail: rate['method_title'] + }); + }); - var totals = { - subtotal: this.quote.totals().subtotal_incl_tax, - discount: this.quote.totals().discount_amount, - shipping: this.quote.totals().shipping_incl_tax, - grand_total: this.quote.totals().grand_total - }; + return shippingMethods; + }, - if (this.quote.totals().custom_grand_total) { - return totals; - } + timeoutRedirect: function (url = false) { + this.devLog('==============applepaydebug/38', url); + /** Set Timeout to prevent Safari from crashing and reload window to show error in Magento. */ + setTimeout( + function() { + if (url) { + window.location.href = url; + } else { + window.location.reload(); + } + }, 1500 + ) + }, + + onSelectedShipmentMethod: function (event) { + this.devLog('==============applepaydebug/27'); + + if ((this.payMode == 'product') || (this.payMode == 'cart')) { + var update = $.ajax({ + url: urlBuilder.build('buckaroo/applepay/updateShippingMethods'), + type: 'POST', + data: { + wallet: { + identifier: event.identifier + } + }, + global: false, + dataType: 'json', + async: false, + dataFilter: function(data, type) { + var result = JSON.parse(data); + if (result.success == 'true') { + + var authorizationResult = { + newTotal: this.processTotalLineItems('final', result.data.totals), + newLineItems: this.processLineItems('final', result.data.totals) + }; + + this.devLog('==============applepaydebug/37'); + + return JSON.stringify(authorizationResult); + } else { + this.timeoutRedirect(); + } + }.bind(this), + }) + .fail(function() { + this.timeoutRedirect(); + }.bind(this)); - var segments = this.quote.totals().total_segments || []; - segments.forEach(function (segment) { - if (segment.code === 'grand_total') { - totals.grand_total = segment.value; - } - }); + return update; - return totals; - }, + } else { - availableShippingMethodInformation: function () { - var shippingMethods = []; + var newShippingMethod = this.shippingGroups[event.identifier]; + this.updateQuoteRate(newShippingMethod); - $.each(this.shippingGroups, function (index, rate) { - var shippingInclTax = parseFloat(rate.price_incl_tax).toFixed(2); + var authorizationResult = { + newTotal: this.processTotalLineItems(), + newLineItems: this.processLineItems() + }; - shippingMethods.push({ - label: rate.carrier_title, - amount: shippingInclTax, - identifier: rate.method_code, - detail: rate.method_title - }); - }); + return Promise.resolve(authorizationResult); + } + }, + + onSelectedShippingContact: function (event) { + this.devLog('==============applepaydebug/28'); + + if (this.payMode == 'product') { + + var update = $.ajax({ + url: urlBuilder.build('buckaroo/applepay/add'), + type: 'POST', + data: { + product: this.productSelected, + wallet: event + }, + global: false, + dataType: 'json', + async: false, + dataFilter: function(data, type) { + var result = JSON.parse(data); + if (result.success == 'true') { + + this.shippingGroups = {}; + $.each(result.data.shipping_methods, function (index, rate) { + this.shippingGroups[rate['method_code']] = rate; + }.bind(this)); + + var authorizationResult = { + errors: [], + newShippingMethods: this.availableShippingMethodInformation(), + newTotal: this.processTotalLineItems('final', result.data.totals), + newLineItems: this.processLineItems('final', result.data.totals) + }; + + this.devLog('==============applepaydebug/30'); + + return JSON.stringify(authorizationResult); + } else { + this.timeoutRedirect(); + } + }.bind(this), + }) + .fail(function() { + this.timeoutRedirect(); + }.bind(this)); - return shippingMethods; - }, + return update; + } else if (this.payMode == 'cart') { + + var update = $.ajax({ + url: urlBuilder.build('buckaroo/applepay/getShippingMethods'), + type: 'POST', + data: { + wallet: event + }, + global: false, + dataType: 'json', + async: false, + dataFilter: function(data, type) { + var result = JSON.parse(data); + if (result.success == 'true') { + + this.shippingGroups = {}; + $.each(result.data.shipping_methods, function (index, rate) { + this.shippingGroups[rate['method_code']] = rate; + }.bind(this)); + + var authorizationResult = { + errors: [], + newShippingMethods: this.availableShippingMethodInformation(), + newTotal: this.processTotalLineItems('final', result.data.totals), + newLineItems: this.processLineItems('final', result.data.totals) + }; + + this.devLog('==============applepaydebug/53'); + + return JSON.stringify(authorizationResult); + } else { + this.timeoutRedirect(); + } + }.bind(this), + }) + .fail(function() { + this.timeoutRedirect(); + }.bind(this)); - timeoutRedirect: function (url) { - this.devLog('applepaydebug/38', url); - setTimeout(function () { - if (url) { - window.location.href = url; + return update; } else { - window.location.reload(); + var newShippingAddress = shippingHandler.setShippingAddress(event); + this.updateShippingMethods(newShippingAddress); } - }, 1500); - }, - - onSelectedShipmentMethod: function (event) { - this.devLog('applepaydebug/27'); - - if (this.payMode === 'product' || this.payMode === 'cart') { - return $.ajax({ - url: urlBuilder.build('buckaroo/applepay/updateShippingMethods'), - type: 'POST', - data: { - wallet: { - identifier: event.identifier - } - }, - global: false, - dataType: 'json' - }).then(function (result) { - if (result.success === 'true') { - var authorizationResult = { - newTotal: this.processTotalLineItems('final', result.data.totals), - newLineItems: this.processLineItems('final', result.data.totals) - }; - - this.devLog('applepaydebug/37'); - - return authorizationResult; - } else { - this.timeoutRedirect(); - return $.Deferred().reject(); - } - }.bind(this)).fail(function () { - this.timeoutRedirect(); - return $.Deferred().reject(); - }.bind(this)); - } else { - var newShippingMethod = this.shippingGroups[event.identifier]; - this.updateQuoteRate(newShippingMethod); var authorizationResult = { + errors: [], + newShippingMethods: this.availableShippingMethodInformation(), newTotal: this.processTotalLineItems(), newLineItems: this.processLineItems() }; return Promise.resolve(authorizationResult); - } - }, - - onSelectedShippingContact: function (event) { - this.devLog('applepaydebug/28'); - - if (this.payMode === 'product' || this.payMode === 'cart') { - var urlEndpoint = this.payMode === 'product' ? 'buckaroo/applepay/add' : 'buckaroo/applepay/getShippingMethods'; - var requestData = this.payMode === 'product' ? { product: this.productSelected, wallet: event } : { wallet: event }; + }, + + updateShippingMethods: function (address) { + this.devLog('==============applepaydebug/16'); + var serviceUrl = resourceUrlManager.getUrlForEstimationShippingMethodsForNewAddress(this.quote); + var payload = JSON.stringify({ + address: { + 'street': address.street, + 'city': address.city, + 'region_id': address.regionId, + 'region': address.region, + 'country_id': address.countryId, + 'postcode': address.postcode, + 'firstname': address.firstname, + 'lastname': address.lastname, + 'company': address.company, + 'telephone': address.telephone, + 'custom_attributes': address.customAttributes, + 'save_in_address_book': address.saveInAddressBook + } + }); - return $.ajax({ - url: urlBuilder.build(urlEndpoint), + $.ajax({ + url: urlBuilder.build(serviceUrl), type: 'POST', - data: requestData, + data: payload, global: false, - dataType: 'json' - }).then(function (result) { - if (result.success === 'true') { - this.shippingGroups = {}; - $.each(result.data.shipping_methods, function (index, rate) { - this.shippingGroups[rate.method_code] = rate; - }.bind(this)); + contentType: 'application/json', + async: false + }).done(function (result) { + this.shippingGroups = {}; + var firstLoop = true; + + $.each(result, function (index, rate) { + this.shippingGroups[rate['method_code']] = rate; + + if (firstLoop) { + this.updateQuoteRate(rate); + firstLoop = false; + } + }.bind(this)); + }.bind(this)); + }, - var authorizationResult = { - errors: [], - newShippingMethods: this.availableShippingMethodInformation(), - newTotal: this.processTotalLineItems('final', result.data.totals), - newLineItems: this.processLineItems('final', result.data.totals) - }; + updateQuoteRate: function (newRate) { + shippingHandler.selectShippingMethod(newRate); - this.devLog('applepaydebug/30'); + var subtotal = this.quote.totals().subtotal_incl_tax; + this.quote.totals().shipping_incl_tax = newRate['price_incl_tax']; + this.quote.totals().grand_total = subtotal + newRate['price_incl_tax']; + this.quote.totals().custom_grand_total = true; + }, - return authorizationResult; - } else { - this.timeoutRedirect(); - return $.Deferred().reject(); - } - }.bind(this)).fail(function () { - this.timeoutRedirect(); - return $.Deferred().reject(); - }.bind(this)); - } else { - var newShippingAddress = shippingHandler.setShippingAddress(event); - return this.updateShippingMethods(newShippingAddress).then(function () { - var authorizationResult = { - errors: [], - newShippingMethods: this.availableShippingMethodInformation(), - newTotal: this.processTotalLineItems(), - newLineItems: this.processLineItems() - }; - return authorizationResult; - }.bind(this)); - } - }, - - updateShippingMethods: function (address) { - this.devLog('applepaydebug/16'); - var serviceUrl = resourceUrlManager.getUrlForEstimationShippingMethodsForNewAddress(this.quote); - var payload = JSON.stringify({ - address: { - street: address.street, - city: address.city, - region_id: address.regionId, - region: address.region, - country_id: address.countryId, - postcode: address.postcode, - firstname: address.firstname, - lastname: address.lastname, - company: address.company, - telephone: address.telephone, - custom_attributes: address.customAttributes, - save_in_address_book: address.saveInAddressBook - } - }); - - return $.ajax({ - url: urlBuilder.build(serviceUrl), - type: 'POST', - data: payload, - global: false, - contentType: 'application/json', - dataType: 'json' - }).done(function (result) { - this.shippingGroups = {}; - var firstLoop = true; - - $.each(result, function (index, rate) { - this.shippingGroups[rate.method_code] = rate; - - if (firstLoop) { - this.updateQuoteRate(rate); - firstLoop = false; - } - }.bind(this)); - }.bind(this)).fail(function () { - this.devLog('Failed to update shipping methods'); - }.bind(this)); - }, - - updateQuoteRate: function (newRate) { - shippingHandler.selectShippingMethod(newRate); - - var subtotal = parseFloat(this.quote.totals().subtotal_incl_tax || 0); - var shipping = parseFloat(newRate.price_incl_tax || 0); - this.quote.totals().shipping_incl_tax = shipping; - this.quote.totals().grand_total = subtotal + shipping; - this.quote.totals().custom_grand_total = true; - }, - - captureFunds: function (payment) { - this.devLog('applepaydebug/12', payment); - - var authorizationResult = { - status: ApplePaySession.STATUS_SUCCESS, - errors: [] - }; - - if (this.payMode === 'product' || this.payMode === 'cart') { - return $.ajax({ - url: urlBuilder.build('buckaroo/applepay/saveOrder'), - type: 'POST', - data: { - payment: payment, - extra: this.getData(payment) - }, - global: false, - dataType: 'json' - }).then(function (result) { - if (result.success === 'true') { - if (result.data && result.data.RequiredAction && result.data.RequiredAction.RedirectURL) { - this.timeoutRedirect(result.data.RequiredAction.RedirectURL); - } else { - this.timeoutRedirect(); - } - this.payMode = ''; - return authorizationResult; - } else { - this.timeoutRedirect(); - return { - status: ApplePaySession.STATUS_FAILURE, - errors: [] - }; - } - }.bind(this)).fail(function () { - this.timeoutRedirect(); - return { + /** + * @param payment + * @returns {Promise<{errors: Array, status: *}>} + */ + captureFunds: function (payment) { + this.devLog('==========applepaydebug/12',payment); + + var authorizationResult = { + status: ApplePaySession.STATUS_SUCCESS, + errors: [] + }; + + if ((this.payMode == 'product') || (this.payMode == 'cart')) { + + var authorizationFailedResult = { status: ApplePaySession.STATUS_FAILURE, errors: [] }; - }.bind(this)); - } else { - this.transactionResult(payment); - return Promise.resolve(authorizationResult); - } - }, - - getData: function (payment) { - var transactionData = this.formatTransactionResponse(payment); - - return { - method: 'buckaroo_magento2_applepay', - po_number: null, - additional_data: { - applepayTransaction: transactionData, - billingContact: payment && payment.billingContact - ? JSON.stringify(payment.billingContact) - : '' - } - }; - }, - formatTransactionResponse: function (response) { - if (!response || !response.token || !response.token.paymentData) { - return null; - } - var paymentData = response.token.paymentData; + var update = $.ajax({ + url: urlBuilder.build('buckaroo/applepay/saveOrder'), + type: 'POST', + data: { + payment: payment, + extra: this.getData(payment) + }, + global: false, + dataType: 'json', + async: false, + dataFilter: function(data, type) { + var result = JSON.parse(data); + if (result.success == 'true') { + if (result.data && result.data.RequiredAction !== undefined && result.data.RequiredAction.RedirectURL !== undefined) { + this.timeoutRedirect(result.data.RequiredAction.RedirectURL); + } else { + this.timeoutRedirect(); + } + this.payMode = ''; + return JSON.stringify(authorizationResult); + } else { + this.timeoutRedirect(); + } + }.bind(this), + }) + .fail(function() { + this.timeoutRedirect(); + }.bind(this)); - var formattedData = { - paymentData: { - version: paymentData.version, - data: paymentData.data, - signature: paymentData.signature, - header: paymentData.header + return update; + + } else { + + this.transactionResult(payment); + + return Promise.resolve(authorizationResult); + } + }, + + getData: function (payment) { + var transactionResult = payment; + var transactionData = this.formatTransactionResponse(transactionResult); + + return { + "method": 'buckaroo_magento2_applepay', + "po_number": null, + "additional_data": { + "applepayTransaction" : transactionData, + "billingContact" : transactionResult && transactionResult.billingContact ? + JSON.stringify(transactionResult.billingContact) : '' + } + }; + }, + + /** + * @param response + * @returns {string|null} + */ + formatTransactionResponse: function (response) { + if (null === response || 'undefined' === response) { + return null; } - }; - return JSON.stringify(formattedData); - }, + var paymentData = response.token.paymentData; + + var formattedData = { + "paymentData": { + "version": paymentData.version, + "data": paymentData.data, + "signature": paymentData.signature, + "header": { + "ephemeralPublicKey": paymentData.header.ephemeralPublicKey, + "publicKeyHash": paymentData.header.publicKeyHash, + "transactionId": paymentData.header.transactionId, + } + } + }; - initProductViewWatchers: function () { - this.devLog('applepaydebug/initProductViewWatchers'); + return JSON.stringify(formattedData); + }, - var productId = $('.price-box').attr('data-product-id'); - var productQty = $('#qty').val() || '1'; + initProductViewWatchers: function () { + this.devLog('==============applepaydebug/initProductViewWatchers'); - if (!productId) { - console.error('Product ID not found on the page.'); - return; - } + var productId = $('.price-box').attr('data-product-id'); + var productQty = $('#qty').val(); - this.productSelected.id = productId; - this.productSelected.qty = productQty; + if (!productId) { + console.error('Product ID not found on the page.'); + return; + } - $('#qty').on('change', function () { - this.productSelected.qty = $(this).val(); - }.bind(this)); + if (!productQty) { + productQty = 1; + } - $('.product-options-wrapper').on('click', 'div', function () { - var selectedOptions = {}; - $('div.swatch-attribute').each(function () { - var attributeId = $(this).attr('attribute-id') || $(this).attr('data-attribute-id'); - var optionSelected = $(this).attr('option-selected') || $(this).attr('data-option-selected'); + this.productSelected.id = productId; + this.productSelected.qty = productQty; - if (attributeId && optionSelected) { - selectedOptions[attributeId] = optionSelected; - } + var self = this; + $('#qty').change(function() { + self.productSelected.qty = $(this).val(); }); - this.productSelected.selected_options = selectedOptions; - }.bind(this)); - }, + $('.product-options-wrapper div').click(function() { + var selected_options = {}; + $('div.swatch-attribute').each(function(k,v){ + var attribute_id = $(v).attr('attribute-id'); + var option_selected = $(v).attr('option-selected'); + if(!attribute_id || !option_selected) { + attribute_id = $(v).attr('data-attribute-id'); + option_selected = $(v).attr('data-option-selected'); + if(!attribute_id || !option_selected) { + return; + } + } + selected_options[attribute_id] = option_selected; + }); - isOsc: function () { - return !!this.getOscButton(); - }, + self.productSelected.selected_options = selected_options; + }); + }, - getOscButton: function () { - return document.querySelector('.action.primary.checkout.iosc-place-order-button'); - }, + isOsc: function () { + return this.getOscButton(); + }, - devLog: function (msg, params) { - if (window.buckarooDebug) { - console.log(msg, params); + getOscButton: function () { + return document.querySelector('.action.primary.checkout.iosc-place-order-button'); + }, + + devLog: function (msg, params) { + //window.buckarooDebug = 1; + if (window.buckarooDebug) { + console.log(msg, params); + } } - } - }; -}); + + }; + } +); From 068b3ee1dda91533eebfae99891007780d382e8d Mon Sep 17 00:00:00 2001 From: "v.carkaxhija" Date: Tue, 5 Nov 2024 14:40:35 +0100 Subject: [PATCH 7/7] update applepay --- Service/Applepay/Add.php | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/Service/Applepay/Add.php b/Service/Applepay/Add.php index e605a6d30..f9fa4263a 100644 --- a/Service/Applepay/Add.php +++ b/Service/Applepay/Add.php @@ -168,16 +168,28 @@ public function process($request) } $this->quoteRepository->save($cart); //this delivery address is already assigned to the cart - $shippingMethods = $this->appleShippingMethod->getAvailableMethods( $cart); - foreach ($shippingMethods as $index => $shippingMethod) { + + try { + $shippingMethods = $this->appleShippingMethod->getAvailableMethods($cart); + } catch (\Exception $e) { + throw new \Exception(__('Unable to retrieve shipping methods.')); + } + + foreach ($shippingMethods as $method) { $shippingMethodsResult[] = [ - 'carrier_title' => $shippingMethod['carrier_title'], - 'price_incl_tax' => round($shippingMethod['amount'], 2), - 'method_code' => $shippingMethod['carrier_code'] . '_' . $shippingMethod['method_code'], - 'method_title' => $shippingMethod['method_title'], + 'carrier_title' => $method['carrier_title'], + 'price_incl_tax' => round($method['amount']['value'], 2), + 'method_code' => $method['carrier_code'] . '__SPLIT__' . $method['method_code'], + 'method_title' => $method['method_title'], ]; } - $cart->getShippingAddress()->setShippingMethod($shippingMethodsResult[0]['method_code']); + + if (!empty($shippingMethodsResult)) { + // Set the first available shipping method + $cart->getShippingAddress()->setShippingMethod($shippingMethodsResult[0]['method_code']); + } else { + throw new \Exception(__('No shipping methods are available for the provided address.')); + } } $cart->setTotalsCollectedFlag(false); $cart->collectTotals();