Commit 1bd1e08e authored by rikterbeek's avatar rikterbeek

Fix validation for creditcard, added directory lookup to HPP payment method

parent d479ed1f
...@@ -52,12 +52,12 @@ class AbstractInfo extends \Magento\Payment\Block\Info ...@@ -52,12 +52,12 @@ class AbstractInfo extends \Magento\Payment\Block\Info
public function getAdyenPspReference() public function getAdyenPspReference()
{ {
return $this->getMethod()->getInfoInstance()->getAdyenPspReference(); return $this->getInfo()->getAdyenPspReference();
} }
public function isDemoMode() public function isDemoMode()
{ {
$storeId = $this->getMethod()->getInfoInstance()->getOrder()->getStoreId(); $storeId = $this->getInfo()->getOrder()->getStoreId();
return $this->_adyenHelper->getAdyenAbstractConfigDataFlag('demo_mode', $storeId); return $this->_adyenHelper->getAdyenAbstractConfigDataFlag('demo_mode', $storeId);
} }
......
...@@ -75,6 +75,7 @@ class Redirect extends \Magento\Payment\Block\Form ...@@ -75,6 +75,7 @@ class Redirect extends \Magento\Payment\Block\Form
} }
} catch(Exception $e) { } catch(Exception $e) {
// do nothing for now // do nothing for now
throw($e);
} }
return $result; return $result;
......
...@@ -25,15 +25,50 @@ namespace Adyen\Payment\Model; ...@@ -25,15 +25,50 @@ namespace Adyen\Payment\Model;
use Magento\Checkout\Model\ConfigProviderInterface; use Magento\Checkout\Model\ConfigProviderInterface;
use Magento\Payment\Helper\Data as PaymentHelper; use Magento\Payment\Helper\Data as PaymentHelper;
use Magento\Directory\Helper\Data;
class AdyenHppConfigProvider implements ConfigProviderInterface class AdyenHppConfigProvider implements ConfigProviderInterface
{ {
/**
* @var \Magento\Framework\App\State
*/
protected $_appState;
/**
* @var \Magento\Checkout\Model\Session
*/
protected $_session;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $_storeManager;
/**
* @var PaymentHelper
*/
protected $_paymentHelper;
/**
* @var \Magento\Framework\Locale\ResolverInterface
*/
protected $_localeResolver;
/**
* @var \Adyen\Payment\Helper\Data
*/
protected $_adyenHelper;
/**
* @var \Adyen\Payment\Logger\AdyenLogger
*/
protected $_adyenLogger;
/** /**
* @var Config * @var \Magento\Framework\App\Config\ScopeConfigInterface $config
*/ */
protected $config; protected $_config;
/** /**
* @var string[] * @var string[]
...@@ -48,20 +83,33 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -48,20 +83,33 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
protected $methods = []; protected $methods = [];
/** /**
* @var PaymentHelper * @param \Magento\Framework\Model\Context $context
*/ * @param \Magento\Checkout\Model\Session $session
protected $paymentHelper; * @param \Magento\Store\Model\StoreManagerInterface $storeManager
/**
* @param PaymentHelper $paymentHelper * @param PaymentHelper $paymentHelper
* @param \Adyen\Payment\Helper\Data $adyenHelper
*/ */
public function __construct( public function __construct(
PaymentHelper $paymentHelper \Magento\Framework\Model\Context $context,
\Magento\Checkout\Model\Session $session,
\Magento\Store\Model\StoreManagerInterface $storeManager,
PaymentHelper $paymentHelper,
\Magento\Framework\Locale\ResolverInterface $localeResolver,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Adyen\Payment\Helper\Data $adyenHelper,
\Adyen\Payment\Logger\AdyenLogger $adyenLogger
) { ) {
$this->paymentHelper = $paymentHelper; $this->_appState = $context->getAppState();
$this->_session = $session;
$this->_storeManager = $storeManager;
$this->_paymentHelper = $paymentHelper;
$this->_localeResolver = $localeResolver;
$this->_config = $config;
$this->_adyenHelper = $adyenHelper;
$this->_adyenLogger = $adyenLogger;
foreach ($this->methodCodes as $code) { foreach ($this->methodCodes as $code) {
$this->methods[$code] = $this->paymentHelper->getMethodInstance($code); $this->methods[$code] = $this->_paymentHelper->getMethodInstance($code);
} }
} }
...@@ -77,8 +125,16 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -77,8 +125,16 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
foreach ($this->methodCodes as $code) { foreach ($this->methodCodes as $code) {
if ($this->methods[$code]->isAvailable()) { if ($this->methods[$code]->isAvailable()) {
$config['payment']['adyenHpp']['redirectUrl'][$code] = $this->getMethodRedirectUrl($code); $config['payment']['adyenHpp']['redirectUrl'][$code] = $this->getMethodRedirectUrl($code);
// get payment methods
// print_r($this->getAdyenHppPaymentMethods());die();
$config['payment'] ['adyenHpp']['paymentMethods'] = $this->getAdyenHppPaymentMethods();
} }
} }
$paymentMethodSelectionOnAdyen = $this->_adyenHelper->getAdyenHppConfigDataFlag('payment_selection_on_adyen');
$config['payment'] ['adyenHpp']['isPaymentMethodSelectionOnAdyen'] = $paymentMethodSelectionOnAdyen;
return $config; return $config;
} }
...@@ -93,4 +149,244 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -93,4 +149,244 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
return $this->methods[$code]->getCheckoutRedirectUrl(); return $this->methods[$code]->getCheckoutRedirectUrl();
} }
public function getAdyenHppPaymentMethods()
{
$paymentMethods = null;
// is admin?
if ($this->_appState->getAreaCode() === \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE) {
//retrieve storeId from quote
$store = $this->_session->getQuote()->getStore();
} else {
$store = $this->_storeManager->getStore();
}
// is adyen HPP enabled ?
$hppActive = $this->methods['adyen_hpp']->isAvailable();
if($hppActive) {
$paymentMethods = $this->_addHppMethodsToConfig($store);
}
return $paymentMethods;
}
protected function _addHppMethodsToConfig($store)
{
$paymentMethods = [];
foreach ($this->_fetchHppMethods($store) as $methodCode => $methodData) {
$paymentMethods[$methodCode] = $methodData;
}
return $paymentMethods;
}
protected function _fetchHppMethods($store)
{
$skinCode = $this->_adyenHelper->getAdyenHppConfigData('skin_code');
$merchantAccount = $this->_adyenHelper->getAdyenAbstractConfigData('merchant_account');
if (!$skinCode || !$merchantAccount) {
return array();
}
$adyFields = array(
"paymentAmount" => (int) $this->_adyenHelper->formatAmount($this->_getCurrentPaymentAmount(), $this->_getCurrentCurrencyCode($store)),
"currencyCode" => $this->_getCurrentCurrencyCode($store),
"merchantReference" => "Get Payment methods",
"skinCode" => $skinCode,
"merchantAccount" => $merchantAccount,
"sessionValidity" => date(
DATE_ATOM,
mktime(date("H") + 1, date("i"), date("s"), date("m"), date("j"), date("Y"))
),
"countryCode" => $this->_getCurrentCountryCode($store),
"shopperLocale" => $this->_getCurrentLocaleCode($store)
);
$responseData = $this->_getDirectoryLookupResponse($adyFields, $store);
$paymentMethods = array();
if(isset($responseData['paymentMethods'])) {
foreach ($responseData['paymentMethods'] as $paymentMethod) {
// TODO: validate if brancode and title exists
$paymentMethod = $this->_fieldMapPaymentMethod($paymentMethod);
$paymentMethodCode = $paymentMethod['brandCode'];
$paymentMethod = $this->_fieldMapPaymentMethod($paymentMethod);
// TODO: IMPLEMENT SKIP CARDS if adyen cc is enabled
$paymentMethods[$paymentMethodCode] = $paymentMethod;
}
}
return $paymentMethods;
}
/**
* @return bool|int
*/
protected function _getCurrentPaymentAmount()
{
if (($grandTotal = $this->_getQuote()->getGrandTotal()) > 0) {
return $grandTotal;
}
return 10;
}
/**
* @return string
*/
protected function _getCurrentCurrencyCode($store)
{
return $this->_getQuote()->getQuoteCurrencyCode() ?: $store->getBaseCurrencyCode();
}
/**
* @return string
*/
protected function _getCurrentCountryCode($store)
{
// if fixed countryCode is setup in config use this
$countryCode = $this->_adyenHelper->getAdyenHppConfigData('country_code', $store->getId());
if($countryCode != "") {
return $countryCode;
}
if ($country = $this->_getQuote()->getBillingAddress()->getCountry()) {
return $country;
}
$defaultCountry = $this->_config->getValue(
\Magento\Tax\Model\Config::CONFIG_XML_PATH_DEFAULT_COUNTRY,
\Magento\Store\Model\ScopeInterface::SCOPE_STORES,
$store->getCode()
);
if($defaultCountry) {
return $defaultCountry;
}
}
/**
* @return string
*/
protected function _getCurrentLocaleCode($store)
{
$localeCode = $this->_adyenHelper->getAdyenAbstractConfigData('shopper_locale', $store->getId());
if($localeCode != "") {
return $localeCode;
}
$locale = $this->_localeResolver->getLocale();
if($locale) {
return $locale;
}
// should have the vulue if not fall back to default
$localeCode = $this->_config->getValue(
Data::XML_PATH_DEFAULT_LOCALE,
\Magento\Store\Model\ScopeInterface::SCOPE_STORES,
$store->getCode()
);
return $localeCode;
}
protected $_fieldMapPaymentMethod = array(
'name' => 'title'
);
protected function _fieldMapPaymentMethod($paymentMethod)
{
foreach ($this->_fieldMapPaymentMethod as $field => $newField) {
if (isset($paymentMethod[$field])) {
$paymentMethod[$newField] = $paymentMethod[$field];
unset($paymentMethod[$field]);
}
}
return $paymentMethod;
}
protected function _getDirectoryLookupResponse($requestParams, $store)
{
$cacheKey = $this->_getCacheKeyForRequest($requestParams, $store);
if (! $hmacKey = $this->_adyenHelper->getHmac()) {
// TODO THROW ADYEN EXEPTION
}
// initialize the adyen client
$client = new \Adyen\Client();
if($this->_adyenHelper->isDemoMode()) {
$client->setModus("test");
} else {
$client->setModus("live");
}
// connect to magento log
$client->setLogger($this->_adyenLogger);
// create and add signature
$requestParams["merchantSig"] = \Adyen\Util\Util::calculateSha256Signature($hmacKey, $requestParams);
// print_R($requestParams);die();
// intialize service
$service = new \Adyen\Service\DirectoryLookup($client);
try {
$responseData = $service->directoryLookup($requestParams);
}catch (Exception $e) {
$this->_adyenLogger->error("The Directory Lookup response is empty check your Adyen configuration in Magento.");
// return empty result
return array();
}
// save result in cache
// Mage::app()->getCache()->save(
// serialize($responseData),
// $cacheKey,
// array(Mage_Core_Model_Config::CACHE_TAG),
// 60 * 60 * 6
// );
return $responseData;
}
protected $_cacheParams = array(
'currencyCode',
'merchantReference',
'skinCode',
'merchantAccount',
'countryCode',
'shopperLocale',
);
protected function _getCacheKeyForRequest($requestParams, $store)
{
$cacheParams = array();
$cacheParams['store'] = $store->getId();
foreach ($this->_cacheParams as $paramKey) {
if (isset($requestParams[$paramKey])) {
$cacheParams[$paramKey] = $requestParams[$paramKey];
}
}
return md5(implode('|', $cacheParams));
}
protected function _getQuote()
{
return $this->_session->getQuote();
}
} }
\ No newline at end of file
...@@ -27,7 +27,6 @@ use Magento\Framework\DataObject; ...@@ -27,7 +27,6 @@ use Magento\Framework\DataObject;
use Magento\Payment\Model\Method\ConfigInterface; use Magento\Payment\Model\Method\ConfigInterface;
use Magento\Payment\Model\Method\Online\GatewayInterface; use Magento\Payment\Model\Method\Online\GatewayInterface;
/** /**
* @method \Magento\Quote\Api\Data\PaymentMethodExtensionInterface getExtensionAttributes()
* @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/ */
class AdyenAbstract extends \Magento\Payment\Model\Method\AbstractMethod implements GatewayInterface class AdyenAbstract extends \Magento\Payment\Model\Method\AbstractMethod implements GatewayInterface
......
...@@ -23,6 +23,12 @@ ...@@ -23,6 +23,12 @@
namespace Adyen\Payment\Model\Method; namespace Adyen\Payment\Model\Method;
/**
* Adyen CreditCard payment method
* @SuppressWarnings(PHPMD.ExcessivePublicCount)
* @SuppressWarnings(PHPMD.TooManyFields)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Cc extends \Magento\Payment\Model\Method\Cc class Cc extends \Magento\Payment\Model\Method\Cc
{ {
...@@ -256,7 +262,7 @@ class Cc extends \Magento\Payment\Model\Method\Cc ...@@ -256,7 +262,7 @@ class Cc extends \Magento\Payment\Model\Method\Cc
if ($errorMsg) { if ($errorMsg) {
$this->_logger->critical($errorMsg); $this->_logger->critical($errorMsg);
throw new \Magento\Framework\Exception\LocalizedException($errorMsg); throw new \Magento\Framework\Exception\LocalizedException(__($errorMsg));
} }
break; break;
} }
......
...@@ -28,7 +28,8 @@ use Magento\Payment\Model\Method\ConfigInterface; ...@@ -28,7 +28,8 @@ use Magento\Payment\Model\Method\ConfigInterface;
use Magento\Payment\Model\Method\Online\GatewayInterface; use Magento\Payment\Model\Method\Online\GatewayInterface;
/** /**
* @method \Magento\Quote\Api\Data\PaymentMethodExtensionInterface getExtensionAttributes() * @SuppressWarnings(PHPMD.ExcessivePublicCount)
* @SuppressWarnings(PHPMD.TooManyFields)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects) * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/ */
class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements GatewayInterface class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements GatewayInterface
...@@ -159,6 +160,31 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -159,6 +160,31 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
$stateObject->setStatus($this->_adyenHelper->getAdyenAbstractConfigData('order_status')); $stateObject->setStatus($this->_adyenHelper->getAdyenAbstractConfigData('order_status'));
} }
/**
* Assign data to info model instance
*
* @param \Magento\Framework\DataObject|mixed $data
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function assignData(\Magento\Framework\DataObject $data)
{
parent::assignData($data);
$infoInstance = $this->getInfoInstance();
if(isset($data['brand_code'])) {
$infoInstance->setAdditionalInformation('brand_code', $data['brand_code']);
}
if(isset($data['issuer_id'])) {
$infoInstance->setAdditionalInformation('issuer_id', $data['issuer_id']);
}
$this->_adyenLogger->info(print_r($data,1));
return $this;
}
/** /**
* Checkout redirect URL getter for onepage checkout (hardcode) * Checkout redirect URL getter for onepage checkout (hardcode)
* *
...@@ -190,11 +216,9 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -190,11 +216,9 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
/** /**
* @desc Get url of Adyen payment * @desc Get url of Adyen payment
* @return string * @return string
* @todo add brandCode here
*/ */
public function getFormUrl() public function getFormUrl()
{ {
// $brandCode = $this->getInfoInstance()->getCcType();
$paymentRoutine = $this->getConfigData('payment_routine'); $paymentRoutine = $this->getConfigData('payment_routine');
switch ($this->_adyenHelper->isDemoMode()) { switch ($this->_adyenHelper->isDemoMode()) {
...@@ -217,15 +241,7 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -217,15 +241,7 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
} }
break; break;
} }
//IDEAL
// $idealBankUrl = false;
// $bankData = $this->getInfoInstance()->getPoNumber();
// if ($brandCode == 'ideal' && !empty($bankData)) {
// $idealBankUrl = ($isConfigDemoMode == true)
// ? 'https://test.adyen.com/hpp/redirectIdeal.shtml'
// : 'https://live.adyen.com/hpp/redirectIdeal.shtml';
// }
// return (!empty($idealBankUrl)) ? $idealBankUrl : $url;
return $url; return $url;
} }
...@@ -257,7 +273,6 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -257,7 +273,6 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
} }
} }
$formFields = array(); $formFields = array();
$formFields['merchantAccount'] = $merchantAccount; $formFields['merchantAccount'] = $merchantAccount;
...@@ -291,11 +306,16 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -291,11 +306,16 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
$hmacKey = $this->_adyenHelper->getHmac(); $hmacKey = $this->_adyenHelper->getHmac();
$brandCode = $this->getInfoInstance()->getCcType(); $brandCode = $order->getPayment()->getAdditionalInformation("brand_code");
if($brandCode) { if($brandCode) {
$formFields['brandCode'] = $brandCode; $formFields['brandCode'] = $brandCode;
} }
$issuerId = $order->getPayment()->getAdditionalInformation("issuer_id");
if($issuerId) {
$formFields['issuerId'] = $issuerId;
}
// Sort the array by key using SORT_STRING order // Sort the array by key using SORT_STRING order
ksort($formFields, SORT_STRING); ksort($formFields, SORT_STRING);
......
...@@ -32,7 +32,7 @@ ...@@ -32,7 +32,7 @@
<fieldset_css>adyen-method-adyen-cc</fieldset_css> <fieldset_css>adyen-method-adyen-cc</fieldset_css>
<comment>Process creditcard payments inside your checkout.</comment> <comment>Process creditcard payments inside your checkout.</comment>
<field id="active" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="0"> <field id="active" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Enabled</label> <label>Enabled</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model> <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<config_path>payment/adyen_cc/active</config_path> <config_path>payment/adyen_cc/active</config_path>
......
...@@ -32,7 +32,7 @@ ...@@ -32,7 +32,7 @@
<fieldset_css>adyen-method-adyen-cc</fieldset_css> <fieldset_css>adyen-method-adyen-cc</fieldset_css>
<comment>Process alternative payments methods</comment> <comment>Process alternative payments methods</comment>
<field id="active" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="0"> <field id="active" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Enabled</label> <label>Enabled</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model> <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<config_path>payment/adyen_hpp/active</config_path> <config_path>payment/adyen_hpp/active</config_path>
...@@ -68,7 +68,7 @@ ...@@ -68,7 +68,7 @@
<label>Advanced Settings</label> <label>Advanced Settings</label>
<frontend_model>Magento\Config\Block\System\Config\Form\Fieldset</frontend_model> <frontend_model>Magento\Config\Block\System\Config\Form\Fieldset</frontend_model>
<field id="payment_selection_on_adyen" translate="label" type="select" sortOrder="70" showInDefault="1" showInWebsite="1" showInStore="0"> <field id="payment_selection_on_adyen" translate="label" type="select" sortOrder="70" showInDefault="1" showInWebsite="1" showInStore="0">
<label>Payment method selection in Adyen</label> <label>Payment method selection on Adyen Hosted Payment Page (HPP)</label>
<tooltip>If you set this to 'Yes', payment methods in the checkout won't be displayed and you will be redirected to the Adyen HPP to make the selection.</tooltip> <tooltip>If you set this to 'Yes', payment methods in the checkout won't be displayed and you will be redirected to the Adyen HPP to make the selection.</tooltip>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model> <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<config_path>payment/adyen_hpp/payment_selection_on_adyen</config_path> <config_path>payment/adyen_hpp/payment_selection_on_adyen</config_path>
......
...@@ -32,15 +32,17 @@ ...@@ -32,15 +32,17 @@
<?php echo $block->escapeHtml($block->getMethod()->getTitle()) ?> <?php echo $block->escapeHtml($block->getMethod()->getTitle()) ?>
<?php <?php
$isDemoMode = $block->isDemoMode(); $_info = $this->getInfo();
$_isDemoMode = $block->isDemoMode();
?> ?>
<?php if ($block->getAdyenPspReference()):?> <?php if ($_pspReference = $_info->getAdditionalInformation('pspReference')):?>
<?php if($isDemoMode): ?> <div>
<div><?php echo __("Adyen PSP Reference: <a href=\"https://ca-test.adyen.com/ca/ca/accounts/showTx.shtml?pspReference=%1&txType=Payment\" target=\"__blank\">%1</a>", $block->escapeHtml($block->getAdyenPspReference())); ?> <?php if($_isDemoMode): ?>
<?php echo __('Adyen PSP Reference: <a href="https://ca-test.adyen.com/ca/ca/accounts/showTx.shtml?pspReference=%1&txType=Payment" target="__blank">%1</a>', $block->escapeHtml($_pspReference), $block->escapeHtml($_pspReference)) ?>
<?php else: ?> <?php else: ?>
<div><?php echo __('Adyen PSP Reference: <a href="https://ca-live.adyen.com/ca/ca/accounts/showTx.shtml?pspReference=%1&txType=Payment" target="__blank">%1</a>', $block->escapeHtml($block->getAdyenPspReference())); ?> <?php echo __('Adyen PSP Reference: <a href="https://ca-live.adyen.com/ca/ca/accounts/showTx.shtml?pspReference=%1&txType=Payment" target="__blank">%1</a>', $block->escapeHtml($_pspReference), $block->escapeHtml($_pspReference)) ?>
<?php endif; ?> <?php endif; ?>
</div> </div>
<?php endif;?> <?php endif;?>
<?php if ($_specificInfo = $block->getSpecificInformation()):?> <?php if ($_specificInfo = $block->getSpecificInformation()):?>
......
...@@ -31,12 +31,24 @@ ...@@ -31,12 +31,24 @@
?> ?>
<?php echo $block->escapeHtml($block->getMethod()->getTitle()) ?> <?php echo $block->escapeHtml($block->getMethod()->getTitle()) ?>
<?php $_info = $this->getInfo(); ?> <?php
<?php if ($_pspReference = $block->getPspReference()):?> $_info = $this->getInfo();
<div><?php echo __('Adyen PSP Reference: <a href="https://ca-test.adyen.com/ca/ca/accounts/showTx.shtml?pspReference=%1&txType=Payment" target="__blank">%1</a>', $block->escapeHtml($_info->getAdditionalInformation('pspReference')), $block->escapeHtml($_info->getAdditionalInformation('pspReference'))) ?> $_isDemoMode = $block->isDemoMode();
?>
<?php if ($_pspReference = $_info->getAdditionalInformation('pspReference')):?>
<div>
<?php if($_isDemoMode): ?>
<?php echo __('Adyen PSP Reference: <a href="https://ca-test.adyen.com/ca/ca/accounts/showTx.shtml?pspReference=%1&txType=Payment" target="__blank">%1</a>', $block->escapeHtml($_pspReference), $block->escapeHtml($_pspReference)) ?>
<?php else: ?>
<?php echo __('Adyen PSP Reference: <a href="https://ca-live.adyen.com/ca/ca/accounts/showTx.shtml?pspReference=%1&txType=Payment" target="__blank">%1</a>', $block->escapeHtml($_pspReference), $block->escapeHtml($_pspReference)) ?>
<?php endif; ?>
</div> </div>
<?php endif;?> <?php endif;?>
<?php if ($_brandCode = $_info->getAdditionalInformation('brand_code')):?>
<div><?php echo __('Payment Method: %1', $_brandCode); ?>
</div>
<?php endif;?>
<?php if ($_specificInfo = $block->getSpecificInformation()):?> <?php if ($_specificInfo = $block->getSpecificInformation()):?>
<table class="data-table admin__table-secondary"> <table class="data-table admin__table-secondary">
......
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
/*jshint browser:true jquery:true*/
/*global alert*/
var config = {
config: {
mixins: {
'Adyen_Payment/js/action/place-order': {
'Magento_CheckoutAgreements/js/model/place-order-mixin': true
}
}
}
};
...@@ -26,15 +26,17 @@ define( ...@@ -26,15 +26,17 @@ define(
'mage/storage', 'mage/storage',
'mage/url', 'mage/url',
'Magento_Checkout/js/model/error-processor', 'Magento_Checkout/js/model/error-processor',
'Magento_Customer/js/model/customer' 'Magento_Customer/js/model/customer',
'Magento_Checkout/js/model/full-screen-loader'
], ],
function (quote, urlBuilder, storage, url, errorProcessor, customer) { function (quote, urlBuilder, storage, url, errorProcessor, customer, fullScreenLoader) {
'use strict'; 'use strict';
return function (paymentData, redirectOnSuccess) { return function (paymentData, redirectOnSuccess) {
var serviceUrl, var serviceUrl,
payload; payload;
//redirectOnSuccess = redirectOnSuccess !== false;
redirectOnSuccess = redirectOnSuccess === false ? false : true; redirectOnSuccess = redirectOnSuccess === false ? false : true;
/** Checkout for guest and registered customer. */ /** Checkout for guest and registered customer. */
...@@ -56,6 +58,9 @@ define( ...@@ -56,6 +58,9 @@ define(
billingAddress: quote.billingAddress() billingAddress: quote.billingAddress()
}; };
} }
fullScreenLoader.startLoader();
return storage.post( return storage.post(
serviceUrl, JSON.stringify(payload) serviceUrl, JSON.stringify(payload)
).done( ).done(
...@@ -67,6 +72,7 @@ define( ...@@ -67,6 +72,7 @@ define(
).fail( ).fail(
function (response) { function (response) {
errorProcessor.process(response); errorProcessor.process(response);
fullScreenLoader.stopLoader();
} }
); );
}; };
......
...@@ -26,46 +26,12 @@ define( ...@@ -26,46 +26,12 @@ define(
'Magento_Checkout/js/model/url-builder', 'Magento_Checkout/js/model/url-builder',
'mage/storage', 'mage/storage',
'Magento_Checkout/js/model/error-processor', 'Magento_Checkout/js/model/error-processor',
'Magento_Customer/js/model/customer' 'Magento_Customer/js/model/customer',
'Magento_Checkout/js/model/full-screen-loader'
], ],
function ($, quote, urlBuilder, storage, errorProcessor, customer) { function ($, quote, urlBuilder, storage, errorProcessor, customer, fullScreenLoader) {
'use strict'; 'use strict';
var agreementsConfig = window.checkoutConfig.checkoutAgreements;
//return function () {
// var serviceUrl,
// payload,
// paymentData = quote.paymentMethod();
//
// /**
// * Checkout for guest and registered customer.
// */
// if (!customer.isLoggedIn()) {
// serviceUrl = urlBuilder.createUrl('/guest-carts/:cartId/selected-payment-method', {
// cartId: quote.getQuoteId()
// });
// payload = {
// cartId: quote.getQuoteId(),
// method: paymentData
// };
// } else {
// serviceUrl = urlBuilder.createUrl('/carts/mine/selected-payment-method', {});
// payload = {
// cartId: quote.getQuoteId(),
// method: paymentData
// };
// }
// return storage.put(
// serviceUrl, JSON.stringify(payload)
// ).done(
// function () {
// $.mage.redirect(window.checkoutConfig.payment.adyenHpp.redirectUrl[quote.paymentMethod().method]);
// }
// ).fail(
// function (response) {
// errorProcessor.process(response);
// }
// );
//};
return function () { return function () {
...@@ -73,6 +39,21 @@ define( ...@@ -73,6 +39,21 @@ define(
payload, payload,
paymentData = quote.paymentMethod(); paymentData = quote.paymentMethod();
// check if agreement is enabled if so add it to payload
if (agreementsConfig.isEnabled) {
var agreementForm = $('.payment-method._active form[data-role=checkout-agreements]'),
agreementData = agreementForm.serializeArray(),
agreementIds = [];
agreementData.forEach(function(item) {
agreementIds.push(item.value);
});
paymentData.extension_attributes = {agreement_ids: agreementIds};
}
/** Checkout for guest and registered customer. */ /** Checkout for guest and registered customer. */
if (!customer.isLoggedIn()) { if (!customer.isLoggedIn()) {
serviceUrl = urlBuilder.createUrl('/guest-carts/:quoteId/payment-information', { serviceUrl = urlBuilder.createUrl('/guest-carts/:quoteId/payment-information', {
...@@ -92,6 +73,10 @@ define( ...@@ -92,6 +73,10 @@ define(
billingAddress: quote.billingAddress() billingAddress: quote.billingAddress()
}; };
} }
fullScreenLoader.startLoader();
return storage.post( return storage.post(
serviceUrl, JSON.stringify(payload) serviceUrl, JSON.stringify(payload)
).done( ).done(
...@@ -101,6 +86,7 @@ define( ...@@ -101,6 +86,7 @@ define(
).fail( ).fail(
function (response) { function (response) {
errorProcessor.process(response); errorProcessor.process(response);
fullScreenLoader.stopLoader();
} }
); );
}; };
......
...@@ -26,15 +26,18 @@ define( ...@@ -26,15 +26,18 @@ define(
'underscore', 'underscore',
'jquery', 'jquery',
'Magento_Payment/js/view/payment/cc-form', 'Magento_Payment/js/view/payment/cc-form',
'Magento_Checkout/js/action/set-payment-information',
'Adyen_Payment/js/action/place-order', 'Adyen_Payment/js/action/place-order',
'mage/translate', 'mage/translate',
'Magento_Checkout/js/model/payment/additional-validators', 'Magento_Checkout/js/model/payment/additional-validators',
'Magento_Checkout/js/model/full-screen-loader', 'Adyen_Payment/js/view/payment/adyen-encrypt'
'Adyen_Payment/js/view/payment/adyen-encrypt',
], ],
function (_, $, Component, setPaymentInformationAction, placeOrderAction, $t, additionalValidators, fullScreenLoader) { function (_, $, Component, placeOrderAction, $t, additionalValidators) {
'use strict'; 'use strict';
$.validator.addMethod(
'validate-custom-required', function (value) {
return (value === 'test'); // Validation logic here
}, $.mage.__('Enter This is a required field custom.')
);
return Component.extend({ return Component.extend({
defaults: { defaults: {
template: 'Adyen_Payment/payment/cc-form', template: 'Adyen_Payment/payment/cc-form',
...@@ -58,29 +61,6 @@ define( ...@@ -58,29 +61,6 @@ define(
]); ]);
return this; return this;
}, },
initialize: function() {
var self = this;
this._super();
// when creditCarNumber change call encrypt function
this.creditCardNumber.subscribe(function(value) {
self.calculateCseKey();
});
this.creditCardOwner.subscribe(function(value) {
self.calculateCseKey();
});
//this.creditCardExpMonth.subscribe(function(value) {
// self.calculateCseKey();
//});
//this.creditCardExpYear.subscribe(function(value) {
// self.calculateCseKey();
//});
this.creditCardVerificationNumber.subscribe(function(value) {
self.calculateCseKey();
});
},
placeOrderHandler: null, placeOrderHandler: null,
validateHandler: null, validateHandler: null,
setPlaceOrderHandler: function(handler) { setPlaceOrderHandler: function(handler) {
...@@ -115,17 +95,17 @@ define( ...@@ -115,17 +95,17 @@ define(
/** /**
* @override * @override
*/ */
placeOrder: function() { placeOrder: function(data, event) {
var self = this; var self = this,
placeOrder;
if (event) {
event.preventDefault();
}
//var cse_form = $("adyen-cc-form"); //var cse_form = $("adyen-cc-form");
var cse_form = document.getElementById('adyen-cc-form'); var cse_form = document.getElementById('adyen-cc-form');
var cse_key = this.getCSEKey(); var cse_key = this.getCSEKey();
//var cse_options = {
// name: 'payment[encrypted_data]',
// enableValidations: true,
// submitButtonAlwaysEnabled: true
//};
var options = {}; var options = {};
var cseInstance = adyen.encrypt.createEncryption(cse_key, options); var cseInstance = adyen.encrypt.createEncryption(cse_key, options);
...@@ -143,26 +123,16 @@ define( ...@@ -143,26 +123,16 @@ define(
var data = cseInstance.encrypt(cardData); var data = cseInstance.encrypt(cardData);
self.encryptedData(data); self.encryptedData(data);
// loading icon if (this.validate() && additionalValidators.validate()) {
fullScreenLoader.startLoader(); this.isPlaceOrderActionAllowed(false);
placeOrder = placeOrderAction(this.getData(), this.redirectAfterPlaceOrder);
var placeOrder = placeOrderAction(this.getData(), this.redirectAfterPlaceOrder); $.when(placeOrder).fail(function(response) {
$.when(placeOrder).fail(function(){
self.isPlaceOrderActionAllowed(true); self.isPlaceOrderActionAllowed(true);
fullScreenLoader.stopLoader();
}); });
//return true; return true;
// }
//if (this.validateHandler()) { return false;
// this.isPlaceOrderActionAllowed(false);
// $.when(setPaymentInformationAction()).done(function() {
// self.placeOrderHandler();
// }).fail(function() {
// self.isPlaceOrderActionAllowed(true);
// });
//}
}, },
getControllerName: function() { getControllerName: function() {
return window.checkoutConfig.payment.iframe.controllerName[this.getCode()]; return window.checkoutConfig.payment.iframe.controllerName[this.getCode()];
...@@ -185,22 +155,22 @@ define( ...@@ -185,22 +155,22 @@ define(
isShowLegend: function() { isShowLegend: function() {
return true; return true;
}, },
calculateCseKey: function() { validate: function () {
var form = 'form[data-role=adyen-cc-form]';
//
////var cse_form = $("adyen-cc-form");
//var cse_form = document.getElementById('adyen-cc-form');
//var cse_key = this.getCSEKey();
//var cse_options = {
// name: 'payment[encrypted_data]',
// enableValidations: true, // disable because month needs to be 01 isntead of 1
// //submitButtonAlwaysEnabled: true
//};
//
//var result = adyen.encrypt.createEncryptedForm(cse_form, cse_key, cse_options);
var validate = $(form).validation() && $(form).validation('isValid');
// add extra validation because jqeury validation will not work on non name attributes
var ccNumber = Boolean($(form + ' #adyen_cc_cc_number').valid());
var owner = Boolean($(form + ' #adyen_cc_cc_owner').valid());
var expiration = Boolean($(form + ' #adyen_cc_expiration').valid());
var expiration_yr = Boolean($(form + ' #adyen_cc_expiration_yr').valid());
var $cid = Boolean($(form + ' #adyen_cc_cc_cid').valid());
if(!validate || !ccNumber || !owner || !expiration || !expiration_yr || !$cid) {
return false;
}
return true;
} }
}); });
} }
......
...@@ -23,15 +23,33 @@ ...@@ -23,15 +23,33 @@
/*global define*/ /*global define*/
define( define(
[ [
'ko',
'jquery', 'jquery',
'Magento_Checkout/js/view/payment/default', 'Magento_Checkout/js/view/payment/default',
'Adyen_Payment/js/action/set-payment-method' 'Adyen_Payment/js/action/set-payment-method',
'Magento_Checkout/js/action/select-payment-method',
'Magento_Checkout/js/model/quote',
'Magento_Checkout/js/checkout-data',
'Magento_Checkout/js/model/full-screen-loader',
], ],
function ($, Component, setPaymentMethodAction) { function (ko, $, Component, setPaymentMethodAction, selectPaymentMethodAction,quote, checkoutData, fullScreenLoader) {
'use strict'; 'use strict';
var brandCode = ko.observable(null);
var paymentMethod = ko.observable(null);
return Component.extend({ return Component.extend({
self: this,
defaults: { defaults: {
template: 'Adyen_Payment/payment/hpp-form' template: 'Adyen_Payment/payment/hpp-form',
brandCode: ''
},
initObservable: function () {
this._super()
.observe([
'brandCode',
'issuerId'
]);
return this;
}, },
/** Redirect to adyen */ /** Redirect to adyen */
continueToAdyen: function () { continueToAdyen: function () {
...@@ -39,6 +57,102 @@ define( ...@@ -39,6 +57,102 @@ define(
this.selectPaymentMethod(); this.selectPaymentMethod();
setPaymentMethodAction(); setPaymentMethodAction();
return false; return false;
},
continueToAdyenBrandCode: function() {
// set payment method to adyen_hpp
var self = this;
// for ideal add brand_code in request
if(brandCode() == "ideal") {
var data = {
"method": self.method,
"po_number": null,
"additional_data": {
issuer_id: this.issuerId(),
brand_code: self.value
}
};
} else {
var data = {
"method": self.method,
"po_number": null,
"additional_data": {
brand_code: self.value
}
};
}
selectPaymentMethodAction(data);
setPaymentMethodAction();
return false;
},
getAdyenHppPaymentMethods: function() {
var self = this;
// convert to list so you can iterate
var paymentList = _.map(window.checkoutConfig.payment.adyenHpp.paymentMethods, function(value, key) {
if(key == "ideal") {
return {
'value': key,
'name': value,
'method': self.item.method,
'issuerIds': value.issuers,
'issuerId': ko.observable(null),
getCode: function() {
return self.item.method;
}
}
} else {
return {
'value': key,
'name': value,
'method': self.item.method,
getCode: function() {
return self.item.method;
}
}
}
}
);
return paymentList;
},
selectPaymentMethodBrandCode: function() {
var self = this;
// set payment method to adyen_hpp
var data = {
"method": self.method,
"po_number": null,
"additional_data": {
//brand_code: this.brandCode()
brand_code: self.value,
}
};
// set the brandCode
brandCode(self.value);
// set payment method
paymentMethod(self.method);
selectPaymentMethodAction(data);
checkoutData.setSelectedPaymentMethod(self.method);
return true;
},
isBrandCodeChecked: ko.computed(function () {
if(!quote.paymentMethod()) {
return null;
}
if(quote.paymentMethod().method == paymentMethod()) {
return brandCode();
}
return null;
}),
isPaymentMethodSelectionOnAdyen: function() {
return window.checkoutConfig.payment.adyenHpp.isPaymentMethodSelectionOnAdyen;
} }
}); });
} }
......
...@@ -39,7 +39,7 @@ ...@@ -39,7 +39,7 @@
<form class="form" id="adyen-cc-form" action="#" method="post" data-bind="mageInit: { <form class="form" id="adyen-cc-form" data-role="adyen-cc-form" action="#" method="post" data-bind="mageInit: {
'transparent':{ 'transparent':{
'context': context(), 'context': context(),
'controller': getControllerName(), 'controller': getControllerName(),
...@@ -94,7 +94,7 @@ ...@@ -94,7 +94,7 @@
id: getCode() + '_cc_number', id: getCode() + '_cc_number',
title: $t('Credit Card Number'), title: $t('Credit Card Number'),
'data-container': getCode() + '-cc-number', 'data-container': getCode() + '-cc-number',
'data-validate': JSON.stringify({'required-number':true, 'validate-card-number':'#' + getCode() + '_cc_type', 'validate-cc-type':'#' + getCode() + '_cc_type'})}, 'data-validate': JSON.stringify({'required-number':true, 'validate-card-type':getCcAvailableTypesValues(), 'validate-card-number':'#' + getCode() + '_cc_type', 'validate-cc-type':'#' + getCode() + '_cc_type'})},
enable: isActive($parents), enable: isActive($parents),
value: creditCardNumber, value: creditCardNumber,
valueUpdate: 'keyup' "/> valueUpdate: 'keyup' "/>
...@@ -106,12 +106,19 @@ ...@@ -106,12 +106,19 @@
</label> </label>
<div class="control"> <div class="control">
<input type="text" <input type="text"
class="input-text" class="input-text required-entry"
value=""
data-encrypted-name="holderName" data-encrypted-name="holderName"
data-bind="attr: {id: getCode() + '_cc_owner', 'data-container': getCode() + '-cc-owner'}, value=""
data-bind="attr: {
id: getCode() + '_cc_owner',
title: $t('Credit Card Owner'),
'data-container': getCode() + '-cc-owner'
},
enable: isActive($parents), enable: isActive($parents),
value: creditCardOwner"> value: creditCardOwner,
valueUpdate: 'keyup' "
data-validate="{required:true}"
/>
</div> </div>
</div> </div>
<div class="field date required" data-bind="attr: {id: getCode() + '_cc_type_exp_div'}"> <div class="field date required" data-bind="attr: {id: getCode() + '_cc_type_exp_div'}">
...@@ -130,7 +137,8 @@ ...@@ -130,7 +137,8 @@
optionsValue: 'value', optionsValue: 'value',
optionsText: 'month', optionsText: 'month',
optionsCaption: $t('Month'), optionsCaption: $t('Month'),
value: creditCardExpMonth"> value: creditCardExpMonth"
data-validate="{required:true}">
</select> </select>
</div> </div>
</div> </div>
...@@ -144,7 +152,8 @@ ...@@ -144,7 +152,8 @@
optionsValue: 'value', optionsValue: 'value',
optionsText: 'year', optionsText: 'year',
optionsCaption: $t('Year'), optionsCaption: $t('Year'),
value: creditCardExpYear"> value: creditCardExpYear"
data-validate="{required:true}">
</select> </select>
</div> </div>
</div> </div>
...@@ -167,7 +176,8 @@ ...@@ -167,7 +176,8 @@
'data-container': getCode() + '-cc-cvv', 'data-container': getCode() + '-cc-cvv',
'data-validate': JSON.stringify({'required-number':true, 'validate-card-cvv':'#' + getCode() + '_cc_type'})}, 'data-validate': JSON.stringify({'required-number':true, 'validate-card-cvv':'#' + getCode() + '_cc_type'})},
enable: isActive($parents), enable: isActive($parents),
value: creditCardVerificationNumber" /> value: creditCardVerificationNumber"
data-validate="{required:true}"/>
<div class="field-tooltip toggle"> <div class="field-tooltip toggle">
<span class="field-tooltip-action action-cvv" <span class="field-tooltip-action action-cvv"
tabindex="0" tabindex="0"
......
...@@ -21,7 +21,72 @@ ...@@ -21,7 +21,72 @@
* Author: Adyen <magento@adyen.com> * Author: Adyen <magento@adyen.com>
*/ */
--> -->
<div class="payment-method" data-bind="css: {'_active': (getCode() == isChecked())}">
<!-- ko ifnot: (isPaymentMethodSelectionOnAdyen())-->
<!-- ko foreach: getAdyenHppPaymentMethods() -->
<div class="payment-method" data-bind="css: {'_active': (value == $parent.isBrandCodeChecked())}">
<div class="payment-method-title field choice">
<input type="radio"
name="payment[method]"
class="radio"
data-bind="attr: {'id': value}, value: value, checked: $parent.isBrandCodeChecked, click: $parent.selectPaymentMethodBrandCode"/>
<label data-bind="attr: {'for': value}" class="label"><span data-bind="text: name.title"></span></label>
</div>
<div class="payment-method-content">
<div class="payment-method-billing-address">
<!-- ko foreach: $parents[1].getRegion($parent.getBillingAddressFormName()) -->
<!-- ko template: getTemplate() --><!-- /ko -->
<!--/ko-->
</div>
<fieldset class="fieldset" data-bind='attr: {id: "payment_form_" + $parent.getCode() + "_" + value}'>
<div class="payment-method-note">
<!-- ko if: value == 'ideal' -->
<label data-bind="attr: {'for': 'issuerId'}" class="label">
<span><!-- ko text: $t('Select Your Bank') --><!-- /ko --></span>
</label>
<select name="payment[issuer_id]" data-bind="
options: name.issuers,
optionsText: 'name',
optionsValue: 'issuerId',
value: issuerId,
optionsCaption: $t('Choose Your Bank')">
</select>
<!--/ko-->
</div>
</fieldset>
<div class="checkout-agreements-block">
<!-- ko foreach: $parents[1].getRegion('before-place-order') -->
<!-- ko template: getTemplate() --><!-- /ko -->
<!--/ko-->
</div>
<div class="actions-toolbar">
<div class="primary">
<button class="action primary checkout"
type="submit"
data-bind="click: $parent.continueToAdyenBrandCode, enable: (value == $parent.isBrandCodeChecked())"
disabled>
<span data-bind="text: $t('Place order')"></span>
</button>
</div>
</div>
</div>
</div>
<!--/ko-->
<!--/ko-->
<!-- ko if: (isPaymentMethodSelectionOnAdyen()) -->
<div class="payment-method" data-bind="css: {'_active': (getCode() == isChecked())}">
<div class="payment-method-title field choice"> <div class="payment-method-title field choice">
<input type="radio" <input type="radio"
name="payment[method]" name="payment[method]"
...@@ -56,4 +121,5 @@ ...@@ -56,4 +121,5 @@
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<!--/ko-->
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment