diff --git a/Block/Info.php b/Block/Info.php
index 9d9be2a52..ed2e03f71 100644
--- a/Block/Info.php
+++ b/Block/Info.php
@@ -41,7 +41,7 @@ class Info extends \Magento\Payment\Block\Info
/**
* @param \Magento\Framework\View\Element\Template\Context $context
* @param array $data
- * @param \Buckaroo\Magento2\Model\ConfigProvider\Method\Creditcards $configProvider
+ * @param \Buckaroo\Magento2\Model\ConfigProvider\Method\Creditcard $configProvider
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
@@ -98,6 +98,7 @@ public function getPaymentLogo(string $method): string
"afterpay20" => "svg/riverty.svg",
"capayablein3" => "svg/in3.svg",
"capayablepostpay" => "svg/in3.svg",
+ "creditcard" => "svg/creditcards.svg",
"creditcards" => "svg/creditcards.svg",
"giftcards" => "svg/giftcards.svg",
"idealprocessing" => "svg/ideal.svg",
@@ -113,7 +114,7 @@ public function getPaymentLogo(string $method): string
];
$name = "svg/{$method}.svg";
-
+
if(isset($mappings[$method])) {
$name = $mappings[$method];
}
@@ -162,7 +163,7 @@ public function getCreditcardLogo(string $code): string
if($code === 'cartebleuevisa') {
$code = 'cartebleue';
}
-
+
return $this->assetRepo->getUrl("Buckaroo_Magento2::images/creditcards/{$code}.svg");
}
}
diff --git a/Block/Info/Creditcard.php b/Block/Info/Creditcard.php
index 8ae3f968e..6eb551d95 100644
--- a/Block/Info/Creditcard.php
+++ b/Block/Info/Creditcard.php
@@ -38,14 +38,14 @@ class Creditcard extends \Buckaroo\Magento2\Block\Info
protected $mpiStatus;
/**
- * @var \Buckaroo\Magento2\Model\ConfigProvider\Method\Creditcards
+ * @var \Buckaroo\Magento2\Model\ConfigProvider\Method\Creditcard
*/
protected $configProvider;
/**
* @var string
*/
- protected $_template = 'Buckaroo_Magento2::info/creditcards.phtml';
+ protected $_template = 'Buckaroo_Magento2::info/creditcard.phtml';
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
@@ -54,7 +54,7 @@ public function __construct(
Repository $assetRepo,
UrlInterface $baseUrl,
array $data = [],
- \Buckaroo\Magento2\Model\ConfigProvider\Method\Creditcards $configProvider = null
+ \Buckaroo\Magento2\Model\ConfigProvider\Method\Creditcard $configProvider = null
) {
parent::__construct($context, $groupTransaction, $giftcardCollection, $assetRepo, $baseUrl, $data);
$this->configProvider = $configProvider;
diff --git a/Block/Widget/Button/Toolbar.php b/Block/Widget/Button/Toolbar.php
index f2d28fbb8..93bc406d5 100644
--- a/Block/Widget/Button/Toolbar.php
+++ b/Block/Widget/Button/Toolbar.php
@@ -37,6 +37,7 @@ class Toolbar
'buckaroo_magento2_billink',
'buckaroo_magento2_payperemail',
'buckaroo_magento2_paylink',
+ 'buckaroo_magento2_creditcard',
'buckaroo_magento2_creditcards',
'buckaroo_magento2_ideal',
'buckaroo_magento2_idealprocessing',
diff --git a/Controller/CredentialsChecker/GetToken.php b/Controller/CredentialsChecker/GetToken.php
deleted file mode 100644
index b9b13c2c7..000000000
--- a/Controller/CredentialsChecker/GetToken.php
+++ /dev/null
@@ -1,164 +0,0 @@
-resultJsonFactory = $resultJsonFactory;
- $this->logger = $logger;
- $this->configProviderCreditcard = $configProviderCreditcard;
- $this->encryptor = $encryptor;
- $this->store = $storeManager->getStore();
- $this->curlClient = $curlClient;
- parent::__construct($context);
- }
-
- /**
- * Send POST request using Magento's Curl client.
- */
- private function sendPostRequest($url, $username, $password, $postData) {
- try {
- // Set Basic Auth credentials without base64_encode()
- $this->curlClient->setCredentials($username, $password);
-
- // Set the headers and post fields
- $this->curlClient->addHeader("Content-Type", "application/x-www-form-urlencoded");
-
- // Send the POST request
- $this->curlClient->post($url, http_build_query($postData));
-
- // Get the response body
- return $this->curlClient->getBody();
- } catch (\Exception $e) {
- $this->logger->error('Curl request error: ' . $e->getMessage());
- throw new \Exception('Error occurred during cURL request: ' . $e->getMessage());
- }
- }
-
- protected function getHostedFieldsClientId()
- {
- try {
- return $this->encryptor->decrypt(
- $this->configProviderCreditcard->getHostedFieldsClientId($this->store)
- );
- } catch (\Exception $e) {
- $this->logger->error('Error decrypting Hosted Fields fields: ' . $e->getMessage());
- return null;
- }
- }
-
- protected function getHostedFieldsClientSecret()
- {
- try {
- return $this->encryptor->decrypt(
- $this->configProviderCreditcard->getHostedFieldsClientSecret($this->store)
- );
- } catch (\Exception $e) {
- $this->logger->error('Error decrypting Hosted Fields fields: ' . $e->getMessage());
- return null;
- }
- }
-
- protected function getAllowedIssuers()
- {
- try {
- return $this->configProviderCreditcard->getSupportedServices();
- } catch (\Exception $e) {
- $this->logger->error('Error getting Allowed Issuers: ' . $e->getMessage());
- return null;
- }
- }
-
- public function execute()
- {
- $result = $this->resultJsonFactory->create();
-
- // Validate the request origin
- $requestOrigin = $this->getRequest()->getHeader('X-Requested-From');
- if ($requestOrigin !== 'MagentoFrontend') {
- return $result->setHttpResponseCode(403)->setData([
- 'error' => true,
- 'message' => 'Unauthorized request'
- ]);
- }
-
- // Get username and password
- $hostedFieldsClientId = $this->getHostedFieldsClientId();
- $hostedFieldsClientSecret = $this->getHostedFieldsClientSecret();
- $issuers = $this->getAllowedIssuers();
-
- if (empty($hostedFieldsClientId) || empty($hostedFieldsClientSecret)) {
- return $result->setHttpResponseCode(400)->setData([
- 'error' => true,
- 'message' => 'Hosted Fields Username or Password is empty.'
- ]);
- }
- if (empty($issuers)) {
- return $result->setHttpResponseCode(400)->setData([
- 'error' => true,
- 'message' => 'There is no Allowed Issuers for Hosted Fields.'
- ]);
- }
-
- // Try to fetch the token
- try {
- $url = "https://auth.buckaroo.io/oauth/token";
- $postData = [
- 'scope' => 'hostedfields:save',
- 'grant_type' => 'client_credentials'
- ];
-
- $response = $this->sendPostRequest($url, $hostedFieldsClientId, $hostedFieldsClientSecret, $postData);
- $responseArray = json_decode($response, true);
-
- // Check for successful response
- if (isset($responseArray['access_token'])) {
- return $result->setData([
- 'error' => false,
- 'data' => [
- 'access_token' => $responseArray['access_token'],
- 'issuers' => $issuers
- ]
- ]);
- }
-
- // Handle error response
- $message = isset($responseArray['message']) ? $responseArray['message'] : 'Unknown error occurred';
- return $result->setHttpResponseCode(400)->setData([
- 'error' => true,
- 'message' => 'Error fetching token.'
- ]);
-
- } catch (\Exception $e) {
- $this->logger->error('Error occurred while fetching token.');
- return $result->setHttpResponseCode(500)->setData([
- 'error' => true,
- 'message' => 'An error occurred while fetching the token.'
- ]);
- }
- }
-}
diff --git a/Helper/Data.php b/Helper/Data.php
index 55131d6d8..b5410a56d 100644
--- a/Helper/Data.php
+++ b/Helper/Data.php
@@ -300,6 +300,17 @@ public function getStore()
}
}
+ public function getConfigCardSort()
+ {
+ $configValue = $this->scopeConfig->getValue(
+ 'payment/buckaroo_magento2_creditcard/sorted_issuers',
+ $this->scopeDefiner->getScope(),
+ ($this->scopeDefiner->getScope() == ScopeInterface::SCOPE_WEBSITES) ? $this->storeManager->getStore() : null
+ );
+
+ return $configValue;
+ }
+
public function getConfigGiftCardsSort()
{
$configValue = $this->scopeConfig->getValue(
@@ -422,7 +433,8 @@ public function getPaymentMethodsList()
['value' => 'applepay', 'label' => __('Apple Pay')],
['value' => 'billink', 'label' => __('Billink')],
['value' => 'capayablein3', 'label' => __('In3')],
- ['value' => 'creditcards', 'label' => __('Credit and debit cards')],
+ ['value' => 'creditcard', 'label' => __('Credit and debit cards')],
+ ['value' => 'creditcards', 'label' => __('Credit and debit cards (Client sided)')],
['value' => 'emandate', 'label' => __('Digital Debit Authorization')],
['value' => 'eps', 'label' => __('EPS')],
['value' => 'giftcards', 'label' => __('Giftcards')],
diff --git a/Model/Config/Source/Creditcard.php b/Model/Config/Source/Creditcard.php
index c7e877f2d..04a77c6c2 100644
--- a/Model/Config/Source/Creditcard.php
+++ b/Model/Config/Source/Creditcard.php
@@ -22,17 +22,17 @@
class Creditcard implements \Magento\Framework\Option\ArrayInterface
{
/**
- * @var \Buckaroo\Magento2\Model\ConfigProvider\Method\Creditcards
+ * @var \Buckaroo\Magento2\Model\ConfigProvider\Method\Creditcard
*/
protected $configProvider;
/**
* Use the constructor to get the requested config provider.
*
- * @param \Buckaroo\Magento2\Model\ConfigProvider\Method\Creditcards $configProvider
+ * @param \Buckaroo\Magento2\Model\ConfigProvider\Method\Creditcard $configProvider
*/
public function __construct(
- \Buckaroo\Magento2\Model\ConfigProvider\Method\Creditcards $configProvider
+ \Buckaroo\Magento2\Model\ConfigProvider\Method\Creditcard $configProvider
) {
$this->configProvider = $configProvider;
}
diff --git a/Model/ConfigProvider/Account.php b/Model/ConfigProvider/Account.php
index bd3bdde8a..9ad470a2d 100644
--- a/Model/ConfigProvider/Account.php
+++ b/Model/ConfigProvider/Account.php
@@ -252,7 +252,7 @@ public function getParsedLabel(Store $store, OrderInterface $order)
if ($label === null) {
return $store->getName();
}
-
+
$label = preg_replace('/\{order_number\}/', $order->getIncrementId(), $label);
$label = preg_replace('/\{shop_name\}/', $store->getName(), $label);
diff --git a/Model/ConfigProvider/Method/Creditcard.php b/Model/ConfigProvider/Method/Creditcard.php
new file mode 100644
index 000000000..57f40535c
--- /dev/null
+++ b/Model/ConfigProvider/Method/Creditcard.php
@@ -0,0 +1,342 @@
+ 'American Express',
+ 'code' => self::CREDITCARD_SERVICE_CODE_AMEX,
+ 'sort' => 0
+ ],
+ [
+ 'name' => 'Carte Bancaire',
+ 'code' => self::CREDITCARD_SERVICE_CODE_CARTEBANCAIRE,
+ 'sort' => 0
+ ],
+ [
+ 'name' => 'Carte Bleue',
+ 'code' => self::CREDITCARD_SERVICE_CODE_CARTEBLEUE,
+ 'sort' => 0
+ ],
+ [
+ 'name' => 'Dankort',
+ 'code' => self::CREDITCARD_SERVICE_CODE_DANKORT,
+ 'sort' => 0
+ ],
+ [
+ 'name' => 'Maestro',
+ 'code' => self::CREDITCARD_SERVICE_CODE_MAESTRO,
+ 'sort' => 0
+ ],
+ [
+ 'name' => 'MasterCard',
+ 'code' => self::CREDITCARD_SERVICE_CODE_MASTERCARD,
+ 'sort' => 0
+ ],
+ [
+ 'name' => 'Nexi',
+ 'code' => self::CREDITCARD_SERVICE_CODE_NEXI,
+ 'sort' => 0
+ ],
+ [
+ 'name' => 'PostePay',
+ 'code' => self::CREDITCARD_SERVICE_CODE_POSTEPAY,
+ 'sort' => 0
+ ],
+ [
+ 'name' => 'VISA',
+ 'code' => self::CREDITCARD_SERVICE_CODE_VISA,
+ 'sort' => 0
+ ],
+ [
+ 'name' => 'VISA Electron',
+ 'code' => self::CREDITCARD_SERVICE_CODE_VISAELECTRON,
+ 'sort' => 0
+ ],
+ [
+ 'name' => 'VPay',
+ 'code' => self::CREDITCARD_SERVICE_CODE_VPAY,
+ 'sort' => 0
+ ],
+ ];
+
+ /**
+ * Add the active flag to the creditcard list. This is used in the checkout process.
+ *
+ * @return array
+ */
+ public function formatIssuers()
+ {
+ $sorted = $this->getSortedIssuers();
+ $sorted = $sorted ? explode(',',$sorted) : [];
+
+ if (!empty($sorted)) {
+ $sortedPosition = 1;
+ foreach ($sorted as $cardCode) {
+ $sorted_array[$cardCode] = $sortedPosition++;
+ }
+ }
+
+ foreach ($this->getIssuers() as $item) {
+ $item['sort'] = isset($sorted_array[$item['code']]) ?
+ $sorted_array[$item['code']] : self::DEFAULT_SORT_VALUE;
+ $item['img'] = $this->getImageUrl($item['code']);
+ $allCreditcard[$item['code']] = $item;
+ }
+
+ $allowed = explode(',', (string)$this->scopeConfig->getValue(
+ self::XPATH_CREDITCARD_ALLOWED_CREDITCARDS,
+ \Magento\Store\Model\ScopeInterface::SCOPE_STORE
+ ));
+
+ $cards = [];
+ foreach ($allowed as $key => $value) {
+ if (isset($allCreditcard[$value])) {
+ $cards[] = $allCreditcard[$value];
+ }
+ }
+
+ usort($cards, function ($cardA, $cardB) {
+ return $cardA['sort'] - $cardB['sort'];
+ });
+
+ return $cards;
+ }
+
+ /**
+ * @return array|void
+ */
+ public function getConfig()
+ {
+ $issuers = $this->formatIssuers();
+ $paymentFeeLabel = $this->getBuckarooPaymentFeeLabel(
+ \Buckaroo\Magento2\Model\Method\Creditcard::PAYMENT_METHOD_CODE
+ );
+
+ $selectionType = $this->scopeConfig->getValue(
+ self::XPATH_SELECTION_TYPE,
+ \Magento\Store\Model\ScopeInterface::SCOPE_STORE
+ );
+
+ $paymentFlow = $this->scopeConfig->getValue(
+ self::XPATH_PAYMENT_FLOW,
+ \Magento\Store\Model\ScopeInterface::SCOPE_STORE
+ );
+
+ return [
+ 'payment' => [
+ 'buckaroo' => [
+ 'creditcard' => [
+ 'cards' => $issuers,
+ 'groupCreditcards' => $this->isGroupCreditcards(),
+ 'paymentFeeLabel' => $paymentFeeLabel,
+ 'subtext' => $this->getSubtext(),
+ 'subtext_style' => $this->getSubtextStyle(),
+ 'subtext_color' => $this->getSubtextColor(),
+ 'allowedCurrencies' => $this->getAllowedCurrencies(),
+ 'selectionType' => $selectionType,
+ 'paymentFlow' => $paymentFlow,
+ ],
+ ],
+ ],
+ ];
+ }
+
+ /**
+ * @param null|int $storeId
+ *
+ * @return float
+ */
+ public function getPaymentFee($storeId = null)
+ {
+ $paymentFee = $this->scopeConfig->getValue(
+ self::XPATH_CREDITCARD_PAYMENT_FEE,
+ \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
+ $storeId
+ );
+
+ return $paymentFee ? $paymentFee : false;
+ }
+
+ /**
+ * @param string $cardType
+ *
+ * @return string
+ *
+ * @throws \InvalidArgumentException
+ */
+ public function getCardName($cardType)
+ {
+ $config = $this->getConfig();
+
+ foreach ($config['payment']['buckaroo']['creditcard']['cards'] as $card) {
+ if ($card['code'] == $cardType) {
+ return $card['name'];
+ }
+ }
+
+ throw new \InvalidArgumentException("No card found for card type: {$cardType}");
+ }
+
+ /**
+ * @param string $cardType
+ *
+ * @return string
+ *
+ * @throws \InvalidArgumentException
+ */
+ public function getCardCode($cardType)
+ {
+ $config = $this->getConfig();
+ foreach ($config['payment']['buckaroo']['creditcard']['cards'] as $card) {
+ if ($card['name'] == $cardType) {
+ return $card['code'];
+ }
+ }
+
+ throw new \InvalidArgumentException("No card found for card type: {$cardType}");
+ }
+
+ public function getConfigCardSort()
+ {
+ $configValue = $this->scopeConfig->getValue(
+ 'payment/buckaroo_magento2_creditcard/sorted_issuers',
+ $this->scopeDefiner->getScope(),
+ ($this->scopeDefiner->getScope() == ScopeInterface::SCOPE_WEBSITES) ? $this->storeManager->getStore() : null
+ );
+
+ return $configValue;
+ }
+
+ /**
+ * @param $storeId
+ * @return ?string
+ */
+ public function getSortedIssuers($storeId = null): ?string
+ {
+ return $this->scopeConfig->getValue(
+ self::XPATH_SORTED_ISSUERS,
+ \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
+ $storeId
+ );
+ }
+
+ /**
+ * Generate the url to the desired asset.
+ *
+ * @param string $imgName
+ * @param string $extension
+ *
+ * @return string
+ */
+ public function getImageUrl($imgName, string $extension = 'png')
+ {
+ if($imgName === 'cartebleuevisa') {
+ $imgName = 'cartebleue';
+ }
+
+ return parent::getImageUrl("creditcards/{$imgName}", "svg");
+ }
+
+ /**
+ * Get all issuers not sorted
+ *
+ * @return array
+ */
+ public function getAllIssuers(): array
+ {
+ $issuers = $this->getIssuers();
+ $issuersPrepared = [];
+ foreach ($issuers as $issuer) {
+ $issuer['img'] = $this->getImageUrl($issuer['code']);
+ $issuersPrepared[$issuer['code']] = $issuer;
+ }
+
+ return $issuersPrepared;
+ }
+
+ /**
+ * Credit cards are displayed separately in the checkout.
+ *
+ * @param $storeId
+ * @return string
+ */
+ public function isGroupCreditcards($storeId = null): string
+ {
+ return (bool)$this->scopeConfig->getValue(
+ self::XPATH_CREDITCARD_GROUP_CREDITCARD,
+ \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
+ $storeId
+ );
+ }
+}
diff --git a/Model/ConfigProvider/Method/Creditcards.php b/Model/ConfigProvider/Method/Creditcards.php
index d5619f73a..638598061 100644
--- a/Model/ConfigProvider/Method/Creditcards.php
+++ b/Model/ConfigProvider/Method/Creditcards.php
@@ -36,21 +36,6 @@
*/
class Creditcards extends AbstractConfigProvider
{
- /**#@+
- * Creditcard service codes.
- */
- const CREDITCARD_SERVICE_CODE_MASTERCARD = 'MasterCard';
- const CREDITCARD_SERVICE_CODE_VISA = 'Visa';
- const CREDITCARD_SERVICE_CODE_AMEX = 'Amex';
- const CREDITCARD_SERVICE_CODE_MAESTRO = 'Maestro';
- const CREDITCARD_SERVICE_CODE_VPAY = 'vpay';
- const CREDITCARD_SERVICE_CODE_VISAELECTRON = 'visaelectron';
- const CREDITCARD_SERVICE_CODE_CARTEBLEUE = 'cartebleuevisa';
- const CREDITCARD_SERVICE_CODE_CARTEBANCAIRE = 'cartebancaire';
- const CREDITCARD_SERVICE_CODE_DANKORT = 'dankort';
- const CREDITCARD_SERVICE_CODE_NEXI = 'nexi';
- const CREDITCARD_SERVICE_CODE_POSTEPAY = 'postepay';
-
const XPATH_CREDITCARDS_PAYMENT_FEE = 'payment/buckaroo_magento2_creditcards/payment_fee';
const XPATH_CREDITCARDS_PAYMENT_FEE_LABEL = 'payment/buckaroo_magento2_creditcards/payment_fee_label';
const XPATH_CREDITCARDS_ACTIVE = 'payment/buckaroo_magento2_creditcards/active';
@@ -71,35 +56,31 @@ class Creditcards extends AbstractConfigProvider
const XPATH_CREDITCARDS_SELLERS_PROTECTION_UNAUTHORIZEDPAYMENT_ELIGIBLE = 'payment/'.
'buckaroo_magento2_creditcards/sellers_protection_unauthorizedpayment_eligible';
const XPATH_CREDITCARDS_ALLOWED_ISSUERS = 'payment/buckaroo_magento2_creditcards/allowed_issuers';
- const XPATH_CREDITCARDS_HOSTED_FIELDS_CLIENT_ID = 'payment/buckaroo_magento2_creditcards/hosted_fields_client_id';
- const XPATH_CREDITCARDS_HOSTED_FIELDS_CLIENT_SECRET = 'payment/buckaroo_magento2_creditcards/hosted_fields_client_secret';
const XPATH_ALLOWED_CURRENCIES = 'payment/buckaroo_magento2_creditcards/allowed_currencies';
const XPATH_ALLOW_SPECIFIC = 'payment/buckaroo_magento2_creditcards/allowspecific';
const XPATH_SPECIFIC_COUNTRY = 'payment/buckaroo_magento2_creditcards/specificcountry';
const XPATH_SPECIFIC_CUSTOMER_GROUP = 'payment/buckaroo_magento2_creditcards/specificcustomergroup';
- protected $issuers = [
- [
- 'name' => 'American Express',
- 'code' => self::CREDITCARD_SERVICE_CODE_AMEX,
- 'sort' => 0
- ],
- [
- 'name' => 'Maestro',
- 'code' => self::CREDITCARD_SERVICE_CODE_MAESTRO,
- 'sort' => 0
- ],
- [
- 'name' => 'MasterCard',
- 'code' => self::CREDITCARD_SERVICE_CODE_MASTERCARD,
- 'sort' => 0
- ],
- [
- 'name' => 'VISA',
- 'code' => self::CREDITCARD_SERVICE_CODE_VISA,
- 'sort' => 0
- ]
- ];
+ /**
+ * Creditcards constructor.
+ *
+ * @param Repository $assetRepo
+ * @param ScopeConfigInterface $scopeConfig
+ * @param AllowedCurrencies $allowedCurrencies
+ * @param PaymentFee $paymentFeeHelper
+ * @param Creditcard $creditcardConfigProvider
+ */
+ public function __construct(
+ Repository $assetRepo,
+ ScopeConfigInterface $scopeConfig,
+ AllowedCurrencies $allowedCurrencies,
+ PaymentFee $paymentFeeHelper,
+ Creditcard $creditcardConfigProvider
+ ) {
+ parent::__construct($assetRepo, $scopeConfig, $allowedCurrencies, $paymentFeeHelper);
+
+ $this->issuers = $creditcardConfigProvider->getIssuers();
+ }
/**
* @return array
@@ -145,22 +126,6 @@ public function getPaymentFee($storeId = null)
return $paymentFee ? $paymentFee : false;
}
- public function getHostedFieldsClientId()
- {
- return $this->scopeConfig->getValue(
- self::XPATH_CREDITCARDS_HOSTED_FIELDS_CLIENT_ID,
- ScopeInterface::SCOPE_STORE
- );
- }
-
- public function getHostedFieldsClientSecret()
- {
- return $this->scopeConfig->getValue(
- self::XPATH_CREDITCARDS_HOSTED_FIELDS_CLIENT_SECRET,
- ScopeInterface::SCOPE_STORE
- );
- }
-
/**
* Add the active flag to the creditcard list. This is used in the checkout process.
*
@@ -182,18 +147,4 @@ public function formatIssuers()
return $issuers;
}
-
- public function getSupportedServices(): array
- {
- $issuers = $this->formatIssuers();
- $supportedServices = [];
-
- foreach ($issuers as $issuer) {
- if ($issuer['active']) {
- $supportedServices[] = $issuer['code'];
- }
- }
-
- return $supportedServices;
- }
}
diff --git a/Model/Method/Creditcard.php b/Model/Method/Creditcard.php
new file mode 100644
index 000000000..a55665730
--- /dev/null
+++ b/Model/Method/Creditcard.php
@@ -0,0 +1,207 @@
+assignDataConvertToArray($data);
+
+ if (isset($data['additional_data']['card_type'])) {
+ $this->getInfoInstance()->setAdditionalInformation(
+ 'card_type',
+ $data['additional_data']['card_type']
+ );
+ }
+
+ return $this;
+ }
+
+ /**
+ * Check capture availability
+ *
+ * @return bool
+ * @api
+ */
+ public function canCapture()
+ {
+ if ($this->getConfigData('payment_action') == 'order') {
+ return false;
+ }
+ return $this->_canCapture;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function isAvailable(\Magento\Quote\Api\Data\CartInterface $quote = null)
+ {
+ /**
+ * If there are no credit cards chosen, we can't be available
+ */
+ /**
+ * @var \Buckaroo\Magento2\Model\ConfigProvider\Method\Creditcard $ccConfig
+ */
+ $ccConfig = $this->configProviderMethodFactory->get('creditcard');
+ if (null === $ccConfig->getAllowedCreditcards()) {
+ return false;
+ }
+ /**
+ * Return the regular isAvailable result
+ */
+ return parent::isAvailable($quote);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getOrderTransactionBuilder($payment)
+ {
+ $transactionBuilder = $this->transactionBuilderFactory->get('order');
+
+ $services = [
+ 'Name' => $payment->getAdditionalInformation('card_type'),
+ 'Action' => $this->getPayRemainder($payment, $transactionBuilder),
+ 'Version' => 1,
+ ];
+
+ /**
+ * @noinspection PhpUndefinedMethodInspection
+ */
+ $transactionBuilder->setOrder($payment->getOrder())
+ ->setServices($services)
+ ->setMethod('TransactionRequest');
+
+ return $transactionBuilder;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getCaptureTransactionBuilder($payment)
+ {
+ $transactionBuilder = $this->transactionBuilderFactory->get('order');
+
+ $services = [
+ 'Name' => $payment->getAdditionalInformation('card_type'),
+ 'Action' => 'Capture',
+ 'Version' => 1,
+ ];
+
+ /**
+ * @noinspection PhpUndefinedMethodInspection
+ */
+ $transactionBuilder->setOrder($payment->getOrder())
+ ->setServices($services)
+ ->setMethod('TransactionRequest')
+ ->setChannel('CallCenter')
+ ->setOriginalTransactionKey(
+ $payment->getAdditionalInformation(
+ self::BUCKAROO_ORIGINAL_TRANSACTION_KEY_KEY
+ )
+ );
+
+ return $transactionBuilder;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getAuthorizeTransactionBuilder($payment)
+ {
+ $transactionBuilder = $this->transactionBuilderFactory->get('order');
+
+ $services = [
+ 'Name' => $payment->getAdditionalInformation('card_type'),
+ 'Action' => 'Authorize',
+ 'Version' => 1,
+ ];
+
+ /**
+ * @noinspection PhpUndefinedMethodInspection
+ */
+ $transactionBuilder->setOrder($payment->getOrder())
+ ->setServices($services)
+ ->setMethod('TransactionRequest');
+
+ return $transactionBuilder;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getVoidTransactionBuilder($payment)
+ {
+ return true;
+ }
+
+ /**
+ * @param \Magento\Sales\Api\Data\OrderPaymentInterface|\Magento\Payment\Model\InfoInterface $payment
+ *
+ * @return bool|string
+ */
+ public function getPaymentMethodName($payment)
+ {
+ return $payment->getAdditionalInformation('card_type');
+ }
+}
diff --git a/Model/Method/Creditcards.php b/Model/Method/Creditcards.php
index 329155a9d..a6e8f3816 100644
--- a/Model/Method/Creditcards.php
+++ b/Model/Method/Creditcards.php
@@ -116,28 +116,6 @@ public function __construct(
$this->serviceParameters = $serviceParameters;
}
- /**
- * {@inheritdoc}
- */
- public function isAvailable(\Magento\Quote\Api\Data\CartInterface $quote = null)
- {
- /**
- * If there are no giftcards chosen, we can't be available
- */
- /**
- * @var \Buckaroo\Magento2\Model\ConfigProvider\Method\Giftcards $ccConfig
- */
- $gcConfig = $this->configProviderMethodFactory->get('creditcards');
-
- if ($gcConfig->getHostedFieldsClientId() === null || $gcConfig->getHostedFieldsClientSecret() === null) {
- return false;
- }
- /**
- * Return the regular isAvailable result
- */
- return parent::isAvailable($quote);
- }
-
public function assignData(\Magento\Framework\DataObject $data)
{
parent::assignData($data);
@@ -168,7 +146,7 @@ public function getOrderTransactionBuilder($payment)
{
$transactionBuilder = $this->transactionBuilderFactory->get('order');
- $serviceAction = $this->getPayRemainder($payment, $transactionBuilder, 'PayWithToken', 'PayRemainderEncrypted');
+ $serviceAction = $this->getPayRemainder($payment, $transactionBuilder, 'PayEncrypted', 'PayRemainderEncrypted');
$services = [];
$services[] = $this->getCreditcardsService($payment, $serviceAction);
@@ -214,11 +192,11 @@ public function getCreditcardsService($payment, $serviceAction)
$services = [
'Name' => $additionalInformation['customer_creditcardcompany'],
'Action' => $serviceAction,
- 'Version' => 0,
+ 'Version' => 2,
'RequestParameter' => [
[
'_' => $additionalInformation['customer_encrypteddata'],
- 'Name' => 'SessionId',
+ 'Name' => 'EncryptedCardData',
],
],
];
diff --git a/Model/Push.php b/Model/Push.php
index cbb0d396a..d8c374298 100644
--- a/Model/Push.php
+++ b/Model/Push.php
@@ -33,7 +33,7 @@
use Buckaroo\Magento2\Model\Method\Afterpay;
use Buckaroo\Magento2\Model\Method\Afterpay2;
use Buckaroo\Magento2\Model\Method\Afterpay20;
-use Buckaroo\Magento2\Model\Method\Creditcards;
+use Buckaroo\Magento2\Model\Method\Creditcard;
use Buckaroo\Magento2\Model\Method\Klarnakp;
use Buckaroo\Magento2\Model\Method\Giftcards;
use Buckaroo\Magento2\Model\Method\Paypal;
@@ -2131,7 +2131,7 @@ private function processSucceededPushAuth($payment)
Afterpay::PAYMENT_METHOD_CODE,
Afterpay2::PAYMENT_METHOD_CODE,
Afterpay20::PAYMENT_METHOD_CODE,
- Creditcards::PAYMENT_METHOD_CODE,
+ Creditcard::PAYMENT_METHOD_CODE,
Klarnakp::PAYMENT_METHOD_CODE
];
diff --git a/Model/Service/Plugin/Mpi/Push.php b/Model/Service/Plugin/Mpi/Push.php
new file mode 100644
index 000000000..4f361eaca
--- /dev/null
+++ b/Model/Service/Plugin/Mpi/Push.php
@@ -0,0 +1,109 @@
+configProviderCreditcard = $configProviderCreditcard;
+ }
+
+ /**
+ * @param \Buckaroo\Magento2\Model\Push $push
+ * @param boolean $result
+ *
+ * @return boolean
+ */
+ public function afterProcessSucceededPush(
+ \Buckaroo\Magento2\Model\Push $push,
+ $result
+ ) {
+ $payment = $push->order->getPayment();
+ $method = $payment->getMethod();
+
+ if (strpos($method, 'buckaroo_magento2') === false) {
+ return $this;
+ }
+
+ /**
+ * @var \Buckaroo\Magento2\Model\Method\AbstractMethod $paymentMethodInstance
+ */
+ $paymentMethodInstance = $payment->getMethodInstance();
+ $card = $paymentMethodInstance->getInfoInstance()->getAdditionalInformation('card_type');
+
+ if (empty($push->postData["brq_service_{$card}_authentication"])
+ || empty($push->postData["brq_service_{$card}_enrolled"])
+ ) {
+ return $result;
+ }
+
+ $authentication = $push->postData["brq_service_{$card}_authentication"];
+
+ if ($authentication == 'U' || $authentication == 'N') {
+ switch ($card) {
+ case 'maestro':
+ $putOrderOnHold = (bool) $this->configProviderCreditcard->getMaestroUnsecureHold();
+ break;
+ case 'visa':
+ $putOrderOnHold = (bool) $this->configProviderCreditcard->getVisaUnsecureHold();
+ break;
+ case 'mastercard':
+ $putOrderOnHold = (bool) $this->configProviderCreditcard->getMastercardUnsecureHold();
+ break;
+ default:
+ $putOrderOnHold = false;
+ break;
+ }
+
+ if ($putOrderOnHold) {
+ $push->order
+ ->hold()
+ ->addStatusHistoryComment(
+ __('Order has been put on hold, because it is unsecure.')
+ );
+
+ $push->order->save();
+ }
+ }
+
+ $paymentMethodInstance->getInfoInstance()->setAdditionalInformation(
+ 'buckaroo_mpi_status',
+ [
+ 'enrolled' => $push->postData["brq_service_{$card}_enrolled"],
+ 'authentication' => $push->postData["brq_service_{$card}_authentication"],
+ ]
+ );
+
+ return $result;
+ }
+}
diff --git a/Test/Unit/Model/Config/Source/CreditcardTest.php b/Test/Unit/Model/Config/Source/CreditcardTest.php
new file mode 100644
index 000000000..abc086f82
--- /dev/null
+++ b/Test/Unit/Model/Config/Source/CreditcardTest.php
@@ -0,0 +1,69 @@
+ 'Test 1',
+ 'code' => 'code1',
+ ],
+ [
+ 'name' => 'Test 2',
+ 'code' => 'code2',
+ ],
+ [
+ 'name' => 'Test 3',
+ 'code' => 'code3',
+ ],
+ ];
+
+ $configProviderMock = $this->getFakeMock(CreditcardProvider::class)->setMethods(['getIssuers'])->getMock();
+ $configProviderMock->expects($this->once())->method('getIssuers')->willReturn($issuers);
+
+ $instance = $this->getInstance(['configProvider' => $configProviderMock]);
+ $result = $instance->toOptionArray();
+
+ $expected = [
+ [
+ 'value' => 'code1',
+ 'label' => 'Test 1',
+ ],
+ [
+ 'value' => 'code2',
+ 'label' => 'Test 2',
+ ],
+ [
+ 'value' => 'code3',
+ 'label' => 'Test 3',
+ ],
+ ];
+
+ $this->assertEquals($expected, $result);
+ }
+}
diff --git a/Test/Unit/Model/ConfigProvider/Method/CreditcardTest.php b/Test/Unit/Model/ConfigProvider/Method/CreditcardTest.php
new file mode 100644
index 000000000..0b38f52bf
--- /dev/null
+++ b/Test/Unit/Model/ConfigProvider/Method/CreditcardTest.php
@@ -0,0 +1,76 @@
+markTestIncomplete(
+ 'This test needs to be reviewed.'
+ );
+ $issuers = 'amex,visa';
+ $allowedCurrencies = 'USD,EUR';
+
+ $scopeConfigMock = $this->getFakeMock(ScopeConfigInterface::class)
+ ->setMethods(['getValue'])
+ ->getMockForAbstractClass();
+ $scopeConfigMock->method('getValue')
+ ->withConsecutive(
+ [Creditcard::XPATH_CREDITCARD_ALLOWED_CREDITCARDS, ScopeInterface::SCOPE_STORE],
+ [Creditcard::XPATH_ALLOWED_CURRENCIES, ScopeInterface::SCOPE_STORE, null]
+ )->willReturnOnConsecutiveCalls($issuers, $allowedCurrencies);
+
+ $instance = $this->getInstance(['scopeConfig' => $scopeConfigMock]);
+ $result = $instance->getConfig();
+
+ $this->assertInternalType('array', $result);
+ $this->assertArrayHasKey('payment', $result);
+ $this->assertArrayHasKey('buckaroo', $result['payment']);
+ $this->assertArrayHasKey('creditcard', $result['payment']['buckaroo']);
+ $this->assertArrayHasKey('cards', $result['payment']['buckaroo']['creditcard']);
+ $this->assertInternalType('array', $result['payment']['buckaroo']['creditcard']['cards']);
+ }
+
+ /**
+ * Test if the getActive magic method returns the correct value.
+ */
+ public function testGetActive()
+ {
+ $scopeConfigMock = $this->getFakeMock(ScopeConfigInterface::class)
+ ->setMethods(['getValue'])
+ ->getMockForAbstractClass();
+ $scopeConfigMock->method('getValue')
+ ->with(Creditcard::XPATH_CREDITCARD_ACTIVE, ScopeInterface::SCOPE_STORE, null)
+ ->willReturn('1');
+
+ $instance = $this->getInstance(['scopeConfig' => $scopeConfigMock]);
+ $result = $instance->getActive();
+
+ $this->assertEquals(1, $result);
+ }
+}
diff --git a/Test/Unit/Model/ConfigProvider/Method/CreditcardsTest.php b/Test/Unit/Model/ConfigProvider/Method/CreditcardsTest.php
index 239132f35..6bf5a761e 100644
--- a/Test/Unit/Model/ConfigProvider/Method/CreditcardsTest.php
+++ b/Test/Unit/Model/ConfigProvider/Method/CreditcardsTest.php
@@ -22,9 +22,10 @@
use Magento\Store\Model\ScopeInterface;
use Buckaroo\Magento2\Helper\PaymentFee;
-use Buckaroo\Magento2\Model\ConfigProvider\Method\Creditcards;
+use Buckaroo\Magento2\Model\ConfigProvider\Method\Creditcard;
use Buckaroo\Magento2\Model\Method\Creditcards as CreditcardsMethod;
use Buckaroo\Magento2\Test\BaseTest;
+use Buckaroo\Magento2\Model\ConfigProvider\Method\Creditcards;
use \Magento\Framework\App\Config\ScopeConfigInterface;
class CreditcardsTest extends BaseTest
@@ -72,7 +73,7 @@ public function testGetConfig($expected)
$paymentFeeMock = $this->getFakeMock(PaymentFee::class)->setMethods(['getBuckarooPaymentFeeLabel'])->getMock();
$paymentFeeMock->method('getBuckarooPaymentFeeLabel')->with(CreditcardsMethod::PAYMENT_METHOD_CODE)->willReturn('Fee');
- $creditcardMock = $this->getFakeMock(Creditcards::class)->setMethods(['getIssuers'])->getMock();
+ $creditcardMock = $this->getFakeMock(Creditcard::class)->setMethods(['getIssuers'])->getMock();
$creditcardMock->expects($this->once())->method('getIssuers')->willReturn([]);
$instance = $this->getInstance([
diff --git a/Test/Unit/Model/Method/CreditcardTest.php b/Test/Unit/Model/Method/CreditcardTest.php
index 149374e24..f0e448e5c 100644
--- a/Test/Unit/Model/Method/CreditcardTest.php
+++ b/Test/Unit/Model/Method/CreditcardTest.php
@@ -26,11 +26,11 @@
use Magento\Sales\Model\Order\Payment;
use Buckaroo\Magento2\Gateway\Http\TransactionBuilder\Order;
use Buckaroo\Magento2\Gateway\Http\TransactionBuilderFactory;
-use Buckaroo\Magento2\Model\Method\Creditcards;
+use Buckaroo\Magento2\Model\Method\Creditcard;
class CreditcardTest extends \Buckaroo\Magento2\Test\BaseTest
{
- protected $instanceClass = Creditcards::class;
+ protected $instanceClass = Creditcard::class;
/**
* Test the assignData method.
@@ -57,7 +57,7 @@ public function testAssignData()
$instance->setData('info_instance', $infoInstanceMock);
$result = $instance->assignData($data);
- $this->assertInstanceOf(Creditcards::class, $result);
+ $this->assertInstanceOf(Creditcard::class, $result);
}
/**
@@ -150,7 +150,7 @@ public function testGetCaptureTransactionBuilder()
$paymentMock->expects($this->once())->method('getOrder')->willReturn($fixture['order']);
$paymentMock->expects($this->exactly(2))
->method('getAdditionalInformation')
- ->withConsecutive(['card_type'], [Creditcards::BUCKAROO_ORIGINAL_TRANSACTION_KEY_KEY])
+ ->withConsecutive(['card_type'], [Creditcard::BUCKAROO_ORIGINAL_TRANSACTION_KEY_KEY])
->willReturnOnConsecutiveCalls($fixture['card_type'], $fixture['transaction_key']);
$orderMock = $this->getFakeMock(Order::class)
@@ -242,7 +242,7 @@ public function testGetRefundTransactionBuilder()
$paymentMock->expects($this->once())->method('getOrder')->willReturn($fixture['order']);
$paymentMock->expects($this->exactly(2))
->method('getAdditionalInformation')
- ->withConsecutive(['card_type'], [Creditcards::BUCKAROO_ORIGINAL_TRANSACTION_KEY_KEY])
+ ->withConsecutive(['card_type'], [Creditcard::BUCKAROO_ORIGINAL_TRANSACTION_KEY_KEY])
->willReturnOnConsecutiveCalls($fixture['card_type'], 'getAdditionalInformation');
$trxFactoryMock = $this->getFakeMock(TransactionBuilderFactory::class)
@@ -258,7 +258,7 @@ public function testGetRefundTransactionBuilder()
->willReturnSelf();
$trxFactoryMock->expects($this->once())->method('setServices')->willReturnCallback(
function ($services) use ($trxFactoryMock) {
- $services['Name'] = 'creditcards';
+ $services['Name'] = 'creditcard';
$services['Action'] = 'Refund';
return $trxFactoryMock;
diff --git a/etc/adminhtml/system/payment_methods.xml b/etc/adminhtml/system/payment_methods.xml
index 3db61196a..dfb664a7e 100644
--- a/etc/adminhtml/system/payment_methods.xml
+++ b/etc/adminhtml/system/payment_methods.xml
@@ -52,6 +52,8 @@
+
+
diff --git a/etc/adminhtml/system/payment_methods/creditcard.xml b/etc/adminhtml/system/payment_methods/creditcard.xml
new file mode 100644
index 000000000..92f2ff3c5
--- /dev/null
+++ b/etc/adminhtml/system/payment_methods/creditcard.xml
@@ -0,0 +1,312 @@
+
+
+
+
+
+
+ Buckaroo\Magento2\Block\Config\Form\Field\Fieldset
+
+
+
+
+ Buckaroo\Magento2\Model\Config\Source\Enablemode
+ payment/buckaroo_magento2_creditcard/active
+
+
+
+
+
+ payment/buckaroo_magento2_creditcard/title
+
+
+
+
+
+ payment/buckaroo_magento2_creditcard/subtext
+
+
+
+
+
+ Buckaroo\Magento2\Model\Config\Source\SubtextStyle
+ payment/buckaroo_magento2_creditcard/subtext_style
+
+
+
+
+
+ payment/buckaroo_magento2_creditcard/subtext_color
+ Buckaroo\Magento2\Block\Config\Form\Field\ColorPicker
+
+
+
+
+
+
+ payment/buckaroo_magento2_creditcard/sort_order
+
+
+
+
+ Separate: Creditcards are show seperate in checkout. A frontend subtext is not supported when the separate option is chosen.
Grouped: Creditcards get redirected to the buckaroo checkout.]]>
+ Buckaroo\Magento2\Model\Config\Source\SeparateOrGrouped
+ payment/buckaroo_magento2_creditcard/group_creditcards
+
+
+
+
+
+ payment/buckaroo_magento2_creditcard/allowed_issuers
+ Buckaroo\Magento2\Model\Config\Source\Creditcard
+
+
+
+
+ Buckaroo\Magento2\Block\Adminhtml\Form\Field\SortIssuers
+
+ payment/buckaroo_magento2_creditcard/sorted_issuers
+
+
+
+
+
+
+
+
+ Magento\Config\Model\Config\Source\Yesno
+ payment/buckaroo_magento2_creditcard/order_email
+
+
+
+
+
+ payment/buckaroo_magento2_creditcard/payment_action
+ Buckaroo\Magento2\Model\Config\Source\PaymentFlow
+
+
+
+
+
+ The payment method shows only for orders with an order amount greater than the minimum amount.
+ payment/buckaroo_magento2_creditcard/min_amount
+ Buckaroo\Magento2\Model\Config\Backend\Price
+
+
+
+
+
+ The payment method shows only for orders with an order amount smaller than the maximum amount.
+ payment/buckaroo_magento2_creditcard/max_amount
+ Buckaroo\Magento2\Model\Config\Backend\Price
+
+
+
+
+
+ Magento\Config\Model\Config\Source\Yesno
+ payment/buckaroo_magento2_creditcard/active_status
+
+
+
+
+
+ To make a new status available it needs to be assigned to the correct state. See Magento documentation about state and status.
+ Buckaroo\Magento2\Model\Config\Source\StatusesSuccess
+ payment/buckaroo_magento2_creditcard/order_status_success
+
+ 1
+
+
+
+
+
+
+ To make a new status available it needs to be assigned to the correct state. See Magento documentation about state and status.
+ Buckaroo\Magento2\Model\Config\Source\StatusesFailed
+ payment/buckaroo_magento2_creditcard/order_status_failed
+
+ 1
+
+
+
+
+
+
+ Your contract with Buckaroo must allow for the selected currencies to be used with this payment method.
+ payment/buckaroo_magento2_creditcard/allowed_currencies
+ Buckaroo\Magento2\Model\Config\Source\AllowedCurrencies::creditcard
+ Buckaroo\Magento2\Model\Config\Backend\AllowedCurrencies
+
+
+
+
+ Buckaroo\Magento2\Model\Config\Source\AllOrSpecificCountries
+ payment/buckaroo_magento2_creditcard/allowspecific
+
+
+
+
+
+ Magento\Config\Model\Config\Source\Locale\Country
+ payment/buckaroo_magento2_creditcard/specificcountry
+
+ 1
+
+
+
+
+
+
+ Magento developer client restrictions.
+ Magento\Config\Model\Config\Source\Yesno
+ payment/buckaroo_magento2_creditcard/limit_by_ip
+
+
+
+
+ Buckaroo\Magento2\Model\Config\Source\SpecificCustomerGroups
+ 1
+ payment/buckaroo_magento2_creditcard/specificcustomergroup
+
+
+
+
+ Configuration > Sales > Tax.]]>
+ payment/buckaroo_magento2_creditcard/payment_fee
+ Buckaroo\Magento2\Model\Config\Backend\PaymentFee
+
+
+
+
+
+ payment/buckaroo_magento2_creditcard/payment_fee_label
+
+
+
+
+
+ Magento\Config\Block\System\Config\Form\Field\Heading
+
+
+
+
+
+ Magento\Config\Model\Config\Source\Yesno
+ payment/buckaroo_magento2_creditcard/limit_by_ip
+
+
+
+
+
+ Magento\Config\Block\System\Config\Form\Field\Heading
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Magento\Config\Model\Config\Source\Yesno
+ payment/buckaroo_magento2_creditcard/mastercard_unsecure_hold
+
+
+
+
+
+ Magento\Config\Block\System\Config\Form\Field\Heading
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Magento\Config\Model\Config\Source\Yesno
+ payment/buckaroo_magento2_creditcard/visa_unsecure_hold
+
+
+
+
+
+ Magento\Config\Block\System\Config\Form\Field\Heading
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Magento\Config\Model\Config\Source\Yesno
+ payment/buckaroo_magento2_creditcard/maestro_unsecure_hold
+
+
+
+
+
+
+
+ Magento\Config\Block\System\Config\Form\Field\Heading
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Magento\Config\Model\Config\Source\Yesno
+ payment/buckaroo_magento2_creditcard/dankort_unsecure_hold
+
+
+
+
+
+
+
+
diff --git a/etc/adminhtml/system/payment_methods/creditcards.xml b/etc/adminhtml/system/payment_methods/creditcards.xml
index 32fbc902a..9eb7499eb 100644
--- a/etc/adminhtml/system/payment_methods/creditcards.xml
+++ b/etc/adminhtml/system/payment_methods/creditcards.xml
@@ -22,11 +22,11 @@
-
+
Buckaroo\Magento2\Block\Config\Form\Field\Fieldset
-
+
Buckaroo\Magento2\Model\Config\Source\Enablemode
payment/buckaroo_magento2_creditcards/active
@@ -35,22 +35,6 @@
-
-
- Token registration.]]>
- Please enter your Buckaroo Hosted Fields Client ID.
- Magento\Config\Model\Config\Backend\Encrypted
- payment/buckaroo_magento2_creditcards/hosted_fields_client_id
-
-
-
-
- Token registration.]]>
- Please enter your Buckaroo Hosted Fields Client Secret.
- Magento\Config\Model\Config\Backend\Encrypted
- payment/buckaroo_magento2_creditcards/hosted_fields_client_secret
-
-
@@ -63,7 +47,7 @@
payment/buckaroo_magento2_creditcards/subtext
-
+
diff --git a/etc/config.xml b/etc/config.xml
index d1de43ba8..4cd38a542 100644
--- a/etc/config.xml
+++ b/etc/config.xml
@@ -132,6 +132,27 @@
0
+
+ 0
+ Buckaroo\Magento2\Model\Method\Creditcard
+ pending
+ Creditcard and Debit Cards
+ 0
+ 30
+ 1
+ Fee
+ Fee
+ Fee
+ Fee
+
+ Fee
+
+ buckaroo_magento2
+ order
+ 0
+ 1
+
+
0
Buckaroo\Magento2\Model\Method\Creditcards
diff --git a/etc/csp_whitelist.xml b/etc/csp_whitelist.xml
index 89463e313..8aadc2928 100644
--- a/etc/csp_whitelist.xml
+++ b/etc/csp_whitelist.xml
@@ -1,5 +1,6 @@
-
+
@@ -7,9 +8,6 @@
https://checkout.buckaroo.nl
https://testcheckout.buckaroo.nl
https://buckaroo.nl
- https://hostedfields-externalapi.alpha.buckaroo.aws
- https://hostedfields-externalapi.prod-pci.buckaroo.io
- https://cdn.tailwindcss.com
@@ -31,16 +29,8 @@
wss://websockets.buckaroo.io/
https://checkout.buckaroo.nl
https://testcheckout.buckaroo.nl
- https://hostedfields-externalapi.alpha.buckaroo.aws
- https://hostedfields-externalapi.prod-pci.buckaroo.io
https://applepay.buckaroo.io
-
-
- https://hostedfields-externalapi.alpha.buckaroo.aws
- https://hostedfields-externalapi.prod-pci.buckaroo.io
-
-
diff --git a/etc/di.xml b/etc/di.xml
index d644fc032..4aa047713 100644
--- a/etc/di.xml
+++ b/etc/di.xml
@@ -124,6 +124,7 @@
+
Magento\Framework\Filesystem\Driver\File
@@ -240,6 +241,10 @@
- idealprocessing
- Buckaroo\Magento2\Model\ConfigProvider\Method\IdealProcessing
+ -
+
- creditcard
+ - Buckaroo\Magento2\Model\ConfigProvider\Method\Creditcard
+
-
- creditcards
- Buckaroo\Magento2\Model\ConfigProvider\Method\Creditcards
@@ -495,7 +500,7 @@
- Buckaroo\Magento2\Model\ConfigProvider\Method\Creditcards
+ Buckaroo\Magento2\Model\ConfigProvider\Method\Creditcard
diff --git a/etc/frontend/di.xml b/etc/frontend/di.xml
index e562d7843..740d585f3 100644
--- a/etc/frontend/di.xml
+++ b/etc/frontend/di.xml
@@ -28,6 +28,7 @@
- Buckaroo\Magento2\Model\ConfigProvider\Method\Ideal
- Buckaroo\Magento2\Model\ConfigProvider\Method\IdealProcessing
- Buckaroo\Magento2\Model\ConfigProvider\Method\Transfer
+ - Buckaroo\Magento2\Model\ConfigProvider\Method\Creditcard
- Buckaroo\Magento2\Model\ConfigProvider\Method\Creditcards
- Buckaroo\Magento2\Model\ConfigProvider\BuckarooFee
- Buckaroo\Magento2\Model\ConfigProvider\Method\Paypal
diff --git a/etc/payment.xml b/etc/payment.xml
index ca6ae4ce4..b107ba51d 100644
--- a/etc/payment.xml
+++ b/etc/payment.xml
@@ -42,6 +42,9 @@
0
+
+ 0
+
0
diff --git a/i18n/de_DE.csv b/i18n/de_DE.csv
index e381bd765..a1357efe9 100644
--- a/i18n/de_DE.csv
+++ b/i18n/de_DE.csv
@@ -475,10 +475,6 @@
"Cannot create payment","Zahlung kann nicht erstellt werden"
"Failed to create quote","Angebotserstellung fehlgeschlagen"
"Failed to add address to quote","Adresse konnte dem Angebot nicht hinzugefügt werden"
-"Buckaroo Hosted Fields Client ID:","Buckaroo Hosted Fields Client ID:"
-"Buckaroo Hosted Fields Client Secret:","Buckaroo Hosted Fields Client Secret:"
-"Enter your Buckaroo Hosted Fields Client ID, obtainable from the Buckaroo Plaza at → Settings → Token registration.","Geben Sie hier Ihren Buckaroo Hosted Fields Client ID ein, den Sie von der Buckaroo Plaza unter → Einstellungen → Tokenregistrierung."
-"Enter your Buckaroo Hosted Fields Client Secret, obtainable from the Buckaroo Plaza at → Settings → Token registration.","Geben Sie hier Ihr Buckaroo Hosted Fields Client Secret ein, das Sie von der Buckaroo Plaza unter → Einstellungen → Tokenregistrierung."
"Mar","Mär"
"May","Mai"
"Oct","Okt"
diff --git a/i18n/es_ES.csv b/i18n/es_ES.csv
index 0cd6a17ee..c8d8d0aa6 100644
--- a/i18n/es_ES.csv
+++ b/i18n/es_ES.csv
@@ -465,10 +465,6 @@
"iDEAL Fast Checkout logo scheme","Esquema de color del logo de pago rápido iDEAL"
"Select the iDEAL fast checkout button (text) color.","Seleccione el color del botón de pago rápido iDEAL (texto)."
"Select where you want the button to be visible. Multiple options can be selected at the same time.","Seleccione dónde desea que el botón sea visible. Se pueden seleccionar varias opciones al mismo tiempo."
-"Buckaroo Hosted Fields Client ID:","Buckaroo Hosted Fields Client ID:"
-"Buckaroo Hosted Fields Client Secret:","Buckaroo Hosted Fields Client Secret:"
-"Enter your Buckaroo Hosted Fields Client ID, obtainable from the Buckaroo Plaza at → Settings → Token registration.","Ingrese su Buckaroo Hosted Fields Client ID, disponible en Buckaroo Plaza en → Configuración → Registro de token."
-"Enter your Buckaroo Hosted Fields Client Secret, obtainable from the Buckaroo Plaza at → Settings → Token registration.","Ingrese su Buckaroo Hosted Fields Client Secret, disponible en Buckaroo Plaza en → Configuración → Registro de token."
"Cart","Carrito"
"Light","Claro"
"Dark","Oscuro"
diff --git a/i18n/fr_BE.csv b/i18n/fr_BE.csv
index 8d3ef9682..61152e5e4 100644
--- a/i18n/fr_BE.csv
+++ b/i18n/fr_BE.csv
@@ -24,10 +24,6 @@
"Cannot create payment","Impossible de créer le paiement"
"Failed to create quote","Échec de la création du devis"
"Failed to add address to quote","Échec de l'ajout de l'adresse au devis"
-"Buckaroo Hosted Fields Client ID:","Buckaroo Hosted Fields Client ID:"
-"Buckaroo Hosted Fields Client Secret:","Buckaroo Hosted Fields Client Secret:"
-"Enter your Buckaroo Hosted Fields Client ID, obtainable from the Buckaroo Plaza at → Settings → Token registration.","Entrez votre Buckaroo Hosted Fields Client ID, disponible depuis le Buckaroo Plaza dans → Paramètres → Enregistrement du jeton."
-"Enter your Buckaroo Hosted Fields Client Secret, obtainable from the Buckaroo Plaza at → Settings → Token registration.","Entrez votre Buckaroo Hosted Fields Client Secret, disponible depuis le Buckaroo Plaza dans → Paramètres → Enregistrement du jeton."
"Feb","Fév"
"Mar","Mar"
"Apr","Avr"
diff --git a/i18n/fr_FR.csv b/i18n/fr_FR.csv
index 9d690c7d9..d0169fd9b 100644
--- a/i18n/fr_FR.csv
+++ b/i18n/fr_FR.csv
@@ -475,10 +475,6 @@
"Cannot create payment","Impossible de créer le paiement"
"Failed to create quote","Échec de la création du devis"
"Failed to add address to quote","Échec de l'ajout de l'adresse au devis"
-"Buckaroo Hosted Fields Client ID:","Buckaroo Hosted Fields Client ID:"
-"Buckaroo Hosted Fields Client Secret:","Buckaroo Hosted Fields Client Secret:"
-"Enter your Buckaroo Hosted Fields Client ID, obtainable from the Buckaroo Plaza at → Settings → Token registration.","Entrez votre Buckaroo Hosted Fields Client ID, disponible depuis le Buckaroo Plaza dans → Paramètres → Enregistrement du jeton."
-"Enter your Buckaroo Hosted Fields Client Secret, obtainable from the Buckaroo Plaza at → Settings → Token registration.","Entrez votre Buckaroo Hosted Fields Client Secret, disponible depuis le Buckaroo Plaza dans → Paramètres → Enregistrement du jeton."
"Feb","Fév"
"Mar","Mar"
"Apr","Avr"
diff --git a/i18n/nl_BE.csv b/i18n/nl_BE.csv
index 3610b5f1d..288d0d70e 100644
--- a/i18n/nl_BE.csv
+++ b/i18n/nl_BE.csv
@@ -475,10 +475,6 @@
"Cannot create payment","Betaling kan niet worden aangemaakt"
"Failed to create quote","Offerte aanmaken mislukt"
"Failed to add address to quote","Adres kan niet aan offerte worden toegevoegd"
-"Buckaroo Hosted Fields Client ID:","Buckaroo Hosted Fields Client ID:"
-"Buckaroo Hosted Fields Client Secret:","Buckaroo Hosted Fields Client Secret:"
-"Enter your Buckaroo Hosted Fields Client ID, obtainable from the Buckaroo Plaza at → Settings → Token registration.","Entrez votre Buckaroo Hosted Fields Client ID, disponible depuis le Buckaroo Plaza dans → Paramètres → Enregistrement du jeton."
-"Enter your Buckaroo Hosted Fields Client Secret, obtainable from the Buckaroo Plaza at → Settings → Token registration.","Entrez votre Buckaroo Hosted Fields Client Secret, disponible depuis le Buckaroo Plaza dans → Paramètres → Enregistrement du jeton."
"Mar","Mrt"
"May","Mei"
"Oct","Okt"
diff --git a/i18n/nl_NL.csv b/i18n/nl_NL.csv
index 861dd6f05..11e22f204 100644
--- a/i18n/nl_NL.csv
+++ b/i18n/nl_NL.csv
@@ -487,10 +487,6 @@
"Cannot create payment","Betaling kan niet worden aangemaakt"
"Failed to create quote","Offerte aanmaken mislukt"
"Failed to add address to quote","Adres kan niet aan offerte worden toegevoegd"
-"Buckaroo Hosted Fields Client ID:","Buckaroo Hosted Fields Client ID:"
-"Buckaroo Hosted Fields Client Secret:","Buckaroo Hosted Fields Client Secret:"
-"Enter your Buckaroo Hosted Fields Client ID, obtainable from the Buckaroo Plaza at → Settings → Token registration.","Voer hier je Buckaroo Hosted Fields Client ID in, die je kunt verkrijgen vanuit de Buckaroo Plaza bij → Instellingen → Tokenregistratie."
-"Enter your Buckaroo Hosted Fields Client Secret, obtainable from the Buckaroo Plaza at → Settings → Token registration.","Voer hier je Buckaroo Hosted Fields Client Secret in, die je kunt verkrijgen vanuit de Buckaroo Plaza bij → Instellingen → Tokenregistratie."
"Mar","Mrt"
"May","Mei"
"Oct","Okt"
diff --git a/view/frontend/layout/checkout_index_index.xml b/view/frontend/layout/checkout_index_index.xml
index 79fd2e81f..1ee6c5c25 100644
--- a/view/frontend/layout/checkout_index_index.xml
+++ b/view/frontend/layout/checkout_index_index.xml
@@ -22,7 +22,6 @@
-
@@ -114,6 +113,9 @@
-
- true
+ -
+
- true
+
-
- true
diff --git a/view/frontend/requirejs-config.js b/view/frontend/requirejs-config.js
index 0d17c9bc7..800e78a59 100644
--- a/view/frontend/requirejs-config.js
+++ b/view/frontend/requirejs-config.js
@@ -37,14 +37,11 @@ var config = {
"buckaroo/payconiq/pay": "Buckaroo_Magento2/js/view/checkout/payconiq/pay",
"buckaroo/mrcash/pay": "Buckaroo_Magento2/js/view/checkout/mrcash/pay",
"BuckarooClientSideEncryption": "//static.buckaroo.nl/script/ClientSideEncryption001.js",
- "BuckarooHostedFieldsSdkAlpha": "//hostedfields-externalapi.alpha.buckaroo.aws/v1/sdk",
- "BuckarooHostedFieldsSdk": "//hostedfields-externalapi.prod-pci.buckaroo.io/v1/sdk",
"buckaroo/checkout/common": "Buckaroo_Magento2/js/view/checkout/common",
"buckaroo/checkout/datepicker": "Buckaroo_Magento2/js/view/checkout/datepicker",
"buckaroo/paypal-express/pay": "Buckaroo_Magento2/js/view/checkout/paypal-express/pay",
"buckaroo/paypal-express/button": "Buckaroo_Magento2/js/view/checkout/paypal-express/button",
"buckaroo/ideal-fast-checkout/pay": "Buckaroo_Magento2/js/view/checkout/ideal-fast-checkout/pay",
- 'buckaroo_magento2_creditcards': 'Buckaroo_Magento2/js/view/payment/method-renderer/creditcards'
}
},
shim: {
diff --git a/view/frontend/web/css/styles.css b/view/frontend/web/css/styles.css
index e2c1e91f4..e89a11212 100644
--- a/view/frontend/web/css/styles.css
+++ b/view/frontend/web/css/styles.css
@@ -165,6 +165,7 @@
.buckaroo_magento2_ideal .payment-method-second-col,
.buckaroo_magento2_idealprocessing .payment-method-second-col,
+ .buckaroo_magento2_creditcard .payment-method-second-col,
.buckaroo_magento2_creditcards .payment-method-second-col,
.buckaroo_magento2_transfer .payment-method-second-col,
.buckaroo_magento2_afterpay .payment-method-second-col,
@@ -195,6 +196,7 @@
.buckaroo_magento2_ideal .payment-method-billing-address,
.buckaroo_magento2_idealprocessing .payment-method-billing-address,
+ .buckaroo_magento2_creditcard .payment-method-billing-address,
.buckaroo_magento2_creditcards .payment-method-billing-address,
.buckaroo_magento2_transfer .payment-method-billing-address,
.buckaroo_magento2_afterpay .payment-method-billing-address,
@@ -229,6 +231,7 @@
@media screen and (min-width: 768px){
.magento-blank .buckaroo_magento2_ideal .fieldset > .field:not(.choice) > .label,
.magento-blank .buckaroo_magento2_idealprocessing .fieldset > .field:not(.choice) > .label,
+ .magento-blank .buckaroo_magento2_creditcard .fieldset > .field:not(.choice) > .label,
.magento-blank .buckaroo_magento2_creditcards .fieldset > .field:not(.choice) > .label,
.magento-blank .buckaroo_magento2_transfer .fieldset > .field:not(.choice) > .label,
.magento-blank .buckaroo_magento2_afterpay .fieldset > .field:not(.choice) > .label,
@@ -254,6 +257,7 @@
.magento-blank .buckaroo_magento2_ideal di.fieldset > .field:not(.choice) > .control,
.magento-blank .buckaroo_magento2_idealprocessing .fieldset > .field:not(.choice) > .control,
+ .magento-blank .buckaroo_magento2_creditcard .fieldset > .field:not(.choice) > .control,
.magento-blank .buckaroo_magento2_creditcards .fieldset > .field:not(.choice) > .control,
.magento-blank .buckaroo_magento2_transfer .fieldset > .field:not(.choice) > .control,
.magento-blank .buckaroo_magento2_afterpay .fieldset > .field:not(.choice) > .control,
@@ -277,6 +281,7 @@
.magento-blank .buckaroo_magento2_ideal .fieldset > .field.choice:before,
.magento-blank .buckaroo_magento2_idealprocessing .fieldset > .field.choice:before,
+ .magento-blank .buckaroo_magento2_creditcard .fieldset > .field.choice:before,
.magento-blank .buckaroo_magento2_creditcards .fieldset > .field.choice:before,
.magento-blank .buckaroo_magento2_transfer .fieldset > .field.choice:before,
.magento-blank .buckaroo_magento2_afterpay .fieldset > .field.choice:before,
@@ -323,16 +328,19 @@
/* ===================== Credit Card =========================== */
-.buckaroo_magento2_creditcards .payment-method-second-col .card-types{
+.buckaroo_magento2_creditcards .payment-method-second-col .card-types,
+.buckaroo_magento2_creditcard .payment-method-second-col .card-types{
float:left; width: 100%;
}
-.buckaroo_magento2_creditcards .payment-method-second-col .card-types-img{
+.buckaroo_magento2_creditcards .payment-method-second-col .card-types-img,
+.buckaroo_magento2_creditcard .payment-method-second-col .card-types-img {
vertical-align:middle;
margin-right:10px;
}
-.buckaroo_magento2_creditcards .payment-method-second-col .card-types-input{
+.buckaroo_magento2_creditcards .payment-method-second-col .card-types-input,
+.buckaroo_magento2_creditcard .payment-method-second-col .card-types-input {
margin-top:10px;
}
diff --git a/view/frontend/web/js/view/payment/buckaroo-payments.js b/view/frontend/web/js/view/payment/buckaroo-payments.js
index 0e1b39510..c426a8701 100644
--- a/view/frontend/web/js/view/payment/buckaroo-payments.js
+++ b/view/frontend/web/js/view/payment/buckaroo-payments.js
@@ -81,6 +81,10 @@ define(
type: 'buckaroo_magento2_payconiq',
component: 'Buckaroo_Magento2/js/view/payment/method-renderer/payconiq'
},
+ {
+ type: 'buckaroo_magento2_creditcard',
+ component: 'Buckaroo_Magento2/js/view/payment/method-renderer/creditcard'
+ },
{
type: 'buckaroo_magento2_creditcards',
component: 'Buckaroo_Magento2/js/view/payment/method-renderer/creditcards'
@@ -179,7 +183,7 @@ define(
},
{
type: 'buckaroo_magento2_blik',
- component: 'Buckaroo_Magento2/js/view/payment/method-renderer/blik'
+ component: 'Buckaroo_Magento2/js/view/payment/method-renderer/blik'
}
);
/**
diff --git a/view/frontend/web/js/view/payment/method-renderer/creditcard.js b/view/frontend/web/js/view/payment/method-renderer/creditcard.js
new file mode 100644
index 000000000..410124774
--- /dev/null
+++ b/view/frontend/web/js/view/payment/method-renderer/creditcard.js
@@ -0,0 +1,218 @@
+/**
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the MIT License
+ * It is available through the world-wide-web at this URL:
+ * https://tldrlegal.com/license/mit-license
+ * If you are unable to obtain it through the world-wide-web, please send an email
+ * to support@buckaroo.nl so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade this module to newer
+ * versions in the future. If you wish to customize this module for your
+ * needs please contact support@buckaroo.nl for more information.
+ *
+ * @copyright Copyright (c) Buckaroo B.V.
+ * @license https://tldrlegal.com/license/mit-license
+ */
+/*browser:true*/
+/*global define*/
+define(
+ [
+ 'jquery',
+ 'Magento_Checkout/js/view/payment/default',
+ 'Magento_Checkout/js/model/payment/additional-validators',
+ 'Buckaroo_Magento2/js/action/place-order',
+ 'ko',
+ 'mage/translate',
+ 'Magento_Checkout/js/checkout-data',
+ 'Magento_Checkout/js/action/select-payment-method',
+ 'buckaroo/checkout/common'
+ ],
+ function (
+ $,
+ Component,
+ additionalValidators,
+ placeOrderAction,
+ ko,
+ $t,
+ checkoutData,
+ selectPaymentMethodAction,
+ checkoutCommon
+ ) {
+ 'use strict';
+
+ return Component.extend(
+ {
+ defaults: {
+ template: 'Buckaroo_Magento2/payment/buckaroo_magento2_creditcard'
+ },
+ creditcards: [],
+ groupCreditcards: false,
+ redirectAfterPlaceOrder: false,
+ creditcardIssuer: null,
+ selectedBank: null,
+ selectedBankDropDown: null,
+ selectionType: null,
+ paymentFeeLabel : window.checkoutConfig.payment.buckaroo.creditcard.paymentFeeLabel,
+ subtext : window.checkoutConfig.payment.buckaroo.creditcard.subtext,
+ subTextStyle : checkoutCommon.getSubtextStyle('creditcard'),
+ currencyCode : window.checkoutConfig.quoteData.quote_currency_code,
+ baseCurrencyCode : window.checkoutConfig.quoteData.base_currency_code,
+ paymentFlow : window.checkoutConfig.payment.buckaroo.creditcard.paymentFlow,
+
+ /**
+ * @override
+ */
+ initialize : function (options) {
+ if (checkoutData.getSelectedPaymentMethod() == options.index) {
+ window.checkoutConfig.buckarooFee.title(this.paymentFeeLabel);
+ }
+ return this._super(options);
+ },
+
+ initObservable: function () {
+ this._super().observe(['selectedCard', 'creditcards', 'selectionType']);
+
+ this.creditcards = ko.observableArray(window.checkoutConfig.payment.buckaroo.creditcard.cards);
+
+ this.selectionType = window.checkoutConfig.payment.buckaroo.creditcard.selectionType;
+
+ /**
+ * observe radio buttons
+ * check if selected
+ */
+ var self = this;
+ this.setSelectedCard = function (value) {
+ self.selectedCard(value);
+ return true;
+ };
+
+ /**
+ * Check if the required fields are filled. If so: enable place order button (true) | ifnot: disable place order button (false)
+ */
+ this.buttoncheck = ko.computed(
+ function () {
+ return this.selectedCard();
+ },
+ this
+ );
+
+ $('.iosc-place-order-button').on('click', function(e){
+ if(self.selectedCard() == null){
+ self.messageContainer.addErrorMessage({'message': $t('You need select a card')});
+ }
+ });
+
+ return this;
+ },
+
+ setSelectedBankDropDown: function() {
+ var el = document.getElementById("buckaroo_magento2_creditcard_issuer");
+ this.selectedCard(el.options[el.selectedIndex].value);
+ return true;
+ },
+
+ /**
+ * Place order.
+ *
+ * placeOrderAction has been changed from Magento_Checkout/js/action/place-order to our own version
+ * (Buckaroo_Magento2/js/action/place-order) to prevent redirect and handle the response.
+ */
+ placeOrder: function (data, event) {
+ var self = this,
+ placeOrder;
+
+ if (event) {
+ event.preventDefault();
+ }
+
+ if (this.validate() && additionalValidators.validate()) {
+ this.isPlaceOrderActionAllowed(false);
+ placeOrder = placeOrderAction(this.getData(), this.redirectAfterPlaceOrder, this.messageContainer);
+
+ $.when(placeOrder).fail(
+ function () {
+ self.isPlaceOrderActionAllowed(true);
+ }
+ ).done(this.afterPlaceOrder.bind(this));
+ return true;
+ }
+ return false;
+ },
+
+ afterPlaceOrder: function () {
+ var response = window.checkoutConfig.payment.buckaroo.response;
+ checkoutCommon.redirectHandle(response);
+ },
+
+ isCheckedCreditCardPaymentMethod: function (code) {
+ return ((this.creditcardIssuer !== undefined) && this.creditcardIssuer == code);
+ },
+
+ selectCreditCardPaymentMethod: function (code) {
+ this.setSelectedCard(code);
+ this.item.method = 'buckaroo_magento2_creditcard';
+ this.paymentMethod = this.item.method;
+ this.selectPaymentMethod();
+ return true;
+ },
+
+ selectPaymentMethod: function () {
+ window.checkoutConfig.buckarooFee.title(this.paymentFeeLabel);
+
+ selectPaymentMethodAction(this.getData());
+ checkoutData.setSelectedPaymentMethod(this.item.method);
+ return true;
+ },
+
+ isCredicardGroupMode: function () {
+ return window.checkoutConfig.payment.buckaroo.creditcard.groupCreditcards === '1';
+ },
+
+ getData: function () {
+ var selectedCardCode = null;
+ if (this.selectedCard()) {
+ selectedCardCode = typeof this.selectedCard() === 'object' ?
+ this.selectedCard().code :
+ this.selectedCard();
+ }
+
+ if(this.creditcardIssuer){
+ selectedCardCode = this.creditcardIssuer;
+ }
+
+ return {
+ "method": this.item.method,
+ "po_number": null,
+ "additional_data": {
+ "card_type" : selectedCardCode
+ }
+ };
+ },
+
+ payWithBaseCurrency: function () {
+ var allowedCurrencies = window.checkoutConfig.payment.buckaroo.creditcard.allowedCurrencies;
+
+ return allowedCurrencies.indexOf(this.currencyCode) < 0;
+ },
+
+ getPayWithBaseCurrencyText: function () {
+ var text = $.mage.__('The transaction will be processed using %s.');
+
+ return text.replace('%s', this.baseCurrencyCode);
+ }
+
+ }
+ );
+ }
+);
+
+
+
+
+
+
+
+
diff --git a/view/frontend/web/js/view/payment/method-renderer/creditcards.js b/view/frontend/web/js/view/payment/method-renderer/creditcards.js
index df39bc0fe..7825b2d77 100644
--- a/view/frontend/web/js/view/payment/method-renderer/creditcards.js
+++ b/view/frontend/web/js/view/payment/method-renderer/creditcards.js
@@ -25,11 +25,10 @@ define(
'Magento_Checkout/js/model/payment/additional-validators',
'Buckaroo_Magento2/js/action/place-order',
'ko',
- 'mage/url',
'Magento_Checkout/js/checkout-data',
'Magento_Checkout/js/action/select-payment-method',
'buckaroo/checkout/common',
- 'BuckarooHostedFieldsSdk'
+ 'BuckarooClientSideEncryption'
],
function (
$,
@@ -37,253 +36,328 @@ define(
additionalValidators,
placeOrderAction,
ko,
- urlBuilder,
checkoutData,
selectPaymentMethodAction,
- checkoutCommon,
- BuckarooHostedFieldsSdk
+ checkoutCommon
) {
'use strict';
+
- return Component.extend({
- defaults: {
- template: 'Buckaroo_Magento2/payment/buckaroo_magento2_creditcards',
- encryptedCardData: null,
- service: null
+ /**
+ * Add validation methods
+ */
+ $.validator.addMethod('validateCardNumber', function (value) {
+ return BuckarooClientSideEncryption.V001.validateCardNumber(value.replace(/\s+/g, ''));
},
- paymentFeeLabel: window.checkoutConfig.payment.buckaroo.creditcards.paymentFeeLabel,
- subtext: window.checkoutConfig.payment.buckaroo.creditcards.subtext,
- subTextStyle: checkoutCommon.getSubtextStyle('creditcards'),
+ $.mage.__('Please enter a valid creditcard number.')
+ );
- oauthTokenError: ko.observable(''),
- paymentError: ko.observable(''),
-
- initialize: function (options) {
- this._super(options);
- this.getOAuthToken();
- return this;
+ $.validator.addMethod('validateCvc', function (value) {
+ return BuckarooClientSideEncryption.V001.validateCvc(
+ value,
+ $('#buckaroo_magento2_creditcards_issuer').val()
+ );
},
+ $.mage.__('Please enter a valid Cvc number.')
+ );
- async getOAuthToken() {
- try {
- const response = await $.ajax({
- url: urlBuilder.build('/buckaroo/credentialschecker/gettoken'),
- type: "GET",
- headers: {
- 'X-Requested-From': 'MagentoFrontend'
- }
- });
-
- // Check for error field in response
- if (response.error) {
- // Display the error message in the observable
- this.oauthTokenError("An error occurred, please try another payment method or try again later.");
- } else {
- const accessToken = response.data.access_token;
- const issuers = response.data.issuers;
- // Success: Initialize hosted fields with access token
- await this.initHostedFields(accessToken,issuers);
- }
- } catch (error) {
- // Catch any other errors (e.g., network issues)
- this.oauthTokenError("An error occurred, please try another payment method or try again later.");
- }
+ $.validator.addMethod('validateCardHolderName', function (value) {
+ return BuckarooClientSideEncryption.V001.validateCardholderName(value);
},
-
- resetForm: function() {
- // Remove hosted field iframes from DOM
- this.removeHostedFieldIframes();
-
- // Re-fetch the OAuth token and reinitialize the hosted fields
- this.getOAuthToken();
- this.paymentError('');
-
- // Re-enable the submit button
- let payButton = document.getElementById("pay");
- if (payButton) {
- payButton.disabled = false;
- payButton.style.backgroundColor = ""; // Reset to original
- payButton.style.cursor = "";
- payButton.style.opacity = "";
+ $.mage.__('Please enter a valid card holder name.')
+ );
+
+ $.validator.addMethod('bkValidateYear', function (value) {
+ if(value.length === 0) {
+ return false;
}
+ const parts = value.split("/");
+ return BuckarooClientSideEncryption.V001.validateYear(parts[1]);
},
+ $.mage.__('Enter a valid year number.')
+ );
+ $.validator.addMethod('bkValidateMonth', function (value) {
+ if(value.length === 0) {
+ return false;
+ }
- removeHostedFieldIframes: function() {
- // Remove the iframes for the hosted fields by targeting their container
- $('#cc-name-wrapper iframe').remove();
- $('#cc-number-wrapper iframe').remove();
- $('#cc-expiry-wrapper iframe').remove();
- $('#cc-cvc-wrapper iframe').remove();
+ const parts = value.split("/");
+ return BuckarooClientSideEncryption.V001.validateMonth(parts[0]);
},
+ $.mage.__('Enter a valid month number.')
+ );
- async initHostedFields(accessToken,issuers) {
- try {
- const sdkClient = new BuckarooHostedFieldsSdk.HFClient(accessToken);
- var locale = document.documentElement.lang;
- var languageCode = locale.split('_')[0];
- sdkClient.setLanguage(languageCode);
- sdkClient.setSupportedServices(issuers);
-
- await sdkClient.startSession(event => {
- sdkClient.handleValidation(event, 'cc-name-error', 'cc-number-error', 'cc-expiry-error', 'cc-cvc-error');
-
- let payButton = document.getElementById("pay");
- if (payButton) {
- let disabled = !sdkClient.formIsValid();
- payButton.disabled = disabled;
- if (disabled) {
- payButton.style.backgroundColor = "";
- payButton.style.cursor = "not-allowed";
- payButton.style.opacity = "0.5";
- } else {
- payButton.style.backgroundColor = "";
- payButton.style.cursor = "";
- payButton.style.opacity = "";
- }
- }
+ return Component.extend(
+ {
+ defaults: {
+ template : 'Buckaroo_Magento2/payment/buckaroo_magento2_creditcards',
+ cardNumber : '',
+ cvc : '',
+ cardHolderName : '',
+ expireDate : '',
+ encryptedCardData : null,
+ cardIssuer : null,
+ validationState : {},
+ issuerImage : window.checkoutConfig.payment.buckaroo.creditcards.defaultCardImage
+ },
+ paymentFeeLabel : window.checkoutConfig.payment.buckaroo.creditcards.paymentFeeLabel,
+ subtext : window.checkoutConfig.payment.buckaroo.creditcards.subtext,
+ subTextStyle : checkoutCommon.getSubtextStyle('creditcards'),
+ currencyCode : window.checkoutConfig.quoteData.quote_currency_code,
+ baseCurrencyCode : window.checkoutConfig.quoteData.base_currency_code,
+ creditcards : window.checkoutConfig.payment.buckaroo.creditcards.creditcards,
+ defaultCardImage : window.checkoutConfig.payment.buckaroo.creditcards.defaultCardImage,
+ isTestMode: window.checkoutConfig.payment.buckaroo.creditcards.isTestMode,
- this.service = sdkClient.getService();
- });
+ /**
+ * @override
+ */
+ initialize : function (options) {
+ if (checkoutData.getSelectedPaymentMethod() == options.index) {
+ window.checkoutConfig.buckarooFee.title(this.paymentFeeLabel);
+ }
- let cardLogoStyling = {
- height:"80%",
- position: 'absolute',
- border: '1px solid #d6d6d6',
- borderRadius: "4px",
- opacity:'1',
- transition:'all 0.3s ease',
- right:'5px',
- backgroundColor:'inherit'
- };
+ return this._super(options);
+ },
- // Define styling and mount hosted fields as needed...
- let styling = {
- fontSize: "14px",
- fontStyle: "normal",
- fontWeight: 400,
- fontFamily: 'Open Sans, Helvetica Neue, Helvetica, Arial, sans-serif',
- textAlign: 'left',
- background: '#fefefe',
- color: '#333333',
- placeholderColor: '#888888',
- borderRadius: '5px',
- padding: '8px 10px',
- boxShadow: 'none',
- transition: 'border-color 0.2s ease, box-shadow 0.2s ease',
- border: '1px solid #d6d6d6',
- cardLogoStyling: cardLogoStyling
- };
+ initObservable: function () {
+ /** Observed fields **/
+ this._super().observe(
+ [
+ 'cardNumber',
+ 'cvc',
+ 'cardHolderName',
+ 'expireDate',
+ 'cardIssuer',
+ 'validationState'
+ ]
+ );
- await sdkClient.mountCardHolderName("#cc-name-wrapper", {
- id: "ccname",
- placeHolder: "John Doe",
- labelSelector: "#cc-name-label",
- baseStyling: styling
- }).then(field => field.focus());
-
- await sdkClient.mountCardNumber("#cc-number-wrapper", {
- id: "cc",
- placeHolder: "555x xxxx xxxx xxxx",
- labelSelector: "#cc-number-label",
- baseStyling: styling
+ this.setTestParameters()
+ this.formatedCardNumber = ko.computed({
+ read: function () {
+ let cardNumber = this.cardNumber();
+ if(cardNumber.length) {
+ return this.cardNumber().match(new RegExp('.{1,4}', 'g')).join(" ");
+ }
+ return '';
+ },
+ write: function (value) {
+ this.cardNumber(value.replace(/\s/g, ''));
+ },
+ owner: this
});
- await sdkClient.mountCvc("#cc-cvc-wrapper", {
- id: "cvc",
- placeHolder: "1234",
- labelSelector: "#cc-cvc-label",
- baseStyling: styling
+ this.formatedExpirationDate = ko.computed({
+ read: function () {
+ let expireDate = this.expireDate();
+ if(expireDate.length) {
+ return expireDate.replace(
+ /^([1-9]\/|[2-9])$/g, '0$1/' // 3 > 03/
+ ).replace(
+ /^(0[1-9]|1[0-2])$/g, '$1/' // 11 > 11/
+ ).replace(
+ /^([0-1])([3-9])$/g, '0$1/$2' // 13 > 01/3
+ ).replace(
+ /^(0?[1-9]|1[0-2])([0-9]{2})$/g, '$1/$2' // 141 > 01/41
+ ).replace(
+ /^([0]+)\/|[0]+$/g, '0' // 0/ > 0 and 00 > 0
+ ).replace(
+ /[^\d\/]|^[\/]*$/g, '' // To allow only digits and `/`
+ ).replace(
+ /\/\//g, '/' // Prevent entering more than 1 `/`
+ );
+ }
+ return '';
+ },
+ write: function (value) {
+ this.expireDate(value);
+ },
+ owner: this
});
+
- await sdkClient.mountExpiryDate("#cc-expiry-wrapper", {
- id: "expiry",
- placeHolder: "MM / YY",
- labelSelector: "#cc-expiry-label",
- baseStyling: styling
- });
+ this.issuerImage = ko.computed(
+ function () {
+ var cardLogo = this.defaultCardImage;
+
+ var issuer = this.creditcards.find(o => o.code === this.cardIssuer());
+ if (issuer) {
+ cardLogo = issuer.img;
+ }
- let payButton = document.getElementById("pay");
- if (payButton) {
- payButton.addEventListener("click", async function (event) {
- event.preventDefault();
- payButton.disabled = true; // Disable button to prevent double submissions
+ return cardLogo;
+ },
+ this
+ );
- try {
- let paymentToken = await sdkClient.submitSession();
- if (!paymentToken) {
- throw new Error("Failed to get encrypted card data.");
- }
- this.encryptedCardData = paymentToken;
- this.service = sdkClient.getService();
- this.finalizePlaceOrder(event);
- } catch (error) {
- this.paymentError("Payment processing failed. Please try again.");
- payButton.disabled = false;
- }
- }.bind(this));
- }
- } catch (error) {
- console.error("Error initializing hosted fields:", error);
- }
- },
+ return this;
+ },
- /**
- * Place order.
- *
- * placeOrderAction has been changed from Magento_Checkout/js/action/place-order to our own version
- * (Buckaroo_Magento2/js/action/place-order) to prevent redirect and handle the response.
- */
- finalizePlaceOrder: function (event) {
- var self = this,
- placeOrder;
-
- if (event) {
- event.preventDefault();
- }
+
+ validateCardNumber(data, event) {
+ this.validateField(data, event);
- if (!this.encryptedCardData) {
- this.paymentError("Payment token is missing. Please try again.");
- return;
- }
+ //set card issuer
+ this.cardIssuer(
+ this.determineIssuer(data.cardNumber())
+ )
+
+ //validate the cvc if exists
+ if(this.cvc().length) {
+ $('#buckaroo_magento2_creditcards_cvc').valid();
+ }
+ },
- if (this.validate() && additionalValidators.validate()) {
- this.isPlaceOrderActionAllowed(false);
- placeOrder = placeOrderAction(self.getData(), self.redirectAfterPlaceOrder, self.messageContainer);
+ validateField(data, event) {
+ const isValid = $(event.target).valid();
+ let state = this.validationState();
+ state[event.target.id] = isValid;
+ this.validationState(state);
+ },
- $.when(placeOrder).fail(
- function () {
- self.isPlaceOrderActionAllowed(true);
- self.paymentError("Payment token is missing. Please try again.");
+ /** Get the card issuer based on the creditcard number **/
+ determineIssuer: function (cardNumber) {
+ var issuers = {
+ 'amex': {
+ 'regex': '^3[47][0-9]{13}$',
+ 'name': 'American Express'
+ },
+ 'maestro': {
+ 'regex': '^(5018|5020|5038|6304|6759|6761|6763)[0-9]{8,15}$',
+ 'name': 'Maestro'
+ },
+ 'dankort': {
+ 'regex': '^(5019|4571)[0-9]{12}$',
+ 'name': 'Dankort'
+ },
+ 'mastercard': {
+ 'regex': '^(5[1-5]|2[2-7])[0-9]{14}$',
+ 'name': 'Mastercard'
+ },
+ 'visaelectron': {
+ 'regex': '^(4026[0-9]{2}|417500|4508[0-9]{2}|4844[0-9]{2}|4913[0-9]{2}|4917[0-9]{2})[0-9]{10}$',
+ 'name': 'Visa Electron'
+ },
+ 'visa': {
+ 'regex': '^4[0-9]{12}(?:[0-9]{3})?$',
+ 'name': 'Visa'
}
- ).done(self.afterPlaceOrder.bind(self));
+ };
+
+ for (var key in issuers) {
+ if (cardNumber !== undefined && cardNumber.match(issuers[key].regex)) {
+ return key;
+ }
+ }
+
+ return false;
+ },
+
+ validate: function () {
+ return $('.' + this.getCode() + ' .payment-method-second-col form').valid();
+ },
+
+ selectPaymentMethod: function () {
+ window.checkoutConfig.buckarooFee.title(this.paymentFeeLabel);
+
+ selectPaymentMethodAction(this.getData());
+ checkoutData.setSelectedPaymentMethod(this.item.method);
return true;
- }
- return false;
- },
+ },
- afterPlaceOrder: function () {
- var response = window.checkoutConfig.payment.buckaroo.response;
- checkoutCommon.redirectHandle(response);
- },
- getData: function() {
+ payWithBaseCurrency: function () {
+ var allowedCurrencies = window.checkoutConfig.payment.buckaroo.creditcards.allowedCurrencies;
+
+ return allowedCurrencies.indexOf(this.currencyCode) < 0;
+ },
+
+ getPayWithBaseCurrencyText: function () {
+ var text = $.mage.__('The transaction will be processed using %s.');
+
+ return text.replace('%s', this.baseCurrencyCode);
+ },
+
+ /**
+ * Place order.
+ *
+ * placeOrderAction has been changed from Magento_Checkout/js/action/place-order to our own version
+ * (Buckaroo_Magento2/js/action/place-order) to prevent redirect and handle the response.
+ */
+ placeOrder: function (data, event) {
+ var self = this,
+ placeOrder;
- return {
- "method": this.item.method,
- "po_number": null,
- "additional_data": {
- "customer_encrypteddata": this.encryptedCardData,
- "customer_creditcardcompany": this.service
+ if (event) {
+ event.preventDefault();
}
- }
- },
- selectPaymentMethod: function () {
- window.checkoutConfig.buckarooFee.title(this.paymentFeeLabel);
- selectPaymentMethodAction(this.getData());
- checkoutData.setSelectedPaymentMethod(this.item.method);
- return true;
+ if (this.validate() && additionalValidators.validate()) {
+ this.isPlaceOrderActionAllowed(false);
+ this.encryptCardData().then(function() {
+ placeOrder = placeOrderAction(self.getData(), self.redirectAfterPlaceOrder, self.messageContainer);
+
+ $.when(placeOrder).fail(
+ function () {
+ self.isPlaceOrderActionAllowed(true);
+ }
+ ).done(self.afterPlaceOrder.bind(self));
+ })
+ return true;
+ }
+ return false;
+ },
+
+ afterPlaceOrder: function () {
+ var response = window.checkoutConfig.payment.buckaroo.response;
+ checkoutCommon.redirectHandle(response);
+ },
+
+ getData: function() {
+ let cardIssuer = this.cardIssuer();
+
+ if(cardIssuer == null) {
+ cardIssuer = this.determineIssuer(this.cardNumber());
+ }
+ return {
+ "method": this.item.method,
+ "po_number": null,
+ "additional_data": {
+ "customer_encrypteddata" : this.encryptedCardData,
+ "customer_creditcardcompany" : cardIssuer
+ }
+ }
+ },
+
+ encryptCardData: function () {
+ return new Promise(function(resolve) {
+ const parts = this.expireDate().split("/");
+ const month = parts[0];
+ const year = parts[1];
+
+ BuckarooClientSideEncryption.V001.encryptCardData(
+ this.cardNumber(),
+ year,
+ month,
+ this.cvc(),
+ this.cardHolderName(),
+ function(encryptedCardData) {
+ this.encryptedCardData = encryptedCardData;
+ resolve()
+ }.bind(this));
+ }.bind(this))
+ },
+ setTestParameters() {
+ if (this.isTestMode) {
+ this.cardNumber('4563550000000005')
+ this.cardIssuer('visa')
+ this.cardHolderName('Test Acceptation')
+ this.expireDate('01/' + (new Date(new Date().setFullYear(new Date().getFullYear() + 1)).getFullYear().toString().substr(-2)))
+ this.cvc('123')
+ }
+ }
}
- });
+ );
}
);
diff --git a/view/frontend/web/template/payment/buckaroo_magento2_creditcard.html b/view/frontend/web/template/payment/buckaroo_magento2_creditcard.html
new file mode 100644
index 000000000..951818c1e
--- /dev/null
+++ b/view/frontend/web/template/payment/buckaroo_magento2_creditcard.html
@@ -0,0 +1,168 @@
+
+
+
+
+
+
+
![]()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
![]()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/view/frontend/web/template/payment/buckaroo_magento2_creditcards.html b/view/frontend/web/template/payment/buckaroo_magento2_creditcards.html
index 7bc7be80f..8ec957306 100644
--- a/view/frontend/web/template/payment/buckaroo_magento2_creditcards.html
+++ b/view/frontend/web/template/payment/buckaroo_magento2_creditcards.html
@@ -6,15 +6,15 @@
name="payment[method]"
class="radio"
data-bind="attr: {'id': getCode()}, value: getCode(), checked: isChecked, click: selectPaymentMethod, visible: isRadioButtonVisible()"/>
-