diff --git a/Block/Cart/Button.php b/Block/Cart/Button.php index b127e77..5b5596c 100644 --- a/Block/Cart/Button.php +++ b/Block/Cart/Button.php @@ -7,15 +7,15 @@ */ namespace Afterpay\Afterpay\Block\Cart; -use Magento\Framework\View\Element\Template; use Magento\Checkout\Model\Session as CheckoutSession; -use Magento\Directory\Model\Currency as Currency; use Afterpay\Afterpay\Model\Config\Payovertime as AfterpayConfig; use Afterpay\Afterpay\Model\Payovertime as AfterpayPayovertime; use Magento\Customer\Model\Session as CustomerSession; -use Magento\Framework\Component\ComponentRegistrar as ComponentRegistrar; +use Magento\Framework\View\Element\Template\Context; +use Magento\Framework\Locale\Resolver as Resolver; -class Button extends Template + +class Button extends \Afterpay\Afterpay\Block\JsConfig { /** * @var AfterpayConfig @@ -23,35 +23,32 @@ class Button extends Template protected $afterpayConfig; protected $afterpayPayovertime; protected $checkoutSession; - protected $currency; protected $customerSession; - protected $componentRegistrar; /** * Button constructor. - * @param Template\Context $context + * @param Context $context * @param AfterpayConfig $afterpayConfig + * @param AfterpayPayovertime $afterpayPayovertime * @param CheckoutSession $checkoutSession - * @param Currency $currency + * @param CustomerSession $customerSession * @param array $data + * @param Resolver $localeResolver */ public function __construct( - Template\Context $context, + Context $context, AfterpayConfig $afterpayConfig, AfterpayPayovertime $afterpayPayovertime, CheckoutSession $checkoutSession, - Currency $currency, CustomerSession $customerSession, - ComponentRegistrar $componentRegistrar, - array $data + array $data=[], + Resolver $localeResolver ) { $this->afterpayConfig = $afterpayConfig; $this->afterpayPayovertime = $afterpayPayovertime; $this->checkoutSession = $checkoutSession; - $this->currency = $currency; $this->customerSession = $customerSession; - $this->componentRegistrar = $componentRegistrar; - parent::__construct($context, $data); + parent::__construct($afterpayConfig,$context, $localeResolver,$data); } /** @@ -61,35 +58,7 @@ protected function _getPaymentIsActive() { return $this->afterpayConfig->isActive(); } - - /** - * @return float - */ - public function getInstallmentsTotal() - { - $quote = $this->checkoutSession->getQuote(); - - if ($grandTotal = $quote->getGrandTotal()) { - return $grandTotal / 4; - } - } - - /** - * @return string - */ - public function getInstallmentsTotalHtml() - { - return $this->getCurrency()->getCurrencySymbol() . number_format($this->getInstallmentsTotal(), 2); - } - - /** - * @return Currency - */ - protected function getCurrency() - { - return $this->currency; - } - + /** * @return bool */ @@ -108,7 +77,7 @@ public function canShow() $grandTotal =$quote->getGrandTotal(); $excluded_categories=$this->afterpayConfig->getExcludedCategories(); - if($this->afterpayPayovertime->canUseForCurrency($this->afterpayConfig->getCurrencyCode()) && $this->afterpayConfig->getMaxOrderLimit() >= $grandTotal && $this->afterpayConfig->getMinOrderLimit() <= $grandTotal){ + if($this->afterpayPayovertime->canUseForCurrency($this->afterpayConfig->getCurrencyCode()) ){ if($excluded_categories !=""){ $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); @@ -139,46 +108,31 @@ public function canShow() } } } - + /** - * @return boolean + * @return string */ + public function getFinalAmount() + { + + $grandTotal = $this->checkoutSession->getQuote()->getGrandTotal(); + + return !empty($grandTotal)?number_format($grandTotal, 2,".",""):"0.00"; + + } + /* + * @return boolean + */ public function canUseCurrency() { + $canUse=false; //Check for Supported currency if($this->afterpayConfig->getCurrencyCode()) { - return $this->afterpayPayovertime->canUseForCurrency($this->afterpayConfig->getCurrencyCode()); - } else { - return false; + $canUse= $this->afterpayPayovertime->canUseForCurrency($this->afterpayConfig->getCurrencyCode()); } - } - - /** - * Calculate region specific Instalment Text for Cart page - * @return string - */ - public function getCartPageText() - { - $currencyCode = $this->afterpayConfig->getCurrencyCode(); - $assetsPath = $this->componentRegistrar->getPath(ComponentRegistrar::MODULE, 'Afterpay_Afterpay'); - $assets_cart_page = []; - - if(file_exists($assetsPath.'/assets.ini')) - { - $assets = parse_ini_file($assetsPath.'/assets.ini',true); - if(isset($assets[$currencyCode]['cart_page1'])) - { - $assets_cart_page['snippet1'] = $assets[$currencyCode]['cart_page1']; - $assets_cart_page['snippet2'] = $assets[$currencyCode]['cart_page2']; - $assets_cart_page['snippet2'] = str_replace(array('[modal-href]'), - array('javascript:void(0)'), $assets_cart_page['snippet2']); - } - else{ - $assets_cart_page['snippet1'] = ''; - $assets_cart_page['snippet2'] = ''; - } - } - return $assets_cart_page; + + return $canUse; + } } diff --git a/Block/Catalog/Installments.php b/Block/Catalog/Installments.php index 8e2074a..482ffe4 100644 --- a/Block/Catalog/Installments.php +++ b/Block/Catalog/Installments.php @@ -7,52 +7,42 @@ */ namespace Afterpay\Afterpay\Block\Catalog; -use Magento\Framework\View\Element\Template; -use Magento\Catalog\Model\Product as Product; use Magento\Framework\Registry as Registry; -use Magento\Directory\Model\Currency as Currency; use Afterpay\Afterpay\Model\Config\Payovertime as AfterpayConfig; use Afterpay\Afterpay\Model\Payovertime as AfterpayPayovertime; -use Magento\Framework\Component\ComponentRegistrar as ComponentRegistrar; +use Magento\Framework\View\Element\Template\Context; +use Magento\Framework\Locale\Resolver as Resolver; -class Installments extends Template +class Installments extends \Afterpay\Afterpay\Block\JsConfig { - /** - * @var Product - */ - protected $product; + protected $registry; - protected $currency; protected $afterpayConfig; protected $afterpayPayovertime; - protected $componentRegistrar; + private $localeResolver; /** * Installments constructor. - * @param Template\Context $context - * @param Product $product + * @param Context $context + * @param AfterpayConfig $afterpayConfig + * @param AfterpayPayovertime $afterpayPayovertime * @param Registry $registry - * @param Currency $currency * @param AfterpayConfig $afterpayConfig * @param array $data */ public function __construct( - Template\Context $context, - Product $product, + Context $context, Registry $registry, - Currency $currency, AfterpayConfig $afterpayConfig, AfterpayPayovertime $afterpayPayovertime, - ComponentRegistrar $componentRegistrar, - array $data + array $data, + Resolver $localeResolver ) { - $this->product = $product; $this->registry = $registry; - $this->currency = $currency; $this->afterpayConfig = $afterpayConfig; $this->afterpayPayovertime = $afterpayPayovertime; - $this->componentRegistrar = $componentRegistrar; - parent::__construct($context, $data); + $this->localeResolver = $localeResolver; + parent::__construct($afterpayConfig,$context, $localeResolver,$data); } /** @@ -63,20 +53,6 @@ protected function _getPaymentIsActive() return $this->afterpayConfig->isActive(); } - /** - * @return string - */ - public function getInstallmentsAmount() - { - // get product - $product = $this->registry->registry('product'); - - // set if final price is exist - if ($price = $product->getFinalPrice()) { - return $this->currency->getCurrencySymbol() . number_format($price / 4, 2); - } - } - /** * @return bool */ @@ -111,84 +87,46 @@ public function canShow() return false; } } - } - /** - * @return bool - */ - public function isProductEligible(){ - - $product = $this->registry->registry('product'); - if ($product->getFinalPrice() > $this->afterpayConfig->getMaxOrderLimit() // greater than max order limit - || $product->getFinalPrice() < $this->afterpayConfig->getMinOrderLimit()) { // lower than min order limit - return false; - } - return true; - } + } + - /** - * @return boolean - */ - public function canUseCurrency() - { - //Check for Supported currency - if($this->afterpayConfig->getCurrencyCode()) - { - return $this->afterpayPayovertime->canUseForCurrency($this->afterpayConfig->getCurrencyCode()); - } else { - return false; - } - } - - /** - * Calculate region specific Instalment Text + /** * @return string */ - public function getInstalmentText() + public function getTypeOfProduct() { - $currencyCode = $this->afterpayConfig->getCurrencyCode(); - $assetsPath = $this->componentRegistrar->getPath(ComponentRegistrar::MODULE, 'Afterpay_Afterpay'); - $assets_product_page = []; - if(file_exists($assetsPath.'/assets.ini')) - { - $assets = parse_ini_file($assetsPath.'/assets.ini',true); - if(isset($assets[$currencyCode]['product_page1'])) - { - $assets_product_page['snippet1'] = $assets[$currencyCode]['product_page1']; - if($this->getTypeOfProduct()=="bundle"){ - $assets_product_page['snippet1'] = $assets[$currencyCode]['product_page_from']; - } - $assets_product_page['snippet2'] = $assets[$currencyCode]['product_page2']; - } else { - $assets_product_page['snippet1'] = ''; - $assets_product_page['snippet2'] = ''; - } - } - return $assets_product_page; + $product = $this->registry->registry('product'); + return $product->getTypeId(); } - /** - * @return float + * @return string */ - public function getMaxOrderLimit() + public function getFinalAmount() { - return $this->afterpayConfig->getMaxOrderLimit(); - } - + // get product + $product = $this->registry->registry('product'); + + // set if final price is exist + $price = $product->getFinalPrice(); + + return !empty($price)?number_format($price, 2,".",""):"0.00"; + + } /** - * @return float - */ - public function getMinOrderLimit() - { - return $this->afterpayConfig->getMinOrderLimit(); - } - - /** - * @return string + * @return boolean */ - public function getTypeOfProduct() + public function canUseCurrency() { - $product = $this->registry->registry('product'); - return $product->getTypeId(); + $canUse=false; + //Check for Supported currency + if($this->afterpayConfig->getCurrencyCode()) + { + $canUse= $this->afterpayPayovertime->canUseForCurrency($this->afterpayConfig->getCurrencyCode()); + } + + return $canUse; + } + } diff --git a/Block/JsConfig.php b/Block/JsConfig.php new file mode 100644 index 0000000..000362a --- /dev/null +++ b/Block/JsConfig.php @@ -0,0 +1,138 @@ +_payOverTime = $payovertime; + $this->localeResolver = $localeResolver; + + parent::__construct($context, $data); + } + + protected function _construct() + { + parent::_construct(); + + return $this; + } + /** + * @return float + */ + public function getMaxOrderLimit() + { + return number_format($this->_payOverTime->getMaxOrderLimit(), 2,".",""); + } + + /** + * @return float + */ + public function getMinOrderLimit() + { + return number_format($this->_payOverTime->getMinOrderLimit(), 2,".",""); + } + + /** + * @return bool + */ + protected function _getPaymentIsActive() + { + return $this->_payOverTime->isActive(); + } + + /* Get Current Locale + * + * @return string + */ + public function getCurrentLocale() + { + return $this->localeResolver->getLocale(); // eg. fr_CA + } + + /** + * Get JS Library URL + * + * @return string + */ + public function getAfterpayJsLibUrl() + { + return $this->_payOverTime->getJSLibUrl('afterpay-1.x.js'); + } + /** + * check if payment is active + * + * @return bool + */ + public function isPaymentMethodActive() + { + $isPaymentMethodActive=true; + if (!$this->_getPaymentIsActive()) { + $isPaymentMethodActive= false; + } + return $isPaymentMethodActive; + } + + /* Get Current Currency + * + * @return string + */ + public function getCurrentCurrency() + { + return $this->_payOverTime->getCurrencyCode(); // eg. AUD + } + + /** + * check if payment is active for product page + * + * @return bool + */ + public function isDisplayOnProductPage() + { + $isEnabledForProductPage=true; + if (!$this->_payOverTime->isEnabledForProductDisplayPage()) { + $isEnabledForProductPage= false; + } + return $isEnabledForProductPage; + } + + /** + * check if payment is active for cart page + * + * @return bool + */ + public function isDisplayOnCartPage() + { + $isEnabledForCartPage=true; + if (!$this->_payOverTime->isEnabledForCartPage()) { + $isEnabledForCartPage= false; + } + return $isEnabledForCartPage; + } + +} diff --git a/CHANGELOG.md b/CHANGELOG.md index 248424b..c943afa 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,30 @@ # Afterpay Magento 2 Extension Changelog +## Version 3.3.0 + +_Wed 13 Jan 2021_ + +### Supported Editions & Versions + +Tested and verified in clean installations of Magento 2: + +- Magento Enterprise Edition (EE) version 2.4.1 +- Magento Enterprise Edition (EE) version 2.3.5-p1 + +### Highlights + +- Implemented the JS Library for asset placement on PDP and Cart page. +- Added new admin options to enable/disable display of Afterpay/Clearpay assets on PDP and Cart page. +- Moved the Afterpay/Clearpay PDP assets for “Bundle” products. +- Improved Cross Border Trade (CBT) configuration to update automatically in sync with the nominated Merchant account. +- Improved support for multi-currency configurations. +- Improved compatibility with PHP 7.4. +- Improved compatibility with third-party "Fraud Prevention" modules while saving admin configuration. +- Improved visual quality of UI assets. +- Improved support for refunding unshipped items in Deferred Payment Flow. + +--- + ## Version 3.2.0 _Wed 19 Aug 2020_ diff --git a/Controller/Payment/Response.php b/Controller/Payment/Response.php index 7d8be8d..da2a912 100644 --- a/Controller/Payment/Response.php +++ b/Controller/Payment/Response.php @@ -167,7 +167,7 @@ private function _processAuthCapture($query) } elseif ($merchant_order_id != $response_check['merchantReference']) { // Check order id throw new \Magento\Framework\Exception\LocalizedException(__('There are issues when processing your payment. Invalid Merchant Reference')); - } elseif (round($quote->getGrandTotal(), 2) != round($response_check['amount']['amount'], 2)) { + } elseif (round($quote->getBaseGrandTotal(), 2) != round($response_check['amount']['amount'], 2)) { // Check the order amount throw new \Magento\Framework\Exception\LocalizedException(__('There are issues when processing your payment. Invalid Amount')); } diff --git a/Model/Adapter/Afterpay/Call.php b/Model/Adapter/Afterpay/Call.php index 123f1b1..d932442 100644 --- a/Model/Adapter/Afterpay/Call.php +++ b/Model/Adapter/Afterpay/Call.php @@ -73,8 +73,13 @@ public function send($url, $body = false, $method = \Magento\Framework\HTTP\Zend $client->setUri($url); // set body and the url - if ($body || ($method == \Magento\Framework\HTTP\ZendClient::POST || $method == \Magento\Framework\HTTP\ZendClient::PUT)) { - $client->setRawData($this->jsonHelper->jsonEncode($body), 'application/json'); + if ($body || ($method == \Magento\Framework\HTTP\ZendClient::POST || $method == \Magento\Framework\HTTP\ZendClient::PUT)) { + $newbody=''; + if(!empty($body)){ + $newbody=$this->jsonHelper->jsonEncode($body); + } + + $client->setRawData($newbody, 'application/json'); } // add auth for API requirements @@ -84,7 +89,8 @@ public function send($url, $body = false, $method = \Magento\Framework\HTTP\Zend ); //Additional debugging on the merchant ID and Key being sent on Update Payment Limits - if ($url == $this->afterpayConfig->getApiUrl('v2/configuration') || + $queryString=array("include"=>"cbt"); + if ($url == $this->afterpayConfig->getApiUrl('v2/configuration',$queryString) || $url == $this->afterpayConfig->getApiUrl('merchants/valid-payment-types') ) { //Solves the problem of magento 2 cron not working for some merchants if(array_key_exists('REQUEST_URI',$_SERVER)){ diff --git a/Model/Adapter/AfterpayPayment.php b/Model/Adapter/AfterpayPayment.php index bfa538b..7adda43 100644 --- a/Model/Adapter/AfterpayPayment.php +++ b/Model/Adapter/AfterpayPayment.php @@ -148,7 +148,7 @@ public function voidOrder($orderId, $override = []) try { $response = $this->afterpayApiCall->send( $url, - [], + "", \Magento\Framework\HTTP\ZendClient::POST, $override ); diff --git a/Model/Adapter/AfterpayTotalLimit.php b/Model/Adapter/AfterpayTotalLimit.php index d2ac84b..283ddd2 100644 --- a/Model/Adapter/AfterpayTotalLimit.php +++ b/Model/Adapter/AfterpayTotalLimit.php @@ -50,8 +50,9 @@ public function __construct( */ public function getLimit($override = []) { + $queryString=array("include"=>"cbt"); /** @var \Afterpay\Afterpay\Model\Config\Payovertime $url */ - $url = $this->afterpayConfig->getApiUrl('v2/configuration'); //V2 + $url = $this->afterpayConfig->getApiUrl('v2/configuration',$queryString); //V2 // calling API try { diff --git a/Model/Adapter/V2/AfterpayOrderTokenV2.php b/Model/Adapter/V2/AfterpayOrderTokenV2.php index a0472b1..fed1061 100644 --- a/Model/Adapter/V2/AfterpayOrderTokenV2.php +++ b/Model/Adapter/V2/AfterpayOrderTokenV2.php @@ -177,7 +177,7 @@ public function handleValidation($requestData) } if (count($errors)) { - throw new \Magento\Framework\Exception\LocalizedException(__(implode($errors, ' ; '))); + throw new \Magento\Framework\Exception\LocalizedException(__(implode(' ; ', $errors))); } else { return true; } @@ -236,7 +236,7 @@ protected function _buildOrderTokenRequest($object, $override = []) 'imageUrl' => $imageHelper->init($product, 'product_page_image_small')->setImageFile($product->getFile())->getUrl(), 'quantity' => (int)$item->getQty(), 'price' => [ - 'amount' => round((float)$item->getPriceInclTax(), $precision), + 'amount' => round((float)$item->getBasePriceInclTax(), $precision), 'currency' => (string)$data['store_currency_code'] ], 'categories' => [$categories] @@ -245,18 +245,18 @@ protected function _buildOrderTokenRequest($object, $override = []) } if ($object->getShippingInclTax()) { $params['shippingAmount'] = [ - 'amount' => round((float)$object->getShippingInclTax(), $precision), // with tax + 'amount' => round((float)$object->getBaseShippingInclTax(), $precision), // with tax 'currency' => (string)$data['store_currency_code'] ]; } if (isset($data['discount_amount'])) { $params['discounts']['displayName'] = 'Discount'; $params['orderDetail']['amount'] = [ - 'amount' => round((float)$data['discount_amount'], $precision), + 'amount' => round((float)$data['base_discount_amount'], $precision), 'currency' => (string)$data['store_currency_code'] ]; } - $taxAmount = array_key_exists('tax_amount', $data) ? $data['tax_amount'] : $shippingAddress->getTaxAmount(); + $taxAmount = array_key_exists('base_tax_amount', $data) ? $data['base_tax_amount'] : $shippingAddress->getBaseTaxAmount(); $params['taxAmount'] = [ 'amount' => isset($taxAmount) ? round((float)$taxAmount, $precision) : 0, 'currency' => (string)$data['store_currency_code'] @@ -290,7 +290,7 @@ protected function _buildOrderTokenRequest($object, $override = []) 'phoneNumber' => (string)$billingAddress->getTelephone(), ]; $params['amount'] = [ - 'amount' => round((float)$object->getGrandTotal(), $precision), + 'amount' => round((float)$object->getBaseGrandTotal(), $precision), 'currency' => (string)$data['store_currency_code'], ]; diff --git a/Model/Config/Payovertime.php b/Model/Config/Payovertime.php index 609cf86..b7227ff 100644 --- a/Model/Config/Payovertime.php +++ b/Model/Config/Payovertime.php @@ -23,9 +23,10 @@ class Payovertime * constant data for static */ const ACTIVE = 'active'; - const API_MODE_XML_NODE = 'api_mode'; + const API_MODE_XML_NODE = 'api_mode'; const API_URL_XML_NODE = 'api_url'; const WEB_URL_XML_NODE = 'web_url'; + const JSLib_URL_XML_NODE = 'js_lib_url'; const MERCHANT_ID_XML_NODE = 'merchant_id'; const MERCHANT_KEY_XML_NODE = 'merchant_key'; const PAYMENT_ACTION = 'payment_action'; @@ -34,6 +35,10 @@ class Payovertime const MAX_TOTAL_LIMIT = 'max_order_total'; const HTTP_HEADER_SUPPORT = 'http_header_support'; const EXCLUDE_CATEGORY = 'exclude_category'; + const ENABLE_CBT = 'enable_cbt'; + const CBT_COUNTRY = 'cbt_country'; + const ENABLE_FOR_PRODUCT_PAGE= "enable_for_product_page"; + const ENABLE_FOR_CART_PAGE = "enable_for_cart_page"; /** * @var ApiMode @@ -93,6 +98,18 @@ public function getWebUrl($path = '', $query = [], $override = []) return $this->_getRequestedUrl(self::WEB_URL_XML_NODE, $path, $query, $override); } + /** + * Get JS Library url based on configuration + * + * @param string $path + * @param array $query + * @param array $override + * @return bool|string + */ + public function getJSLibUrl($path = '', $query = [], $override = []) + { + return $this->_getRequestedUrl(self::JSLib_URL_XML_NODE, $path, $query, $override); + } /** * Calculated the url to generate api/web url * @@ -155,6 +172,9 @@ public function getSiteConfig($apiMode, $type, $websiteId) $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface'); + $store = $storeManager->getStore(); + $currency = $store->getCurrentCurrencyCode(); + //In case of multiple websites, find the currency for the selected store based on the website ID. if (!empty($websiteId)) { $websites = $storeManager->getWebsites(); @@ -167,11 +187,9 @@ public function getSiteConfig($apiMode, $type, $websiteId) } } } - } else { - $store = $storeManager->getStore(); - $currency = $store->getCurrentCurrencyCode(); - } + } + $url =""; if ($type=='api_url') { if ($apiMode == 'Sandbox') { if ($currency == 'USD' || $currency == 'CAD') { @@ -195,6 +213,15 @@ public function getSiteConfig($apiMode, $type, $websiteId) $url = 'https://portal.afterpay.com/'; } } + + // get JS Library URL + if ($type=='js_lib_url') { + if ($apiMode == 'Sandbox') { + $url = 'https://js.sandbox.afterpay.com/'; + } elseif ($apiMode == 'Production') { + $url = 'https://js.afterpay.com/'; + } + } return $url; } @@ -326,19 +353,19 @@ public function isActive($override = []) } /** - * @return int + * @return float */ public function getMaxOrderLimit() { - return (int)$this->_getConfigData(self::MAX_TOTAL_LIMIT); + return (float)$this->_getConfigData(self::MAX_TOTAL_LIMIT); } /** - * @return int + * @return float */ public function getMinOrderLimit() { - return (int)$this->_getConfigData(self::MIN_TOTAL_LIMIT); + return (float)$this->_getConfigData(self::MIN_TOTAL_LIMIT); } /** @@ -360,4 +387,20 @@ private function _cleanup_string($string) $result = preg_replace("/[^a-zA-Z0-9]+/", "", $string); return $result; } + + /** + * @return bool + */ + public function isEnabledForProductDisplayPage() + { + return (bool)$this->_getConfigData(self::ENABLE_FOR_PRODUCT_PAGE); + } + + /** + * @return bool + */ + public function isEnabledForCartPage() + { + return (bool)$this->_getConfigData(self::ENABLE_FOR_CART_PAGE); + } } diff --git a/Model/Config/Save/Plugin.php b/Model/Config/Save/Plugin.php index 5d3d929..ae02479 100644 --- a/Model/Config/Save/Plugin.php +++ b/Model/Config/Save/Plugin.php @@ -6,6 +6,7 @@ * @copyright 2016-2020 Afterpay https://www.afterpay.com */ namespace Afterpay\Afterpay\Model\Config\Save; +use Magento\Store\Model\ScopeInterface; /** * Class Plugin @@ -23,6 +24,7 @@ class Plugin protected $storeManager; protected $request; protected $messageManager; + protected $_scopeConfig; /** * Plugin constructor. @@ -36,7 +38,9 @@ public function __construct( \Magento\Config\Model\ResourceModel\Config $resourceConfig, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\App\Request\Http $request, - \Magento\Framework\Message\ManagerInterface $messageManager + \Magento\Framework\Message\ManagerInterface $messageManager, + \Magento\Framework\App\Config\Storage\WriterInterface $configWriter, + \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig ) { $this->jsonHelper = $jsonHelper; $this->afterpayTotalLimit = $afterpayTotalLimit; @@ -44,6 +48,8 @@ public function __construct( $this->storeManager = $storeManager; $this->request = $request; $this->messageManager = $messageManager; + $this->configWriter = $configWriter; + $this->_scopeConfig = $scopeConfig; } /** @@ -62,6 +68,7 @@ public function aroundSave( try { $configRequest = $subject->getGroups(); + if(!empty($configRequest) && is_array($configRequest)){ $this->requested = array_key_exists(\Afterpay\Afterpay\Model\Payovertime::METHOD_CODE, $configRequest); if ($this->requested) { @@ -88,12 +95,46 @@ public function aroundSave( $maxTotal="N/A"; } - // set on config request + // Set on config request $configRequest[\Afterpay\Afterpay\Model\Payovertime::METHOD_CODE]['groups'][\Afterpay\Afterpay\Model\Payovertime::METHOD_CODE . '_advanced']['fields'][\Afterpay\Afterpay\Model\Config\Payovertime::MIN_TOTAL_LIMIT]['value'] = $minTotal; $configRequest[\Afterpay\Afterpay\Model\Payovertime::METHOD_CODE]['groups'][\Afterpay\Afterpay\Model\Payovertime::METHOD_CODE . '_advanced']['fields'][\Afterpay\Afterpay\Model\Config\Payovertime::MAX_TOTAL_LIMIT]['value'] = $maxTotal; + // Check for Cross Border Trade(CBT) + $enable_cbt = (array_key_exists('CBT',$response) && isset($response['CBT']['enabled']) && ($response['CBT']['enabled']===true)) ? "1" : "0"; + + // Get current Store Id + $storeId=(int) $this->request->getParam('store', 0); + // Get current Website Id + $websiteId = (int) $this->request->getParam('website', 0); + + // Set current scope + $scope='default'; + $scopeId=0; + if(!empty($websiteId)){ + $scope=ScopeInterface::SCOPE_WEBSITES; + $scopeId=$websiteId; + }elseif (!empty($storeId)){ + $scope=ScopeInterface::SCOPE_STORE; + $scopeId=$storeId; + } + + $countryName=""; + if($enable_cbt=="1"){ + $countryName = $this->_scopeConfig->getValue('general/country/default', $scope,$scopeId); + if(isset($response['CBT']['countries']) && !empty($response['CBT']['countries'])){ + if(is_array($response['CBT']['countries'])){ + $countryName .=",".implode(",",$response['CBT']['countries']); + } + } + } + + + + // Save Cross Border Trade(CBT) details on config request + $this->configWriter->save("payment/afterpaypayovertime/".\Afterpay\Afterpay\Model\Config\Payovertime::ENABLE_CBT, $enable_cbt, $scope, $scopeId); + $this->configWriter->save("payment/afterpaypayovertime/".\Afterpay\Afterpay\Model\Config\Payovertime::CBT_COUNTRY, $countryName, $scope, $scopeId); + $subject->setGroups($configRequest); - $returnValue=$proceed(); } else { $this->messageManager->addWarningMessage('Afterpay Update Limits Failed. Please check Merchant ID and Key.'); @@ -102,6 +143,7 @@ public function aroundSave( } } } + } } catch (\Exception $e) { $this->messageManager->addErrorMessage($e->getMessage()); diff --git a/Model/Payovertime.php b/Model/Payovertime.php index 52b2919..35ac3ab 100644 --- a/Model/Payovertime.php +++ b/Model/Payovertime.php @@ -54,7 +54,7 @@ class Payovertime extends \Magento\Payment\Model\Method\AbstractMethod /** * For dependency injection */ - protected $supportedCurrencyCodes = ['AUD','NZD','USD','CAD']; + protected $supportedContryCurrencyCodes = array('AU'=>'AUD','NZ'=>'NZD','US'=>'USD','CA'=>'CAD'); protected $afterPayPaymentTypeCode = self::AFTERPAY_PAYMENT_TYPE_CODE; protected $logger; @@ -320,10 +320,26 @@ public function isAvailable(\Magento\Quote\Api\Data\CartInterface $quote = null) */ public function canUseForCurrency($currencyCode) { - if (!in_array($currencyCode, $this->supportedCurrencyCodes)) { - return false; + $canUseForCurrency= false; + + if (in_array($currencyCode, $this->supportedContryCurrencyCodes) ) { + + $canUseForCurrency=parent::canUseForCurrency($currencyCode); + //Currency Check for Cross Border trade + if(!empty($this->getConfigData('enable_cbt'))){ + $specifiedCountires=explode(",",$this->getConfigData('cbt_country')); + $canUseForCurrency=false; + foreach($specifiedCountires AS $country){ + if(isset($this->supportedContryCurrencyCodes[$country]) && ($currencyCode==$this->supportedContryCurrencyCodes[$country])){ + $canUseForCurrency=parent::canUseForCurrency($currencyCode); + break; + } + } + + } + } - return parent::canUseForCurrency($currencyCode); + return $canUseForCurrency; } /** diff --git a/composer.json b/composer.json index 1d5c87b..74822ee 100644 --- a/composer.json +++ b/composer.json @@ -3,7 +3,7 @@ "license" : "OSL-3.0", "type" : "magento2-module", "description" : "Magento 2 Afterpay Payment Module", - "version" : "3.2.0", + "version" : "3.3.0", "authors" : [{ "name" : "Afterpay", "homepage" : "https://www.afterpay.com" @@ -17,4 +17,4 @@ "Afterpay\\Afterpay\\" : "" } } -} \ No newline at end of file +} diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index d8fa2fd..6c59ece 100644 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -122,14 +122,20 @@ - - - + + + Magento\Config\Model\Config\Source\Yesno - payment/afterpaypayovertime/enable_cbt - + payment/afterpaypayovertime/enable_for_product_page - + + + + + Magento\Config\Model\Config\Source\Yesno + payment/afterpaypayovertime/enable_for_cart_page + + diff --git a/etc/config.xml b/etc/config.xml index 74051f2..6941484 100644 --- a/etc/config.xml +++ b/etc/config.xml @@ -20,6 +20,8 @@ 1 AU 0 + 1 + 1 diff --git a/etc/csp_whitelist.xml b/etc/csp_whitelist.xml index c8d8d7b..15a7e63 100644 --- a/etc/csp_whitelist.xml +++ b/etc/csp_whitelist.xml @@ -6,21 +6,27 @@ https://portal.sandbox.afterpay.com https://portal.afterpay.com https://static.afterpay.com + https://js.sandbox.afterpay.com + https://js.afterpay.com static.afterpay.com + js.sandbox.afterpay.com + js.afterpay.com static.afterpay.com/ + js.sandbox.afterpay.com + js.afterpay.com - https://static.afterpay.com + https://static.afterpay.com diff --git a/etc/di.xml b/etc/di.xml index 315850c..b6e3c2a 100644 --- a/etc/di.xml +++ b/etc/di.xml @@ -15,11 +15,13 @@ Sandbox https://api-sandbox.afterpay.com/ https://portal.sandbox.afterpay.com/ + https://js.sandbox.afterpay.com/ Production https://api.afterpay.com/ https://portal.afterpay.com/ + https://js.afterpay.com/ diff --git a/etc/module.xml b/etc/module.xml index 91db7af..4d29068 100644 --- a/etc/module.xml +++ b/etc/module.xml @@ -8,7 +8,7 @@ */ --> - + diff --git a/view/frontend/layout/catalog_product_view.xml b/view/frontend/layout/catalog_product_view.xml index ca7702e..33fbbe2 100644 --- a/view/frontend/layout/catalog_product_view.xml +++ b/view/frontend/layout/catalog_product_view.xml @@ -10,14 +10,11 @@ - + - - - \ No newline at end of file diff --git a/view/frontend/layout/catalog_product_view_type_bundle.xml b/view/frontend/layout/catalog_product_view_type_bundle.xml index 7f7dff8..275cc8e 100644 --- a/view/frontend/layout/catalog_product_view_type_bundle.xml +++ b/view/frontend/layout/catalog_product_view_type_bundle.xml @@ -9,6 +9,6 @@ --> - + \ No newline at end of file diff --git a/view/frontend/templates/afterpay/cart.phtml b/view/frontend/templates/afterpay/cart.phtml index 1785126..86e6dfa 100644 --- a/view/frontend/templates/afterpay/cart.phtml +++ b/view/frontend/templates/afterpay/cart.phtml @@ -5,20 +5,43 @@ * @author Afterpay * @copyright 2016-2020 Afterpay https://www.afterpay.com */ -?> -canShow()) : ?> -

- getCartPageText(); - echo $assets_cart_page['snippet1']; - ?> - getInstallmentsTotalHtml();?> - -

+if($block->isPaymentMethodActive() && $block->isDisplayOnCartPage() && $block->canUseCurrency() ){ + $afterpay_eligible = "true"; + if (($block->canShow() === false)) { + $afterpay_eligible = "false"; + } + + $min_limit=$block->getMinOrderLimit(); + $max_limit=$block->getMaxOrderLimit(); + $show_lower_limit="true"; + if((float)$min_limit<1){ + $show_lower_limit="false"; + } + ?> + getCurrentCurrency(); + $data_locale = $block->getCurrentLocale(); + $data_amount = $block->getFinalAmount(); + $enable_cbt = $this->helper('Afterpay\Afterpay\Helper\Data')->getConfig('payment/afterpaypayovertime/enable_cbt'); + $data_enable_cbt = ! empty($enable_cbt) ? "true" : "false"; +?> + +=$min_limit && $data_amount<=$max_limit && $afterpay_eligible!="false" ){?> - + diff --git a/view/frontend/templates/afterpay/product.phtml b/view/frontend/templates/afterpay/product.phtml index 0998c9b..207568e 100644 --- a/view/frontend/templates/afterpay/product.phtml +++ b/view/frontend/templates/afterpay/product.phtml @@ -5,27 +5,37 @@ * @author Afterpay * @copyright 2016-2020 Afterpay https://www.afterpay.com */ -?> -getTypeOfProduct(); -$display=""; -//Check currency and if Afterpay is enabled -if($block->canShow() && $product_type!="grouped") : -if(!$block->isProductEligible()){ - $display="display:none"; +$product_type = $block->getTypeOfProduct(); + +if($block->isPaymentMethodActive() && $block->isDisplayOnProductPage() && $product_type != "grouped" && $block->canUseCurrency()){ + $afterpay_eligible = "true"; + if (($block->canShow() === false)) { + $afterpay_eligible = "false"; + } + $min_limit=$block->getMinOrderLimit(); + $show_lower_limit="true"; + if((float)$min_limit<1){ + $show_lower_limit="false"; + } + ?> + + getCurrentCurrency(); + $data_locale = $block->getCurrentLocale(); + $data_amount = $block->getFinalAmount(); + $enable_cbt = $this->helper('Afterpay\Afterpay\Helper\Data')->getConfig('payment/afterpaypayovertime/enable_cbt'); + $data_enable_cbt = ! empty($enable_cbt) ? "true" : "false"; + ?> + + -
- getInstalmentText(); - echo $assets_product_page['snippet1']; - ?> - getInstallmentsAmount(); ?> -
- -
- diff --git a/view/frontend/web/js/view/cart/afterpay-cart.js b/view/frontend/web/js/view/cart/afterpay-cart.js index c67da82..194ad57 100644 --- a/view/frontend/web/js/view/cart/afterpay-cart.js +++ b/view/frontend/web/js/view/cart/afterpay-cart.js @@ -12,10 +12,8 @@ require( $(".cart-totals").bind("DOMSubtreeModified", function() { var totals = quote.getTotals()(); - var instalment_price = parseFloat(Math.round(totals['base_grand_total'] / 4 * 100) / 100); - var format = {decimalSymbol: '.',pattern:'$%s'}; - var formatted_instalment_price = priceUtils.formatPrice(instalment_price,format); - $('.payment-method-note.afterpay-checkout-note .afterpay_instalment_price').text(formatted_instalment_price); + $('afterpay-placement').attr('data-amount',totals['base_grand_total']); + }); } ); \ No newline at end of file diff --git a/view/frontend/web/js/view/product/afterpay-products.js b/view/frontend/web/js/view/product/afterpay-products.js index aa0056c..bc0275c 100644 --- a/view/frontend/web/js/view/product/afterpay-products.js +++ b/view/frontend/web/js/view/product/afterpay-products.js @@ -8,18 +8,12 @@ require( "Magento_Catalog/js/price-utils" ], function ( $, priceUtils, quote ) { - - var afterpay_instalment_element = $('.afterpay-installments.afterpay-installments-amount'); - - var max_limit = afterpay_instalment_element.attr('maxLimit'); - var min_limit = afterpay_instalment_element.attr('minLimit'); - var product_type = afterpay_instalment_element.attr('product_type'); $(document).ready(function($) { - setInstalment(afterpay_instalment_element, max_limit, min_limit); - + setFinalAmount(); + $('body').on('click change', $('form#product_addtocart_form'), function (e) { - setInstalment(afterpay_instalment_element, max_limit, min_limit); + setFinalAmount(); }); $('body').on('input', $('form#product_addtocart_form select'), function (e) { setTimeout(function() { @@ -28,14 +22,9 @@ require( }); }); - function setInstalment(afterpay_instalment_element, max_limit, min_limit) - { - //var price_raw = $('span.price-final_price > span.price-wrapper > span.price:first'); - //Above line only extracts the value from first price element product page. This might cause problem in some cases - if(product_type=="bundle" && $("[data-price-type=minPrice]:first").text()!=""){ - var price_raw = $("[data-price-type=minPrice]:first").text(); - } - else if($("[data-price-type=finalPrice]:first").text()!=""){ + function setFinalAmount(){ + + if($("[data-price-type=finalPrice]:first").text()!=""){ var price_raw = $("[data-price-type=finalPrice]:first").text(); } else{ @@ -43,31 +32,20 @@ require( } var price = price_raw.match(/[\d\.]+/g); - + + var product_variant_price=parseFloat($('span.price-final_price > span[data-price-type="finalPrice"]').attr('data-price-amount')); if(price != null){ if (price[1]) { product_variant_price = price[0]+price[1]; } else { product_variant_price = price[0]; } - var instalment_price = parseFloat(Math.round(product_variant_price / 4 * 100) / 100); - - //pass the price format object - fix for the group product format - - var format = {decimalSymbol: '.',pattern:'$%s'}; - var formatted_instalment_price = priceUtils.formatPrice(instalment_price,format); - - $('.afterpay-installments.afterpay-installments-amount .afterpay_instalment_price').text(formatted_instalment_price); - - if (parseFloat(product_variant_price) >= parseFloat(min_limit) && parseFloat(product_variant_price) <= parseFloat(max_limit)) { - afterpay_instalment_element.show(); - } else { - afterpay_instalment_element.hide(); - } - } - else{ - afterpay_instalment_element.hide(); } + + $('afterpay-placement').attr('data-amount',product_variant_price); + } + } -); \ No newline at end of file +); +