diff --git a/Api/Data/CheckoutInterface.php b/Api/Data/CheckoutInterface.php
index 4c5530e..5da20ad 100644
--- a/Api/Data/CheckoutInterface.php
+++ b/Api/Data/CheckoutInterface.php
@@ -11,11 +11,11 @@ interface CheckoutInterface
/**#@+
* Checkout result keys
*/
- const AFTERPAY_TOKEN = 'afterpay_token';
- const AFTERPAY_AUTH_TOKEN_EXPIRES = 'afterpay_expires';
- const AFTERPAY_REDIRECT_CHECKOUT_URL = 'afterpay_redirectCheckoutUrl';
- const AFTERPAY_IS_CBT_CURRENCY = 'afterpay_is_cbt_currency';
- const AFTERPAY_CBT_CURRENCY = 'afterpay_cbt_currency';
+ public const AFTERPAY_TOKEN = 'afterpay_token';
+ public const AFTERPAY_AUTH_TOKEN_EXPIRES = 'afterpay_expires';
+ public const AFTERPAY_REDIRECT_CHECKOUT_URL = 'afterpay_redirectCheckoutUrl';
+ public const AFTERPAY_IS_CBT_CURRENCY = 'afterpay_is_cbt_currency';
+ public const AFTERPAY_CBT_CURRENCY = 'afterpay_cbt_currency';
/**#@-*/
/**
diff --git a/Block/Adminhtml/System/Config/Button/LimitUpdate.php b/Block/Adminhtml/System/Config/Button/LimitUpdate.php
index 753377a..440ec10 100644
--- a/Block/Adminhtml/System/Config/Button/LimitUpdate.php
+++ b/Block/Adminhtml/System/Config/Button/LimitUpdate.php
@@ -6,7 +6,7 @@
class LimitUpdate extends \Magento\Config\Block\System\Config\Form\Field
{
- const TEMPLATE = 'Afterpay_Afterpay::system/config/button/update.phtml';
+ public const TEMPLATE = 'Afterpay_Afterpay::system/config/button/update.phtml';
public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
diff --git a/Block/Adminhtml/System/Config/Form/Field/CBTAvailableCurrencies.php b/Block/Adminhtml/System/Config/Form/Field/CBTAvailableCurrencies.php
index fb50036..5b24446 100644
--- a/Block/Adminhtml/System/Config/Form/Field/CBTAvailableCurrencies.php
+++ b/Block/Adminhtml/System/Config/Form/Field/CBTAvailableCurrencies.php
@@ -34,8 +34,8 @@ protected function _renderValue(\Magento\Framework\Data\Form\Element\AbstractEle
}
foreach ($CbtAvailableCurrencies as $currencyCode => $currency) {
- $newValue .= $currencyCode . '(min:' . $currency['minimumAmount']['amount']
- . ',max:' . $currency['maximumAmount']['amount'] . ') ';
+ $min = $currency['minimumAmount']['amount'] ?? '0';
+ $newValue .= $currencyCode . '(min:' . $min . ',max:' . $currency['maximumAmount']['amount'] . ') ';
}
$element->setValue($newValue);
} catch (\Exception $e) {
diff --git a/Block/Adminhtml/System/Config/Form/Field/Version.php b/Block/Adminhtml/System/Config/Form/Field/Version.php
index 2e79629..d3bcb20 100644
--- a/Block/Adminhtml/System/Config/Form/Field/Version.php
+++ b/Block/Adminhtml/System/Config/Form/Field/Version.php
@@ -8,7 +8,7 @@
class Version extends \Magento\Config\Block\System\Config\Form\Field
{
- const MODULE_NAME = "Afterpay_Afterpay";
+ public const MODULE_NAME = "Afterpay_Afterpay";
private $resource;
diff --git a/Controller/Express/CreateCheckout.php b/Controller/Express/CreateCheckout.php
index 17902b6..1017b5e 100644
--- a/Controller/Express/CreateCheckout.php
+++ b/Controller/Express/CreateCheckout.php
@@ -44,7 +44,7 @@ public function execute(): \Magento\Framework\Controller\ResultInterface
$this->messageManager->addErrorMessage($e->getMessage());
} catch (\Throwable $e) {
$this->logger->error($e->getMessage());
- $this->messageManager->addErrorMessage((string)__('Afterpay payment declined. Please select an alternative payment method.'));
+ $this->messageManager->addErrorMessage((string)__('Afterpay payment is declined. Please select an alternative payment method.'));
}
return $result;
}
diff --git a/Controller/Express/PlaceOrder.php b/Controller/Express/PlaceOrder.php
index 57c0756..8353443 100644
--- a/Controller/Express/PlaceOrder.php
+++ b/Controller/Express/PlaceOrder.php
@@ -80,6 +80,6 @@ public function execute()
$this->messageManager->addSuccessMessage((string)__('Afterpay Transaction Completed.'));
- return $jsonResult->setData(['redirectUrl' => $this->storeManager->getStore()->getUrl('checkout/onepage/success')]);
+ return $jsonResult->setData(['redirectUrl' => $this->storeManager->getStore()->getUrl('checkout/onepage/success')]);// @codingStandardsIgnoreLine
}
}
diff --git a/Controller/Payment/Capture.php b/Controller/Payment/Capture.php
index b39ac0d..7d30e16 100644
--- a/Controller/Payment/Capture.php
+++ b/Controller/Payment/Capture.php
@@ -14,8 +14,8 @@
class Capture implements HttpGetActionInterface
{
- const CHECKOUT_STATUS_CANCELLED = 'CANCELLED';
- const CHECKOUT_STATUS_SUCCESS = 'SUCCESS';
+ public const CHECKOUT_STATUS_CANCELLED = 'CANCELLED';
+ public const CHECKOUT_STATUS_SUCCESS = 'SUCCESS';
private $request;
private $session;
private $redirectFactory;
diff --git a/Gateway/Command/GetMerchantConfigurationCommandWrapper.php b/Gateway/Command/GetMerchantConfigurationCommandWrapper.php
index 77fd0ca..2cc6489 100644
--- a/Gateway/Command/GetMerchantConfigurationCommandWrapper.php
+++ b/Gateway/Command/GetMerchantConfigurationCommandWrapper.php
@@ -7,7 +7,7 @@
class GetMerchantConfigurationCommandWrapper implements \Magento\Payment\Gateway\CommandInterface
{
- const DEFAULT_WEBSITE_ID = 0;
+ public const DEFAULT_WEBSITE_ID = 0;
private $merchantConfigurationCommand;
private $afterpayConfig;
@@ -48,6 +48,10 @@ public function execute(array $commandSubject)
}
$this->checkCountry($scope, $websiteId);
$this->checkCurrency($scope, $websiteId);
+ // Disable Cash App Pay if Afterpay is disabled
+ if($this->afterpayConfig->getIsPaymentActive($websiteId)===false){
+ $this->afterpayConfig->setCashAppPayActive(0,$websiteId);
+ }
$this->debugLogger->setForceDebug($this->afterpayConfig->getIsDebug($websiteId));
return $this->merchantConfigurationCommand->execute($commandSubject);
} catch (\Magento\Payment\Gateway\Command\CommandException $e) {
diff --git a/Gateway/Config/Config.php b/Gateway/Config/Config.php
index c3d84f4..905cb1f 100644
--- a/Gateway/Config/Config.php
+++ b/Gateway/Config/Config.php
@@ -4,7 +4,7 @@
class Config extends \Magento\Payment\Gateway\Config\Config
{
- const CODE = 'afterpay';
+ public const CODE = 'afterpay';
public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
diff --git a/Gateway/ErrorMessageMapper/CaptureErrorMessageMapper.php b/Gateway/ErrorMessageMapper/CaptureErrorMessageMapper.php
index f94ffcb..219ffa3 100644
--- a/Gateway/ErrorMessageMapper/CaptureErrorMessageMapper.php
+++ b/Gateway/ErrorMessageMapper/CaptureErrorMessageMapper.php
@@ -7,13 +7,14 @@
class CaptureErrorMessageMapper implements ErrorMessageMapperInterface
{
- public const STATUS_DECLINED_ERROR_MESSAGE = 'Aftepay payment declined. Please select an alternative payment method.';
+ public const STATUS_DECLINED_ERROR_MESSAGE = 'Aftepay payment declined. Please select an alternative payment method.'; // @codingStandardsIgnoreLine
public function getMessage(string $code)
{
+ $message = (string)self::STATUS_DECLINED_ERROR_MESSAGE;
switch ($code) {
case CaptureResponseValidator::STATUS_DECLINED:
- return __(self::STATUS_DECLINED_ERROR_MESSAGE);
+ return __($message);
default:
return null;
}
diff --git a/Gateway/Http/TransferFactory.php b/Gateway/Http/TransferFactory.php
index d977c7c..bfda469 100644
--- a/Gateway/Http/TransferFactory.php
+++ b/Gateway/Http/TransferFactory.php
@@ -6,10 +6,10 @@
class TransferFactory implements \Magento\Payment\Gateway\Http\TransferFactoryInterface
{
- const METHOD_POST = "post";
- const METHOD_GET = "get";
+ public const METHOD_POST = "post";
+ public const METHOD_GET = "get";
- const ARGS = [
+ public const ARGS = [
'orderId',
'websiteId',
'storeId',
@@ -42,7 +42,7 @@ public function __construct(
$this->method = $method;
}
- public function create(array $request): \Magento\Payment\Gateway\Http\TransferInterface
+ public function create(array $request): \Magento\Payment\Gateway\Http\TransferInterface // @codingStandardsIgnoreLine
{
$args = $this->removeAndReturnArgs($request);
diff --git a/Gateway/Http/TransferFactory/UserAgentProvider.php b/Gateway/Http/TransferFactory/UserAgentProvider.php
index 478b601..6c7a7a5 100644
--- a/Gateway/Http/TransferFactory/UserAgentProvider.php
+++ b/Gateway/Http/TransferFactory/UserAgentProvider.php
@@ -41,5 +41,6 @@ public function provide(?int $websiteId = null): string
return "AfterpayMagento2Plugin $moduleVersion ($magentoProductName $magentoProductEdition $magentoVersion) " .
"PHPVersion: PHP/$phpVersion MerchantID: $afterpayMerchantId; MPID/$afterpayMPId; CAPAvailable/$CashAppPayAvailable; CAPEnabled/$CashAppPayEnabled; URL: $websiteDomain";
+
}
}
diff --git a/Gateway/Request/Checkout/CheckoutDataBuilder.php b/Gateway/Request/Checkout/CheckoutDataBuilder.php
index 2a9d211..edc5dbf 100644
--- a/Gateway/Request/Checkout/CheckoutDataBuilder.php
+++ b/Gateway/Request/Checkout/CheckoutDataBuilder.php
@@ -151,7 +151,7 @@ protected function getItemsImages(array $items): array
{
$itemsImages = [];
$searchCriteria = $this->searchCriteriaBuilder
- ->addFilter('entity_id', array_map(static function ($item) {return $item->getProduct()->getId();}, $items), 'in')
+ ->addFilter('entity_id', array_map(static function ($item) {return $item->getProduct()->getId();}, $items), 'in') // @codingStandardsIgnoreLine
->create();
$products = $this->productRepository->getList($searchCriteria)->getItems();
diff --git a/Gateway/Response/Checkout/CheckoutItemsAmountValidationHandler.php b/Gateway/Response/Checkout/CheckoutItemsAmountValidationHandler.php
index 30792d8..464ed67 100644
--- a/Gateway/Response/Checkout/CheckoutItemsAmountValidationHandler.php
+++ b/Gateway/Response/Checkout/CheckoutItemsAmountValidationHandler.php
@@ -10,7 +10,7 @@ public function handle(array $handlingSubject, array $response)
$payment = $paymentDO->getPayment();
/** @var \Magento\Quote\Model\Quote $quote */
$quote = $payment->getQuote();
- $isCBTCurrency = $payment->getAdditionalInformation(\Afterpay\Afterpay\Api\Data\CheckoutInterface::AFTERPAY_IS_CBT_CURRENCY);
+ $isCBTCurrency = $payment->getAdditionalInformation(\Afterpay\Afterpay\Api\Data\CheckoutInterface::AFTERPAY_IS_CBT_CURRENCY); // @codingStandardsIgnoreLine
$grandTotal = $isCBTCurrency ? $quote->getGrandTotal() : $quote->getBaseGrandTotal();
if (round(1 * $grandTotal, 2) != round(1 * $response['amount']['amount'], 2)) {
diff --git a/Gateway/Response/MerchantConfiguration/ChannelsConfigurationHandler.php b/Gateway/Response/MerchantConfiguration/ChannelsConfigurationHandler.php
index eae41f0..75f6104 100644
--- a/Gateway/Response/MerchantConfiguration/ChannelsConfigurationHandler.php
+++ b/Gateway/Response/MerchantConfiguration/ChannelsConfigurationHandler.php
@@ -8,12 +8,14 @@
class ChannelsConfigurationHandler implements HandlerInterface
{
private $config;
+ private $logger;
public function __construct(
- Config $config
- )
- {
+ Config $config,
+ \Psr\Log\LoggerInterface $logger
+ ) {
$this->config = $config;
+ $this->logger = $logger;
}
public function handle(array $handlingSubject, array $response): void
@@ -23,18 +25,26 @@ public function handle(array $handlingSubject, array $response): void
$getCashAppConfig = array_search("CASH_APP", array_column($response['channels'], 'name'));
$isCashAppEnabled = 0;
- if (isset($response['channels'][$getCashAppConfig])) {
+
+ if ( isset($response['channels'][$getCashAppConfig]) &&
+ isset($response['channels'][$getCashAppConfig]['name']) &&
+ strtoupper($response['channels'][$getCashAppConfig]['name'])== "CASH_APP") {
$cashappData=$response['channels'][$getCashAppConfig];
+
if (isset($cashappData['enabled']) && $cashappData['enabled']==true &&
isset($cashappData['integrationCompleted']) && $cashappData['integrationCompleted']==true &&
isset($cashappData['enabledForOrders']) && $cashappData['enabledForOrders']==true) {
$isCashAppEnabled = (int)$cashappData['enabled'];
}
- $this->config->setCashAppPayAvailable($isCashAppEnabled, $websiteId);
+ }else{
+ if( $this->config->getCashAppPayActive($websiteId)==true) {
+ //Disable the Cash App Pay if it's not available for the Merchant
+ $this->config->setCashAppPayActive($isCashAppEnabled, $websiteId);
+ $this->logger->notice("Disable the Cash App Pay as it's not available for the Merchant");
+ }
}
+ $this->config->setCashAppPayAvailable($isCashAppEnabled, $websiteId);
}
}
-
-
}
diff --git a/Gateway/Validator/CaptureResponseValidator.php b/Gateway/Validator/CaptureResponseValidator.php
index d0de33d..c786860 100644
--- a/Gateway/Validator/CaptureResponseValidator.php
+++ b/Gateway/Validator/CaptureResponseValidator.php
@@ -4,8 +4,8 @@
class CaptureResponseValidator extends \Magento\Payment\Gateway\Validator\AbstractValidator
{
- const STATUS_DECLINED = 'DECLINED';
- const STATUS_APPROVED = 'APPROVED';
+ public const STATUS_DECLINED = 'DECLINED';
+ public const STATUS_APPROVED = 'APPROVED';
public function validate(array $validationSubject): \Magento\Payment\Gateway\Validator\ResultInterface
{
diff --git a/Model/CheckoutConfigProvider.php b/Model/CheckoutConfigProvider.php
index 8156f9e..ec4b04d 100644
--- a/Model/CheckoutConfigProvider.php
+++ b/Model/CheckoutConfigProvider.php
@@ -34,6 +34,7 @@ public function getConfig(): array
'isCBTCurrency' => $this->checkCBTCurrencyAvailability->checkByQuote($quote),
'consumerLendingEnabled' => $this->config->getConsumerLendingEnabled(),
'consumerLendingMinimumAmount' => $this->config->getConsumerLendingMinAmount(),
+ 'mpid' => $this->config->getPublicId(),
]
]
];
diff --git a/Model/Config.php b/Model/Config.php
index 5d79850..c471a44 100644
--- a/Model/Config.php
+++ b/Model/Config.php
@@ -10,38 +10,40 @@
class Config
{
- const XML_PATH_PAYMENT_ACTIVE = 'payment/afterpay/active';
- const XML_PATH_API_MODE = 'payment/afterpay/api_mode';
- const XML_PATH_DEBUG = 'payment/afterpay/debug';
- const XML_PATH_ENABLE_CTA_PRODUCT = 'payment/afterpay/enable_cta_product_page';
- const XML_PATH_ENABLE_CTA_MINI_CART = 'payment/afterpay/enable_cta_mini_cart';
- const XML_PATH_ENABLE_CTA_CART_PAGE = 'payment/afterpay/enable_cta_cart_page';
- const XML_PATH_ENABLE_EXPRESS_CHECKOUT_ACTION_PRODUCT = 'payment/afterpay/enable_express_checkout_product_page';
- const XML_PATH_ENABLE_EXPRESS_CHECKOUT_ACTION_MINI_CART = 'payment/afterpay/enable_express_checkout_mini_cart';
- const XML_PATH_ENABLE_EXPRESS_CHECKOUT_ACTION_CART_PAGE = 'payment/afterpay/enable_express_checkout_cart_page';
- const XML_PATH_MERCHANT_ID = 'payment/afterpay/merchant_id';
- const XML_PATH_MERCHANT_KEY = 'payment/afterpay/merchant_key';
- const XML_PATH_PAYMENT_FLOW = 'payment/afterpay/payment_flow';
- const XML_PATH_MIN_LIMIT = 'payment/afterpay/min_order_total';
- const XML_PATH_MAX_LIMIT = 'payment/afterpay/max_order_total';
- const XML_PATH_CBT_CURRENCY_LIMITS = 'payment/afterpay/cbt_currency_limits';
- const XML_PATH_EXCLUDE_CATEGORIES = 'payment/afterpay/exclude_categories';
- const XML_PATH_ALLOW_SPECIFIC_COUNTRIES = 'payment/afterpay/allowspecific';
- const XML_PATH_SPECIFIC_COUNTRIES = 'payment/afterpay/specificcountry';
- const XML_PATH_ALLOWED_MERCHANT_COUNTRIES = 'payment/afterpay/allowed_merchant_countries';
- const XML_PATH_ALLOWED_MERCHANT_CURRENCIES = 'payment/afterpay/allowed_merchant_currencies';
- const XML_PATH_PAYPAL_MERCHANT_COUNTRY = 'paypal/general/merchant_country';
- const XML_PATH_ENABLE_REVERSAL = 'payment/afterpay/enable_reversal';
- const XML_PATH_MPID = 'payment/afterpay/public_id';
- const XML_PATH_CASHAPP_PAY_AVAILABLE = 'payment/afterpay/cash_app_pay_available';
- const XML_PATH_CASHAPP_PAY_ENABLE = 'payment/cashapp/active';
- const XML_PATH_CONSUMER_LENDING_ENABLED = 'payment/afterpay/consumer_lending_enabled';
- const XML_PATH_CONSUMER_LENDING_MIN_AMOUNT = 'payment/afterpay/consumer_lending_min_amount';
-
- private $scopeConfig;
- private $writer;
- private $resourceConnection;
- private $serializer;
+
+ public const XML_PATH_PAYMENT_ACTIVE = 'payment/afterpay/active';
+ public const XML_PATH_API_MODE = 'payment/afterpay/api_mode';
+ public const XML_PATH_DEBUG = 'payment/afterpay/debug';
+ public const XML_PATH_ENABLE_CTA_PRODUCT = 'payment/afterpay/enable_cta_product_page';
+ public const XML_PATH_ENABLE_CTA_MINI_CART = 'payment/afterpay/enable_cta_mini_cart';
+ public const XML_PATH_ENABLE_CTA_CART_PAGE = 'payment/afterpay/enable_cta_cart_page';
+ public const XML_PATH_ENABLE_EXPRESS_CHECKOUT_ACTION_PRODUCT = 'payment/afterpay/enable_express_checkout_product_page'; // @codingStandardsIgnoreLine
+ public const XML_PATH_ENABLE_EXPRESS_CHECKOUT_ACTION_MINI_CART = 'payment/afterpay/enable_express_checkout_mini_cart'; // @codingStandardsIgnoreLine
+ public const XML_PATH_ENABLE_EXPRESS_CHECKOUT_ACTION_CART_PAGE = 'payment/afterpay/enable_express_checkout_cart_page'; // @codingStandardsIgnoreLine
+ public const XML_PATH_ADD_LAST_SELECTED_SHIP_RATE = 'payment/afterpay/add_last_selected_ship_rate';
+ public const XML_PATH_MERCHANT_ID = 'payment/afterpay/merchant_id';
+ public const XML_PATH_MERCHANT_KEY = 'payment/afterpay/merchant_key';
+ public const XML_PATH_PAYMENT_FLOW = 'payment/afterpay/payment_flow';
+ public const XML_PATH_MIN_LIMIT = 'payment/afterpay/min_order_total';
+ public const XML_PATH_MAX_LIMIT = 'payment/afterpay/max_order_total';
+ public const XML_PATH_CBT_CURRENCY_LIMITS = 'payment/afterpay/cbt_currency_limits';
+ public const XML_PATH_EXCLUDE_CATEGORIES = 'payment/afterpay/exclude_categories';
+ public const XML_PATH_ALLOW_SPECIFIC_COUNTRIES = 'payment/afterpay/allowspecific';
+ public const XML_PATH_SPECIFIC_COUNTRIES = 'payment/afterpay/specificcountry';
+ public const XML_PATH_ALLOWED_MERCHANT_COUNTRIES = 'payment/afterpay/allowed_merchant_countries';
+ public const XML_PATH_ALLOWED_MERCHANT_CURRENCIES = 'payment/afterpay/allowed_merchant_currencies';
+ public const XML_PATH_PAYPAL_MERCHANT_COUNTRY = 'paypal/general/merchant_country';
+ public const XML_PATH_ENABLE_REVERSAL = 'payment/afterpay/enable_reversal';
+ public const XML_PATH_MPID = 'payment/afterpay/public_id';
+ public const XML_PATH_CASHAPP_PAY_AVAILABLE = 'payment/afterpay/cash_app_pay_available';
+ public const XML_PATH_CASHAPP_PAY_ACTIVE = 'payment/cashapp/active';
+ public const XML_PATH_CONSUMER_LENDING_ENABLED = 'payment/afterpay/consumer_lending_enabled';
+ public const XML_PATH_CONSUMER_LENDING_MIN_AMOUNT = 'payment/afterpay/consumer_lending_min_amount';
+
+ private $scopeConfig;
+ private $writer;
+ private $resourceConnection;
+ private $serializer;
public function __construct(
ScopeConfigInterface $scopeConfig,
@@ -501,7 +503,7 @@ public function getCashAppPayAvailable(?int $scopeCode = null): bool
public function getCashAppPayEnabled(?int $scopeCode = null): bool
{
return (bool)$this->scopeConfig->getValue(
- self::XML_PATH_CASHAPP_PAY_ENABLE,
+ self::XML_PATH_CASHAPP_PAY_ACTIVE,
ScopeInterface::SCOPE_WEBSITE,
$scopeCode
);
@@ -564,4 +566,40 @@ public function getConsumerLendingMinAmount(?int $scopeCode = null): float
$scopeCode
);
}
+
+ public function getAddLastSelectedShipRate(?int $scopeCode = null): bool
+ {
+ return $this->scopeConfig->isSetFlag(
+ self::XML_PATH_ADD_LAST_SELECTED_SHIP_RATE,
+ ScopeInterface::SCOPE_WEBSITE,
+ $scopeCode
+ );
+ }
+
+ public function setCashAppPayActive(int $value, int $scopeId = 0): self
+ {
+ if ($scopeId) {
+ $this->writer->save(
+ self::XML_PATH_CASHAPP_PAY_ACTIVE,
+ $value,
+ ScopeInterface::SCOPE_WEBSITES,
+ $scopeId
+ );
+ return $this;
+ }
+ $this->writer->save(
+ self::XML_PATH_CASHAPP_PAY_ACTIVE,
+ $value
+ );
+ return $this;
+ }
+
+ public function getCashAppPayActive(?int $scopeCode = null): bool
+ {
+ return (bool)$this->scopeConfig->isSetFlag(
+ self::XML_PATH_CASHAPP_PAY_ACTIVE,
+ ScopeInterface::SCOPE_WEBSITE,
+ $scopeCode
+ );
+ }
}
diff --git a/Model/Config/Source/ApiMode.php b/Model/Config/Source/ApiMode.php
index 25aca3b..4176ebb 100644
--- a/Model/Config/Source/ApiMode.php
+++ b/Model/Config/Source/ApiMode.php
@@ -4,8 +4,8 @@
class ApiMode implements \Magento\Framework\Data\OptionSourceInterface
{
- const SANDBOX = 'sandbox';
- const PRODUCTION = 'production';
+ public const SANDBOX = 'sandbox';
+ public const PRODUCTION = 'production';
public function toOptionArray(): array
{
diff --git a/Model/Config/Source/PaymentFlow.php b/Model/Config/Source/PaymentFlow.php
index b5e7e67..2620237 100644
--- a/Model/Config/Source/PaymentFlow.php
+++ b/Model/Config/Source/PaymentFlow.php
@@ -4,8 +4,8 @@
class PaymentFlow implements \Magento\Framework\Data\OptionSourceInterface
{
- const IMMEDIATE = 'immediate';
- const DEFERRED = 'deferred';
+ public const IMMEDIATE = 'immediate';
+ public const DEFERRED = 'deferred';
public function toOptionArray(): array
{
diff --git a/Model/GraphQl/Resolver/CreateAfterpayCheckout.php b/Model/GraphQl/Resolver/CreateAfterpayCheckout.php
index fb543ed..1f56918 100644
--- a/Model/GraphQl/Resolver/CreateAfterpayCheckout.php
+++ b/Model/GraphQl/Resolver/CreateAfterpayCheckout.php
@@ -2,21 +2,27 @@
namespace Afterpay\Afterpay\Model\GraphQl\Resolver;
+use Afterpay\Afterpay\Api\CheckoutManagementInterface;
use Afterpay\Afterpay\Api\Data\CheckoutInterface;
+use Afterpay\Afterpay\Api\Data\RedirectPathInterfaceFactory;
+use Afterpay\Afterpay\Model\Config;
+use GraphQL\Error\Error;
+use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
+use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
-class CreateAfterpayCheckout implements \Magento\Framework\GraphQl\Query\ResolverInterface
+class CreateAfterpayCheckout implements ResolverInterface
{
private $config;
private $afterpayCheckoutManagement;
private $redirectPathFactory;
public function __construct(
- \Afterpay\Afterpay\Model\Config $config,
- \Afterpay\Afterpay\Api\CheckoutManagementInterface $afterpayCheckoutManagement,
- \Afterpay\Afterpay\Api\Data\RedirectPathInterfaceFactory $redirectPathFactory
+ Config $config,
+ CheckoutManagementInterface $afterpayCheckoutManagement,
+ RedirectPathInterfaceFactory $redirectPathFactory
) {
$this->config = $config;
$this->afterpayCheckoutManagement = $afterpayCheckoutManagement;
@@ -28,30 +34,34 @@ public function __construct(
*/
public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null): array
{
- /** @phpstan-ignore-next-line */
- $storeId = $context->getExtensionAttributes()->getStore()->getId();
+ try {
+ /** @phpstan-ignore-next-line */
+ $storeId = $context->getExtensionAttributes()->getStore()->getId();
- if (!$this->config->getIsPaymentActive((int)$storeId)) {
- throw new GraphQlInputException(__('Afterpay payment method is not active'));
- }
+ if (!$this->config->getIsPaymentActive((int)$storeId)) {
+ throw new GraphQlInputException(__('Afterpay payment method is not active'));
+ }
- if (!$args || !$args['input']) {
- throw new \InvalidArgumentException('Required params cart_id and redirect_path are missing');
- }
+ if (!$args || !$args['input']) {
+ throw new \InvalidArgumentException('Required params cart_id and redirect_path are missing');
+ }
- $maskedCartId = $args['input']['cart_id'];
- $afterpayRedirectPath = $args['input']['redirect_path'];
+ $maskedCartId = $args['input']['cart_id'];
+ $afterpayRedirectPath = $args['input']['redirect_path'];
- $redirectUrls = $this->redirectPathFactory->create()
- ->setConfirmPath($afterpayRedirectPath['confirm_path'])
- ->setCancelPath($afterpayRedirectPath['cancel_path']);
+ $redirectUrls = $this->redirectPathFactory->create()
+ ->setConfirmPath($afterpayRedirectPath['confirm_path'])
+ ->setCancelPath($afterpayRedirectPath['cancel_path']);
- $checkoutResult = $this->afterpayCheckoutManagement->create($maskedCartId, $redirectUrls);
+ $checkoutResult = $this->afterpayCheckoutManagement->create($maskedCartId, $redirectUrls);
- return [
- CheckoutInterface::AFTERPAY_TOKEN => $checkoutResult->getAfterpayToken(),
- CheckoutInterface::AFTERPAY_AUTH_TOKEN_EXPIRES => $checkoutResult->getAfterpayAuthTokenExpires(),
- CheckoutInterface::AFTERPAY_REDIRECT_CHECKOUT_URL => $checkoutResult->getAfterpayRedirectCheckoutUrl()
- ];
+ return [
+ CheckoutInterface::AFTERPAY_TOKEN => $checkoutResult->getAfterpayToken(),
+ CheckoutInterface::AFTERPAY_AUTH_TOKEN_EXPIRES => $checkoutResult->getAfterpayAuthTokenExpires(),
+ CheckoutInterface::AFTERPAY_REDIRECT_CHECKOUT_URL => $checkoutResult->getAfterpayRedirectCheckoutUrl()
+ ];
+ } catch (LocalizedException $exception) {
+ throw new Error($exception->getMessage());
+ }
}
}
diff --git a/Model/Order/OrderItemProvider.php b/Model/Order/OrderItemProvider.php
index a233a8c..95dd04c 100644
--- a/Model/Order/OrderItemProvider.php
+++ b/Model/Order/OrderItemProvider.php
@@ -6,8 +6,8 @@
class OrderItemProvider
{
- const ITEM_SHIPPED = 'shipped';
- const ITEM_REFUNDED = 'refunded';
+ public const ITEM_SHIPPED = 'shipped';
+ public const ITEM_REFUNDED = 'refunded';
private $orderItemFactory;
diff --git a/Model/Order/Payment/Auth/ExpiryDate.php b/Model/Order/Payment/Auth/ExpiryDate.php
index 73d28f7..e528fb4 100644
--- a/Model/Order/Payment/Auth/ExpiryDate.php
+++ b/Model/Order/Payment/Auth/ExpiryDate.php
@@ -4,7 +4,7 @@
class ExpiryDate
{
- const FORMAT = 'Y-m-d H:i T';
+ public const FORMAT = 'Y-m-d H:i T';
private $timezone;
diff --git a/Model/Payment/AdditionalInformationInterface.php b/Model/Payment/AdditionalInformationInterface.php
index 28a3400..bf90cc2 100644
--- a/Model/Payment/AdditionalInformationInterface.php
+++ b/Model/Payment/AdditionalInformationInterface.php
@@ -4,10 +4,10 @@
interface AdditionalInformationInterface
{
- const AFTERPAY_ORDER_ID = 'afterpay_order_id';
- const AFTERPAY_OPEN_TO_CAPTURE_AMOUNT = 'afterpay_open_to_capture_amount';
- const AFTERPAY_PAYMENT_STATE = 'afterpay_payment_state';
- const AFTERPAY_AUTH_EXPIRY_DATE = 'afterpay_auth_expiry_date';
- const AFTERPAY_ROLLOVER_DISCOUNT = 'afterpay_rollover_discount';
- const AFTERPAY_CAPTURED_DISCOUNT = 'afterpay_captured_discount';
+ public const AFTERPAY_ORDER_ID = 'afterpay_order_id';
+ public const AFTERPAY_OPEN_TO_CAPTURE_AMOUNT = 'afterpay_open_to_capture_amount';
+ public const AFTERPAY_PAYMENT_STATE = 'afterpay_payment_state';
+ public const AFTERPAY_AUTH_EXPIRY_DATE = 'afterpay_auth_expiry_date';
+ public const AFTERPAY_ROLLOVER_DISCOUNT = 'afterpay_rollover_discount';
+ public const AFTERPAY_CAPTURED_DISCOUNT = 'afterpay_captured_discount';
}
diff --git a/Model/Payment/AmountProcessor/CreditMemo.php b/Model/Payment/AmountProcessor/CreditMemo.php
index e7d0f53..613bd57 100644
--- a/Model/Payment/AmountProcessor/CreditMemo.php
+++ b/Model/Payment/AmountProcessor/CreditMemo.php
@@ -19,12 +19,14 @@ public function __construct(
public function process(\Magento\Sales\Model\Order\Payment $payment): array
{
$amountToRefund = $amountToVoid = 0;
+
$creditmemo = $payment->getCreditmemo();
foreach ($creditmemo->getAllItems() as $creditmemoItem) {
$orderItem = $creditmemoItem->getOrderItem();
if (!$creditmemoItem->getBaseRowTotalInclTax()) {
continue;
+
}
if ($orderItem->getIsVirtual()) {
@@ -57,11 +59,12 @@ public function process(\Magento\Sales\Model\Order\Payment $payment): array
private function processAdjustmentAmount(
\Magento\Sales\Model\Order\Payment $payment,
+
float &$amountToVoid,
float &$amountToRefund): void
{
$additionalInfo = $payment->getAdditionalInformation();
- $paymentState = $additionalInfo[\Afterpay\Afterpay\Model\Payment\AdditionalInformationInterface::AFTERPAY_PAYMENT_STATE] ?? '';
+ $paymentState = $additionalInfo[\Afterpay\Afterpay\Model\Payment\AdditionalInformationInterface::AFTERPAY_PAYMENT_STATE] ?? '';// @codingStandardsIgnoreLine
$creditmemo = $payment->getCreditmemo();
if ($paymentState === \Afterpay\Afterpay\Model\PaymentStateInterface::AUTH_APPROVED) {
@@ -116,7 +119,7 @@ private function processForCapturedAndRefunded(
(float)($creditmemoItem->getQty() - $allowedToRefundQty)
);
} else {
- $amountToRefund += $this->calculateItemPrice($payment, $creditmemoItem, (float)$creditmemoItem->getQty());
+ $amountToRefund += $this->calculateItemPrice($payment, $creditmemoItem, (float)$creditmemoItem->getQty());// @codingStandardsIgnoreLine
}
} else {
$amountToVoid += $this->calculateItemPrice($payment, $creditmemoItem, (float)$creditmemoItem->getQty());
@@ -193,8 +196,8 @@ private function calculateItemPrice(
\Magento\Sales\Model\Order\Creditmemo\Item $item,
float $qty
): float {
- $isCBTCurrency = $payment->getAdditionalInformation(\Afterpay\Afterpay\Api\Data\CheckoutInterface::AFTERPAY_IS_CBT_CURRENCY);
- $rowTotal = $isCBTCurrency ? $this->priceRenderer->getTotalAmount($item) : $this->priceRenderer->getBaseTotalAmount($item);
+ $isCBTCurrency = $payment->getAdditionalInformation(\Afterpay\Afterpay\Api\Data\CheckoutInterface::AFTERPAY_IS_CBT_CURRENCY);// @codingStandardsIgnoreLine
+ $rowTotal = $isCBTCurrency ? $this->priceRenderer->getTotalAmount($item) : $this->priceRenderer->getBaseTotalAmount($item);// @codingStandardsIgnoreLine
$pricePerItem = $rowTotal / $item->getQty();
return $qty * $pricePerItem;
diff --git a/Model/Payment/AmountProcessor/Order.php b/Model/Payment/AmountProcessor/Order.php
index f39700c..e3b0005 100644
--- a/Model/Payment/AmountProcessor/Order.php
+++ b/Model/Payment/AmountProcessor/Order.php
@@ -33,8 +33,8 @@ protected function calculateItemPrice(
\Magento\Sales\Model\Order\Item $item,
float $qty
): float {
- $isCBTCurrency = $payment->getAdditionalInformation(\Afterpay\Afterpay\Api\Data\CheckoutInterface::AFTERPAY_IS_CBT_CURRENCY);
- $rowTotal = $isCBTCurrency ? $this->priceRenderer->getTotalAmount($item) : $this->priceRenderer->getBaseTotalAmount($item);
+ $isCBTCurrency = $payment->getAdditionalInformation(\Afterpay\Afterpay\Api\Data\CheckoutInterface::AFTERPAY_IS_CBT_CURRENCY);// @codingStandardsIgnoreLine
+ $rowTotal = $isCBTCurrency ? $this->priceRenderer->getTotalAmount($item) : $this->priceRenderer->getBaseTotalAmount($item);// @codingStandardsIgnoreLine
$pricePerItem = $rowTotal / $item->getQtyOrdered();
return $qty * $pricePerItem;
diff --git a/Model/Payment/Capture/CancelOrderProcessor.php b/Model/Payment/Capture/CancelOrderProcessor.php
index 9e6ca38..ab5e2e2 100644
--- a/Model/Payment/Capture/CancelOrderProcessor.php
+++ b/Model/Payment/Capture/CancelOrderProcessor.php
@@ -41,7 +41,7 @@ public function execute(\Magento\Quote\Model\Quote\Payment $payment, int $quoteI
throw new \Magento\Framework\Exception\LocalizedException(
__(
'There was a problem placing your order. Your Afterpay order %1 is refunded.',
- $payment->getAdditionalInformation(\Afterpay\Afterpay\Model\Payment\AdditionalInformationInterface::AFTERPAY_ORDER_ID)
+ $payment->getAdditionalInformation(\Afterpay\Afterpay\Model\Payment\AdditionalInformationInterface::AFTERPAY_ORDER_ID)// @codingStandardsIgnoreLine
)
);
}
diff --git a/Model/Payment/Capture/PlaceOrderProcessor.php b/Model/Payment/Capture/PlaceOrderProcessor.php
index a8ebce6..8ee68c4 100644
--- a/Model/Payment/Capture/PlaceOrderProcessor.php
+++ b/Model/Payment/Capture/PlaceOrderProcessor.php
@@ -55,10 +55,10 @@ public function execute(Quote $quote, CommandInterface $checkoutDataCommand, str
$payment = $quote->getPayment();
try {
- $payment->setAdditionalInformation(CheckoutInterface::AFTERPAY_TOKEN, $afterpayOrderToken);
- $isCBTCurrencyAvailable = $this->checkCBTCurrencyAvailability->checkByQuote($quote);
- $payment->setAdditionalInformation(CheckoutInterface::AFTERPAY_IS_CBT_CURRENCY, $isCBTCurrencyAvailable);
- $payment->setAdditionalInformation(CheckoutInterface::AFTERPAY_CBT_CURRENCY, $quote->getQuoteCurrencyCode());
+ $payment->setAdditionalInformation(CheckoutInterface::AFTERPAY_TOKEN, $afterpayOrderToken);
+ $isCBTCurrencyAvailable = $this->checkCBTCurrencyAvailability->checkByQuote($quote);
+ $payment->setAdditionalInformation(CheckoutInterface::AFTERPAY_IS_CBT_CURRENCY, $isCBTCurrencyAvailable);
+ $payment->setAdditionalInformation(CheckoutInterface::AFTERPAY_CBT_CURRENCY, $quote->getQuoteCurrencyCode());
if (!$quote->getCustomerId()) {
$quote->setCustomerEmail($quote->getBillingAddress()->getEmail())
diff --git a/Model/Payment/PaymentErrorProcessor.php b/Model/Payment/PaymentErrorProcessor.php
index 97b5b19..cf2c8bb 100644
--- a/Model/Payment/PaymentErrorProcessor.php
+++ b/Model/Payment/PaymentErrorProcessor.php
@@ -36,7 +36,8 @@ public function __construct(
public function execute(Quote $quote, \Throwable $e, Payment $payment): int
{
$this->logger->critical('Order placement is failed with error: ' . PHP_EOL . $e);
- if (($this->checkoutSession->getLastSuccessQuoteId() == $quote->getId()) && $this->checkoutSession->getLastOrderId()) {
+ if (($this->checkoutSession->getLastSuccessQuoteId() == $quote->getId()) &&
+ $this->checkoutSession->getLastOrderId()) {
try {
$order = $this->orderRepository->get((int)$this->checkoutSession->getLastOrderId());
$order->addCommentToStatusHistory(
@@ -48,10 +49,12 @@ public function execute(Quote $quote, \Throwable $e, Payment $payment): int
return (int)$order->getEntityId();
} catch (NoSuchEntityException $e) {
+ throw $e;
}
}
- if ($e instanceof CommandException && $e->getMessage() === CaptureErrorMessageMapper::STATUS_DECLINED_ERROR_MESSAGE) {
+ if ($e instanceof CommandException &&
+ $e->getMessage() === CaptureErrorMessageMapper::STATUS_DECLINED_ERROR_MESSAGE) {
throw $e;
}
diff --git a/Model/PaymentStateInterface.php b/Model/PaymentStateInterface.php
index 7b1ca4c..ee81a21 100644
--- a/Model/PaymentStateInterface.php
+++ b/Model/PaymentStateInterface.php
@@ -4,8 +4,8 @@
interface PaymentStateInterface
{
- const AUTH_APPROVED = 'AUTH_APPROVED';
- const PARTIALLY_CAPTURED = 'PARTIALLY_CAPTURED';
- const CAPTURED = 'CAPTURED';
- const VOIDED = 'VOIDED';
+ public const AUTH_APPROVED = 'AUTH_APPROVED';
+ public const PARTIALLY_CAPTURED = 'PARTIALLY_CAPTURED';
+ public const CAPTURED = 'CAPTURED';
+ public const VOIDED = 'VOIDED';
}
diff --git a/Model/Shipment/Express/CreateShippingOption.php b/Model/Shipment/Express/CreateShippingOption.php
index fac265e..7d4fe9c 100644
--- a/Model/Shipment/Express/CreateShippingOption.php
+++ b/Model/Shipment/Express/CreateShippingOption.php
@@ -62,7 +62,7 @@ private function createShippingOptionByMethod(
: $totals->getBaseShippingAmount());
return [
- 'id' => $shippingMethod->getCarrierCode() . "_" . $shippingMethod->getMethodCode(),
+ 'id' => implode('_', [$shippingMethod->getCarrierCode(), $shippingMethod->getMethodCode()]),
'name' => $shippingMethod->getCarrierTitle(),
'description' => $shippingMethod->getCarrierTitle(),
'shippingAmount' => [
diff --git a/Model/SourceValidatorService.php b/Model/SourceValidatorService.php
index 7ef626a..b0ade98 100644
--- a/Model/SourceValidatorService.php
+++ b/Model/SourceValidatorService.php
@@ -11,7 +11,7 @@ class SourceValidatorService implements \Afterpay\Afterpay\Model\Spi\SourceValid
/**
* We avoid strict types in constructor for create instances dynamically look at
* \Afterpay\Afterpay\Model\StockItemsValidator\StockItemsValidatorProxy
- * @param \Magento\InventorySourceDeductionApi\Model\GetSourceItemBySourceCodeAndSku $getSourceItemBySourceCodeAndSku
+ * @param \Magento\InventorySourceDeductionApi\Model\GetSourceItemBySourceCodeAndSku $getSourceItemBySourceCodeAndSku // @codingStandardsIgnoreLine
* @param \Magento\InventoryConfigurationApi\Api\GetStockItemConfigurationInterface $getStockItemConfiguration
* @param \Magento\InventorySalesApi\Api\GetStockBySalesChannelInterface $getStockBySalesChannel
*/
@@ -31,7 +31,7 @@ public function __construct(
* @throws \Magento\Framework\Exception\NoSuchEntityException
* @throws \Magento\InventoryConfigurationApi\Exception\SkuIsNotAssignedToStockException
*/
- public function execute(\Magento\InventorySourceDeductionApi\Model\SourceDeductionRequestInterface $sourceDeductionRequest): void
+ public function execute(\Magento\InventorySourceDeductionApi\Model\SourceDeductionRequestInterface $sourceDeductionRequest): void // @codingStandardsIgnoreLine
{
$sourceCode = $sourceDeductionRequest->getSourceCode();
$salesChannel = $sourceDeductionRequest->getSalesChannel();
diff --git a/Model/Spi/SourceValidatorServiceInterface.php b/Model/Spi/SourceValidatorServiceInterface.php
index 082b687..70cac83 100644
--- a/Model/Spi/SourceValidatorServiceInterface.php
+++ b/Model/Spi/SourceValidatorServiceInterface.php
@@ -14,5 +14,5 @@ interface SourceValidatorServiceInterface
* @param SourceDeductionRequestInterface $sourceDeductionRequest
* @return void
*/
- public function execute(\Magento\InventorySourceDeductionApi\Model\SourceDeductionRequestInterface $sourceDeductionRequest): void;
+ public function execute(\Magento\InventorySourceDeductionApi\Model\SourceDeductionRequestInterface $sourceDeductionRequest): void; // @codingStandardsIgnoreLine
}
diff --git a/Model/StockItemsValidator/StockItemsValidatorProxy.php b/Model/StockItemsValidator/StockItemsValidatorProxy.php
index 0f93973..6677872 100644
--- a/Model/StockItemsValidator/StockItemsValidatorProxy.php
+++ b/Model/StockItemsValidator/StockItemsValidatorProxy.php
@@ -4,7 +4,7 @@
use Magento\Framework\App\ObjectManager;
-class StockItemsValidatorProxy implements \Afterpay\Afterpay\Model\Spi\StockItemsValidatorInterface, \Magento\Framework\ObjectManager\NoninterceptableInterface
+class StockItemsValidatorProxy implements \Afterpay\Afterpay\Model\Spi\StockItemsValidatorInterface, \Magento\Framework\ObjectManager\NoninterceptableInterface // @codingStandardsIgnoreLine
{
private $subject = null;
private $stockItemValidatorFactory;
@@ -46,15 +46,15 @@ private function getStockItemValidator(): \Afterpay\Afterpay\Model\Spi\StockItem
if ($this->subject == null) {
$objectManager = ObjectManager::getInstance();
$sourceValidatorService = $this->sourceValidatorServiceFactory->create([
- 'getSourceItemBySourceCodeAndSku' => $objectManager->create('\\Magento\\InventorySourceDeductionApi\\Model\\GetSourceItemBySourceCodeAndSku'),
- 'getStockItemConfiguration' => $objectManager->create('\\Magento\\InventoryConfigurationApi\\Api\\GetStockItemConfigurationInterface'),
+ 'getSourceItemBySourceCodeAndSku' => $objectManager->create('\\Magento\\InventorySourceDeductionApi\\Model\\GetSourceItemBySourceCodeAndSku'), // @codingStandardsIgnoreLine
+ 'getStockItemConfiguration' => $objectManager->create('\\Magento\\InventoryConfigurationApi\\Api\\GetStockItemConfigurationInterface'), // @codingStandardsIgnoreLine
'getStockBySalesChannel' => $objectManager->create('\\Magento\\InventorySalesApi\\Api\\GetStockBySalesChannelInterface'),
]);
$this->subject = $this->stockItemValidatorFactory->create([
- 'isSingleSourceMode' => $objectManager->create('\\Magento\\InventoryCatalogApi\\Model\\IsSingleSourceModeInterface'),
- 'defaultSourceProvider' => $objectManager->create('\\Magento\\InventoryCatalogApi\\Api\\DefaultSourceProviderInterface'),
- 'getItemsToDeductFromShipment' => $objectManager->create('\\Magento\\InventoryShipping\\Model\\GetItemsToDeductFromShipment'),
- 'sourceDeductionRequestFromShipmentFactory' => $objectManager->create('\\Magento\\InventoryShipping\\Model\\SourceDeductionRequestFromShipmentFactory'),
+ 'isSingleSourceMode' => $objectManager->create('\\Magento\\InventoryCatalogApi\\Model\\IsSingleSourceModeInterface'), // @codingStandardsIgnoreLine
+ 'defaultSourceProvider' => $objectManager->create('\\Magento\\InventoryCatalogApi\\Api\\DefaultSourceProviderInterface'), // @codingStandardsIgnoreLine
+ 'getItemsToDeductFromShipment' => $objectManager->create('\\Magento\\InventoryShipping\\Model\\GetItemsToDeductFromShipment'), // @codingStandardsIgnoreLine
+ 'sourceDeductionRequestFromShipmentFactory' => $objectManager->create('\\Magento\\InventoryShipping\\Model\\SourceDeductionRequestFromShipmentFactory'), // @codingStandardsIgnoreLine
'sourceValidatorService' => $sourceValidatorService,
]);
}
diff --git a/Model/Url/UrlBuilder.php b/Model/Url/UrlBuilder.php
index 614fb7b..c9b0d0f 100644
--- a/Model/Url/UrlBuilder.php
+++ b/Model/Url/UrlBuilder.php
@@ -4,8 +4,8 @@
class UrlBuilder
{
- const TYPE_API = 'api_url';
- const TYPE_JS_LIB = 'js_lib_url';
+ public const TYPE_API = 'api_url';
+ public const TYPE_JS_LIB = 'js_lib_url';
private $urlFactory;
diff --git a/Observer/Adminhtml/ConfigSaveAfter.php b/Observer/Adminhtml/ConfigSaveAfter.php
index c80ed6f..39f94cf 100644
--- a/Observer/Adminhtml/ConfigSaveAfter.php
+++ b/Observer/Adminhtml/ConfigSaveAfter.php
@@ -7,12 +7,12 @@ class ConfigSaveAfter implements \Magento\Framework\Event\ObserverInterface
private $merchantConfigurationCommand;
private $messageManager;
- const AFTERPAY_CONFIGS = [
+ public const AFTERPAY_CONFIGS = [
\Afterpay\Afterpay\Model\Config::XML_PATH_API_MODE,
\Afterpay\Afterpay\Model\Config::XML_PATH_MERCHANT_KEY,
\Afterpay\Afterpay\Model\Config::XML_PATH_MERCHANT_ID
];
- const CONFIGS_PATHS_TO_TRACK = [
+ public const CONFIGS_PATHS_TO_TRACK = [
\Magento\Directory\Model\Currency::XML_PATH_CURRENCY_BASE,
\Magento\Directory\Helper\Data::XML_PATH_DEFAULT_COUNTRY,
\Afterpay\Afterpay\Model\Config::XML_PATH_PAYPAL_MERCHANT_COUNTRY
diff --git a/Observer/AuthCaptureAfterCreditMemo.php b/Observer/AuthCaptureAfterCreditMemo.php
index 04e51ff..9c4667a 100644
--- a/Observer/AuthCaptureAfterCreditMemo.php
+++ b/Observer/AuthCaptureAfterCreditMemo.php
@@ -40,7 +40,8 @@ public function execute(\Magento\Framework\Event\Observer $observer): void
$additionalInfo = $paymentInfo->getAdditionalInformation();
$paymentState = $additionalInfo[AdditionalInformationInterface::AFTERPAY_PAYMENT_STATE] ?? '';
- if ($paymentState !== PaymentStateInterface::AUTH_APPROVED && $paymentState !== PaymentStateInterface::PARTIALLY_CAPTURED) {
+ if ($paymentState !== PaymentStateInterface::AUTH_APPROVED &&
+ $paymentState !== PaymentStateInterface::PARTIALLY_CAPTURED) {
return;
}
diff --git a/Plugin/Checkout/Model/TotalsInformationManagement/AddLastSelectedShippingRate.php b/Plugin/Checkout/Model/TotalsInformationManagement/AddLastSelectedShippingRate.php
index db7b080..6d53712 100644
--- a/Plugin/Checkout/Model/TotalsInformationManagement/AddLastSelectedShippingRate.php
+++ b/Plugin/Checkout/Model/TotalsInformationManagement/AddLastSelectedShippingRate.php
@@ -2,48 +2,74 @@
namespace Afterpay\Afterpay\Plugin\Checkout\Model\TotalsInformationManagement;
+use Afterpay\Afterpay\Api\Data\Quote\ExtendedShippingInformationInterface;
+use Afterpay\Afterpay\Model\Config;
use Magento\Checkout\Api\Data\TotalsInformationInterface;
+use Magento\Checkout\Api\TotalsInformationManagementInterface;
+use Magento\Quote\Api\CartRepositoryInterface;
+use Magento\Quote\Api\Data\TotalsInterface;
+use Magento\Quote\Model\Quote;
class AddLastSelectedShippingRate
{
/**
- * @var \Magento\Quote\Api\CartRepositoryInterface
+ * @var CartRepositoryInterface
*/
private $cartRepository;
+
/**
- * @var \Afterpay\Afterpay\Api\Data\Quote\ExtendedShippingInformationInterface
+ * @var ExtendedShippingInformationInterface
*/
private $extendedShippingInformation;
+ /**
+ * @var Config;
+ */
+ private $config;
+
public function __construct(
- \Magento\Quote\Api\CartRepositoryInterface $cartRepository,
- \Afterpay\Afterpay\Api\Data\Quote\ExtendedShippingInformationInterface $extendedShippingInformation
+ CartRepositoryInterface $cartRepository,
+ ExtendedShippingInformationInterface $extendedShippingInformation,
+ Config $config
) {
$this->cartRepository = $cartRepository;
$this->extendedShippingInformation = $extendedShippingInformation;
+ $this->config = $config;
}
- public function beforeCalculate(
- \Magento\Checkout\Api\TotalsInformationManagementInterface $subject,
- $cartId,
- \Magento\Checkout\Api\Data\TotalsInformationInterface $addressInformation
+ public function afterCalculate(
+ TotalsInformationManagementInterface $subject,
+ TotalsInterface $result,
+ $cartId,
+ TotalsInformationInterface $addressInformation
) {
- /** @var \Magento\Quote\Model\Quote $quote */
+ if (!$this->config->getAddLastSelectedShipRate()
+ || (!$this->config->getIsEnableExpressCheckoutMiniCart()
+ && !$this->config->getIsEnableExpressCheckoutProductPage()
+ && !$this->config->getIsEnableExpressCheckoutCartPage())) {
+ return $result;
+ }
+
+ /** @var Quote $quote */
$quote = $this->cartRepository->get($cartId);
$shippingRate = '';
-
- if ($addressInformation->getShippingMethodCode() && $addressInformation->getShippingCarrierCode()) {
- $shippingRate = $addressInformation->getShippingMethodCode() . '_' . $addressInformation->getShippingCarrierCode();
+ if ($quote->getShippingAddress()->getShippingMethod()) {
+ $shippingRate = $quote->getShippingAddress()->getShippingMethod();
+ } elseif ($addressInformation->getShippingCarrierCode() && $addressInformation->getShippingMethodCode()) {
+ $shippingRate = implode(
+ '_',
+ [$addressInformation->getShippingCarrierCode(), $addressInformation->getShippingMethodCode()]
+ );
}
if ($shippingRate) {
$this->extendedShippingInformation->update(
$quote,
- \Afterpay\Afterpay\Api\Data\Quote\ExtendedShippingInformationInterface::LAST_SELECTED_SHIPPING_RATE,
+ ExtendedShippingInformationInterface::LAST_SELECTED_SHIPPING_RATE,
$shippingRate
);
}
- return [$cartId, $addressInformation];
+ return $result;
}
}
diff --git a/Plugin/Model/Order/Payment/Operations/CaptureOperation.php b/Plugin/Model/Order/Payment/Operations/CaptureOperation.php
index 70cdf86..6eab076 100644
--- a/Plugin/Model/Order/Payment/Operations/CaptureOperation.php
+++ b/Plugin/Model/Order/Payment/Operations/CaptureOperation.php
@@ -56,7 +56,7 @@ public function aroundCapture(
$invoice
) {
if ($this->ckeckPaymentMethod->isAfterPayMethod($payment)
- && $payment->getAdditionalInformation(\Afterpay\Afterpay\Api\Data\CheckoutInterface::AFTERPAY_IS_CBT_CURRENCY)) {
+ && $payment->getAdditionalInformation(\Afterpay\Afterpay\Api\Data\CheckoutInterface::AFTERPAY_IS_CBT_CURRENCY)) { // @codingStandardsIgnoreLine
/**
* @var $payment Payment
*/
diff --git a/Setup/Patch/Data/MigrateTokens.php b/Setup/Patch/Data/MigrateTokens.php
index 3bbe87c..d72a761 100644
--- a/Setup/Patch/Data/MigrateTokens.php
+++ b/Setup/Patch/Data/MigrateTokens.php
@@ -50,22 +50,24 @@ public function apply(): self
$tokenEntries = [];
foreach ($payments as $payment) {
if (!empty($payment[OrderPaymentInterface::ADDITIONAL_INFORMATION])) {
- $additionalInfo = $this->serializer->unserialize($payment[OrderPaymentInterface::ADDITIONAL_INFORMATION]);
- $token = $additionalInfo[CheckoutInterface::AFTERPAY_TOKEN];
- $expiration = $additionalInfo[AdditionalInformationInterface::AFTERPAY_AUTH_EXPIRY_DATE] ?? null;
- if ($expiration) {
- $expiration = $this->dateTime->formatDate($expiration);
+ $additionalInfo = $this->serializer->unserialize($payment[OrderPaymentInterface::ADDITIONAL_INFORMATION]); // @codingStandardsIgnoreLine
+ $token = $additionalInfo[CheckoutInterface::AFTERPAY_TOKEN] ?? null;
+ if ($token) {
+ $expiration = $additionalInfo[AdditionalInformationInterface::AFTERPAY_AUTH_EXPIRY_DATE] ?? null;
+ if ($expiration) {
+ $expiration = $this->dateTime->formatDate($expiration);
+ }
+ $tokenEntries[] = [
+ TokenInterface::ORDER_ID_FIELD => $payment['parent_id'],
+ TokenInterface::TOKEN_FIELD => $token,
+ TokenInterface::EXPIRATION_DATE_FIELD => $expiration
+ ];
}
- $tokenEntries[] = [
- TokenInterface::ORDER_ID_FIELD => $payment['parent_id'],
- TokenInterface::TOKEN_FIELD => $token,
- TokenInterface::EXPIRATION_DATE_FIELD => $expiration
- ];
}
}
if (!empty($tokenEntries)) {
- $this->tokensResource->getConnection()->insertOnDuplicate($this->tokensResource->getMainTable(), $tokenEntries);
+ $this->tokensResource->getConnection()->insertOnDuplicate($this->tokensResource->getMainTable(), $tokenEntries);// @codingStandardsIgnoreLine
}
return $this;
diff --git a/Test/ApiFunctional/GraphQl/CreateAfterpayCheckoutTest.php b/Test/ApiFunctional/GraphQl/CreateAfterpayCheckoutTest.php
index 7426998..992ee96 100644
--- a/Test/ApiFunctional/GraphQl/CreateAfterpayCheckoutTest.php
+++ b/Test/ApiFunctional/GraphQl/CreateAfterpayCheckoutTest.php
@@ -1,6 +1,6 @@
getMaskedQuoteIdByReservedOrderId->execute('test_order_item_with_items');
+ $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('guest_quote');
$mutation = $this->createAfterpayCheckoutMutation($maskedQuoteId);
$response = $this->graphQlMutation($mutation);
diff --git a/Test/Unit/Model/Payment/AmountProcessor/CreditMemoTest.php b/Test/Unit/Model/Payment/AmountProcessor/CreditMemoTest.php
index 31bb2c4..277b9dd 100644
--- a/Test/Unit/Model/Payment/AmountProcessor/CreditMemoTest.php
+++ b/Test/Unit/Model/Payment/AmountProcessor/CreditMemoTest.php
@@ -87,6 +87,12 @@ private function prepareOrderObject(): void
->getMock();
$shipmentCollection->expects($this->atLeastOnce())->method('count')->willReturn(0);
+ $store = $this->createMock(\Magento\Store\Model\Store::class);
+ $store->expects($this->any())->method("getWebsiteId")->willReturn(1);
+
+ $this->order->expects($this->any())->method("getStore")
+ ->with()
+ ->willReturn($store);
$this->order->expects($this->any())->method("getPayment")
->with()
->willReturn($this->payment);
diff --git a/Test/Unit/Model/Shipment/Express/CreateShippingOptionTest.php b/Test/Unit/Model/Shipment/Express/CreateShippingOptionTest.php
index 4944ae3..309fe15 100644
--- a/Test/Unit/Model/Shipment/Express/CreateShippingOptionTest.php
+++ b/Test/Unit/Model/Shipment/Express/CreateShippingOptionTest.php
@@ -25,6 +25,10 @@ class CreateShippingOptionTest extends \PHPUnit\Framework\TestCase
* @var \Magento\Quote\Model\Quote|\PHPUnit\Framework\MockObject\MockObject
*/
private $quote;
+ /**
+ * @var \Afterpay\Afterpay\Model\CBT\CheckCBTCurrencyAvailabilityInterface
+ */
+ private $checkCBTCurrencyAvailability;
protected function setUp(): void
{
@@ -42,7 +46,16 @@ protected function setUp(): void
$this->totalsInformation->method("setShippingCarrierCode")->willReturnSelf();
$this->totalsInformation->method("setShippingMethodCode")->willReturnSelf();
$this->totalsInformationFactory->method("create")->willReturn($this->totalsInformation);
- $this->quote = $this->createMock(\Magento\Quote\Model\Quote::class);
+ $this->checkCBTCurrencyAvailability = $this->createMock(
+ \Afterpay\Afterpay\Model\CBT\CheckCBTCurrencyAvailabilityInterface::class
+ );
+ $this->checkCBTCurrencyAvailability->method("checkByQuote")->willReturn(false);
+ $this->quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class)
+ ->disableOriginalConstructor()
+ ->disableOriginalClone()
+ ->disableArgumentCloning()
+ ->setMethods(['getGrandTotal', 'getBaseGrandTotal', 'getShippingAddress'])
+ ->getMock();
$this->quote->method("getShippingAddress")
->willReturn(
$this->createMock(\Magento\Quote\Api\Data\AddressInterface::class)
@@ -50,7 +63,8 @@ protected function setUp(): void
$this->createShippingOption = new \Afterpay\Afterpay\Model\Shipment\Express\CreateShippingOption(
$this->config,
$this->totalsInformationManagement,
- $this->totalsInformationFactory
+ $this->totalsInformationFactory,
+ $this->checkCBTCurrencyAvailability
);
}
@@ -76,6 +90,8 @@ public function testOrderLimit(
$this->totalsInformationManagement->expects($this->once())
->method("calculate")
->willReturn($calculatedTotals);
+ $this->quote->method("getGrandTotal")->willReturn($calculatedTotals->getGrandTotal());
+ $this->quote->method("getBaseGrandTotal")->willReturn($calculatedTotals->getBaseGrandTotal());
$this->assertEquals($result, $this->createShippingOption->create($this->quote, $shippingMethod));
}
@@ -84,6 +100,7 @@ public function orderLimitDataProvider()
$carrierCode = 'carrierCode';
$carrierMethod = 'carrierMethod';
$carrierTitle = 'carrierTitle';
+ $grandTotal = 10000;
$baseGrandTotal = 10000;
$baseShippingAmount = 20;
$baseTaxAmount = 10;
@@ -91,35 +108,35 @@ public function orderLimitDataProvider()
[
"0",
"1000",
- $this->createCalculatedTotals($baseGrandTotal, $baseShippingAmount, $baseTaxAmount),
+ $this->createCalculatedTotals($grandTotal, $baseGrandTotal, $baseShippingAmount, $baseTaxAmount),
$this->createShippingMethod($carrierCode, $carrierMethod, $carrierTitle),
null,
],
[
"10000",
"1000",
- $this->createCalculatedTotals($baseGrandTotal, $baseShippingAmount, $baseTaxAmount),
+ $this->createCalculatedTotals($grandTotal, $baseGrandTotal, $baseShippingAmount, $baseTaxAmount),
$this->createShippingMethod($carrierCode, $carrierMethod, $carrierTitle),
null,
],
[
null,
"1000",
- $this->createCalculatedTotals($baseGrandTotal, $baseShippingAmount, $baseTaxAmount),
+ $this->createCalculatedTotals($grandTotal, $baseGrandTotal, $baseShippingAmount, $baseTaxAmount),
$this->createShippingMethod($carrierCode, $carrierMethod, $carrierTitle),
null,
],
[
"0",
null,
- $this->createCalculatedTotals($baseGrandTotal, $baseShippingAmount, $baseTaxAmount),
+ $this->createCalculatedTotals($grandTotal, $baseGrandTotal, $baseShippingAmount, $baseTaxAmount),
$this->createShippingMethod($carrierCode, $carrierMethod, $carrierTitle),
null,
],
[
null,
null,
- $this->createCalculatedTotals($baseGrandTotal, $baseShippingAmount, $baseTaxAmount),
+ $this->createCalculatedTotals($grandTotal, $baseGrandTotal, $baseShippingAmount, $baseTaxAmount),
$this->createShippingMethod($carrierCode, $carrierMethod, $carrierTitle),
null,
]
@@ -131,6 +148,7 @@ public function resultNullAmountTestDataProvider()
$carrierCode = 'carrierCode';
$carrierMethod = 'carrierMethod';
$carrierTitle = 'carrierTitle';
+ $grandTotal = 10000;
$baseGrandTotal = 10000;
$baseShippingAmount = 20;
$baseTaxAmount = 10;
@@ -138,14 +156,14 @@ public function resultNullAmountTestDataProvider()
[
"0",
"100000",
- $this->createCalculatedTotals(null, $baseShippingAmount, $baseTaxAmount),
+ $this->createCalculatedTotals(null,null, $baseShippingAmount, $baseTaxAmount),
$this->createShippingMethod($carrierCode, $carrierMethod, $carrierTitle),
null
],
[
"0",
"100000",
- $this->createCalculatedTotals($baseGrandTotal, null, $baseTaxAmount),
+ $this->createCalculatedTotals($grandTotal, $baseGrandTotal, null, $baseTaxAmount),
$this->createShippingMethod($carrierCode, $carrierMethod, $carrierTitle),
[
'id' => $carrierCode . "_" . $carrierMethod,
@@ -168,7 +186,7 @@ public function resultNullAmountTestDataProvider()
[
"0",
"100000",
- $this->createCalculatedTotals($baseGrandTotal, $baseShippingAmount, null),
+ $this->createCalculatedTotals($grandTotal, $baseGrandTotal, $baseShippingAmount, null),
$this->createShippingMethod($carrierCode, $carrierMethod, $carrierTitle),
[
'id' => $carrierCode . "_" . $carrierMethod,
@@ -191,7 +209,7 @@ public function resultNullAmountTestDataProvider()
[
"0",
"100000",
- $this->createCalculatedTotals($baseGrandTotal, null, null),
+ $this->createCalculatedTotals($grandTotal, $baseGrandTotal, null, null),
$this->createShippingMethod($carrierCode, $carrierMethod, $carrierTitle),
[
'id' => $carrierCode . "_" . $carrierMethod,
@@ -220,7 +238,7 @@ public function resultTestDataProvider()
[
"123",
"1234",
- $this->createCalculatedTotals(1233.11, 12.13, 11.15),
+ $this->createCalculatedTotals(1233.11,1233.11, 12.13, 11.15),
$this->createShippingMethod("carrierCode1", "carrierMethod1", "carrierTitle1"),
[
'id' => "carrierCode1" . "_" . "carrierMethod1",
@@ -243,7 +261,7 @@ public function resultTestDataProvider()
[
"22222",
"55555",
- $this->createCalculatedTotals(33333.33, 324.13, 534.234),
+ $this->createCalculatedTotals(33333.33, 33333.33,324.13, 534.234),
$this->createShippingMethod("carrierCode2", "carrierMethod2", "carrierTitle2"),
[
'id' => "carrierCode2" . "_" . "carrierMethod2",
@@ -267,11 +285,13 @@ public function resultTestDataProvider()
}
private function createCalculatedTotals(
+ ?float $grandTotal = 0,
?float $baseGrandTotal = 0,
?float $baseShippingAmount = 0,
?float $baseTaxAmount = 0
) {
$calculatedTotals = $this->createMock(\Magento\Quote\Api\Data\TotalsInterface::class);
+ $calculatedTotals->expects($this->any())->method("getGrandTotal")->willReturn($grandTotal);
$calculatedTotals->expects($this->any())->method("getBaseGrandTotal")->willReturn($baseGrandTotal);
$calculatedTotals->expects($this->any())->method("getBaseTaxAmount")->willReturn($baseTaxAmount);
$calculatedTotals->expects($this->any())->method("getBaseShippingAmount")->willReturn($baseShippingAmount);
diff --git a/Test/Unit/Service/Payment/Auth/ExpiryDateTest.php b/Test/Unit/Service/Payment/Auth/ExpiryDateTest.php
index 539a7ea..1f82a4b 100644
--- a/Test/Unit/Service/Payment/Auth/ExpiryDateTest.php
+++ b/Test/Unit/Service/Payment/Auth/ExpiryDateTest.php
@@ -22,7 +22,7 @@ protected function setUp(): void
/**
* @dataProvider datesProvider
*/
- public function testIsExpired(string $expireDate, ?string $dateToCheck = null, bool $result)
+ public function testIsExpired(string $expireDate, ?string $dateToCheck, bool $result)
{
if (!$dateToCheck) {
$this->timezone->expects($this->once())->method("date")->willReturn(new \DateTime());
diff --git a/ViewModel/Container/Cta/Lib.php b/ViewModel/Container/Cta/Lib.php
index 9cdf23d..f12601c 100644
--- a/ViewModel/Container/Cta/Lib.php
+++ b/ViewModel/Container/Cta/Lib.php
@@ -27,7 +27,7 @@ public function getMinTotalValue(): ?string
$currencyCode = $this->storeManager->getStore()->getCurrentCurrencyCode();
$cbtLimits = $this->config->getCbtCurrencyLimits();
if (isset($cbtLimits[$currencyCode])) {
- return $cbtLimits[$currencyCode]['minimumAmount']['amount'];
+ return $cbtLimits[$currencyCode]['minimumAmount']['amount'] ?? '0';
}
return $this->config->getMinOrderTotal();
diff --git a/ViewModel/Container/ExpressCheckout/ExpressCheckout.php b/ViewModel/Container/ExpressCheckout/ExpressCheckout.php
index 7ee6a15..f91dd35 100644
--- a/ViewModel/Container/ExpressCheckout/ExpressCheckout.php
+++ b/ViewModel/Container/ExpressCheckout/ExpressCheckout.php
@@ -4,7 +4,7 @@
class ExpressCheckout extends \Afterpay\Afterpay\ViewModel\Container\Container
{
- const COUNTRY_CURRENCY_MAP = [
+ public const COUNTRY_CURRENCY_MAP = [
'AUD' => 'AU',
'NZD' => 'NZ',
'USD' => 'US',
@@ -12,15 +12,6 @@ class ExpressCheckout extends \Afterpay\Afterpay\ViewModel\Container\Container
'GBP' => 'GB'
];
- public function __construct(
- \Magento\Framework\Serialize\SerializerInterface $serializer,
- \Afterpay\Afterpay\Model\Config $config,
- \Afterpay\Afterpay\Model\ResourceModel\NotAllowedProductsProvider $notAllowedProductsProvider,
- \Magento\Store\Model\StoreManagerInterface $storeManager
- ) {
- parent::__construct($serializer, $config, $notAllowedProductsProvider, $storeManager);
- }
-
public function updateJsLayout(
string $jsLayoutJson,
bool $remove = false,
diff --git a/composer.json b/composer.json
index 65eac37..493d4a3 100644
--- a/composer.json
+++ b/composer.json
@@ -3,7 +3,7 @@
"license": "Apache-2.0",
"type": "magento2-module",
"description": "Magento 2 Afterpay Payment Module",
- "version": "4.2.2",
+ "version": "4.3.0",
"require": {
"php": "~7.1.3||~7.2.0||~7.3.0||~7.4.0",
"magento/framework": "^102.0",
diff --git a/etc/config.xml b/etc/config.xml
index 7ad7f3b..646671c 100644
--- a/etc/config.xml
+++ b/etc/config.xml
@@ -23,6 +23,7 @@
AU,NZ,US,CA
+ 1
diff --git a/etc/module.xml b/etc/module.xml
index 21cdc3d..aef58de 100644
--- a/etc/module.xml
+++ b/etc/module.xml
@@ -1,7 +1,7 @@
-
+
diff --git a/view/frontend/web/js/view/payment/info/checkout-note.js b/view/frontend/web/js/view/payment/info/checkout-note.js
index 0cbf3ae..145f52c 100644
--- a/view/frontend/web/js/view/payment/info/checkout-note.js
+++ b/view/frontend/web/js/view/payment/info/checkout-note.js
@@ -18,29 +18,30 @@ define([
return Component.extend({
initWidget: function () {
- if (!this._showWidget()) {
- return;
- }
+ let widgetAmount = this._getWidgetAmount(totals.totals());
+
+ window.afterpayWidget = new Square.Marketplace.SquarePlacement();
+ afterpayWidget.mpid = window.checkoutConfig.payment.afterpay.mpid;
+ afterpayWidget.pageType = 'checkout';
+ afterpayWidget.amount = widgetAmount.amount;
+ afterpayWidget.currency = widgetAmount.currency;
+ afterpayWidget.type = 'payment-schedule';
+ afterpayWidget.platform = 'Magento';
+
+ document.getElementById('afterpay-widget-container').appendChild(afterpayWidget);
- window.afterpayWidget = new AfterPay.Widgets.PaymentSchedule({
- target: '#afterpay-widget-container',
- locale: window.checkoutConfig.payment.afterpay.locale.replace('_', '-'),
- amount: this._getWidgetAmount(totals.totals()),
- onError: (event) => console.log(event.data.error)
- })
totals.totals.subscribe((totals) => {
if (afterpayWidget) {
- afterpayWidget.update({
- amount: this._getWidgetAmount(totals),
- })
+ afterpayWidget.setAttribute('data-amount', this._getWidgetAmount(totals).amount);
}
});
+
if (checkoutData.getSelectedPaymentMethod() == 'afterpay'
&& checkoutConfig.payment.afterpay.isCBTCurrency === true) {
this._hideBaseCurrencyChargeInfo();
}
quote.paymentMethod.subscribe(function (value) {
- if (value && value.method == 'afterpay' && checkoutConfig.payment.afterpay.isCBTCurrency) {
+ if (value && value.method == 'afterpay' && checkoutConfig.payment.afterpay.isCBTCurrency === true) {
this._hideBaseCurrencyChargeInfo();
} else {
this._showBaseCurrencyChargeInfo();
@@ -66,14 +67,5 @@ define([
_showBaseCurrencyChargeInfo: function () {
$('.opc-block-summary .totals.charge').show();
},
- _showWidget: function () {
- if (checkoutConfig.payment.afterpay.consumerLendingEnabled) {
- if (totals.totals().base_grand_total >= window.checkoutConfig.payment.afterpay.consumerLendingMinimumAmount) {
- return false
- }
- }
-
- return true;
- },
});
});
diff --git a/view/frontend/web/js/view/payment/method-renderer/afterpay.js b/view/frontend/web/js/view/payment/method-renderer/afterpay.js
old mode 100644
new mode 100755
index 151fa6e..f4c9ea9
--- a/view/frontend/web/js/view/payment/method-renderer/afterpay.js
+++ b/view/frontend/web/js/view/payment/method-renderer/afterpay.js
@@ -6,7 +6,8 @@ define([
'Magento_Checkout/js/action/set-payment-information',
'Magento_Checkout/js/model/error-processor',
'Magento_Customer/js/customer-data',
- 'Magento_Customer/js/section-config'
+ 'Magento_Customer/js/section-config',
+ 'Magento_Checkout/js/model/quote'
], function (
$,
Component,
@@ -15,7 +16,8 @@ define([
setPaymentInformationAction,
errorProcessor,
customerData,
- sectionConfig
+ sectionConfig,
+ quote
) {
'use strict';
@@ -23,7 +25,17 @@ define([
defaults: {
template: 'Afterpay_Afterpay/payment/afterpay'
},
+ getCurrency: function () {
+ let currency = window.checkoutConfig.payment.afterpay.isCBTCurrency
+ ? quote.totals().quote_currency_code
+ : quote.totals().base_currency_code;
+ return currency;
+
+ },
+ getMPID: function () {
+ return window.checkoutConfig.payment.afterpay.mpid;
+ },
continueToAfterpay: function (data, event) {
const self = this;
@@ -44,9 +56,14 @@ define([
confirmPath: captureUrlPath,
cancelPath: captureUrlPath
}).done(function (response) {
+
const sections = sectionConfig.getAffectedSections(captureUrlPath);
customerData.invalidate(sections);
- $.mage.redirect(response.afterpay_redirect_checkout_url);
+
+ let checkoutRedirectUrl=self._getCheckoutUrl(response.afterpay_redirect_checkout_url);
+
+ $.mage.redirect(checkoutRedirectUrl);
+
}).always(function () {
self.isPlaceOrderActionAllowed(true);
});
@@ -57,6 +74,34 @@ define([
self.isPlaceOrderActionAllowed(true);
});
}
- }
+ },
+ _getCheckoutUrl: function (checkoutUrl) {
+
+ let deviceData=$.mage.cookies.get("apt_pixel");
+ let args="";
+ // Append params from the cookie
+ if (deviceData !== undefined && deviceData !=null && deviceData.length>0) {
+
+ let queryParams=checkoutUrl.split("?")[1];
+ const searchParams = new URLSearchParams(queryParams);
+
+ let device=JSON.parse(atob(deviceData));
+ if (device.hasOwnProperty('deviceId') &&
+ (/^[0-9a-z-]*$/i).test(device.deviceId) &&
+ searchParams.has('device_id')===false) {
+ args="&device_id="+device.deviceId;
+ }
+
+ if (device.hasOwnProperty('checkout') ) {
+ for (var prop in device.checkout){
+ let val=device.checkout[prop];
+ if ((/^[0-9a-z]+$/i).test(prop) && (/^[0-9a-z-]*$/i).test(val) && searchParams.has(prop)===false) {
+ args+="&"+prop+"="+val;
+ }
+ }
+ }
+ }
+ return checkoutUrl+args;
+ },
});
});
diff --git a/view/frontend/web/template/payment/afterpay.html b/view/frontend/web/template/payment/afterpay.html
index d762cbf..613fba4 100644
--- a/view/frontend/web/template/payment/afterpay.html
+++ b/view/frontend/web/template/payment/afterpay.html
@@ -3,9 +3,16 @@
-