Commit a822b365 authored by Rik ter Beek's avatar Rik ter Beek

Merge pull request #38 from Adyen/develop

Merge branch 'develop'
parents f38de7c3 866863ba
...@@ -193,10 +193,10 @@ interface NotificationInterface ...@@ -193,10 +193,10 @@ interface NotificationInterface
public function setAmountValue($amountValue); public function setAmountValue($amountValue);
/** /**
* Gets the AmountValue for the notification. * Gets the AmountValue for the notification.
* *
* @return int|null AmountValue. * @return int|null AmountValue.
*/ */
public function getAmountCurency(); public function getAmountCurency();
/** /**
......
...@@ -30,20 +30,33 @@ class Version extends \Magento\Config\Block\System\Config\Form\Field ...@@ -30,20 +30,33 @@ class Version extends \Magento\Config\Block\System\Config\Form\Field
{ {
/** /**
* Contains list of modules
*
* @var \Magento\Framework\Module\ModuleListInterface * @var \Magento\Framework\Module\ModuleListInterface
*/ */
protected $_moduleList; protected $_moduleList;
/**
* Version constructor.
* @param \Magento\Framework\Module\ModuleListInterface $moduleList
* @param \Magento\Backend\Block\Template\Context $context
* @param array $data
*/
public function __construct( public function __construct(
\Magento\Framework\Module\ModuleListInterface $moduleList, \Magento\Framework\Module\ModuleListInterface $moduleList,
\Magento\Backend\Block\Template\Context $context, \Magento\Backend\Block\Template\Context $context,
array $data = [] array $data = []
) ) {
{
parent::__construct($context, $data); parent::__construct($context, $data);
$this->_moduleList = $moduleList; $this->_moduleList = $moduleList;
} }
/**
* Retrieve the setup version of the extension
*
* @param \Magento\Framework\Data\Form\Element\AbstractElement $element
* @return string
*/
protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element) protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{ {
return (string) $this->_moduleList->getOne("Adyen_Payment")['setup_version']; return (string) $this->_moduleList->getOne("Adyen_Payment")['setup_version'];
......
...@@ -23,7 +23,7 @@ ...@@ -23,7 +23,7 @@
namespace Adyen\Payment\Block\Form; namespace Adyen\Payment\Block\Form;
class Cc extends \Magento\Payment\Block\Form class Cc extends \Magento\Payment\Block\Form\Cc
{ {
/** /**
* @var string * @var string
...@@ -43,22 +43,42 @@ class Cc extends \Magento\Payment\Block\Form ...@@ -43,22 +43,42 @@ class Cc extends \Magento\Payment\Block\Form
protected $_adyenHelper; protected $_adyenHelper;
/** /**
* @var \Magento\Framework\App\State
*/
protected $_appState;
/**
* @var \Magento\Checkout\Model\Session
*/
protected $_checkoutSession;
/**
* Cc constructor.
*
* @param \Magento\Framework\View\Element\Template\Context $context * @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Payment\Model\Config $paymentConfig * @param \Magento\Payment\Model\Config $paymentConfig
* @param \Adyen\Payment\Helper\Data $adyenHelper
* @param \Magento\Checkout\Model\Session $checkoutSession
* @param array $data * @param array $data
*/ */
public function __construct( public function __construct(
\Magento\Framework\View\Element\Template\Context $context, \Magento\Framework\View\Element\Template\Context $context,
\Magento\Payment\Model\Config $paymentConfig, \Magento\Payment\Model\Config $paymentConfig,
\Adyen\Payment\Helper\Data $adyenHelper, \Adyen\Payment\Helper\Data $adyenHelper,
\Magento\Checkout\Model\Session $checkoutSession,
array $data = [] array $data = []
) { ) {
parent::__construct($context, $data); parent::__construct($context, $paymentConfig);
$this->_paymentConfig = $paymentConfig;
$this->_adyenHelper = $adyenHelper; $this->_adyenHelper = $adyenHelper;
$this->_appState = $context->getAppState();
$this->_checkoutSession = $checkoutSession;
} }
/**
* @return mixed
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getCsePublicKey() public function getCsePublicKey()
{ {
// get storeId for admin // get storeId for admin
...@@ -77,62 +97,6 @@ class Cc extends \Magento\Payment\Block\Form ...@@ -77,62 +97,6 @@ class Cc extends \Magento\Payment\Block\Form
} }
return $cseKey; return $cseKey;
}
/**
* Retrieve availables credit card types
*
* @return array
* @SuppressWarnings(PHPMD.UnusedLocalVariable)
*/
public function getCcAvailableTypes()
{
$types = $this->_paymentConfig->getCcTypes();
if ($method = $this->getMethod()) {
$availableTypes = $method->getConfigData('cctypes');
if ($availableTypes) {
$availableTypes = explode(',', $availableTypes);
foreach ($types as $code => $name) {
if (!in_array($code, $availableTypes)) {
unset($types[$code]);
}
}
}
}
return $types;
}
/**
* Retrieve credit card expire months
*
* @return array
*/
public function getCcMonths()
{
$months = $this->getData('cc_months');
if ($months === null) {
$months[0] = __('Month');
$months = array_merge($months, $this->_paymentConfig->getMonths());
$this->setData('cc_months', $months);
}
return $months;
}
/**
* Retrieve credit card expire years
*
* @return array
*/
public function getCcYears()
{
$years = $this->getData('cc_years');
if ($years === null) {
$years = $this->_paymentConfig->getYears();
$years = [0 => __('Year')] + $years;
$this->setData('cc_years', $years);
}
return $years;
} }
/** /**
...@@ -142,52 +106,15 @@ class Cc extends \Magento\Payment\Block\Form ...@@ -142,52 +106,15 @@ class Cc extends \Magento\Payment\Block\Form
*/ */
public function hasVerification() public function hasVerification()
{ {
return true; // if backend order and moto payments is turned on don't show cvc
} if ($this->_appState->getAreaCode() === \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE) {
$this->getCheckoutSession();
/** $store = $this->_checkoutSession->getQuote()->getStore();
* Whether switch/solo card type available $enableMoto = $this->_adyenHelper->getAdyenCcConfigDataFlag('enable_moto', $store->getId());
* if($enableMoto) {
* @return bool return false;
*/ }
public function hasSsCardType()
{
$availableTypes = explode(',', $this->getMethod()->getConfigData('cctypes'));
$ssPresenations = array_intersect(['SS', 'SM', 'SO'], $availableTypes);
if ($availableTypes && count($ssPresenations) > 0) {
return true;
}
return false;
}
/**
* Solo/switch card start year
*
* @return array
*/
public function getSsStartYears()
{
$years = [];
$first = date("Y");
for ($index = 5; $index >= 0; $index--) {
$year = $first - $index;
$years[$year] = $year;
} }
$years = [0 => __('Year')] + $years; return true;
return $years;
}
/**
* Render block HTML
*
* @return string
*/
protected function _toHtml()
{
$this->_eventManager->dispatch('payment_form_block_to_html_before', ['block' => $this]);
return parent::_toHtml();
} }
} }
\ No newline at end of file
...@@ -32,10 +32,12 @@ class AbstractInfo extends \Magento\Payment\Block\Info ...@@ -32,10 +32,12 @@ class AbstractInfo extends \Magento\Payment\Block\Info
* @var \Adyen\Payment\Helper\Data * @var \Adyen\Payment\Helper\Data
*/ */
protected $_adyenHelper; protected $_adyenHelper;
/** /**
* Constructor * Constructor
* *
* AbstractInfo constructor.
* @param \Adyen\Payment\Helper\Data $adyenHelper
* @param Template\Context $context * @param Template\Context $context
* @param array $data * @param array $data
*/ */
...@@ -49,12 +51,19 @@ class AbstractInfo extends \Magento\Payment\Block\Info ...@@ -49,12 +51,19 @@ class AbstractInfo extends \Magento\Payment\Block\Info
$this->_adyenHelper = $adyenHelper; $this->_adyenHelper = $adyenHelper;
} }
/**
* @return mixed
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getAdyenPspReference() public function getAdyenPspReference()
{ {
return $this->getInfo()->getAdyenPspReference(); return $this->getInfo()->getAdyenPspReference();
} }
/**
* @return mixed
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function isDemoMode() public function isDemoMode()
{ {
$storeId = $this->getInfo()->getOrder()->getStoreId(); $storeId = $this->getInfo()->getOrder()->getStoreId();
......
...@@ -30,6 +30,11 @@ class Hpp extends AbstractInfo ...@@ -30,6 +30,11 @@ class Hpp extends AbstractInfo
*/ */
protected $_template = 'Adyen_Payment::info/adyen_hpp.phtml'; protected $_template = 'Adyen_Payment::info/adyen_hpp.phtml';
/**
* Check if Payment method selection is configured on Adyen or Magento
*
* @return mixed
*/
public function isPaymentSelectionOnAdyen() public function isPaymentSelectionOnAdyen()
{ {
return $this->_adyenHelper->getAdyenHppConfigDataFlag('payment_selection_on_adyen'); return $this->_adyenHelper->getAdyenHppConfigDataFlag('payment_selection_on_adyen');
......
...@@ -40,6 +40,8 @@ class Pos extends \Magento\Payment\Block\Form ...@@ -40,6 +40,8 @@ class Pos extends \Magento\Payment\Block\Form
protected $_order; protected $_order;
/** /**
* Pos constructor.
*
* @param \Magento\Framework\View\Element\Template\Context $context * @param \Magento\Framework\View\Element\Template\Context $context
* @param array $data * @param array $data
* @param \Magento\Sales\Model\OrderFactory $orderFactory * @param \Magento\Sales\Model\OrderFactory $orderFactory
...@@ -50,20 +52,24 @@ class Pos extends \Magento\Payment\Block\Form ...@@ -50,20 +52,24 @@ class Pos extends \Magento\Payment\Block\Form
array $data = [], array $data = [],
\Magento\Sales\Model\OrderFactory $orderFactory, \Magento\Sales\Model\OrderFactory $orderFactory,
\Magento\Checkout\Model\Session $checkoutSession \Magento\Checkout\Model\Session $checkoutSession
) ) {
{
$this->_orderFactory = $orderFactory; $this->_orderFactory = $orderFactory;
$this->_checkoutSession = $checkoutSession; $this->_checkoutSession = $checkoutSession;
parent::__construct($context, $data); parent::__construct($context, $data);
$this->_getOrder(); $this->_getOrder();
} }
/**
* @return $this
*/
public function _prepareLayout() public function _prepareLayout()
{ {
return parent::_prepareLayout(); return parent::_prepareLayout();
} }
/**
* @return string
*/
public function getLaunchLink() public function getLaunchLink()
{ {
$result = ""; $result = "";
......
...@@ -40,6 +40,8 @@ class Redirect extends \Magento\Payment\Block\Form ...@@ -40,6 +40,8 @@ class Redirect extends \Magento\Payment\Block\Form
protected $_order; protected $_order;
/** /**
* Redirect constructor.
*
* @param \Magento\Framework\View\Element\Template\Context $context * @param \Magento\Framework\View\Element\Template\Context $context
* @param array $data * @param array $data
* @param \Magento\Sales\Model\OrderFactory $orderFactory * @param \Magento\Sales\Model\OrderFactory $orderFactory
...@@ -50,8 +52,7 @@ class Redirect extends \Magento\Payment\Block\Form ...@@ -50,8 +52,7 @@ class Redirect extends \Magento\Payment\Block\Form
array $data = [], array $data = [],
\Magento\Sales\Model\OrderFactory $orderFactory, \Magento\Sales\Model\OrderFactory $orderFactory,
\Magento\Checkout\Model\Session $checkoutSession \Magento\Checkout\Model\Session $checkoutSession
) ) {
{
$this->_orderFactory = $orderFactory; $this->_orderFactory = $orderFactory;
$this->_checkoutSession = $checkoutSession; $this->_checkoutSession = $checkoutSession;
parent::__construct($context, $data); parent::__construct($context, $data);
...@@ -59,11 +60,17 @@ class Redirect extends \Magento\Payment\Block\Form ...@@ -59,11 +60,17 @@ class Redirect extends \Magento\Payment\Block\Form
} }
/**
* @return $this
*/
public function _prepareLayout() public function _prepareLayout()
{ {
return parent::_prepareLayout(); return parent::_prepareLayout();
} }
/**
* @return string
*/
public function getFormUrl() public function getFormUrl()
{ {
$result = ""; $result = "";
...@@ -81,6 +88,9 @@ class Redirect extends \Magento\Payment\Block\Form ...@@ -81,6 +88,9 @@ class Redirect extends \Magento\Payment\Block\Form
return $result; return $result;
} }
/**
* @return array
*/
public function getFormFields() public function getFormFields()
{ {
$result = array(); $result = array();
......
...@@ -26,7 +26,11 @@ namespace Adyen\Payment\Block\Redirect; ...@@ -26,7 +26,11 @@ namespace Adyen\Payment\Block\Redirect;
class Validate3d extends \Magento\Payment\Block\Form class Validate3d extends \Magento\Payment\Block\Form
{ {
/**
* @var \Magento\Sales\Model\OrderFactory
*/
protected $_orderFactory; protected $_orderFactory;
/** /**
* @var \Magento\Checkout\Model\Session * @var \Magento\Checkout\Model\Session
*/ */
...@@ -38,6 +42,8 @@ class Validate3d extends \Magento\Payment\Block\Form ...@@ -38,6 +42,8 @@ class Validate3d extends \Magento\Payment\Block\Form
protected $_order; protected $_order;
/** /**
* Validate3d constructor.
*
* @param \Magento\Framework\View\Element\Template\Context $context * @param \Magento\Framework\View\Element\Template\Context $context
* @param array $data * @param array $data
* @param \Magento\Sales\Model\OrderFactory $orderFactory * @param \Magento\Sales\Model\OrderFactory $orderFactory
...@@ -48,15 +54,13 @@ class Validate3d extends \Magento\Payment\Block\Form ...@@ -48,15 +54,13 @@ class Validate3d extends \Magento\Payment\Block\Form
array $data = [], array $data = [],
\Magento\Sales\Model\OrderFactory $orderFactory, \Magento\Sales\Model\OrderFactory $orderFactory,
\Magento\Checkout\Model\Session $checkoutSession \Magento\Checkout\Model\Session $checkoutSession
) ) {
{
$this->_orderFactory = $orderFactory; $this->_orderFactory = $orderFactory;
$this->_checkoutSession = $checkoutSession; $this->_checkoutSession = $checkoutSession;
parent::__construct($context, $data); parent::__construct($context, $data);
$this->_getOrder(); $this->_getOrder();
} }
/** /**
* Get order object * Get order object
* *
...@@ -81,21 +85,33 @@ class Validate3d extends \Magento\Payment\Block\Form ...@@ -81,21 +85,33 @@ class Validate3d extends \Magento\Payment\Block\Form
return $this->_checkoutSession; return $this->_checkoutSession;
} }
/**
* @return mixed
*/
public function getIssuerUrl() public function getIssuerUrl()
{ {
return $this->_order->getPayment()->getAdditionalInformation('issuerUrl'); return $this->_order->getPayment()->getAdditionalInformation('issuerUrl');
} }
/**
* @return mixed
*/
public function getPaReq() public function getPaReq()
{ {
return $this->_order->getPayment()->getAdditionalInformation('paRequest'); return $this->_order->getPayment()->getAdditionalInformation('paRequest');
} }
/**
* @return mixed
*/
public function getMd() public function getMd()
{ {
return $this->_order->getPayment()->getAdditionalInformation('md'); return $this->_order->getPayment()->getAdditionalInformation('md');
} }
/**
* @return string
*/
public function getTermUrl() public function getTermUrl()
{ {
return $this->getUrl('adyen/process/validate3d'); return $this->getUrl('adyen/process/validate3d');
......
...@@ -36,7 +36,10 @@ class Cron extends \Magento\Framework\App\Action\Action ...@@ -36,7 +36,10 @@ class Cron extends \Magento\Framework\App\Action\Action
* @var \Magento\Framework\Controller\Result\RawFactory * @var \Magento\Framework\Controller\Result\RawFactory
*/ */
protected $_resultFactory; protected $_resultFactory;
/** /**
* Cron constructor.
*
* @param \Magento\Framework\App\Action\Context $context * @param \Magento\Framework\App\Action\Context $context
*/ */
public function __construct( public function __construct(
...@@ -46,8 +49,9 @@ class Cron extends \Magento\Framework\App\Action\Action ...@@ -46,8 +49,9 @@ class Cron extends \Magento\Framework\App\Action\Action
$this->_objectManager = $context->getObjectManager(); $this->_objectManager = $context->getObjectManager();
$this->_resultFactory = $context->getResultFactory(); $this->_resultFactory = $context->getResultFactory();
} }
/** /**
* @throws \Magento\Framework\Exception\LocalizedException * Process Notification from Cron
*/ */
public function execute() public function execute()
{ {
......
...@@ -52,6 +52,8 @@ class Json extends \Magento\Framework\App\Action\Action ...@@ -52,6 +52,8 @@ class Json extends \Magento\Framework\App\Action\Action
protected $_adyenLogger; protected $_adyenLogger;
/** /**
* Json constructor.
*
* @param \Magento\Framework\App\Action\Context $context * @param \Magento\Framework\App\Action\Context $context
* @param \Adyen\Payment\Helper\Data $adyenHelper * @param \Adyen\Payment\Helper\Data $adyenHelper
* @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger * @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger
...@@ -77,20 +79,23 @@ class Json extends \Magento\Framework\App\Action\Action ...@@ -77,20 +79,23 @@ class Json extends \Magento\Framework\App\Action\Action
$notificationItems = json_decode(file_get_contents('php://input'), true); $notificationItems = json_decode(file_get_contents('php://input'), true);
// log the notification // log the notification
$this->_adyenLogger->addAdyenNotification("The content of the notification is: " . print_r($notificationItems,1)); $this->_adyenLogger->addAdyenNotification(
"The content of the notification is: " . print_r($notificationItems, 1)
);
$notificationMode = isset($notificationItems['live']) ? $notificationItems['live'] : ""; $notificationMode = isset($notificationItems['live']) ? $notificationItems['live'] : "";
if($notificationMode != "" && $this->_validateNotificationMode($notificationMode)) if ($notificationMode != "" && $this->_validateNotificationMode($notificationMode)) {
{ foreach ($notificationItems['notificationItems'] as $notificationItem) {
foreach($notificationItems['notificationItems'] as $notificationItem) $status = $this->_processNotification(
{ $notificationItem['NotificationRequestItem'], $notificationMode
$status = $this->_processNotification($notificationItem['NotificationRequestItem'], $notificationMode); );
if($status != true) {
if ($status != true) {
$this->_return401(); $this->_return401();
return; return;
} }
} }
$this->_adyenLogger->addAdyenNotification("The result is accepted"); $this->_adyenLogger->addAdyenNotification("The result is accepted");
...@@ -99,13 +104,14 @@ class Json extends \Magento\Framework\App\Action\Action ...@@ -99,13 +104,14 @@ class Json extends \Magento\Framework\App\Action\Action
->setHeader('Content-Type', 'text/html') ->setHeader('Content-Type', 'text/html')
->setBody("[accepted]"); ->setBody("[accepted]");
return; return;
} else } else {
{ if ($notificationMode == "") {
if($notificationMode == "") {
$this->_return401(); $this->_return401();
return; return;
} }
throw new \Magento\Framework\Exception\LocalizedException(__('Mismatch between Live/Test modes of Magento store and the Adyen platform')); throw new \Magento\Framework\Exception\LocalizedException(
__('Mismatch between Live/Test modes of Magento store and the Adyen platform')
);
} }
} catch (Exception $e) { } catch (Exception $e) {
throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage())); throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage()));
...@@ -119,25 +125,27 @@ class Json extends \Magento\Framework\App\Action\Action ...@@ -119,25 +125,27 @@ class Json extends \Magento\Framework\App\Action\Action
protected function _validateNotificationMode($notificationMode) protected function _validateNotificationMode($notificationMode)
{ {
$mode = $this->_adyenHelper->getAdyenAbstractConfigData('demo_mode'); $mode = $this->_adyenHelper->getAdyenAbstractConfigData('demo_mode');
if ($mode=='1' && $notificationMode == "false" || $mode=='0' && $notificationMode == 'true') {
if (($mode=='1' && $notificationMode == "false") || ($mode=='0' && $notificationMode == 'true')) {
return true; return true;
} }
return false; return false;
} }
/** /**
* $desc save notification into the database for cronjob to execute notificaiton * save notification into the database for cronjob to execute notification
*
* @param $response * @param $response
* @param $notificationMode
* @return bool
* @throws \Magento\Framework\Exception\LocalizedException * @throws \Magento\Framework\Exception\LocalizedException
*/ */
protected function _processNotification($response, $notificationMode) protected function _processNotification($response, $notificationMode)
{ {
// validate the notification // validate the notification
if($this->authorised($response)) if ($this->authorised($response)) {
{
// check if notificaiton already exists // check if notificaiton already exists
if(!$this->_isDuplicate($response)) { if (!$this->_isDuplicate($response)) {
try { try {
$notification = $this->_objectManager->create('Adyen\Payment\Model\Notification'); $notification = $this->_objectManager->create('Adyen\Payment\Model\Notification');
...@@ -191,11 +199,12 @@ class Json extends \Magento\Framework\App\Action\Action ...@@ -191,11 +199,12 @@ class Json extends \Magento\Framework\App\Action\Action
} }
return false; return false;
} }
/** /**
* @desc HTTP Authentication of the notification * HTTP Authentication of the notification
*
* @param $response * @param $response
* @return bool
*/ */
protected function authorised($response) protected function authorised($response)
{ {
...@@ -209,16 +218,20 @@ class Json extends \Magento\Framework\App\Action\Action ...@@ -209,16 +218,20 @@ class Json extends \Magento\Framework\App\Action\Action
$submitedMerchantAccount = $response['merchantAccountCode']; $submitedMerchantAccount = $response['merchantAccountCode'];
if (empty($submitedMerchantAccount) && empty($internalMerchantAccount)) { if (empty($submitedMerchantAccount) && empty($internalMerchantAccount)) {
if(strtolower(substr($response['pspReference'],0,17)) == "testnotification_" || strtolower(substr($response['pspReference'],0,5)) == "test_") { if (strtolower(substr($response['pspReference'], 0, 17)) == "testnotification_" ||
echo 'merchantAccountCode is empty in magento settings'; exit(); strtolower(substr($response['pspReference'], 0, 5)) == "test_") {
echo 'merchantAccountCode is empty in magento settings';
exit();
} }
return false; return false;
} }
// validate username and password // validate username and password
if ((!isset($_SERVER['PHP_AUTH_USER']) && !isset($_SERVER['PHP_AUTH_PW']))) { if ((!isset($_SERVER['PHP_AUTH_USER']) && !isset($_SERVER['PHP_AUTH_PW']))) {
if(strtolower(substr($response['pspReference'],0,17)) == "testnotification_" || strtolower(substr($response['pspReference'],0,5)) == "test_") { if (strtolower(substr($response['pspReference'], 0, 17)) == "testnotification_" ||
echo 'Authentication failed: PHP_AUTH_USER and PHP_AUTH_PW are empty. See Adyen Magento manual CGI mode'; exit(); strtolower(substr($response['pspReference'], 0, 5)) == "test_") {
echo 'Authentication failed: PHP_AUTH_USER and PHP_AUTH_PW are empty. See Adyen Magento manual CGI mode';
exit();
} }
return false; return false;
} }
...@@ -234,22 +247,24 @@ class Json extends \Magento\Framework\App\Action\Action ...@@ -234,22 +247,24 @@ class Json extends \Magento\Framework\App\Action\Action
} }
// If notification is test check if fields are correct if not return error // If notification is test check if fields are correct if not return error
if(strtolower(substr($response['pspReference'],0,17)) == "testnotification_" || strtolower(substr($response['pspReference'],0,5)) == "test_") { if (strtolower(substr($response['pspReference'], 0, 17)) == "testnotification_" ||
if($accountCmp != 0) { strtolower(substr($response['pspReference'], 0, 5)) == "test_") {
echo 'MerchantAccount in notification is not the same as in Magento settings'; exit(); if ($accountCmp != 0) {
} elseif($usernameCmp != 0 || $passwordCmp != 0) { echo 'MerchantAccount in notification is not the same as in Magento settings';
echo 'username (PHP_AUTH_USER) and\or password (PHP_AUTH_PW) are not the same as Magento settings'; exit(); exit();
} elseif ($usernameCmp != 0 || $passwordCmp != 0) {
echo 'username (PHP_AUTH_USER) and\or password (PHP_AUTH_PW) are not the same as Magento settings';
exit();
} }
} }
return false; return false;
} }
/** /**
* $desc if notification is already saved ignore it * If notification is already saved ignore it
*
* @param $response * @param $response
* @return bool * @return mixed
*/ */
protected function _isDuplicate($response) protected function _isDuplicate($response)
{ {
...@@ -264,24 +279,29 @@ class Json extends \Magento\Framework\App\Action\Action ...@@ -264,24 +279,29 @@ class Json extends \Magento\Framework\App\Action\Action
/** /**
* Fix these global variables for the CGI * Fix these global variables for the CGI
*/ */
protected function _fixCgiHttpAuthentication() { // unsupported is $_SERVER['REMOTE_AUTHORIZATION']: as stated in manual :p protected function _fixCgiHttpAuthentication()
if (isset($_SERVER['REDIRECT_REMOTE_AUTHORIZATION']) && $_SERVER['REDIRECT_REMOTE_AUTHORIZATION'] != '') { //pcd note: no idea who sets this {
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode($_SERVER['REDIRECT_REMOTE_AUTHORIZATION'])); if (isset($_SERVER['REDIRECT_REMOTE_AUTHORIZATION']) &&
} elseif(!empty($_SERVER['HTTP_AUTHORIZATION'])){ //pcd note: standard in magento? $_SERVER['REDIRECT_REMOTE_AUTHORIZATION'] != '') {
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6))); list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
} elseif (!empty($_SERVER['REMOTE_USER'])) { //pcd note: when cgi and .htaccess modrewrite patch is executed explode(':', base64_decode($_SERVER['REDIRECT_REMOTE_AUTHORIZATION']));
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode(substr($_SERVER['REMOTE_USER'], 6))); } elseif (!empty($_SERVER['HTTP_AUTHORIZATION'])) {
} elseif (!empty($_SERVER['REDIRECT_REMOTE_USER'])) { //pcd note: no idea who sets this list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode(substr($_SERVER['REDIRECT_REMOTE_USER'], 6))); explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
} elseif (!empty($_SERVER['REMOTE_USER'])) {
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
explode(':', base64_decode(substr($_SERVER['REMOTE_USER'], 6)));
} elseif (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
explode(':', base64_decode(substr($_SERVER['REDIRECT_REMOTE_USER'], 6)));
} }
} }
/** /**
* * Return a 401 result
*/ */
protected function _return401() protected function _return401()
{ {
$this->getResponse()->setHttpResponseCode(401); $this->getResponse()->setHttpResponseCode(401);
} }
} }
\ No newline at end of file
...@@ -36,7 +36,6 @@ class Redirect extends \Magento\Framework\App\Action\Action ...@@ -36,7 +36,6 @@ class Redirect extends \Magento\Framework\App\Action\Action
*/ */
protected $_checkoutSession; protected $_checkoutSession;
/** /**
* @var \Magento\Sales\Model\Order * @var \Magento\Sales\Model\Order
*/ */
...@@ -47,7 +46,6 @@ class Redirect extends \Magento\Framework\App\Action\Action ...@@ -47,7 +46,6 @@ class Redirect extends \Magento\Framework\App\Action\Action
*/ */
protected $_orderFactory; protected $_orderFactory;
/** /**
* @param \Magento\Framework\App\Action\Context $context * @param \Magento\Framework\App\Action\Context $context
*/ */
...@@ -57,7 +55,6 @@ class Redirect extends \Magento\Framework\App\Action\Action ...@@ -57,7 +55,6 @@ class Redirect extends \Magento\Framework\App\Action\Action
parent::__construct($context); parent::__construct($context);
} }
/** /**
* Return checkout session object * Return checkout session object
* *
...@@ -68,6 +65,9 @@ class Redirect extends \Magento\Framework\App\Action\Action ...@@ -68,6 +65,9 @@ class Redirect extends \Magento\Framework\App\Action\Action
return $this->_checkoutSession; return $this->_checkoutSession;
} }
/**
* Set redirect
*/
public function execute() public function execute()
{ {
$this->_view->loadLayout(); $this->_view->loadLayout();
...@@ -98,14 +98,19 @@ class Redirect extends \Magento\Framework\App\Action\Action ...@@ -98,14 +98,19 @@ class Redirect extends \Magento\Framework\App\Action\Action
return $this->_objectManager->get('Magento\Checkout\Model\Session'); return $this->_objectManager->get('Magento\Checkout\Model\Session');
} }
/**
* @return mixed
*/
protected function _getQuote() protected function _getQuote()
{ {
return $this->_objectManager->get('Magento\Quote\Model\Quote'); return $this->_objectManager->get('Magento\Quote\Model\Quote');
} }
/**
* @return mixed
*/
protected function _getQuoteManagement() protected function _getQuoteManagement()
{ {
return $this->_objectManager->get('\Magento\Quote\Model\QuoteManagement'); return $this->_objectManager->get('\Magento\Quote\Model\QuoteManagement');
} }
} }
\ No newline at end of file
...@@ -47,7 +47,6 @@ class RedirectPos extends \Magento\Framework\App\Action\Action ...@@ -47,7 +47,6 @@ class RedirectPos extends \Magento\Framework\App\Action\Action
*/ */
protected $_orderFactory; protected $_orderFactory;
/** /**
* @param \Magento\Framework\App\Action\Context $context * @param \Magento\Framework\App\Action\Context $context
*/ */
...@@ -57,7 +56,6 @@ class RedirectPos extends \Magento\Framework\App\Action\Action ...@@ -57,7 +56,6 @@ class RedirectPos extends \Magento\Framework\App\Action\Action
parent::__construct($context); parent::__construct($context);
} }
/** /**
* Return checkout session object * Return checkout session object
* *
...@@ -98,14 +96,19 @@ class RedirectPos extends \Magento\Framework\App\Action\Action ...@@ -98,14 +96,19 @@ class RedirectPos extends \Magento\Framework\App\Action\Action
return $this->_objectManager->get('Magento\Checkout\Model\Session'); return $this->_objectManager->get('Magento\Checkout\Model\Session');
} }
/**
* @return mixed
*/
protected function _getQuote() protected function _getQuote()
{ {
return $this->_objectManager->get('Magento\Quote\Model\Quote'); return $this->_objectManager->get('Magento\Quote\Model\Quote');
} }
/**
* @return mixed
*/
protected function _getQuoteManagement() protected function _getQuoteManagement()
{ {
return $this->_objectManager->get('\Magento\Quote\Model\QuoteManagement'); return $this->_objectManager->get('\Magento\Quote\Model\QuoteManagement');
} }
} }
\ No newline at end of file
...@@ -23,8 +23,7 @@ ...@@ -23,8 +23,7 @@
namespace Adyen\Payment\Controller\Process; namespace Adyen\Payment\Controller\Process;
use Magento\Customer\Api\AccountManagementInterface; use \Adyen\Payment\Model\Notification;
use Magento\Customer\Api\CustomerRepositoryInterface;
class Result extends \Magento\Framework\App\Action\Action class Result extends \Magento\Framework\App\Action\Action
{ {
...@@ -59,6 +58,8 @@ class Result extends \Magento\Framework\App\Action\Action ...@@ -59,6 +58,8 @@ class Result extends \Magento\Framework\App\Action\Action
protected $_adyenLogger; protected $_adyenLogger;
/** /**
* Result constructor.
*
* @param \Magento\Framework\App\Action\Context $context * @param \Magento\Framework\App\Action\Context $context
* @param \Adyen\Payment\Helper\Data $adyenHelper * @param \Adyen\Payment\Helper\Data $adyenHelper
* @param \Magento\Sales\Model\OrderFactory $orderFactory * @param \Magento\Sales\Model\OrderFactory $orderFactory
...@@ -82,12 +83,15 @@ class Result extends \Magento\Framework\App\Action\Action ...@@ -82,12 +83,15 @@ class Result extends \Magento\Framework\App\Action\Action
parent::__construct($context); parent::__construct($context);
} }
/**
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function execute() public function execute()
{ {
$response = $this->getRequest()->getParams(); $response = $this->getRequest()->getParams();
$this->_adyenLogger->addAdyenResult(print_r($response, true)); $this->_adyenLogger->addAdyenResult(print_r($response, true));
if($response) { if ($response) {
$result = $this->validateResponse($response); $result = $this->validateResponse($response);
if ($result) { if ($result) {
...@@ -104,6 +108,9 @@ class Result extends \Magento\Framework\App\Action\Action ...@@ -104,6 +108,9 @@ class Result extends \Magento\Framework\App\Action\Action
} }
} }
/**
* @param $response
*/
protected function _cancel($response) protected function _cancel($response)
{ {
$session = $this->_session; $session = $this->_session;
...@@ -115,24 +122,32 @@ class Result extends \Magento\Framework\App\Action\Action ...@@ -115,24 +122,32 @@ class Result extends \Magento\Framework\App\Action\Action
$this->_adyenHelper->cancelOrder($order); $this->_adyenHelper->cancelOrder($order);
if(isset($response['authResult']) && $response['authResult'] == \Adyen\Payment\Model\Notification::CANCELLED) { if (isset($response['authResult']) && $response['authResult'] == \Adyen\Payment\Model\Notification::CANCELLED) {
$this->messageManager->addError(__('You have cancelled the order. Please try again')); $this->messageManager->addError(__('You have cancelled the order. Please try again'));
} else { } else {
$this->messageManager->addError(__('Your payment failed, Please try again later')); $this->messageManager->addError(__('Your payment failed, Please try again later'));
} }
} }
/**
* @param $response
* @return bool
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function validateResponse($response) protected function validateResponse($response)
{ {
$result = true; $result = true;
$this->_adyenLogger->addAdyenResult('Processing ResultUrl'); $this->_adyenLogger->addAdyenResult('Processing ResultUrl');
$storeId = null;
if (empty($response)) { if (empty($response)) {
$this->_adyenLogger->addAdyenResult('Response is empty, please check your webserver that the result url accepts parameters'); $this->_adyenLogger->addAdyenResult(
throw new \Magento\Framework\Exception\LocalizedException(__('Response is empty, please check your webserver that the result url accepts parameters')); 'Response is empty, please check your webserver that the result url accepts parameters'
);
throw new \Magento\Framework\Exception\LocalizedException(
__('Response is empty, please check your webserver that the result url accepts parameters')
);
} }
// authenticate result url // authenticate result url
...@@ -143,7 +158,7 @@ class Result extends \Magento\Framework\App\Action\Action ...@@ -143,7 +158,7 @@ class Result extends \Magento\Framework\App\Action\Action
$incrementId = $response['merchantReference']; $incrementId = $response['merchantReference'];
if($incrementId) { if ($incrementId) {
$order = $this->_getOrder($incrementId); $order = $this->_getOrder($incrementId);
if ($order->getId()) { if ($order->getId()) {
...@@ -155,9 +170,6 @@ class Result extends \Magento\Framework\App\Action\Action ...@@ -155,9 +170,6 @@ class Result extends \Magento\Framework\App\Action\Action
return $response['handled_response']; return $response['handled_response'];
} }
// set StoreId for retrieving debug log setting
$storeId = $order->getStoreId();
// update the order // update the order
$result = $this->_validateUpdateOrder($order, $response); $result = $this->_validateUpdateOrder($order, $response);
...@@ -167,17 +179,22 @@ class Result extends \Magento\Framework\App\Action\Action ...@@ -167,17 +179,22 @@ class Result extends \Magento\Framework\App\Action\Action
]); ]);
} else { } else {
throw new \Magento\Framework\Exception\LocalizedException(__('Order does not exists with increment_id: %1', $incrementId)); throw new \Magento\Framework\Exception\LocalizedException(
__('Order does not exists with increment_id: %1', $incrementId)
);
} }
} else { } else {
throw new \Magento\Framework\Exception\LocalizedException(__('Empty merchantReference')); throw new \Magento\Framework\Exception\LocalizedException(
__('Empty merchantReference')
);
} }
return $result; return $result;
} }
/** /**
* @param $order * @param $order
* @param $params * @param $response
* @return bool
*/ */
protected function _validateUpdateOrder($order, $response) protected function _validateUpdateOrder($order, $response)
{ {
...@@ -190,7 +207,9 @@ class Result extends \Magento\Framework\App\Action\Action ...@@ -190,7 +207,9 @@ class Result extends \Magento\Framework\App\Action\Action
$pspReference = isset($response['pspReference']) ? trim($response['pspReference']) : ''; $pspReference = isset($response['pspReference']) ? trim($response['pspReference']) : '';
$type = 'Adyen Result URL response:'; $type = 'Adyen Result URL response:';
$comment = __('%1 <br /> authResult: %2 <br /> pspReference: %3 <br /> paymentMethod: %4', $type, $authResult, $pspReference, $paymentMethod); $comment = __('%1 <br /> authResult: %2 <br /> pspReference: %3 <br /> paymentMethod: %4',
$type, $authResult, $pspReference, $paymentMethod
);
$history = $this->_orderHistoryFactory->create() $history = $this->_orderHistoryFactory->create()
//->setStatus($status) //->setStatus($status)
...@@ -201,28 +220,26 @@ class Result extends \Magento\Framework\App\Action\Action ...@@ -201,28 +220,26 @@ class Result extends \Magento\Framework\App\Action\Action
$history->save(); $history->save();
// needed becuase then we need to save $order objects // needed because then we need to save $order objects
$order->setAdyenResulturlEventCode($authResult); $order->setAdyenResulturlEventCode($authResult);
switch ($authResult) { switch ($authResult) {
case Notification::AUTHORISED:
case \Adyen\Payment\Model\Notification::AUTHORISED: case Notification::PENDING:
case \Adyen\Payment\Model\Notification::PENDING:
// do nothing wait for the notification // do nothing wait for the notification
$result = true; $result = true;
$this->_adyenLogger->addAdyenResult('Do nothing wait for the notification'); $this->_adyenLogger->addAdyenResult('Do nothing wait for the notification');
break; break;
case \Adyen\Payment\Model\Notification::CANCELLED: case Notification::CANCELLED:
$this->_adyenLogger->addAdyenResult('Cancel or Hold the order'); $this->_adyenLogger->addAdyenResult('Cancel or Hold the order');
$result = false; $result = false;
break; break;
case \Adyen\Payment\Model\Notification::REFUSED: case Notification::REFUSED:
// if refused there will be a AUTHORIZATION : FALSE notification send only exception is idea // if refused there will be a AUTHORIZATION : FALSE notification send only exception is idea
$this->_adyenLogger->addAdyenResult('Cancel or Hold the order'); $this->_adyenLogger->addAdyenResult('Cancel or Hold the order');
$result = false; $result = false;
break; break;
case \Adyen\Payment\Model\Notification::ERROR: case Notification::ERROR:
//attempt to hold/cancel //attempt to hold/cancel
$this->_adyenLogger->addAdyenResult('Cancel or Hold the order'); $this->_adyenLogger->addAdyenResult('Cancel or Hold the order');
$result = false; $result = false;
...@@ -235,12 +252,12 @@ class Result extends \Magento\Framework\App\Action\Action ...@@ -235,12 +252,12 @@ class Result extends \Magento\Framework\App\Action\Action
return $result; return $result;
} }
/** /**
* @desc Authenticate using sha1 Merchant signature * Authenticate using sha1 Merchant signature
* @see success Action during checkout *
* @param Varien_Object $response * @param $response
* @return bool
*/ */
protected function _authenticate($response) { protected function _authenticate($response) {
...@@ -254,10 +271,10 @@ class Result extends \Magento\Framework\App\Action\Action ...@@ -254,10 +271,10 @@ class Result extends \Magento\Framework\App\Action\Action
ksort($response, SORT_STRING); ksort($response, SORT_STRING);
// Generate the signing data string // Generate the signing data string
$signData = implode(":",array_map(array($this, 'escapeString'),array_merge(array_keys($response), array_values($response)))); $signData = implode(":", array_map([$this, 'escapeString'],
array_merge(array_keys($response), array_values($response))));
$merchantSig = base64_encode(hash_hmac('sha256',$signData,pack("H*" , $hmacKey),true));
$merchantSig = base64_encode(hash_hmac('sha256', $signData, pack("H*", $hmacKey), true));
if (strcmp($merchantSig, $merchantSigNotification) === 0) { if (strcmp($merchantSig, $merchantSigNotification) === 0) {
return true; return true;
...@@ -265,16 +282,23 @@ class Result extends \Magento\Framework\App\Action\Action ...@@ -265,16 +282,23 @@ class Result extends \Magento\Framework\App\Action\Action
return false; return false;
} }
/* /**
* @desc The character escape function is called from the array_map function in _signRequestParams * The character escape function is called from the array_map function in _signRequestParams
* $param $val *
* return string * @param $val
*/ * @return mixed
*/
protected function escapeString($val) protected function escapeString($val)
{ {
return str_replace(':','\\:',str_replace('\\','\\\\',$val)); return str_replace(':','\\:',str_replace('\\','\\\\',$val));
} }
/**
* Get order based on increment_id
*
* @param $incrementId
* @return \Magento\Sales\Model\Order
*/
protected function _getOrder($incrementId) protected function _getOrder($incrementId)
{ {
if (!$this->_order) { if (!$this->_order) {
...@@ -282,5 +306,4 @@ class Result extends \Magento\Framework\App\Action\Action ...@@ -282,5 +306,4 @@ class Result extends \Magento\Framework\App\Action\Action
} }
return $this->_order; return $this->_order;
} }
} }
\ No newline at end of file
...@@ -57,6 +57,8 @@ class ResultPos extends \Magento\Framework\App\Action\Action ...@@ -57,6 +57,8 @@ class ResultPos extends \Magento\Framework\App\Action\Action
protected $_adyenLogger; protected $_adyenLogger;
/** /**
* ResultPos constructor.
*
* @param \Magento\Framework\App\Action\Context $context * @param \Magento\Framework\App\Action\Context $context
* @param \Adyen\Payment\Helper\Data $adyenHelper * @param \Adyen\Payment\Helper\Data $adyenHelper
* @param \Magento\Sales\Model\OrderFactory $orderFactory * @param \Magento\Sales\Model\OrderFactory $orderFactory
...@@ -80,6 +82,9 @@ class ResultPos extends \Magento\Framework\App\Action\Action ...@@ -80,6 +82,9 @@ class ResultPos extends \Magento\Framework\App\Action\Action
parent::__construct($context); parent::__construct($context);
} }
/**
* Return result
*/
public function execute() public function execute()
{ {
$response = $this->getRequest()->getParams(); $response = $this->getRequest()->getParams();
...@@ -97,23 +102,27 @@ class ResultPos extends \Magento\Framework\App\Action\Action ...@@ -97,23 +102,27 @@ class ResultPos extends \Magento\Framework\App\Action\Action
} }
} }
/**
* @param $response
* @return bool
*/
private function _validateResponse($response) private function _validateResponse($response)
{ {
$result = false; $result = false;
if($response != null && $response['result'] != "" && $this->_validateChecksum($response)) { if ($response != null && $response['result'] != "" && $this->_validateChecksum($response)) {
$incrementId = $response['merchantReference']; $incrementId = $response['merchantReference'];
$responseResult = $response['result']; $responseResult = $response['result'];
if($incrementId) { if ($incrementId) {
$order = $this->_getOrder($incrementId); $order = $this->_getOrder($incrementId);
if ($order->getId()) { if ($order->getId()) {
$comment = __('%1 <br /> Result: %2 <br /> paymentMethod: %3', 'Adyen App Result URL Notification:', $responseResult, 'POS'); $comment = __('%1 <br /> Result: %2 <br /> paymentMethod: %3',
'Adyen App Result URL Notification:', $responseResult, 'POS');
if($responseResult == 'APPROVED') { if ($responseResult == 'APPROVED') {
$this->_adyenLogger->addAdyenResult('Result is approved'); $this->_adyenLogger->addAdyenResult('Result is approved');
...@@ -163,6 +172,12 @@ class ResultPos extends \Magento\Framework\App\Action\Action ...@@ -163,6 +172,12 @@ class ResultPos extends \Magento\Framework\App\Action\Action
return $result; return $result;
} }
/**
* Validate checksum from result parameters
*
* @param $response
* @return bool
*/
protected function _validateChecksum($response) protected function _validateChecksum($response)
{ {
$checksum = $response['cs']; $checksum = $response['cs'];
...@@ -171,51 +186,46 @@ class ResultPos extends \Magento\Framework\App\Action\Action ...@@ -171,51 +186,46 @@ class ResultPos extends \Magento\Framework\App\Action\Action
$currency = $response['originalCustomCurrency']; $currency = $response['originalCustomCurrency'];
$sessionId = $response['sessionId']; $sessionId = $response['sessionId'];
// for android sessionis is with low i // for android sessionis is with low i
if($sessionId == "") { if ($sessionId == "") {
$sessionId = $response['sessionid']; $sessionId = $response['sessionid'];
} }
// calculate amount checksum // calculate amount checksum
$amount_checksum = 0; $amountChecksum = 0;
$amountLength = strlen($amount); $amountLength = strlen($amount);
for($i=0;$i<$amountLength;$i++) for ($i=0; $i<$amountLength; $i++) {
{
// ASCII value use ord // ASCII value use ord
$checksumCalc = ord($amount[$i]) - 48; $checksumCalc = ord($amount[$i]) - 48;
$amount_checksum += $checksumCalc; $amountChecksum += $checksumCalc;
} }
$currency_checksum = 0; $currencyChecksum = 0;
$currencyLength = strlen($currency); $currencyLength = strlen($currency);
for($i=0;$i<$currencyLength;$i++) for ($i=0; $i<$currencyLength; $i++) {
{
$checksumCalc = ord($currency[$i]) - 64; $checksumCalc = ord($currency[$i]) - 64;
$currency_checksum += $checksumCalc; $currencyChecksum += $checksumCalc;
} }
$result_checksum = 0; $resultChecksum = 0;
$resultLength = strlen($result); $resultLength = strlen($result);
for($i=0;$i<$resultLength;$i++) for ($i=0; $i<$resultLength; $i++) {
{
$checksumCalc = ord($result[$i]) - 64; $checksumCalc = ord($result[$i]) - 64;
$result_checksum += $checksumCalc; $resultChecksum += $checksumCalc;
} }
$sessionId_checksum = 0; $sessionIdChecksum = 0;
$sessionIdLength = strlen($sessionId); $sessionIdLength = strlen($sessionId);
for($i=0;$i<$sessionIdLength;$i++) for ($i=0; $i<$sessionIdLength; $i++) {
{
$checksumCalc = $this->_getAscii2Int($sessionId[$i]); $checksumCalc = $this->_getAscii2Int($sessionId[$i]);
$sessionId_checksum += $checksumCalc; $sessionIdChecksum += $checksumCalc;
} }
$total_result_checksum = (($amount_checksum + $currency_checksum + $result_checksum) * $sessionId_checksum) % 100; $totalResultChecksum = (($amountChecksum + $currencyChecksum + $resultChecksum) * $sessionIdChecksum) % 100;
// check if request is valid // check if request is valid
if($total_result_checksum == $checksum) { if ($totalResultChecksum == $checksum) {
$this->_adyenLogger->addAdyenResult('Checksum is valid'); $this->_adyenLogger->addAdyenResult('Checksum is valid');
return true; return true;
} }
...@@ -223,9 +233,13 @@ class ResultPos extends \Magento\Framework\App\Action\Action ...@@ -223,9 +233,13 @@ class ResultPos extends \Magento\Framework\App\Action\Action
return false; return false;
} }
/**
* @param $ascii
* @return int
*/
protected function _getAscii2Int($ascii) protected function _getAscii2Int($ascii)
{ {
if (is_numeric($ascii)){ if (is_numeric($ascii)) {
$int = ord($ascii) - 48; $int = ord($ascii) - 48;
} else { } else {
$int = ord($ascii) - 64; $int = ord($ascii) - 64;
...@@ -233,6 +247,10 @@ class ResultPos extends \Magento\Framework\App\Action\Action ...@@ -233,6 +247,10 @@ class ResultPos extends \Magento\Framework\App\Action\Action
return $int; return $int;
} }
/**
* @param $incrementId
* @return \Magento\Sales\Model\Order
*/
protected function _getOrder($incrementId) protected function _getOrder($incrementId)
{ {
if (!$this->_order) { if (!$this->_order) {
...@@ -241,6 +259,9 @@ class ResultPos extends \Magento\Framework\App\Action\Action ...@@ -241,6 +259,9 @@ class ResultPos extends \Magento\Framework\App\Action\Action
return $this->_order; return $this->_order;
} }
/**
* @param $response
*/
protected function _cancel($response) protected function _cancel($response)
{ {
$session = $this->_session; $session = $this->_session;
...@@ -250,15 +271,15 @@ class ResultPos extends \Magento\Framework\App\Action\Action ...@@ -250,15 +271,15 @@ class ResultPos extends \Magento\Framework\App\Action\Action
$order = $this->_order; $order = $this->_order;
if($order) { if ($order) {
$this->_adyenHelper->cancelOrder($order); $this->_adyenHelper->cancelOrder($order);
if(isset($response['authResult']) && $response['authResult'] == \Adyen\Payment\Model\Notification::CANCELLED) { if (isset($response['authResult']) &&
$response['authResult'] == \Adyen\Payment\Model\Notification::CANCELLED) {
$this->messageManager->addError(__('You have cancelled the order. Please try again')); $this->messageManager->addError(__('You have cancelled the order. Please try again'));
} else { } else {
$this->messageManager->addError(__('Your payment failed, Please try again later')); $this->messageManager->addError(__('Your payment failed, Please try again later'));
} }
} }
} }
} }
\ No newline at end of file
...@@ -46,6 +46,8 @@ class Validate3d extends \Magento\Framework\App\Action\Action ...@@ -46,6 +46,8 @@ class Validate3d extends \Magento\Framework\App\Action\Action
protected $_adyenHelper; protected $_adyenHelper;
/** /**
* Validate3d constructor.
*
* @param \Magento\Framework\App\Action\Context $context * @param \Magento\Framework\App\Action\Context $context
* @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger * @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger
* @param \Adyen\Payment\Helper\Data $adyenHelper * @param \Adyen\Payment\Helper\Data $adyenHelper
...@@ -60,6 +62,9 @@ class Validate3d extends \Magento\Framework\App\Action\Action ...@@ -60,6 +62,9 @@ class Validate3d extends \Magento\Framework\App\Action\Action
$this->_adyenHelper = $adyenHelper; $this->_adyenHelper = $adyenHelper;
} }
/**
* Validate 3D secure payment
*/
public function execute() public function execute()
{ {
$active = null; $active = null;
...@@ -67,19 +72,18 @@ class Validate3d extends \Magento\Framework\App\Action\Action ...@@ -67,19 +72,18 @@ class Validate3d extends \Magento\Framework\App\Action\Action
// check if 3d is active // check if 3d is active
$order = $this->_getOrder(); $order = $this->_getOrder();
if($order->getPayment()) { if ($order->getPayment()) {
$active = $order->getPayment()->getAdditionalInformation('3dActive'); $active = $order->getPayment()->getAdditionalInformation('3dActive');
} }
// check if 3D secure is active. If not just go to success page // check if 3D secure is active. If not just go to success page
if($active) { if ($active) {
$this->_adyenLogger->addAdyenResult("3D secure is active"); $this->_adyenLogger->addAdyenResult("3D secure is active");
// check if it is already processed // check if it is already processed
if ($this->getRequest()->isPost()) { if ($this->getRequest()->isPost()) {
$this->_adyenLogger->addAdyenResult("Process 3D secure payment"); $this->_adyenLogger->addAdyenResult("Process 3D secure payment");
$requestMD = $this->getRequest()->getPost('MD'); $requestMD = $this->getRequest()->getPost('MD');
$requestPaRes = $this->getRequest()->getPost('PaRes'); $requestPaRes = $this->getRequest()->getPost('PaRes');
$md = $order->getPayment()->getAdditionalInformation('md'); $md = $order->getPayment()->getAdditionalInformation('md');
...@@ -98,15 +102,16 @@ class Validate3d extends \Magento\Framework\App\Action\Action ...@@ -98,15 +102,16 @@ class Validate3d extends \Magento\Framework\App\Action\Action
if ($result == 'Authorised') { if ($result == 'Authorised') {
$order->addStatusHistoryComment(__('3D-secure validation was successful'))->save(); $order->addStatusHistoryComment(__('3D-secure validation was successful'))->save();
$this->_redirect('checkout/onepage/success'); $this->_redirect('checkout/onepage/success');
} } else {
else {
$order->addStatusHistoryComment(__('3D-secure validation was unsuccessful.'))->save(); $order->addStatusHistoryComment(__('3D-secure validation was unsuccessful.'))->save();
$this->_adyenHelper->cancelOrder($order); $this->_adyenHelper->cancelOrder($order);
} }
} }
} else { } else {
$this->_adyenLogger->addAdyenResult("Customer was redirected to bank for 3D-secure validation."); $this->_adyenLogger->addAdyenResult("Customer was redirected to bank for 3D-secure validation.");
$order->addStatusHistoryComment(__('Customer was redirected to bank for 3D-secure validation.'))->save(); $order->addStatusHistoryComment(
__('Customer was redirected to bank for 3D-secure validation.')
)->save();
$this->_view->loadLayout(); $this->_view->loadLayout();
$this->_view->getLayout()->initMessages(); $this->_view->getLayout()->initMessages();
......
...@@ -36,39 +36,34 @@ class Data extends AbstractHelper ...@@ -36,39 +36,34 @@ class Data extends AbstractHelper
*/ */
protected $_encryptor; protected $_encryptor;
/**
* @var \Magento\Payment\Model\Config
*/
protected $_config;
/** /**
* @var \Magento\Framework\Config\DataInterface * @var \Magento\Framework\Config\DataInterface
*/ */
protected $_dataStorage; protected $_dataStorage;
/** /**
* @param Context $context * Data constructor.
*
* @param \Magento\Framework\App\Helper\Context $context
* @param \Magento\Framework\Encryption\EncryptorInterface $encryptor
* @param \Magento\Framework\Config\DataInterface $dataStorage
*/ */
public function __construct( public function __construct(
\Magento\Framework\App\Helper\Context $context, \Magento\Framework\App\Helper\Context $context,
\Magento\Framework\Encryption\EncryptorInterface $encryptor, \Magento\Framework\Encryption\EncryptorInterface $encryptor,
\Magento\Payment\Model\Config $config,
\Magento\Framework\Config\DataInterface $dataStorage \Magento\Framework\Config\DataInterface $dataStorage
) ) {
{
parent::__construct($context); parent::__construct($context);
$this->_encryptor = $encryptor; $this->_encryptor = $encryptor;
$this->_config = $config;
$this->_dataStorage = $dataStorage; $this->_dataStorage = $dataStorage;
} }
/** /**
* @desc return recurring types for configuration setting * @desc return recurring types for configuration setting
* @return array * @return array
*/ */
public function getRecurringTypes() { public function getRecurringTypes()
{
return [ return [
\Adyen\Payment\Model\RecurringType::ONECLICK => 'ONECLICK', \Adyen\Payment\Model\RecurringType::ONECLICK => 'ONECLICK',
\Adyen\Payment\Model\RecurringType::ONECLICK_RECURRING => 'ONECLICK,RECURRING', \Adyen\Payment\Model\RecurringType::ONECLICK_RECURRING => 'ONECLICK,RECURRING',
...@@ -80,7 +75,8 @@ class Data extends AbstractHelper ...@@ -80,7 +75,8 @@ class Data extends AbstractHelper
* @desc return recurring types for configuration setting * @desc return recurring types for configuration setting
* @return array * @return array
*/ */
public function getModes() { public function getModes()
{
return [ return [
'1' => 'Test Mode', '1' => 'Test Mode',
'0' => 'Production Mode' '0' => 'Production Mode'
...@@ -157,6 +153,11 @@ class Data extends AbstractHelper ...@@ -157,6 +153,11 @@ class Data extends AbstractHelper
return number_format($amount, $format, '', ''); return number_format($amount, $format, '', '');
} }
/**
* @param $amount
* @param $currency
* @return float
*/
public function originalAmount($amount, $currency) public function originalAmount($amount, $currency)
{ {
// check the format // check the format
...@@ -206,14 +207,15 @@ class Data extends AbstractHelper ...@@ -206,14 +207,15 @@ class Data extends AbstractHelper
*/ */
public function getStreet($address) public function getStreet($address)
{ {
if (empty($address)) return false; if (empty($address)) {
return false;
}
$street = self::formatStreet($address->getStreet()); $street = self::formatStreet($address->getStreet());
$streetName = $street['0']; $streetName = $street['0'];
unset($street['0']); unset($street['0']);
// $streetNr = implode('',$street); $streetNr = implode(' ', $street);
$streetNr = implode(' ',$street); return (['name' => $streetName, 'house_number' => $streetNr]);
return (array('name' => $streetName, 'house_number' => $streetNr));
} }
/** /**
...@@ -228,11 +230,11 @@ class Data extends AbstractHelper ...@@ -228,11 +230,11 @@ class Data extends AbstractHelper
return $street; return $street;
} }
preg_match('/((\s\d{0,10})|(\s\d{0,10}\w{1,3}))$/i', $street['0'], $houseNumber, PREG_OFFSET_CAPTURE); preg_match('/((\s\d{0,10})|(\s\d{0,10}\w{1,3}))$/i', $street['0'], $houseNumber, PREG_OFFSET_CAPTURE);
if(!empty($houseNumber['0'])) { if (!empty($houseNumber['0'])) {
$_houseNumber = trim($houseNumber['0']['0']); $_houseNumber = trim($houseNumber['0']['0']);
$position = $houseNumber['0']['1']; $position = $houseNumber['0']['1'];
$streeName = trim(substr($street['0'], 0, $position)); $streetName = trim(substr($street['0'], 0, $position));
$street = array($streeName,$_houseNumber); $street = [$streetName, $_houseNumber];
} }
return $street; return $street;
} }
...@@ -389,7 +391,7 @@ class Data extends AbstractHelper ...@@ -389,7 +391,7 @@ class Data extends AbstractHelper
*/ */
public function getWsUsername() public function getWsUsername()
{ {
if($this->isDemoMode()) { if ($this->isDemoMode()) {
$wsUsername = trim($this->getAdyenAbstractConfigData('ws_username_test')); $wsUsername = trim($this->getAdyenAbstractConfigData('ws_username_test'));
} else { } else {
$wsUsername = trim($this->getAdyenAbstractConfigData('ws_username_live')); $wsUsername = trim($this->getAdyenAbstractConfigData('ws_username_live'));
...@@ -403,7 +405,7 @@ class Data extends AbstractHelper ...@@ -403,7 +405,7 @@ class Data extends AbstractHelper
*/ */
public function getWsPassword() public function getWsPassword()
{ {
if($this->isDemoMode()) { if ($this->isDemoMode()) {
$wsPassword = $this->_encryptor->decrypt(trim($this->getAdyenAbstractConfigData('ws_password_test'))); $wsPassword = $this->_encryptor->decrypt(trim($this->getAdyenAbstractConfigData('ws_password_test')));
} else { } else {
$wsPassword = $this->_encryptor->decrypt(trim($this->getAdyenAbstractConfigData('ws_password_live'))); $wsPassword = $this->_encryptor->decrypt(trim($this->getAdyenAbstractConfigData('ws_password_live')));
...@@ -417,7 +419,7 @@ class Data extends AbstractHelper ...@@ -417,7 +419,7 @@ class Data extends AbstractHelper
*/ */
public function getWsUrl() public function getWsUrl()
{ {
if($this->isDemoMode()) { if ($this->isDemoMode()) {
$url = $this->getAdyenAbstractConfigData('ws_url_test'); $url = $this->getAdyenAbstractConfigData('ws_url_test');
} else { } else {
$url = $this->getAdyenAbstractConfigData('ws_url_live'); $url = $this->getAdyenAbstractConfigData('ws_url_live');
...@@ -441,7 +443,7 @@ class Data extends AbstractHelper ...@@ -441,7 +443,7 @@ class Data extends AbstractHelper
} }
break; break;
default: default:
if($order->canCancel()) { if ($order->canCancel()) {
$order->cancel()->save(); $order->cancel()->save();
} }
break; break;
...@@ -456,20 +458,22 @@ class Data extends AbstractHelper ...@@ -456,20 +458,22 @@ class Data extends AbstractHelper
*/ */
public function getMagentoCreditCartType($ccType) public function getMagentoCreditCartType($ccType)
{ {
$ccTypesMapper = $this->getCcTypesAltData(); $ccTypesMapper = $this->getCcTypesAltData();
if(isset($ccTypesMapper[$ccType])) { if (isset($ccTypesMapper[$ccType])) {
$ccType = $ccTypesMapper[$ccType]['code']; $ccType = $ccTypesMapper[$ccType]['code'];
} }
return $ccType; return $ccType;
} }
/**
* @return array
*/
public function getCcTypesAltData() public function getCcTypesAltData()
{ {
$adyenCcTypes = $this->getAdyenCcTypes(); $adyenCcTypes = $this->getAdyenCcTypes();
$types = array(); $types = [];
foreach ($adyenCcTypes as $key => $data) { foreach ($adyenCcTypes as $key => $data) {
$types[$data['code_alt']] = $data; $types[$data['code_alt']] = $data;
$types[$data['code_alt']]['code'] = $key; $types[$data['code_alt']]['code'] = $key;
...@@ -477,6 +481,9 @@ class Data extends AbstractHelper ...@@ -477,6 +481,9 @@ class Data extends AbstractHelper
return $types; return $types;
} }
/**
* @return mixed
*/
public function getAdyenCcTypes() public function getAdyenCcTypes()
{ {
return $this->_dataStorage->get('adyen_credit_cards'); return $this->_dataStorage->get('adyen_credit_cards');
...@@ -499,6 +506,5 @@ class Data extends AbstractHelper ...@@ -499,6 +506,5 @@ class Data extends AbstractHelper
} else { } else {
return $this->scopeConfig->isSetFlag($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId); return $this->scopeConfig->isSetFlag($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
} }
} }
} }
\ No newline at end of file
...@@ -42,7 +42,7 @@ class AdyenLogger extends Logger ...@@ -42,7 +42,7 @@ class AdyenLogger extends Logger
* *
* @var array $levels Logging levels * @var array $levels Logging levels
*/ */
protected static $levels = array( protected static $levels = [
100 => 'DEBUG', 100 => 'DEBUG',
101 => 'ADYEN_DEBUG', 101 => 'ADYEN_DEBUG',
200 => 'INFO', 200 => 'INFO',
...@@ -55,7 +55,7 @@ class AdyenLogger extends Logger ...@@ -55,7 +55,7 @@ class AdyenLogger extends Logger
500 => 'CRITICAL', 500 => 'CRITICAL',
550 => 'ALERT', 550 => 'ALERT',
600 => 'EMERGENCY', 600 => 'EMERGENCY',
); ];
/** /**
* Adds a log record at the INFO level. * Adds a log record at the INFO level.
...@@ -86,7 +86,6 @@ class AdyenLogger extends Logger ...@@ -86,7 +86,6 @@ class AdyenLogger extends Logger
return $this->addRecord(static::ADYEN_NOTIFICATION_CRONJOB, $message, $context); return $this->addRecord(static::ADYEN_NOTIFICATION_CRONJOB, $message, $context);
} }
/** /**
* Adds a log record. * Adds a log record.
* *
......
...@@ -23,60 +23,10 @@ ...@@ -23,60 +23,10 @@
namespace Adyen\Payment\Logger\Handler; namespace Adyen\Payment\Logger\Handler;
use Magento\Framework\Filesystem\DriverInterface; use Magento\Framework\Logger\Handler\Base;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
class AdyenBase extends StreamHandler class AdyenBase extends Base
{ {
/**
* @var string
*/
protected $fileName;
/**
* @var int
*/
protected $loggerType = Logger::DEBUG;
/**
* @var DriverInterface
*/
protected $filesystem;
/**
* @param DriverInterface $filesystem
* @param string $filePath
*/
public function __construct(
DriverInterface $filesystem,
$filePath = null
) {
$this->filesystem = $filesystem;
parent::__construct(
$filePath ? $filePath . $this->fileName : BP . $this->fileName,
$this->loggerType
);
$this->setFormatter(new LineFormatter(null, null, true));
}
/**
* @{inheritDoc}
*
* @param $record array
* @return void
*/
public function write(array $record)
{
$logDir = $this->filesystem->getParentDirectory($this->url);
if (!$this->filesystem->isDirectory($logDir)) {
$this->filesystem->createDirectory($logDir, 0777);
}
parent::write($record);
}
/** /**
* overwrite core it needs to be the exact level otherwise use different handler * overwrite core it needs to be the exact level otherwise use different handler
* *
......
...@@ -29,32 +29,22 @@ use Magento\Payment\Helper\Data as PaymentHelper; ...@@ -29,32 +29,22 @@ use Magento\Payment\Helper\Data as PaymentHelper;
class AdyenCcConfigProvider extends CcGenericConfigProvider class AdyenCcConfigProvider extends CcGenericConfigProvider
{ {
/**
* @var Config
*/
protected $config;
/** /**
* @var string[] * @var string[]
*/ */
protected $methodCodes = [ protected $_methodCodes = [
\Adyen\Payment\Model\Method\Cc::METHOD_CODE \Adyen\Payment\Model\Method\Cc::METHOD_CODE
]; ];
/**
* @var \Magento\Payment\Model\Method\AbstractMethod[]
*/
protected $methods = [];
/** /**
* @var PaymentHelper * @var PaymentHelper
*/ */
protected $paymentHelper; protected $_paymentHelper;
/** /**
* @var \Adyen\Payment\Helper\Data * @var \Adyen\Payment\Helper\Data
*/ */
protected $adyenHelper; protected $_adyenHelper;
/** /**
* @var AdyenGenericConfig * @var AdyenGenericConfig
...@@ -62,9 +52,12 @@ class AdyenCcConfigProvider extends CcGenericConfigProvider ...@@ -62,9 +52,12 @@ class AdyenCcConfigProvider extends CcGenericConfigProvider
protected $_genericConfig; protected $_genericConfig;
/** /**
* AdyenCcConfigProvider constructor.
*
* @param \Magento\Payment\Model\CcConfig $ccConfig * @param \Magento\Payment\Model\CcConfig $ccConfig
* @param PaymentHelper $paymentHelper * @param PaymentHelper $paymentHelper
* @param \Adyen\Payment\Helper\Data $adyenHelper * @param \Adyen\Payment\Helper\Data $adyenHelper
* @param AdyenGenericConfig $genericConfig
*/ */
public function __construct( public function __construct(
\Magento\Payment\Model\CcConfig $ccConfig, \Magento\Payment\Model\CcConfig $ccConfig,
...@@ -72,32 +65,35 @@ class AdyenCcConfigProvider extends CcGenericConfigProvider ...@@ -72,32 +65,35 @@ class AdyenCcConfigProvider extends CcGenericConfigProvider
\Adyen\Payment\Helper\Data $adyenHelper, \Adyen\Payment\Helper\Data $adyenHelper,
\Adyen\Payment\Model\AdyenGenericConfig $genericConfig \Adyen\Payment\Model\AdyenGenericConfig $genericConfig
) { ) {
parent::__construct($ccConfig, $paymentHelper, $this->methodCodes); parent::__construct($ccConfig, $paymentHelper, $this->_methodCodes);
$this->adyenHelper = $adyenHelper; $this->_paymentHelper = $paymentHelper;
$this->_adyenHelper = $adyenHelper;
$this->_genericConfig = $genericConfig; $this->_genericConfig = $genericConfig;
} }
/**
* @return array
*/
public function getConfig() public function getConfig()
{ {
$config = parent::getConfig(); $config = parent::getConfig();
$demoMode = $this->adyenHelper->getAdyenAbstractConfigDataFlag('demo_mode'); $demoMode = $this->_adyenHelper->getAdyenAbstractConfigDataFlag('demo_mode');
if($demoMode) { if ($demoMode) {
$cseKey = $this->adyenHelper->getAdyenCcConfigData('cse_publickey_test'); $cseKey = $this->_adyenHelper->getAdyenCcConfigData('cse_publickey_test');
} else { } else {
$cseKey = $this->adyenHelper->getAdyenCcConfigData('cse_publickey_live'); $cseKey = $this->_adyenHelper->getAdyenCcConfigData('cse_publickey_live');
} }
$cseEnabled = $this->adyenHelper->getAdyenCcConfigDataFlag('cse_enabled'); $cseEnabled = $this->_adyenHelper->getAdyenCcConfigDataFlag('cse_enabled');
$recurringType = $this->adyenHelper->getAdyenAbstractConfigData('recurring_type'); $recurringType = $this->_adyenHelper->getAdyenAbstractConfigData('recurring_type');
$canCreateBillingAgreement = false; $canCreateBillingAgreement = false;
if($recurringType == "ONECLICK" || $recurringType == "ONECLICK,RECURRING") { if ($recurringType == "ONECLICK" || $recurringType == "ONECLICK,RECURRING") {
$canCreateBillingAgreement = true; $canCreateBillingAgreement = true;
} }
$config['payment'] ['adyenCc']['cseKey'] = $cseKey; $config['payment'] ['adyenCc']['cseKey'] = $cseKey;
$config['payment'] ['adyenCc']['cseEnabled'] = $cseEnabled; $config['payment'] ['adyenCc']['cseEnabled'] = $cseEnabled;
$config['payment'] ['adyenCc']['cseEnabled'] = $cseEnabled; $config['payment'] ['adyenCc']['cseEnabled'] = $cseEnabled;
...@@ -105,20 +101,21 @@ class AdyenCcConfigProvider extends CcGenericConfigProvider ...@@ -105,20 +101,21 @@ class AdyenCcConfigProvider extends CcGenericConfigProvider
$config['payment']['adyenCc']['canCreateBillingAgreement'] = $canCreateBillingAgreement; $config['payment']['adyenCc']['canCreateBillingAgreement'] = $canCreateBillingAgreement;
// show logos turned on by default // show logos turned on by default
if($this->_genericConfig->showLogos()) { if ($this->_genericConfig->showLogos()) {
$config['payment']['adyenCc']['creditCardPaymentMethodIcon'] = $this->_getCreditCardPaymentMethodIcon(); $config['payment']['adyenCc']['creditCardPaymentMethodIcon'] = $this->_getCreditCardPaymentMethodIcon();
} }
return $config; return $config;
} }
/**
* @return array|null
*/
protected function _getCreditCardPaymentMethodIcon() protected function _getCreditCardPaymentMethodIcon()
{ {
$asset = $this->_genericConfig->createAsset('Adyen_Payment::images/logos/img_trans.gif'); $asset = $this->_genericConfig->createAsset('Adyen_Payment::images/logos/img_trans.gif');
$placeholder = $this->_genericConfig->findRelativeSourceFilePath($asset); $placeholder = $this->_genericConfig->findRelativeSourceFilePath($asset);
$icon = null; $icon = null;
if ($placeholder) { if ($placeholder) {
list($width, $height) = getimagesize($asset->getSourceFile()); list($width, $height) = getimagesize($asset->getSourceFile());
$icon = [ $icon = [
...@@ -127,7 +124,6 @@ class AdyenCcConfigProvider extends CcGenericConfigProvider ...@@ -127,7 +124,6 @@ class AdyenCcConfigProvider extends CcGenericConfigProvider
'height' => $height 'height' => $height
]; ];
} }
return $icon; return $icon;
} }
} }
\ No newline at end of file
...@@ -34,17 +34,17 @@ class AdyenGenericConfig ...@@ -34,17 +34,17 @@ class AdyenGenericConfig
/** /**
* @var Repository * @var Repository
*/ */
protected $assetRepo; protected $_assetRepo;
/** /**
* @var RequestInterface * @var RequestInterface
*/ */
protected $request; protected $_request;
/** /**
* @var \Magento\Framework\View\Asset\Source * @var \Magento\Framework\View\Asset\Source
*/ */
protected $assetSource; protected $_assetSource;
/** /**
* @var \Adyen\Payment\Helper\Data * @var \Adyen\Payment\Helper\Data
...@@ -52,11 +52,12 @@ class AdyenGenericConfig ...@@ -52,11 +52,12 @@ class AdyenGenericConfig
protected $_adyenHelper; protected $_adyenHelper;
/** /**
* @param PaymentConfig $paymentConfig * AdyenGenericConfig constructor.
*
* @param Repository $assetRepo * @param Repository $assetRepo
* @param RequestInterface $request * @param RequestInterface $request
* @param UrlInterface $urlBuilder * @param Source $assetSource
* @param LoggerInterface $logger * @param \Adyen\Payment\Helper\Data $adyenHelper
*/ */
public function __construct( public function __construct(
Repository $assetRepo, Repository $assetRepo,
...@@ -64,9 +65,9 @@ class AdyenGenericConfig ...@@ -64,9 +65,9 @@ class AdyenGenericConfig
Source $assetSource, Source $assetSource,
\Adyen\Payment\Helper\Data $adyenHelper \Adyen\Payment\Helper\Data $adyenHelper
) { ) {
$this->assetRepo = $assetRepo; $this->_assetRepo = $assetRepo;
$this->request = $request; $this->_request = $request;
$this->assetSource = $assetSource; $this->_assetSource = $assetSource;
$this->_adyenHelper = $adyenHelper; $this->_adyenHelper = $adyenHelper;
} }
...@@ -79,21 +80,28 @@ class AdyenGenericConfig ...@@ -79,21 +80,28 @@ class AdyenGenericConfig
*/ */
public function createAsset($fileId, array $params = []) public function createAsset($fileId, array $params = [])
{ {
$params = array_merge(['_secure' => $this->request->isSecure()], $params); $params = array_merge(['_secure' => $this->_request->isSecure()], $params);
return $this->assetRepo->createAsset($fileId, $params); return $this->_assetRepo->createAsset($fileId, $params);
} }
public function findRelativeSourceFilePath($asset) { /**
return $this->assetSource->findRelativeSourceFilePath($asset); * @param $asset
* @return bool|string
*/
public function findRelativeSourceFilePath($asset)
{
return $this->_assetSource->findRelativeSourceFilePath($asset);
} }
/**
* @return bool
*/
public function showLogos() public function showLogos()
{ {
$showLogos = $this->_adyenHelper->getAdyenAbstractConfigData('title_renderer'); $showLogos = $this->_adyenHelper->getAdyenAbstractConfigData('title_renderer');
if($showLogos == \Adyen\Payment\Model\Config\Source\RenderMode::MODE_TITLE_IMAGE) { if ($showLogos == \Adyen\Payment\Model\Config\Source\RenderMode::MODE_TITLE_IMAGE) {
return true; return true;
} }
return false; return false;
} }
} }
\ No newline at end of file
...@@ -27,69 +27,51 @@ use Magento\Payment\Helper\Data as PaymentHelper; ...@@ -27,69 +27,51 @@ use Magento\Payment\Helper\Data as PaymentHelper;
class AdyenGenericConfigProvider implements ConfigProviderInterface class AdyenGenericConfigProvider implements ConfigProviderInterface
{ {
/**
* @var RequestInterface /**
* @var \Magento\Payment\Model\Method\AbstractMethod[]
*/ */
protected $request; protected $_methods = [];
/** /**
* @var \Adyen\Payment\Helper\Data * @var PaymentHelper
*/ */
protected $_adyenHelper; protected $_paymentHelper;
/** /**
* @var \Magento\Payment\Model\Method\AbstractMethod[] * @var AdyenGenericConfig
*/ */
protected $methods = []; protected $_genericConfig;
/** /**
* @var string[] * @var string[]
*/ */
protected $methodCodes = [ protected $_methodCodes = [
\Adyen\Payment\Model\Method\Cc::METHOD_CODE, \Adyen\Payment\Model\Method\Cc::METHOD_CODE,
\Adyen\Payment\Model\Method\Hpp::METHOD_CODE, \Adyen\Payment\Model\Method\Hpp::METHOD_CODE,
\Adyen\Payment\Model\Method\Oneclick::METHOD_CODE, \Adyen\Payment\Model\Method\Oneclick::METHOD_CODE,
\Adyen\Payment\Model\Method\Pos::METHOD_CODE \Adyen\Payment\Model\Method\Pos::METHOD_CODE,
\Adyen\Payment\Model\Method\Sepa::METHOD_CODE
]; ];
/** /**
* @param \Magento\Framework\Model\Context $context * AdyenGenericConfigProvider constructor.
* @param \Magento\Checkout\Model\Session $session *
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param PaymentHelper $paymentHelper * @param PaymentHelper $paymentHelper
* @param \Magento\Framework\Locale\ResolverInterface $localeResolver
* @param \Magento\Framework\App\Config\ScopeConfigInterface $config
* @param \Adyen\Payment\Helper\Data $adyenHelper
* @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger
* @param AdyenGenericConfig $genericConfig * @param AdyenGenericConfig $genericConfig
*/ */
public function __construct( public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Checkout\Model\Session $session,
\Magento\Store\Model\StoreManagerInterface $storeManager,
PaymentHelper $paymentHelper, PaymentHelper $paymentHelper,
\Magento\Framework\Locale\ResolverInterface $localeResolver,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Adyen\Payment\Helper\Data $adyenHelper,
\Adyen\Payment\Logger\AdyenLogger $adyenLogger,
\Adyen\Payment\Model\AdyenGenericConfig $genericConfig \Adyen\Payment\Model\AdyenGenericConfig $genericConfig
) { ) {
$this->_appState = $context->getAppState();
$this->_session = $session;
$this->_storeManager = $storeManager;
$this->_paymentHelper = $paymentHelper; $this->_paymentHelper = $paymentHelper;
$this->_localeResolver = $localeResolver;
$this->_config = $config;
$this->_adyenHelper = $adyenHelper;
$this->_adyenLogger = $adyenLogger;
$this->_genericConfig = $genericConfig; $this->_genericConfig = $genericConfig;
foreach ($this->methodCodes as $code) { foreach ($this->_methodCodes as $code) {
$this->methods[$code] = $this->_paymentHelper->getMethodInstance($code); $this->_methods[$code] = $this->_paymentHelper->getMethodInstance($code);
} }
} }
/** /**
* Define foreach payment methods the RedirectUrl * Define foreach payment methods the RedirectUrl
* *
...@@ -101,8 +83,8 @@ class AdyenGenericConfigProvider implements ConfigProviderInterface ...@@ -101,8 +83,8 @@ class AdyenGenericConfigProvider implements ConfigProviderInterface
'payment' => [] 'payment' => []
]; ];
foreach ($this->methodCodes as $code) { foreach ($this->_methodCodes as $code) {
if ($this->methods[$code]->isAvailable()) { if ($this->_methods[$code]->isAvailable()) {
$config['payment'][$code] = [ $config['payment'][$code] = [
'redirectUrl' => $this->getMethodRedirectUrl($code) 'redirectUrl' => $this->getMethodRedirectUrl($code)
...@@ -111,13 +93,11 @@ class AdyenGenericConfigProvider implements ConfigProviderInterface ...@@ -111,13 +93,11 @@ class AdyenGenericConfigProvider implements ConfigProviderInterface
} }
// show logos turned on by default // show logos turned on by default
if($this->_genericConfig->showLogos()) { if ($this->_genericConfig->showLogos()) {
$config['payment']['adyen']['showLogo'] = true; $config['payment']['adyen']['showLogo'] = true;
} else { } else {
$config['payment']['adyen']['showLogo'] = false; $config['payment']['adyen']['showLogo'] = false;
} }
return $config; return $config;
} }
...@@ -129,6 +109,6 @@ class AdyenGenericConfigProvider implements ConfigProviderInterface ...@@ -129,6 +109,6 @@ class AdyenGenericConfigProvider implements ConfigProviderInterface
*/ */
protected function getMethodRedirectUrl($code) protected function getMethodRedirectUrl($code)
{ {
return $this->methods[$code]->getCheckoutRedirectUrl(); return $this->_methods[$code]->getCheckoutRedirectUrl();
} }
} }
\ No newline at end of file
...@@ -78,7 +78,7 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -78,7 +78,7 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
/** /**
* @var string[] * @var string[]
*/ */
protected $methodCodes = [ protected $_methodCodes = [
'adyen_hpp' 'adyen_hpp'
]; ];
...@@ -88,6 +88,8 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -88,6 +88,8 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
protected $methods = []; protected $methods = [];
/** /**
* AdyenHppConfigProvider constructor.
*
* @param \Magento\Framework\Model\Context $context * @param \Magento\Framework\Model\Context $context
* @param \Magento\Checkout\Model\Session $session * @param \Magento\Checkout\Model\Session $session
* @param \Magento\Store\Model\StoreManagerInterface $storeManager * @param \Magento\Store\Model\StoreManagerInterface $storeManager
...@@ -119,12 +121,14 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -119,12 +121,14 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
$this->_adyenLogger = $adyenLogger; $this->_adyenLogger = $adyenLogger;
$this->_genericConfig = $genericConfig; $this->_genericConfig = $genericConfig;
foreach ($this->methodCodes as $code) { foreach ($this->_methodCodes as $code) {
$this->methods[$code] = $this->_paymentHelper->getMethodInstance($code); $this->methods[$code] = $this->_paymentHelper->getMethodInstance($code);
} }
} }
/**
* @return array
*/
public function getConfig() public function getConfig()
{ {
$config = [ $config = [
...@@ -133,7 +137,8 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -133,7 +137,8 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
] ]
] ]
]; ];
foreach ($this->methodCodes as $code) {
foreach ($this->_methodCodes as $code) {
if ($this->methods[$code]->isAvailable()) { if ($this->methods[$code]->isAvailable()) {
// get payment methods // get payment methods
$config['payment'] ['adyenHpp']['paymentMethods'] = $this->getAdyenHppPaymentMethods(); $config['payment'] ['adyenHpp']['paymentMethods'] = $this->getAdyenHppPaymentMethods();
...@@ -146,7 +151,10 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -146,7 +151,10 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
return $config; return $config;
} }
/**
* @return array|null
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getAdyenHppPaymentMethods() public function getAdyenHppPaymentMethods()
{ {
$paymentMethods = null; $paymentMethods = null;
...@@ -162,25 +170,33 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -162,25 +170,33 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
// is adyen HPP enabled ? // is adyen HPP enabled ?
$hppActive = $this->methods['adyen_hpp']->isAvailable(); $hppActive = $this->methods['adyen_hpp']->isAvailable();
if($hppActive) { if ($hppActive) {
$paymentMethods = $this->_addHppMethodsToConfig($store); $paymentMethods = $this->_addHppMethodsToConfig($store);
} }
return $paymentMethods; return $paymentMethods;
} }
/**
* @param $store
* @return array
*/
protected function _addHppMethodsToConfig($store) protected function _addHppMethodsToConfig($store)
{ {
$paymentMethods = []; $paymentMethods = [];
$ccEnabled = $this->_config->getValue('payment/'.\Adyen\Payment\Model\Method\Cc::METHOD_CODE.'/active'); $ccEnabled = $this->_config->getValue('payment/'.\Adyen\Payment\Model\Method\Cc::METHOD_CODE.'/active');
$ccTypes = array_keys($this->_adyenHelper->getCcTypesAltData()); $ccTypes = array_keys($this->_adyenHelper->getCcTypesAltData());
$sepaEnabled = $this->_config->getValue('payment/'.\Adyen\Payment\Model\Method\Sepa::METHOD_CODE.'/active');
foreach ($this->_fetchHppMethods($store) as $methodCode => $methodData) { foreach ($this->_fetchHppMethods($store) as $methodCode => $methodData) {
/*
// skip payment methods if it is a creditcard that is enabled in adyen_cc * skip payment methods if it is a creditcard that is enabled in adyen_cc
if ($ccEnabled * or if payment is sepadirectdebit and SEPA api is enabled
&& in_array($methodCode, $ccTypes)) { */
if ($ccEnabled && in_array($methodCode, $ccTypes)) {
continue;
} elseif ($methodCode == 'sepadirectdebit' && $sepaEnabled) {
continue; continue;
} }
...@@ -190,16 +206,20 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -190,16 +206,20 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
return $paymentMethods; return $paymentMethods;
} }
/**
* @param $store
* @return array
*/
protected function _fetchHppMethods($store) protected function _fetchHppMethods($store)
{ {
$skinCode = $this->_adyenHelper->getAdyenHppConfigData('skin_code'); $skinCode = $this->_adyenHelper->getAdyenHppConfigData('skin_code');
$merchantAccount = $this->_adyenHelper->getAdyenAbstractConfigData('merchant_account'); $merchantAccount = $this->_adyenHelper->getAdyenAbstractConfigData('merchant_account');
if (!$skinCode || !$merchantAccount) { if (!$skinCode || !$merchantAccount) {
return array(); return [];
} }
$adyFields = array( $adyFields = [
"paymentAmount" => (int) $this->_adyenHelper->formatAmount($this->_getCurrentPaymentAmount(), $this->_getCurrentCurrencyCode($store)), "paymentAmount" => (int) $this->_adyenHelper->formatAmount($this->_getCurrentPaymentAmount(), $this->_getCurrentCurrencyCode($store)),
"currencyCode" => $this->_getCurrentCurrencyCode($store), "currencyCode" => $this->_getCurrentCurrencyCode($store),
"merchantReference" => "Get Payment methods", "merchantReference" => "Get Payment methods",
...@@ -211,20 +231,20 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -211,20 +231,20 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
), ),
"countryCode" => $this->_getCurrentCountryCode($store), "countryCode" => $this->_getCurrentCountryCode($store),
"shopperLocale" => $this->_getCurrentLocaleCode($store) "shopperLocale" => $this->_getCurrentLocaleCode($store)
); ];
$responseData = $this->_getDirectoryLookupResponse($adyFields, $store); $responseData = $this->_getDirectoryLookupResponse($adyFields, $store);
$paymentMethods = array(); $paymentMethods = [];
if(isset($responseData['paymentMethods'])) { if (isset($responseData['paymentMethods'])) {
foreach ($responseData['paymentMethods'] as $paymentMethod) { foreach ($responseData['paymentMethods'] as $paymentMethod) {
$paymentMethodCode = $paymentMethod['brandCode']; $paymentMethodCode = $paymentMethod['brandCode'];
$paymentMethod = $this->_fieldMapPaymentMethod($paymentMethod); $paymentMethod = $this->_fieldMapPaymentMethod($paymentMethod);
// add icon location in result // add icon location in result
if($this->_genericConfig->showLogos()) { if ($this->_genericConfig->showLogos()) {
$asset = $this->_genericConfig->createAsset('Adyen_Payment::images/logos/' . $paymentMethodCode . '.png'); $asset = $this->_genericConfig->createAsset('Adyen_Payment::images/logos/' .
$paymentMethodCode . '.png');
$placeholder = $this->_genericConfig->findRelativeSourceFilePath($asset); $placeholder = $this->_genericConfig->findRelativeSourceFilePath($asset);
...@@ -240,7 +260,6 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -240,7 +260,6 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
$paymentMethod['icon'] = $icon; $paymentMethod['icon'] = $icon;
} }
$paymentMethods[$paymentMethodCode] = $paymentMethod; $paymentMethods[$paymentMethodCode] = $paymentMethod;
} }
} }
...@@ -260,7 +279,8 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -260,7 +279,8 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
} }
/** /**
* @return string * @param $store
* @return mixed
*/ */
protected function _getCurrentCurrencyCode($store) protected function _getCurrentCurrencyCode($store)
{ {
...@@ -268,15 +288,15 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -268,15 +288,15 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
} }
/** /**
* @return string * @param $store
* @return int|mixed|string
*/ */
protected function _getCurrentCountryCode($store) protected function _getCurrentCountryCode($store)
{ {
// if fixed countryCode is setup in config use this // if fixed countryCode is setup in config use this
$countryCode = $this->_adyenHelper->getAdyenHppConfigData('country_code', $store->getId()); $countryCode = $this->_adyenHelper->getAdyenHppConfigData('country_code', $store->getId());
if($countryCode != "") { if ($countryCode != "") {
return $countryCode; return $countryCode;
} }
...@@ -290,7 +310,7 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -290,7 +310,7 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
$store->getCode() $store->getCode()
); );
if($defaultCountry) { if ($defaultCountry) {
return $defaultCountry; return $defaultCountry;
} }
...@@ -298,17 +318,18 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -298,17 +318,18 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
} }
/** /**
* @return string * @param $store
* @return mixed|string
*/ */
protected function _getCurrentLocaleCode($store) protected function _getCurrentLocaleCode($store)
{ {
$localeCode = $this->_adyenHelper->getAdyenAbstractConfigData('shopper_locale', $store->getId()); $localeCode = $this->_adyenHelper->getAdyenAbstractConfigData('shopper_locale', $store->getId());
if($localeCode != "") { if ($localeCode != "") {
return $localeCode; return $localeCode;
} }
$locale = $this->_localeResolver->getLocale(); $locale = $this->_localeResolver->getLocale();
if($locale) { if ($locale) {
return $locale; return $locale;
} }
...@@ -322,10 +343,17 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -322,10 +343,17 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
return $localeCode; return $localeCode;
} }
protected $_fieldMapPaymentMethod = array( /**
* @var array
*/
protected $_fieldMapPaymentMethod = [
'name' => 'title' 'name' => 'title'
); ];
/**
* @param $paymentMethod
* @return mixed
*/
protected function _fieldMapPaymentMethod($paymentMethod) protected function _fieldMapPaymentMethod($paymentMethod)
{ {
foreach ($this->_fieldMapPaymentMethod as $field => $newField) { foreach ($this->_fieldMapPaymentMethod as $field => $newField) {
...@@ -337,6 +365,12 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -337,6 +365,12 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
return $paymentMethod; return $paymentMethod;
} }
/**
* @param $requestParams
* @param $store
* @return array
* @throws \Adyen\AdyenException
*/
protected function _getDirectoryLookupResponse($requestParams, $store) protected function _getDirectoryLookupResponse($requestParams, $store)
{ {
$cacheKey = $this->_getCacheKeyForRequest($requestParams, $store); $cacheKey = $this->_getCacheKeyForRequest($requestParams, $store);
...@@ -344,7 +378,7 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -344,7 +378,7 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
// initialize the adyen client // initialize the adyen client
$client = new \Adyen\Client(); $client = new \Adyen\Client();
if($this->_adyenHelper->isDemoMode()) { if ($this->_adyenHelper->isDemoMode()) {
$client->setEnvironment(\Adyen\Environment::TEST); $client->setEnvironment(\Adyen\Environment::TEST);
} else { } else {
$client->setEnvironment(\Adyen\Environment::LIVE); $client->setEnvironment(\Adyen\Environment::LIVE);
...@@ -356,30 +390,33 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -356,30 +390,33 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
$hmacKey = $this->_adyenHelper->getHmac(); $hmacKey = $this->_adyenHelper->getHmac();
// create and add signature // create and add signature
$requestParams["merchantSig"] = \Adyen\Util\Util::calculateSha256Signature($hmacKey, $requestParams); try {
$requestParams["merchantSig"] = \Adyen\Util\Util::calculateSha256Signature($hmacKey, $requestParams);
} catch (\Adyen\AdyenException $e) {
$this->_adyenLogger->error($e->getMessage());
// return empty result
return [];
}
// initialize service // initialize service
$service = new \Adyen\Service\DirectoryLookup($client); $service = new \Adyen\Service\DirectoryLookup($client);
try { try {
$responseData = $service->directoryLookup($requestParams); $responseData = $service->directoryLookup($requestParams);
}catch (Exception $e) { } catch (\Adyen\AdyenException $e) {
$this->_adyenLogger->error("The Directory Lookup response is empty check your Adyen configuration in Magento."); $this->_adyenLogger->error(
"The Directory Lookup response is empty check your Adyen configuration in Magento."
);
// return empty result // return empty result
return array(); return [];
} }
// save result in cache
// Mage::app()->getCache()->save(
// serialize($responseData),
// $cacheKey,
// array(Mage_Core_Model_Config::CACHE_TAG),
// 60 * 60 * 6
// );
return $responseData; return $responseData;
} }
/**
* @var array
*/
protected $_cacheParams = array( protected $_cacheParams = array(
'currencyCode', 'currencyCode',
'merchantReference', 'merchantReference',
...@@ -389,9 +426,14 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -389,9 +426,14 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
'shopperLocale', 'shopperLocale',
); );
/**
* @param $requestParams
* @param $store
* @return string
*/
protected function _getCacheKeyForRequest($requestParams, $store) protected function _getCacheKeyForRequest($requestParams, $store)
{ {
$cacheParams = array(); $cacheParams = [];
$cacheParams['store'] = $store->getId(); $cacheParams['store'] = $store->getId();
foreach ($this->_cacheParams as $paramKey) { foreach ($this->_cacheParams as $paramKey) {
if (isset($requestParams[$paramKey])) { if (isset($requestParams[$paramKey])) {
...@@ -402,12 +444,14 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -402,12 +444,14 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
return md5(implode('|', $cacheParams)); return md5(implode('|', $cacheParams));
} }
/**
* @return \Magento\Quote\Model\Quote
*/
protected function _getQuote() protected function _getQuote()
{ {
return $this->_session->getQuote(); return $this->_session->getQuote();
} }
/** /**
* Create a file asset that's subject of fallback system * Create a file asset that's subject of fallback system
* *
...@@ -420,5 +464,4 @@ class AdyenHppConfigProvider implements ConfigProviderInterface ...@@ -420,5 +464,4 @@ class AdyenHppConfigProvider implements ConfigProviderInterface
$params = array_merge(['_secure' => $this->request->isSecure()], $params); $params = array_merge(['_secure' => $this->request->isSecure()], $params);
return $this->assetRepo->createAsset($fileId, $params); return $this->assetRepo->createAsset($fileId, $params);
} }
} }
\ No newline at end of file
...@@ -37,7 +37,7 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider ...@@ -37,7 +37,7 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider
/** /**
* @var string[] * @var string[]
*/ */
protected $methodCodes = [ protected $_methodCodes = [
\Adyen\Payment\Model\Method\Oneclick::METHOD_CODE \Adyen\Payment\Model\Method\Oneclick::METHOD_CODE
]; ];
...@@ -86,11 +86,18 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider ...@@ -86,11 +86,18 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider
*/ */
protected $_genericConfig; protected $_genericConfig;
/** /**
* AdyenOneclickConfigProvider constructor.
*
* @param \Magento\Framework\Model\Context $context
* @param \Magento\Payment\Model\CcConfig $ccConfig * @param \Magento\Payment\Model\CcConfig $ccConfig
* @param PaymentHelper $paymentHelper * @param PaymentHelper $paymentHelper
* @param \Adyen\Payment\Helper\Data $adyenHelper * @param \Adyen\Payment\Helper\Data $adyenHelper
* @param Resource\Billing\Agreement\CollectionFactory $billingAgreementCollectionFactory
* @param \Magento\Customer\Model\Session $customerSession
* @param \Magento\Checkout\Model\Session $session
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param AdyenGenericConfig $genericConfig
*/ */
public function __construct( public function __construct(
\Magento\Framework\Model\Context $context, \Magento\Framework\Model\Context $context,
...@@ -103,7 +110,7 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider ...@@ -103,7 +110,7 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider
\Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Store\Model\StoreManagerInterface $storeManager,
\Adyen\Payment\Model\AdyenGenericConfig $genericConfig \Adyen\Payment\Model\AdyenGenericConfig $genericConfig
) { ) {
parent::__construct($ccConfig, $paymentHelper, $this->methodCodes); parent::__construct($ccConfig, $paymentHelper, $this->_methodCodes);
$this->_paymentHelper = $paymentHelper; $this->_paymentHelper = $paymentHelper;
$this->_adyenHelper = $adyenHelper; $this->_adyenHelper = $adyenHelper;
$this->_billingAgreementCollectionFactory = $billingAgreementCollectionFactory; $this->_billingAgreementCollectionFactory = $billingAgreementCollectionFactory;
...@@ -114,13 +121,16 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider ...@@ -114,13 +121,16 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider
$this->_genericConfig = $genericConfig; $this->_genericConfig = $genericConfig;
} }
/**
* @return array
*/
public function getConfig() public function getConfig()
{ {
$config = parent::getConfig(); $config = parent::getConfig();
$demoMode = $this->_adyenHelper->getAdyenAbstractConfigDataFlag('demo_mode'); $demoMode = $this->_adyenHelper->getAdyenAbstractConfigDataFlag('demo_mode');
if($demoMode) { if ($demoMode) {
$cseKey = $this->_adyenHelper->getAdyenCcConfigData('cse_publickey_test'); $cseKey = $this->_adyenHelper->getAdyenCcConfigData('cse_publickey_test');
} else { } else {
$cseKey = $this->_adyenHelper->getAdyenCcConfigData('cse_publickey_live'); $cseKey = $this->_adyenHelper->getAdyenCcConfigData('cse_publickey_live');
...@@ -130,26 +140,24 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider ...@@ -130,26 +140,24 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider
$recurringType = $this->_adyenHelper->getAdyenAbstractConfigData('recurring_type'); $recurringType = $this->_adyenHelper->getAdyenAbstractConfigData('recurring_type');
$canCreateBillingAgreement = false; $canCreateBillingAgreement = false;
if($recurringType == "ONECLICK" || $recurringType == "ONECLICK,RECURRING") { if ($recurringType == "ONECLICK" || $recurringType == "ONECLICK,RECURRING") {
$canCreateBillingAgreement = true; $canCreateBillingAgreement = true;
} }
$config['payment'] ['adyenOneclick']['cseKey'] = $cseKey; $config['payment'] ['adyenOneclick']['cseKey'] = $cseKey;
$config['payment'] ['adyenOneclick']['cseEnabled'] = $cseEnabled; $config['payment'] ['adyenOneclick']['cseEnabled'] = $cseEnabled;
$config['payment'] ['adyenOneclick']['cseEnabled'] = $cseEnabled; $config['payment'] ['adyenOneclick']['cseEnabled'] = $cseEnabled;
$config['payment']['adyenOneclick']['generationTime'] = date("c"); $config['payment']['adyenOneclick']['generationTime'] = date("c");
$config['payment']['adyenOneclick']['canCreateBillingAgreement'] = $canCreateBillingAgreement; $config['payment']['adyenOneclick']['canCreateBillingAgreement'] = $canCreateBillingAgreement;
foreach ($this->_methodCodes as $code) {
foreach ($this->methodCodes as $code) {
if ($this->methods[$code]->isAvailable()) { if ($this->methods[$code]->isAvailable()) {
$recurringContractType = $this->_getRecurringContractType(); $recurringContractType = $this->_getRecurringContractType();
$config['payment'] ['adyenOneclick']['billingAgreements'] = $this->getAdyenOneclickPaymentMethods(); $config['payment'] ['adyenOneclick']['billingAgreements'] = $this->getAdyenOneclickPaymentMethods();
$config['payment'] ['adyenOneclick']['recurringContractType'] = $recurringContractType; $config['payment'] ['adyenOneclick']['recurringContractType'] = $recurringContractType;
if($recurringContractType == \Adyen\Payment\Model\RecurringType::ONECLICK) { if ($recurringContractType == \Adyen\Payment\Model\RecurringType::ONECLICK) {
$config['payment'] ['adyenOneclick']['hasCustomerInteraction'] = true; $config['payment'] ['adyenOneclick']['hasCustomerInteraction'] = true;
} else { } else {
$config['payment'] ['adyenOneclick']['hasCustomerInteraction'] = false; $config['payment'] ['adyenOneclick']['hasCustomerInteraction'] = false;
...@@ -159,16 +167,15 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider ...@@ -159,16 +167,15 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider
return $config; return $config;
} }
/**
* @return array
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getAdyenOneclickPaymentMethods() public function getAdyenOneclickPaymentMethods()
{ {
$billingAgreements = []; $billingAgreements = [];
if ($this->_customerSession->isLoggedIn()) { if ($this->_customerSession->isLoggedIn()) {
$customerId = $this->_customerSession->getCustomerId(); $customerId = $this->_customerSession->getCustomerId();
// is admin? // is admin?
if ($this->_appState->getAreaCode() === \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE) { if ($this->_appState->getAreaCode() === \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE) {
//retrieve storeId from quote //retrieve storeId from quote
...@@ -190,29 +197,31 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider ...@@ -190,29 +197,31 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider
$agreementData = $billingAgreement->getAgreementData(); $agreementData = $billingAgreement->getAgreementData();
// no agreementData and contractType then ignore // no agreementData and contractType then ignore
if((!is_array($agreementData)) || (!isset($agreementData['contractTypes']))) { if ((!is_array($agreementData)) || (!isset($agreementData['contractTypes']))) {
continue; continue;
} }
// check if contractType is supporting the selected contractType for OneClick payments // check if contractType is supporting the selected contractType for OneClick payments
$allowedContractTypes = $agreementData['contractTypes']; $allowedContractTypes = $agreementData['contractTypes'];
if(in_array($recurringPaymentType, $allowedContractTypes)) { if (in_array($recurringPaymentType, $allowedContractTypes)) {
// check if AgreementLabel is set and if contract has an recurringType // check if AgreementLabel is set and if contract has an recurringType
if($billingAgreement->getAgreementLabel()) { if ($billingAgreement->getAgreementLabel()) {
$data = ['reference_id' => $billingAgreement->getReferenceId(), $data = ['reference_id' => $billingAgreement->getReferenceId(),
'agreement_label' => $billingAgreement->getAgreementLabel(), 'agreement_label' => $billingAgreement->getAgreementLabel(),
'agreement_data' => $agreementData 'agreement_data' => $agreementData
]; ];
if($this->_genericConfig->showLogos()) { if ($this->_genericConfig->showLogos()) {
$logoName = $agreementData['variant']; $logoName = $agreementData['variant'];
// for Ideal use sepadirectdebit because it is // for Ideal use sepadirectdebit because it is
if($agreementData['variant'] == 'ideal') { if ($agreementData['variant'] == 'ideal') {
$logoName = "sepadirectdebit"; $logoName = "sepadirectdebit";
} }
$asset = $this->_genericConfig->createAsset('Adyen_Payment::images/logos/' . $logoName . '.png'); $asset = $this->_genericConfig->createAsset(
'Adyen_Payment::images/logos/' . $logoName . '.png'
);
$placeholder = $this->_genericConfig->findRelativeSourceFilePath($asset); $placeholder = $this->_genericConfig->findRelativeSourceFilePath($asset);
$icon = null; $icon = null;
...@@ -225,9 +234,7 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider ...@@ -225,9 +234,7 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider
]; ];
} }
$data['logo'] = $icon; $data['logo'] = $icon;
} }
$billingAgreements[] = $data; $billingAgreements[] = $data;
} }
} }
...@@ -236,6 +243,9 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider ...@@ -236,6 +243,9 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider
return $billingAgreements; return $billingAgreements;
} }
/**
* @return mixed
*/
protected function _getRecurringContractType() protected function _getRecurringContractType()
{ {
return $this->_adyenHelper->getAdyenOneclickConfigData('recurring_payment_type'); return $this->_adyenHelper->getAdyenOneclickConfigData('recurring_payment_type');
......
<?php
/**
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Payment module (https://www.adyen.com/)
*
* Copyright (c) 2015 Adyen BV (https://www.adyen.com/)
* See LICENSE.txt for license details.
*
* Author: Adyen <magento@adyen.com>
*/
namespace Adyen\Payment\Model;
use Magento\Checkout\Model\ConfigProviderInterface;
use Magento\Payment\Helper\Data as PaymentHelper;
use Magento\Directory\Helper\Data;
class AdyenSepaConfigProvider implements ConfigProviderInterface
{
/**
* @var string[]
*/
protected $_methodCodes = [
'adyen_sepa'
];
/**
* @var \Magento\Payment\Model\Method\AbstractMethod[]
*/
protected $_methods = [];
/**
* @var PaymentHelper
*/
protected $_paymentHelper;
/**
* @var \Magento\Directory\Model\Config\Source\Country
*/
protected $_country;
/**
* AdyenSepaConfigProvider constructor.
*
* @param PaymentHelper $paymentHelper
* @param \Magento\Directory\Model\Config\Source\Country $country
*/
public function __construct(
PaymentHelper $paymentHelper,
\Magento\Directory\Model\Config\Source\Country $country
) {
$this->_paymentHelper = $paymentHelper;
$this->_country = $country;
foreach ($this->_methodCodes as $code) {
$this->_methods[$code] = $this->_paymentHelper->getMethodInstance($code);
}
}
/**
* @return array
*/
public function getConfig()
{
$config = [
'payment' => [
'adyenSepa' => [
'countries' => $this->getCountries()
]
]
];
return $config;
}
/**
* @return array
*/
public function getCountries()
{
$sepaCountriesAllowed = [
"AT", "BE", "BG", "CH", "CY", "CZ", "DE", "DK", "EE", "ES", "FI", "FR", "GB", "GF", "GI", "GP", "GR", "HR",
"HU", "IE", "IS", "IT", "LI", "LT", "LU", "LV", "MC", "MQ", "MT", "NL", "NO", "PL", "PT", "RE", "RO", "SE",
"SI", "SK"
];
$countryList = $this->_country->toOptionArray();
$sepaCountries = [];
foreach ($countryList as $key => $country) {
$value = $country['value'];
if (in_array($value, $sepaCountriesAllowed)) {
$sepaCountries[$value] = $country['label'];
}
}
return $sepaCountries;
}
}
\ No newline at end of file
...@@ -27,15 +27,6 @@ use Magento\Framework\DataObject; ...@@ -27,15 +27,6 @@ use Magento\Framework\DataObject;
class PaymentRequest extends DataObject class PaymentRequest extends DataObject
{ {
/**
* @var \Magento\Framework\App\Config\ScopeConfigInterface
*/
protected $_scopeConfig;
/**
* @var \Psr\Log\LoggerInterface
*/
protected $_logger;
/** /**
* @var \Magento\Framework\Encryption\EncryptorInterface * @var \Magento\Framework\Encryption\EncryptorInterface
...@@ -62,11 +53,17 @@ class PaymentRequest extends DataObject ...@@ -62,11 +53,17 @@ class PaymentRequest extends DataObject
*/ */
protected $_recurringType; protected $_recurringType;
/**
* @var \Magento\Framework\App\State
*/
protected $_appState;
const GUEST_ID = 'customer_'; const GUEST_ID = 'customer_';
/** /**
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig * PaymentRequest constructor.
* @param \Psr\Log\LoggerInterface $logger *
* @param \Magento\Framework\Model\Context $context
* @param \Magento\Framework\Encryption\EncryptorInterface $encryptor * @param \Magento\Framework\Encryption\EncryptorInterface $encryptor
* @param \Adyen\Payment\Helper\Data $adyenHelper * @param \Adyen\Payment\Helper\Data $adyenHelper
* @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger * @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger
...@@ -74,20 +71,18 @@ class PaymentRequest extends DataObject ...@@ -74,20 +71,18 @@ class PaymentRequest extends DataObject
* @param array $data * @param array $data
*/ */
public function __construct( public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Framework\Model\Context $context,
\Psr\Log\LoggerInterface $logger,
\Magento\Framework\Encryption\EncryptorInterface $encryptor, \Magento\Framework\Encryption\EncryptorInterface $encryptor,
\Adyen\Payment\Helper\Data $adyenHelper, \Adyen\Payment\Helper\Data $adyenHelper,
\Adyen\Payment\Logger\AdyenLogger $adyenLogger, \Adyen\Payment\Logger\AdyenLogger $adyenLogger,
\Adyen\Payment\Model\RecurringType $recurringType, \Adyen\Payment\Model\RecurringType $recurringType,
array $data = [] array $data = []
) { ) {
$this->_scopeConfig = $scopeConfig;
$this->_logger = $logger;
$this->_encryptor = $encryptor; $this->_encryptor = $encryptor;
$this->_adyenHelper = $adyenHelper; $this->_adyenHelper = $adyenHelper;
$this->_adyenLogger = $adyenLogger; $this->_adyenLogger = $adyenLogger;
$this->_recurringType = $recurringType; $this->_recurringType = $recurringType;
$this->_appState = $context->getAppState();
// initialize client // initialize client
$webserviceUsername = $this->_adyenHelper->getWsUsername(); $webserviceUsername = $this->_adyenHelper->getWsUsername();
...@@ -98,7 +93,7 @@ class PaymentRequest extends DataObject ...@@ -98,7 +93,7 @@ class PaymentRequest extends DataObject
$client->setUsername($webserviceUsername); $client->setUsername($webserviceUsername);
$client->setPassword($webservicePassword); $client->setPassword($webservicePassword);
if($this->_adyenHelper->isDemoMode()) { if ($this->_adyenHelper->isDemoMode()) {
$client->setEnvironment(\Adyen\Environment::TEST); $client->setEnvironment(\Adyen\Environment::TEST);
} else { } else {
$client->setEnvironment(\Adyen\Environment::LIVE); $client->setEnvironment(\Adyen\Environment::LIVE);
...@@ -108,18 +103,28 @@ class PaymentRequest extends DataObject ...@@ -108,18 +103,28 @@ class PaymentRequest extends DataObject
$client->setLogger($adyenLogger); $client->setLogger($adyenLogger);
$this->_client = $client; $this->_client = $client;
} }
/**
* @param $payment
* @param $paymentMethodCode
* @return mixed
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function fullApiRequest($payment, $paymentMethodCode) public function fullApiRequest($payment, $paymentMethodCode)
{ {
$storeId = null;
if ($this->_appState->getAreaCode() === \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE) {
$storeId = $payment->getOrder()->getStoreId();
}
$order = $payment->getOrder(); $order = $payment->getOrder();
$amount = $order->getGrandTotal(); $amount = $order->getGrandTotal();
$customerEmail = $order->getCustomerEmail(); $customerEmail = $order->getCustomerEmail();
$shopperIp = $order->getRemoteIp(); $shopperIp = $order->getRemoteIp();
$orderCurrencyCode = $order->getOrderCurrencyCode(); $orderCurrencyCode = $order->getOrderCurrencyCode();
$merchantAccount = $this->_adyenHelper->getAdyenAbstractConfigData("merchant_account"); $merchantAccount = $this->_adyenHelper->getAdyenAbstractConfigData("merchant_account", $storeId);
$recurringType = $this->_adyenHelper->getAdyenAbstractConfigData('recurring_type'); $recurringType = $this->_adyenHelper->getAdyenAbstractConfigData('recurring_type', $storeId);
$realOrderId = $order->getRealOrderId(); $realOrderId = $order->getRealOrderId();
$customerId = $order->getCustomerId(); $customerId = $order->getCustomerId();
...@@ -128,10 +133,11 @@ class PaymentRequest extends DataObject ...@@ -128,10 +133,11 @@ class PaymentRequest extends DataObject
// call lib // call lib
$service = new \Adyen\Service\Payment($this->_client); $service = new \Adyen\Service\Payment($this->_client);
$amount = ['currency' => $orderCurrencyCode, 'value' => $this->_adyenHelper->formatAmount($amount, $orderCurrencyCode)]; $amount = ['currency' => $orderCurrencyCode,
'value' => $this->_adyenHelper->formatAmount($amount, $orderCurrencyCode)];
$browserInfo = ['userAgent' => $_SERVER['HTTP_USER_AGENT'], 'acceptHeader' => $_SERVER['HTTP_ACCEPT']]; $browserInfo = ['userAgent' => $_SERVER['HTTP_USER_AGENT'], 'acceptHeader' => $_SERVER['HTTP_ACCEPT']];
$request = array( $request = [
"merchantAccount" => $merchantAccount, "merchantAccount" => $merchantAccount,
"amount" => $amount, "amount" => $amount,
"reference" => $order->getIncrementId(), "reference" => $order->getIncrementId(),
...@@ -140,23 +146,26 @@ class PaymentRequest extends DataObject ...@@ -140,23 +146,26 @@ class PaymentRequest extends DataObject
"shopperReference" => $shopperReference, "shopperReference" => $shopperReference,
"fraudOffset" => "0", "fraudOffset" => "0",
"browserInfo" => $browserInfo "browserInfo" => $browserInfo
); ];
// set the recurring type // set the recurring type
$recurringContractType = null; $recurringContractType = null;
if($recurringType) { if ($recurringType) {
if($paymentMethodCode == \Adyen\Payment\Model\Method\Oneclick::METHOD_CODE) { if ($paymentMethodCode == \Adyen\Payment\Model\Method\Oneclick::METHOD_CODE) {
// For ONECLICK look at the recurringPaymentType that the merchant has selected in Adyen ONECLICK settings /*
if($payment->getAdditionalInformation('customer_interaction')) { * For ONECLICK look at the recurringPaymentType that the merchant
* has selected in Adyen ONECLICK settings
*/
if ($payment->getAdditionalInformation('customer_interaction')) {
$recurringContractType = \Adyen\Payment\Model\RecurringType::ONECLICK; $recurringContractType = \Adyen\Payment\Model\RecurringType::ONECLICK;
} else { } else {
$recurringContractType = \Adyen\Payment\Model\RecurringType::RECURRING; $recurringContractType = \Adyen\Payment\Model\RecurringType::RECURRING;
} }
} else if($paymentMethodCode == \Adyen\Payment\Model\Method\Cc::METHOD_CODE) { } else if ($paymentMethodCode == \Adyen\Payment\Model\Method\Cc::METHOD_CODE) {
if($payment->getAdditionalInformation("store_cc") == "" && ($recurringType == "ONECLICK,RECURRING" || $recurringType == "RECURRING")) { if ($payment->getAdditionalInformation("store_cc") == "" &&
($recurringType == "ONECLICK,RECURRING" || $recurringType == "RECURRING")) {
$recurringContractType = \Adyen\Payment\Model\RecurringType::RECURRING; $recurringContractType = \Adyen\Payment\Model\RecurringType::RECURRING;
} elseif($payment->getAdditionalInformation("store_cc") == "1") { } elseif ($payment->getAdditionalInformation("store_cc") == "1") {
$recurringContractType = $recurringType; $recurringContractType = $recurringType;
} }
} else { } else {
...@@ -164,52 +173,47 @@ class PaymentRequest extends DataObject ...@@ -164,52 +173,47 @@ class PaymentRequest extends DataObject
} }
} }
if($recurringContractType) if ($recurringContractType) {
{ $recurring = ['contract' => $recurringContractType];
$recurring = array('contract' => $recurringContractType);
$request['recurring'] = $recurring; $request['recurring'] = $recurring;
} }
$billingAddress = $order->getBillingAddress(); $billingAddress = $order->getBillingAddress();
if($billingAddress) if ($billingAddress) {
{
$addressArray = $this->_adyenHelper->getStreet($billingAddress); $addressArray = $this->_adyenHelper->getStreet($billingAddress);
$requestBilling = array("street" => $addressArray['name'], $requestBilling = ["street" => $addressArray['name'],
"postalCode" => $billingAddress->getPostcode(), "postalCode" => $billingAddress->getPostcode(),
"city" => $billingAddress->getCity(), "city" => $billingAddress->getCity(),
"houseNumberOrName" => $addressArray['house_number'], "houseNumberOrName" => $addressArray['house_number'],
"stateOrProvince" => $billingAddress->getRegionCode(), "stateOrProvince" => $billingAddress->getRegionCode(),
"country" => $billingAddress->getCountryId() "country" => $billingAddress->getCountryId()
); ];
// houseNumberOrName is mandatory // houseNumberOrName is mandatory
if($requestBilling['houseNumberOrName'] == "") { if ($requestBilling['houseNumberOrName'] == "") {
$requestBilling['houseNumberOrName'] = "NA"; $requestBilling['houseNumberOrName'] = "NA";
} }
$requestBilling['billingAddress'] = $requestBilling; $requestBilling['billingAddress'] = $requestBilling;
$request = array_merge($request, $requestBilling); $request = array_merge($request, $requestBilling);
} }
$deliveryAddress = $order->getDeliveryAddress(); $deliveryAddress = $order->getDeliveryAddress();
if($deliveryAddress) if($deliveryAddress) {
{
$addressArray = $this->_adyenHelper->getStreet($deliveryAddress); $addressArray = $this->_adyenHelper->getStreet($deliveryAddress);
$requestDelivery = array("street" => $addressArray['name'], $requestDelivery = ["street" => $addressArray['name'],
"postalCode" => $deliveryAddress->getPostcode(), "postalCode" => $deliveryAddress->getPostcode(),
"city" => $deliveryAddress->getCity(), "city" => $deliveryAddress->getCity(),
"houseNumberOrName" => $addressArray['house_number'], "houseNumberOrName" => $addressArray['house_number'],
"stateOrProvince" => $deliveryAddress->getRegionCode(), "stateOrProvince" => $deliveryAddress->getRegionCode(),
"country" => $deliveryAddress->getCountryId() "country" => $deliveryAddress->getCountryId()
); ];
// houseNumberOrName is mandatory // houseNumberOrName is mandatory
if($requestDelivery['houseNumberOrName'] == "") { if ($requestDelivery['houseNumberOrName'] == "") {
$requestDelivery['houseNumberOrName'] = "NA"; $requestDelivery['houseNumberOrName'] = "NA";
} }
...@@ -217,54 +221,85 @@ class PaymentRequest extends DataObject ...@@ -217,54 +221,85 @@ class PaymentRequest extends DataObject
$request = array_merge($request, $requestDelivery); $request = array_merge($request, $requestDelivery);
} }
$enableMoto = $this->_adyenHelper->getAdyenCcConfigDataFlag('enable_moto', $storeId);
$recurringDetailReference = null;
// define the shopper interaction // define the shopper interaction
if($paymentMethodCode == \Adyen\Payment\Model\Method\Oneclick::METHOD_CODE) { if ($this->_appState->getAreaCode() === \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE &&
$paymentMethodCode == \Adyen\Payment\Model\Method\Cc::METHOD_CODE &&
$enableMoto) {
// if MOTO for backend is enabled use MOTO as shopper interaction type
$shopperInteraction = "Moto";
} else if ($paymentMethodCode == \Adyen\Payment\Model\Method\Oneclick::METHOD_CODE) {
$recurringDetailReference = $payment->getAdditionalInformation("recurring_detail_reference"); $recurringDetailReference = $payment->getAdditionalInformation("recurring_detail_reference");
if($payment->getAdditionalInformation('customer_interaction')) { if ($payment->getAdditionalInformation('customer_interaction')) {
$shopperInteraction = "Ecommerce"; $shopperInteraction = "Ecommerce";
} else { } else {
$shopperInteraction = "ContAuth"; $shopperInteraction = "ContAuth";
} }
// For recurring Ideal and Sofort needs to be converted to SEPA for this it is mandatory to set selectBrand to sepadirectdebit /*
if(!$payment->getAdditionalInformation('customer_interaction')) { * For recurring Ideal and Sofort needs to be converted to SEPA
if($payment->getCcType() == "directEbanking" || $payment->getCcType() == "ideal") { * for this it is mandatory to set selectBrand to sepadirectdebit
*/
if (!$payment->getAdditionalInformation('customer_interaction')) {
if ($payment->getCcType() == "directEbanking" || $payment->getCcType() == "ideal") {
$request['selectedBrand'] = "sepadirectdebit"; $request['selectedBrand'] = "sepadirectdebit";
} }
} }
} else { } else {
$recurringDetailReference = null;
$shopperInteraction = "Ecommerce"; $shopperInteraction = "Ecommerce";
} }
if($shopperInteraction) { if ($shopperInteraction) {
$request['shopperInteraction'] = $shopperInteraction; $request['shopperInteraction'] = $shopperInteraction;
} }
if($recurringDetailReference && $recurringDetailReference != "") { if ($recurringDetailReference && $recurringDetailReference != "") {
$request['selectedRecurringDetailReference'] = $recurringDetailReference; $request['selectedRecurringDetailReference'] = $recurringDetailReference;
} }
// If cse is enabled add encrypted card date into request if ($paymentMethodCode == \Adyen\Payment\Model\Method\Cc::METHOD_CODE ||
if($this->_adyenHelper->getAdyenCcConfigDataFlag('cse_enabled')) { $paymentMethodCode == \Adyen\Payment\Model\Method\Oneclick::METHOD_CODE) {
$request['additionalData']['card.encrypted.json'] = $payment->getAdditionalInformation("encrypted_data"); // If cse is enabled add encrypted card date into request
} else { if ($this->_adyenHelper->getAdyenCcConfigDataFlag('cse_enabled')) {
$requestCreditCardDetails = array( $request['additionalData']['card.encrypted.json'] =
"expiryMonth" => $payment->getCcExpMonth(), $payment->getAdditionalInformation("encrypted_data");
"expiryYear" => $payment->getCcExpYear(), } else {
"holderName" => $payment->getCcOwner(), $requestCreditCardDetails = [
"number" => $payment->getCcNumber(), "expiryMonth" => $payment->getCcExpMonth(),
"cvc" => $payment->getCcCid(), "expiryYear" => $payment->getCcExpYear(),
); "holderName" => $payment->getCcOwner(),
$cardDetails['card'] = $requestCreditCardDetails; "number" => $payment->getCcNumber(),
$request = array_merge($request, $cardDetails); "cvc" => $payment->getCcCid(),
];
$cardDetails['card'] = $requestCreditCardDetails;
$request = array_merge($request, $cardDetails);
}
} elseif ($paymentMethodCode == \Adyen\Payment\Model\Method\Sepa::METHOD_CODE) {
// set brand to sepa
$request['selectedBrand'] = "sepadirectdebit";
// add bankDetails into request
$bankAccount = [
'iban' => $payment->getAdditionalInformation("iban"),
'ownerName' => $payment->getAdditionalInformation("account_name"),
'countryCode' => $payment->getAdditionalInformation("country")
];
$request['bankAccount'] = $bankAccount;
} }
$result = $service->authorise($request); $result = $service->authorise($request);
return $result; return $result;
} }
/**
* @param $payment
* @return mixed
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function authorise3d($payment) public function authorise3d($payment)
{ {
$order = $payment->getOrder(); $order = $payment->getOrder();
...@@ -275,13 +310,13 @@ class PaymentRequest extends DataObject ...@@ -275,13 +310,13 @@ class PaymentRequest extends DataObject
$paResponse = $payment->getAdditionalInformation('paResponse'); $paResponse = $payment->getAdditionalInformation('paResponse');
$browserInfo = ['userAgent' => $_SERVER['HTTP_USER_AGENT'], 'acceptHeader' => $_SERVER['HTTP_ACCEPT']]; $browserInfo = ['userAgent' => $_SERVER['HTTP_USER_AGENT'], 'acceptHeader' => $_SERVER['HTTP_ACCEPT']];
$request = array( $request = [
"merchantAccount" => $merchantAccount, "merchantAccount" => $merchantAccount,
"browserInfo" => $browserInfo, "browserInfo" => $browserInfo,
"md" => $md, "md" => $md,
"paResponse" => $paResponse, "paResponse" => $paResponse,
"shopperIP" => $shopperIp "shopperIP" => $shopperIp
); ];
try { try {
$service = new \Adyen\Service\Payment($this->_client); $service = new \Adyen\Service\Payment($this->_client);
...@@ -310,20 +345,20 @@ class PaymentRequest extends DataObject ...@@ -310,20 +345,20 @@ class PaymentRequest extends DataObject
//format the amount to minor units //format the amount to minor units
$amount = $this->_adyenHelper->formatAmount($amount, $currency); $amount = $this->_adyenHelper->formatAmount($amount, $currency);
$modificationAmount = array('currency' => $currency, 'value' => $amount); $modificationAmount = ['currency' => $currency, 'value' => $amount];
$request = array( $request = [
"merchantAccount" => $merchantAccount, "merchantAccount" => $merchantAccount,
"modificationAmount" => $modificationAmount, "modificationAmount" => $modificationAmount,
"reference" => $payment->getOrder()->getIncrementId(), "reference" => $payment->getOrder()->getIncrementId(),
"originalReference" => $pspReference "originalReference" => $pspReference
); ];
// call lib // call lib
$service = new \Adyen\Service\Modification($this->_client); $service = new \Adyen\Service\Modification($this->_client);
$result = $service->capture($request); $result = $service->capture($request);
if($result['response'] != '[capture-received]') { if ($result['response'] != '[capture-received]') {
// something went wrong // something went wrong
throw new \Magento\Framework\Exception\LocalizedException(__('The capture action failed')); throw new \Magento\Framework\Exception\LocalizedException(__('The capture action failed'));
} }
...@@ -332,7 +367,7 @@ class PaymentRequest extends DataObject ...@@ -332,7 +367,7 @@ class PaymentRequest extends DataObject
$payment->setAdditionalInformation('capture_pspreference', $result['pspReference']); $payment->setAdditionalInformation('capture_pspreference', $result['pspReference']);
// set pspReference as TransactionId so you can do an online refund // set pspReference as TransactionId so you can do an online refund
if(isset($result['pspReference'])) { if (isset($result['pspReference'])) {
$payment->setTransactionId($result['pspReference']) $payment->setTransactionId($result['pspReference'])
->setIsTransactionClosed(false) ->setIsTransactionClosed(false)
->setParentTransactionId($payment->getAdditionalInformation('pspReference')); ->setParentTransactionId($payment->getAdditionalInformation('pspReference'));
...@@ -353,23 +388,23 @@ class PaymentRequest extends DataObject ...@@ -353,23 +388,23 @@ class PaymentRequest extends DataObject
$pspReference = $this->_getPspReference($payment); $pspReference = $this->_getPspReference($payment);
$merchantAccount = $this->_adyenHelper->getAdyenAbstractConfigData("merchant_account"); $merchantAccount = $this->_adyenHelper->getAdyenAbstractConfigData("merchant_account");
$request = array( $request = [
"merchantAccount" => $merchantAccount, "merchantAccount" => $merchantAccount,
"reference" => $payment->getOrder()->getIncrementId(), "reference" => $payment->getOrder()->getIncrementId(),
"originalReference" => $pspReference "originalReference" => $pspReference
); ];
// call lib // call lib
$service = new \Adyen\Service\Modification($this->_client); $service = new \Adyen\Service\Modification($this->_client);
$result = $service->cancelOrRefund($request); $result = $service->cancelOrRefund($request);
if($result['response'] != '[cancelOrRefund-received]') { if ($result['response'] != '[cancelOrRefund-received]') {
// something went wrong // something went wrong
throw new \Magento\Framework\Exception\LocalizedException(__('The refund action failed')); throw new \Magento\Framework\Exception\LocalizedException(__('The refund action failed'));
} }
// set pspReference as TransactionId so you can do an online refund // set pspReference as TransactionId so you can do an online refund
if(isset($result['pspReference'])) { if (isset($result['pspReference'])) {
$payment->setTransactionId($result['pspReference']) $payment->setTransactionId($result['pspReference'])
->setIsTransactionClosed(false) ->setIsTransactionClosed(false)
->setParentTransactionId($payment->getAdditionalInformation('pspReference')); ->setParentTransactionId($payment->getAdditionalInformation('pspReference'));
...@@ -396,26 +431,26 @@ class PaymentRequest extends DataObject ...@@ -396,26 +431,26 @@ class PaymentRequest extends DataObject
//format the amount to minor units //format the amount to minor units
$amount = $this->_adyenHelper->formatAmount($amount, $currency); $amount = $this->_adyenHelper->formatAmount($amount, $currency);
$modificationAmount = array('currency' => $currency, 'value' => $amount); $modificationAmount = ['currency' => $currency, 'value' => $amount];
$request = array( $request = [
"merchantAccount" => $merchantAccount, "merchantAccount" => $merchantAccount,
"modificationAmount" => $modificationAmount, "modificationAmount" => $modificationAmount,
"reference" => $payment->getOrder()->getIncrementId(), "reference" => $payment->getOrder()->getIncrementId(),
"originalReference" => $pspReference "originalReference" => $pspReference
); ];
// call lib // call lib
$service = new \Adyen\Service\Modification($this->_client); $service = new \Adyen\Service\Modification($this->_client);
$result = $service->refund($request); $result = $service->refund($request);
if($result['response'] != '[refund-received]') { if ($result['response'] != '[refund-received]') {
// something went wrong // something went wrong
throw new \Magento\Framework\Exception\LocalizedException(__('The refund action failed')); throw new \Magento\Framework\Exception\LocalizedException(__('The refund action failed'));
} }
// set pspReference as TransactionId so you can do an online refund // set pspReference as TransactionId so you can do an online refund
if(isset($result['pspReference'])) { if (isset($result['pspReference'])) {
$payment->setTransactionId($result['pspReference']) $payment->setTransactionId($result['pspReference'])
->setIsTransactionClosed(false) ->setIsTransactionClosed(false)
->setParentTransactionId($payment->getAdditionalInformation('pspReference')); ->setParentTransactionId($payment->getAdditionalInformation('pspReference'));
...@@ -424,28 +459,39 @@ class PaymentRequest extends DataObject ...@@ -424,28 +459,39 @@ class PaymentRequest extends DataObject
return $result; return $result;
} }
/**
* @param $shopperReference
* @param $storeId
* @return array
* @throws \Exception
*/
public function getRecurringContractsForShopper($shopperReference, $storeId) public function getRecurringContractsForShopper($shopperReference, $storeId)
{ {
$recurringContracts = array(); $recurringContracts = [];
$recurringTypes = $this->_recurringType->getAllowedRecurringTypesForListRecurringCall(); $recurringTypes = $this->_recurringType->getAllowedRecurringTypesForListRecurringCall();
foreach ($recurringTypes as $recurringType) { foreach ($recurringTypes as $recurringType) {
try { try {
// merge ONECLICK and RECURRING into one record with recurringType ONECLICK,RECURRING // merge ONECLICK and RECURRING into one record with recurringType ONECLICK,RECURRING
$listRecurringContractByType = $this->listRecurringContractByType($shopperReference, $storeId, $recurringType); $listRecurringContractByType =
if(isset($listRecurringContractByType['details'] )) $this->listRecurringContractByType($shopperReference, $storeId, $recurringType);
{
foreach($listRecurringContractByType['details'] as $recurringContractDetails) { if (isset($listRecurringContractByType['details'])) {
if(isset($recurringContractDetails['RecurringDetail'])) { foreach ($listRecurringContractByType['details'] as $recurringContractDetails) {
if (isset($recurringContractDetails['RecurringDetail'])) {
$recurringContract = $recurringContractDetails['RecurringDetail']; $recurringContract = $recurringContractDetails['RecurringDetail'];
if(isset($recurringContract['recurringDetailReference'])) { if (isset($recurringContract['recurringDetailReference'])) {
$recurringDetailReference = $recurringContract['recurringDetailReference']; $recurringDetailReference = $recurringContract['recurringDetailReference'];
// check if recurring reference is already in array // check if recurring reference is already in array
if(isset($recurringContracts[$recurringDetailReference])) { if (isset($recurringContracts[$recurringDetailReference])) {
// recurring reference already exists so recurringType is possible for ONECLICK and RECURRING /*
$recurringContracts[$recurringDetailReference]['recurring_type']= "ONECLICK,RECURRING"; * recurring reference already exists so recurringType is possible
* for ONECLICK and RECURRING
*/
$recurringContracts[$recurringDetailReference]['recurring_type'] =
"ONECLICK,RECURRING";
} else { } else {
$recurringContracts[$recurringDetailReference] = $recurringContract; $recurringContracts[$recurringDetailReference] = $recurringContract;
} }
...@@ -462,16 +508,21 @@ class PaymentRequest extends DataObject ...@@ -462,16 +508,21 @@ class PaymentRequest extends DataObject
return $recurringContracts; return $recurringContracts;
} }
/**
* @param $shopperReference
* @param $storeId
* @param $recurringType
* @return mixed
*/
public function listRecurringContractByType($shopperReference, $storeId, $recurringType) public function listRecurringContractByType($shopperReference, $storeId, $recurringType)
{ {
// rest call to get list of recurring details // rest call to get list of recurring details
$contract = ['contract' => $recurringType]; $contract = ['contract' => $recurringType];
$request = array( $request = [
"merchantAccount" => $this->_adyenHelper->getAdyenAbstractConfigData('merchant_account', $storeId), "merchantAccount" => $this->_adyenHelper->getAdyenAbstractConfigData('merchant_account', $storeId),
"shopperReference" => $shopperReference, "shopperReference" => $shopperReference,
"recurring" => $contract, "recurring" => $contract,
); ];
// call lib // call lib
$service = new \Adyen\Service\Recurring($this->_client); $service = new \Adyen\Service\Recurring($this->_client);
...@@ -483,22 +534,20 @@ class PaymentRequest extends DataObject ...@@ -483,22 +534,20 @@ class PaymentRequest extends DataObject
/** /**
* Disable a recurring contract * Disable a recurring contract
* *
* @param string $recurringDetailReference * @param $recurringDetailReference
* @param string $shopperReference * @param $shopperReference
* @param int|Mage_Core_model_Store|null $store
*
* @throws Adyen_Payment_Exception
* @return bool * @return bool
* @throws \Magento\Framework\Exception\LocalizedException
*/ */
public function disableRecurringContract($recurringDetailReference, $shopperReference) public function disableRecurringContract($recurringDetailReference, $shopperReference)
{ {
$merchantAccount = $this->_adyenHelper->getAdyenAbstractConfigData("merchant_account"); $merchantAccount = $this->_adyenHelper->getAdyenAbstractConfigData("merchant_account");
$request = array( $request = [
"merchantAccount" => $merchantAccount, "merchantAccount" => $merchantAccount,
"shopperReference" => $shopperReference, "shopperReference" => $shopperReference,
"recurringDetailReference" => $recurringDetailReference "recurringDetailReference" => $recurringDetailReference
); ];
// call lib // call lib
$service = new \Adyen\Service\Recurring($this->_client); $service = new \Adyen\Service\Recurring($this->_client);
...@@ -509,7 +558,7 @@ class PaymentRequest extends DataObject ...@@ -509,7 +558,7 @@ class PaymentRequest extends DataObject
$this->_adyenLogger->info($e->getMessage()); $this->_adyenLogger->info($e->getMessage());
} }
if(isset($result['response']) && $result['response'] == '[detail-successfully-disabled]') { if (isset($result['response']) && $result['response'] == '[detail-successfully-disabled]') {
return true; return true;
} else { } else {
throw new \Magento\Framework\Exception\LocalizedException(__('Failed to disable this contract')); throw new \Magento\Framework\Exception\LocalizedException(__('Failed to disable this contract'));
......
...@@ -31,14 +31,17 @@ class Agreement extends \Magento\Paypal\Model\Billing\Agreement ...@@ -31,14 +31,17 @@ class Agreement extends \Magento\Paypal\Model\Billing\Agreement
*/ */
private $_adyenHelper; private $_adyenHelper;
/** /**
* Agreement constructor.
*
* @param \Adyen\Payment\Helper\Data $adyenHelper
* @param \Magento\Framework\Model\Context $context * @param \Magento\Framework\Model\Context $context
* @param \Magento\Framework\Registry $registry * @param \Magento\Framework\Registry $registry
* @param \Magento\Payment\Helper\Data $paymentData * @param \Magento\Payment\Helper\Data $paymentData
* @param \Magento\Paypal\Model\ResourceModel\Billing\Agreement\CollectionFactory $billingAgreementFactory
* @param \Magento\Framework\Stdlib\DateTime\DateTimeFactory $dateFactory
* @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource * @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource
* @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection * @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection
* @param \Adyen\Payment\Helper\Data $adyenHelper
* @param array $data * @param array $data
*/ */
public function __construct( public function __construct(
...@@ -51,10 +54,16 @@ class Agreement extends \Magento\Paypal\Model\Billing\Agreement ...@@ -51,10 +54,16 @@ class Agreement extends \Magento\Paypal\Model\Billing\Agreement
\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
array $data = [] array $data = []
) {
parent::__construct($context,
$registry,
$paymentData,
$billingAgreementFactory,
$dateFactory,
$resource,
$resourceCollection,
$data);
)
{
parent::__construct($context, $registry, $paymentData, $billingAgreementFactory, $dateFactory, $resource, $resourceCollection, $data);
$this->_adyenHelper = $adyenHelper; $this->_adyenHelper = $adyenHelper;
} }
...@@ -68,7 +77,10 @@ class Agreement extends \Magento\Paypal\Model\Billing\Agreement ...@@ -68,7 +77,10 @@ class Agreement extends \Magento\Paypal\Model\Billing\Agreement
return $this->getCustomerId(); return $this->getCustomerId();
} }
/**
* @param $data
* @return $this
*/
public function parseRecurringContractData($data) public function parseRecurringContractData($data)
{ {
$this $this
...@@ -118,6 +130,10 @@ class Agreement extends \Magento\Paypal\Model\Billing\Agreement ...@@ -118,6 +130,10 @@ class Agreement extends \Magento\Paypal\Model\Billing\Agreement
return $this; return $this;
} }
/**
* @param $data
* @return $this
*/
public function setAgreementData($data) public function setAgreementData($data)
{ {
if (is_array($data)) { if (is_array($data)) {
...@@ -130,6 +146,9 @@ class Agreement extends \Magento\Paypal\Model\Billing\Agreement ...@@ -130,6 +146,9 @@ class Agreement extends \Magento\Paypal\Model\Billing\Agreement
return $this; return $this;
} }
/**
* @return mixed
*/
public function getAgreementData() public function getAgreementData()
{ {
return json_decode($this->getData('agreement_data'), true); return json_decode($this->getData('agreement_data'), true);
......
...@@ -28,7 +28,8 @@ namespace Adyen\Payment\Model\Config; ...@@ -28,7 +28,8 @@ namespace Adyen\Payment\Model\Config;
class Converter implements \Magento\Framework\Config\ConverterInterface class Converter implements \Magento\Framework\Config\ConverterInterface
{ {
/** /**
* {@inheritdoc} * @param \DOMDocument $source
* @return array
*/ */
public function convert($source) public function convert($source)
{ {
...@@ -91,8 +92,6 @@ class Converter implements \Magento\Framework\Config\ConverterInterface ...@@ -91,8 +92,6 @@ class Converter implements \Magento\Framework\Config\ConverterInterface
return $left['order'] - $right['order']; return $left['order'] - $right['order'];
} }
/** /**
* Convert methods xml tree to array * Convert methods xml tree to array
* *
......
...@@ -35,63 +35,4 @@ class Reader extends \Magento\Framework\Config\Reader\Filesystem ...@@ -35,63 +35,4 @@ class Reader extends \Magento\Framework\Config\Reader\Filesystem
protected $_idAttributes = [ protected $_idAttributes = [
'/payment/adyen_credit_cards/type' => 'id' '/payment/adyen_credit_cards/type' => 'id'
]; ];
/**
* Load configuration scope
*
* @param string|null $scope
* @return array
*/
public function read($scope = null)
{
$scope = $scope ?: $this->_defaultScope;
$fileList = $this->_fileResolver->get($this->_fileName, $scope);
if (!count($fileList)) {
return [];
}
$output = $this->_readFiles($fileList);
return $output;
}
/**
* Read configuration files
*
* @param array $fileList
* @return array
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function _readFiles($fileList)
{
/** @var \Magento\Framework\Config\Dom $configMerger */
$configMerger = null;
foreach ($fileList as $key => $content) {
try {
if (!$configMerger) {
$configMerger = $this->_createConfigMerger($this->_domDocumentClass, $content);
} else {
$configMerger->merge($content);
}
} catch (\Magento\Framework\Config\Dom\ValidationException $e) {
throw new \Magento\Framework\Exception\LocalizedException(
new \Magento\Framework\Phrase("Invalid XML in file %1:\n%2", [$key, $e->getMessage()])
);
}
}
if ($this->validationState->isValidationRequired()) {
$errors = [];
if ($configMerger && !$configMerger->validate($this->_schemaFile, $errors)) {
$message = "Invalid Document \n";
throw new \Magento\Framework\Exception\LocalizedException(
new \Magento\Framework\Phrase($message . implode("\n", $errors))
);
}
}
$output = [];
if ($configMerger) {
$output = $this->_converter->convert($configMerger->getDom());
}
return $output;
}
} }
...@@ -26,11 +26,6 @@ namespace Adyen\Payment\Model\Config\Source; ...@@ -26,11 +26,6 @@ namespace Adyen\Payment\Model\Config\Source;
class CaptureMode implements \Magento\Framework\Option\ArrayInterface class CaptureMode implements \Magento\Framework\Option\ArrayInterface
{ {
/**
* @var \Magento\Sales\Model\Order\Config
*/
protected $_orderConfig;
/** /**
* @var \Adyen\Payment\Helper\Data * @var \Adyen\Payment\Helper\Data
*/ */
...@@ -38,15 +33,13 @@ class CaptureMode implements \Magento\Framework\Option\ArrayInterface ...@@ -38,15 +33,13 @@ class CaptureMode implements \Magento\Framework\Option\ArrayInterface
/** /**
* @param \Magento\Sales\Model\Order\Config $orderConfig * CaptureMode constructor.
*
* @param \Adyen\Payment\Helper\Data $adyenHelper * @param \Adyen\Payment\Helper\Data $adyenHelper
*/ */
public function __construct( public function __construct(
\Magento\Sales\Model\Order\Config $orderConfig,
\Adyen\Payment\Helper\Data $adyenHelper \Adyen\Payment\Helper\Data $adyenHelper
) ) {
{
$this->_orderConfig = $orderConfig;
$this->_adyenHelper = $adyenHelper; $this->_adyenHelper = $adyenHelper;
} }
......
...@@ -26,26 +26,19 @@ namespace Adyen\Payment\Model\Config\Source; ...@@ -26,26 +26,19 @@ namespace Adyen\Payment\Model\Config\Source;
class DemoMode implements \Magento\Framework\Option\ArrayInterface class DemoMode implements \Magento\Framework\Option\ArrayInterface
{ {
/**
* @var \Magento\Sales\Model\Order\Config
*/
protected $_orderConfig;
/** /**
* @var \Adyen\Payment\Helper\Data * @var \Adyen\Payment\Helper\Data
*/ */
protected $_adyenHelper; protected $_adyenHelper;
/** /**
* @param \Magento\Sales\Model\Order\Config $orderConfig * DemoMode constructor.
*
* @param \Adyen\Payment\Helper\Data $adyenHelper * @param \Adyen\Payment\Helper\Data $adyenHelper
*/ */
public function __construct( public function __construct(
\Magento\Sales\Model\Order\Config $orderConfig,
\Adyen\Payment\Helper\Data $adyenHelper \Adyen\Payment\Helper\Data $adyenHelper
) ) {
{
$this->_orderConfig = $orderConfig;
$this->_adyenHelper = $adyenHelper; $this->_adyenHelper = $adyenHelper;
} }
......
...@@ -26,11 +26,6 @@ namespace Adyen\Payment\Model\Config\Source; ...@@ -26,11 +26,6 @@ namespace Adyen\Payment\Model\Config\Source;
class PaymentRoutine implements \Magento\Framework\Option\ArrayInterface class PaymentRoutine implements \Magento\Framework\Option\ArrayInterface
{ {
/**
* @var \Magento\Sales\Model\Order\Config
*/
protected $_orderConfig;
/** /**
* @var \Adyen\Payment\Helper\Data * @var \Adyen\Payment\Helper\Data
*/ */
...@@ -41,11 +36,8 @@ class PaymentRoutine implements \Magento\Framework\Option\ArrayInterface ...@@ -41,11 +36,8 @@ class PaymentRoutine implements \Magento\Framework\Option\ArrayInterface
* @param \Adyen\Payment\Helper\Data $adyenHelper * @param \Adyen\Payment\Helper\Data $adyenHelper
*/ */
public function __construct( public function __construct(
\Magento\Sales\Model\Order\Config $orderConfig,
\Adyen\Payment\Helper\Data $adyenHelper \Adyen\Payment\Helper\Data $adyenHelper
) ) {
{
$this->_orderConfig = $orderConfig;
$this->_adyenHelper = $adyenHelper; $this->_adyenHelper = $adyenHelper;
} }
......
...@@ -27,26 +27,19 @@ class RecurringPaymentType implements \Magento\Framework\Option\ArrayInterface ...@@ -27,26 +27,19 @@ class RecurringPaymentType implements \Magento\Framework\Option\ArrayInterface
{ {
const UNDEFINED_OPTION_LABEL = 'NONE'; const UNDEFINED_OPTION_LABEL = 'NONE';
/**
* @var \Magento\Sales\Model\Order\Config
*/
protected $_orderConfig;
/** /**
* @var \Adyen\Payment\Helper\Data * @var \Adyen\Payment\Helper\Data
*/ */
protected $_adyenHelper; protected $_adyenHelper;
/** /**
* @param \Magento\Sales\Model\Order\Config $orderConfig * RecurringPaymentType constructor.
*
* @param \Adyen\Payment\Helper\Data $adyenHelper * @param \Adyen\Payment\Helper\Data $adyenHelper
*/ */
public function __construct( public function __construct(
\Magento\Sales\Model\Order\Config $orderConfig,
\Adyen\Payment\Helper\Data $adyenHelper \Adyen\Payment\Helper\Data $adyenHelper
) ) {
{
$this->_orderConfig = $orderConfig;
$this->_adyenHelper = $adyenHelper; $this->_adyenHelper = $adyenHelper;
} }
...@@ -58,7 +51,8 @@ class RecurringPaymentType implements \Magento\Framework\Option\ArrayInterface ...@@ -58,7 +51,8 @@ class RecurringPaymentType implements \Magento\Framework\Option\ArrayInterface
$recurringTypes = $this->_adyenHelper->getRecurringTypes(); $recurringTypes = $this->_adyenHelper->getRecurringTypes();
foreach ($recurringTypes as $code => $label) { foreach ($recurringTypes as $code => $label) {
if($code == \Adyen\Payment\Model\RecurringType::ONECLICK || $code == \Adyen\Payment\Model\RecurringType::RECURRING) { if ($code == \Adyen\Payment\Model\RecurringType::ONECLICK ||
$code == \Adyen\Payment\Model\RecurringType::RECURRING) {
$options[] = ['value' => $code, 'label' => $label]; $options[] = ['value' => $code, 'label' => $label];
} }
} }
......
...@@ -26,27 +26,21 @@ namespace Adyen\Payment\Model\Config\Source; ...@@ -26,27 +26,21 @@ namespace Adyen\Payment\Model\Config\Source;
class RecurringType implements \Magento\Framework\Option\ArrayInterface class RecurringType implements \Magento\Framework\Option\ArrayInterface
{ {
const UNDEFINED_OPTION_LABEL = 'NONE'; const UNDEFINED_OPTION_LABEL = 'NONE';
/**
* @var \Magento\Sales\Model\Order\Config
*/
protected $_orderConfig;
/** /**
* @var \Adyen\Payment\Helper\Data * @var \Adyen\Payment\Helper\Data
*/ */
protected $_adyenHelper; protected $_adyenHelper;
/** /**
* @param \Magento\Sales\Model\Order\Config $orderConfig * RecurringType constructor.
*
* @param \Adyen\Payment\Helper\Data $adyenHelper * @param \Adyen\Payment\Helper\Data $adyenHelper
*/ */
public function __construct( public function __construct(
\Magento\Sales\Model\Order\Config $orderConfig,
\Adyen\Payment\Helper\Data $adyenHelper \Adyen\Payment\Helper\Data $adyenHelper
) )
{ {
$this->_orderConfig = $orderConfig;
$this->_adyenHelper = $adyenHelper; $this->_adyenHelper = $adyenHelper;
} }
......
...@@ -33,9 +33,9 @@ class RenderMode implements \Magento\Framework\Option\ArrayInterface ...@@ -33,9 +33,9 @@ class RenderMode implements \Magento\Framework\Option\ArrayInterface
*/ */
public function toOptionArray() public function toOptionArray()
{ {
return array( return [
array('value' => self::MODE_TITLE, 'label' => __('Title')), ['value' => self::MODE_TITLE, 'label' => __('Title')],
array('value' => self::MODE_TITLE_IMAGE, 'label' => __('Logo + Title')), ['value' => self::MODE_TITLE_IMAGE, 'label' => __('Logo + Title')]
); ];
} }
} }
...@@ -33,10 +33,10 @@ class SepaFlow implements \Magento\Framework\Option\ArrayInterface ...@@ -33,10 +33,10 @@ class SepaFlow implements \Magento\Framework\Option\ArrayInterface
*/ */
public function toOptionArray() public function toOptionArray()
{ {
return array( return [
array('value' => self::SEPA_FLOW_SALE, 'label' => __('Sale')), ['value' => self::SEPA_FLOW_SALE, 'label' => __('Sale')],
array('value' => self::SEPA_FLOW_AUTHCAP, 'label' => __('Auth/Cap')), ['value' => self::SEPA_FLOW_AUTHCAP, 'label' => __('Auth/Cap')],
); ];
} }
} }
\ No newline at end of file
...@@ -40,16 +40,6 @@ class Cron ...@@ -40,16 +40,6 @@ class Cron
*/ */
protected $_notificationFactory; protected $_notificationFactory;
/**
* @var \Magento\Framework\Stdlib\DateTime
*/
protected $_datetime;
/**
* @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface
*/
protected $_localeDate;
/** /**
* @var \Magento\Sales\Model\OrderFactory * @var \Magento\Sales\Model\OrderFactory
*/ */
...@@ -101,29 +91,74 @@ class Cron ...@@ -101,29 +91,74 @@ class Cron
* notification attributes * notification attributes
*/ */
protected $_pspReference; protected $_pspReference;
/**
* @var
*/
protected $_merchantReference; protected $_merchantReference;
/**
* @var
*/
protected $_eventCode; protected $_eventCode;
/**
* @var
*/
protected $_success; protected $_success;
/**
* @var
*/
protected $_paymentMethod; protected $_paymentMethod;
/**
* @var
*/
protected $_reason; protected $_reason;
/**
* @var
*/
protected $_value; protected $_value;
/**
* @var
*/
protected $_boletoOriginalAmount; protected $_boletoOriginalAmount;
/**
* @var
*/
protected $_boletoPaidAmount; protected $_boletoPaidAmount;
/**
* @var
*/
protected $_modificationResult; protected $_modificationResult;
/**
* @var
*/
protected $_klarnaReservationNumber; protected $_klarnaReservationNumber;
/**
* @var
*/
protected $_fraudManualReview; protected $_fraudManualReview;
/** /**
* Cron constructor.
*
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
* @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger * @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger
* @param Resource\Notification\CollectionFactory $notificationFactory * @param Resource\Notification\CollectionFactory $notificationFactory
* @param \Magento\Sales\Model\OrderFactory $orderFactory * @param \Magento\Sales\Model\OrderFactory $orderFactory
* @param \Magento\Framework\Stdlib\DateTime $dateTime
* @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate
* @param \Adyen\Payment\Helper\Data $adyenHelper * @param \Adyen\Payment\Helper\Data $adyenHelper
* @param OrderSender $orderSender * @param OrderSender $orderSender
* @param \Magento\Framework\DB\TransactionFactory $transactionFactory * @param \Magento\Framework\DB\TransactionFactory $transactionFactory
* @param Billing\AgreementFactory $billingAgreementFactory * @param Billing\AgreementFactory $billingAgreementFactory
* @param Resource\Billing\Agreement\CollectionFactory $billingAgreementCollectionFactory
* @param Api\PaymentRequest $paymentRequest * @param Api\PaymentRequest $paymentRequest
*/ */
public function __construct( public function __construct(
...@@ -131,22 +166,17 @@ class Cron ...@@ -131,22 +166,17 @@ class Cron
\Adyen\Payment\Logger\AdyenLogger $adyenLogger, \Adyen\Payment\Logger\AdyenLogger $adyenLogger,
\Adyen\Payment\Model\Resource\Notification\CollectionFactory $notificationFactory, \Adyen\Payment\Model\Resource\Notification\CollectionFactory $notificationFactory,
\Magento\Sales\Model\OrderFactory $orderFactory, \Magento\Sales\Model\OrderFactory $orderFactory,
\Magento\Framework\Stdlib\DateTime $dateTime,
\Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
\Adyen\Payment\Helper\Data $adyenHelper, \Adyen\Payment\Helper\Data $adyenHelper,
OrderSender $orderSender, OrderSender $orderSender,
\Magento\Framework\DB\TransactionFactory $transactionFactory, \Magento\Framework\DB\TransactionFactory $transactionFactory,
\Adyen\Payment\Model\Billing\AgreementFactory $billingAgreementFactory, \Adyen\Payment\Model\Billing\AgreementFactory $billingAgreementFactory,
\Adyen\Payment\Model\Resource\Billing\Agreement\CollectionFactory $billingAgreementCollectionFactory, \Adyen\Payment\Model\Resource\Billing\Agreement\CollectionFactory $billingAgreementCollectionFactory,
\Adyen\Payment\Model\Api\PaymentRequest $paymentRequest \Adyen\Payment\Model\Api\PaymentRequest $paymentRequest
) ) {
{
$this->_scopeConfig = $scopeConfig; $this->_scopeConfig = $scopeConfig;
$this->_adyenLogger = $adyenLogger; $this->_adyenLogger = $adyenLogger;
$this->_notificationFactory = $notificationFactory; $this->_notificationFactory = $notificationFactory;
$this->_orderFactory = $orderFactory; $this->_orderFactory = $orderFactory;
$this->_datetime = $dateTime;
$this->_localeDate = $localeDate;
$this->_adyenHelper = $adyenHelper; $this->_adyenHelper = $adyenHelper;
$this->_orderSender = $orderSender; $this->_orderSender = $orderSender;
$this->_transactionFactory = $transactionFactory; $this->_transactionFactory = $transactionFactory;
...@@ -155,19 +185,21 @@ class Cron ...@@ -155,19 +185,21 @@ class Cron
$this->_adyenPaymentRequest = $paymentRequest; $this->_adyenPaymentRequest = $paymentRequest;
} }
/**
* Process the notification
* @return void
*/
public function processNotification() public function processNotification()
{ {
$this->_order = null; $this->_order = null;
$this->_adyenLogger->addAdyenNotificationCronjob("START OF THE CRONJOB"); $this->_adyenLogger->addAdyenNotificationCronjob("START OF THE CRONJOB");
$dateStart = new \DateTime();
// execute notifications from 2 minute or earlier because order could not yet been created by magento // execute notifications from 2 minute or earlier because order could not yet been created by magento
$dateStart = new \DateTime(); $dateStart = new \DateTime();
$dateStart->modify('-1 day'); $dateStart->modify('-5 day');
$dateEnd = new \DateTime(); $dateEnd = new \DateTime();
$dateEnd->modify('-2 minute'); $dateEnd->modify('-1 minute');
$dateRange = ['from' => $dateStart, 'to' => $dateEnd, 'datetime' => true]; $dateRange = ['from' => $dateStart, 'to' => $dateEnd, 'datetime' => true];
// create collection // create collection
...@@ -176,7 +208,7 @@ class Cron ...@@ -176,7 +208,7 @@ class Cron
$notifications->addFieldToFilter('created_at', $dateRange); $notifications->addFieldToFilter('created_at', $dateRange);
// loop over the notifications // loop over the notifications
foreach($notifications as $notification) { foreach ($notifications as $notification) {
// log the executed notification // log the executed notification
$this->_adyenLogger->addAdyenNotificationCronjob(print_r($notification->debug(), 1)); $this->_adyenLogger->addAdyenNotificationCronjob(print_r($notification->debug(), 1));
...@@ -199,33 +231,49 @@ class Cron ...@@ -199,33 +231,49 @@ class Cron
$this->_addStatusHistoryComment(); $this->_addStatusHistoryComment();
$previousAdyenEventCode = $this->_order->getData('adyen_notification_event_code'); $previousAdyenEventCode = $this->_order->getData('adyen_notification_event_code');
$_paymentCode = $this->_paymentMethodCode();
// update order details // update order details
$this->_updateAdyenAttributes($notification); $this->_updateAdyenAttributes($notification);
// check if success is true of false // check if success is true of false
if (strcmp($this->_success, 'false') == 0 || strcmp($this->_success, '0') == 0) { if (strcmp($this->_success, 'false') == 0 || strcmp($this->_success, '0') == 0) {
// Only cancel the order when it is in state pending, payment review or if the ORDER_CLOSED is failed (means split payment has not be successful) /*
if($this->_order->getState() === \Magento\Sales\Model\Order::STATE_PENDING_PAYMENT || $this->_order->getState() === \Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW || $this->_eventCode == Notification::ORDER_CLOSED) { * Only cancel the order when it is in state pending, payment review or
* if the ORDER_CLOSED is failed (means split payment has not be successful)
*/
if ($this->_order->getState() === \Magento\Sales\Model\Order::STATE_PENDING_PAYMENT ||
$this->_order->getState() === \Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW ||
$this->_eventCode == Notification::ORDER_CLOSED) {
$this->_adyenLogger->addAdyenNotificationCronjob('Going to cancel the order'); $this->_adyenLogger->addAdyenNotificationCronjob('Going to cancel the order');
// if payment is API check, check if API result pspreference is the same as reference // if payment is API check, check if API result pspreference is the same as reference
if($this->_eventCode == NOTIFICATION::AUTHORISATION && $this->_getPaymentMethodType() == 'api') { if ($this->_eventCode == NOTIFICATION::AUTHORISATION && $this->_getPaymentMethodType() == 'api') {
// don't cancel the order becasue order was successfull through api // don't cancel the order becasue order was successfull through api
$this->_adyenLogger->addAdyenNotificationCronjob('order is not cancelled because api result was succesfull'); $this->_adyenLogger->addAdyenNotificationCronjob(
'order is not cancelled because api result was succesfull'
);
} else { } else {
// don't cancel the order if previous state is authorisation with success=true /*
// Split payments can fail if the second payment has failed the first payment is refund/cancelled as well so if it is a split payment that failed cancel the order as well * don't cancel the order if previous state is authorisation with success=true
if($previousAdyenEventCode != "AUTHORISATION : TRUE" || $this->_eventCode == Notification::ORDER_CLOSED) { * Split payments can fail if the second payment has failed the first payment is
* refund/cancelled as well so if it is a split payment that failed cancel the order as well
*/
if ($previousAdyenEventCode != "AUTHORISATION : TRUE" ||
$this->_eventCode == Notification::ORDER_CLOSED) {
$this->_holdCancelOrder(false); $this->_holdCancelOrder(false);
} else { } else {
$this->_order->setData('adyen_notification_event_code', $previousAdyenEventCode); $this->_order->setData('adyen_notification_event_code', $previousAdyenEventCode);
$this->_adyenLogger->addAdyenNotificationCronjob('order is not cancelled because previous notification was a authorisation that succeeded'); $this->_adyenLogger->addAdyenNotificationCronjob(
'order is not cancelled because previous notification
was an authorisation that succeeded'
);
} }
} }
} else { } else {
$this->_adyenLogger->addAdyenNotificationCronjob('Order is already processed so ignore this notification state is:' . $this->_order->getState()); $this->_adyenLogger->addAdyenNotificationCronjob(
'Order is already processed so ignore this notification state is:' . $this->_order->getState()
);
} }
} else { } else {
// Notification is successful // Notification is successful
...@@ -243,6 +291,12 @@ class Cron ...@@ -243,6 +291,12 @@ class Cron
$this->_adyenLogger->addAdyenNotificationCronjob("END OF THE CRONJOB"); $this->_adyenLogger->addAdyenNotificationCronjob("END OF THE CRONJOB");
} }
/**
* Declare private variables for processing notification
*
* @param Object $notification
* @return void
*/
protected function _declareVariables($notification) protected function _declareVariables($notification)
{ {
// declare the common parameters // declare the common parameters
...@@ -258,38 +312,42 @@ class Cron ...@@ -258,38 +312,42 @@ class Cron
$additionalData = unserialize($notification->getAdditionalData()); $additionalData = unserialize($notification->getAdditionalData());
// boleto data // boleto data
if($this->_paymentMethodCode() == "adyen_boleto") { if ($this->_paymentMethodCode() == "adyen_boleto") {
if($additionalData && is_array($additionalData)) { if ($additionalData && is_array($additionalData)) {
$boletobancario = isset($additionalData['boletobancario']) ? $additionalData['boletobancario'] : null; $boletobancario = isset($additionalData['boletobancario']) ? $additionalData['boletobancario'] : null;
if($boletobancario && is_array($boletobancario)) { if ($boletobancario && is_array($boletobancario)) {
$this->_boletoOriginalAmount = isset($boletobancario['originalAmount']) ? trim($boletobancario['originalAmount']) : ""; $this->_boletoOriginalAmount =
$this->_boletoPaidAmount = isset($boletobancario['paidAmount']) ? trim($boletobancario['paidAmount']) : ""; isset($boletobancario['originalAmount']) ? trim($boletobancario['originalAmount']) : "";
$this->_boletoPaidAmount =
isset($boletobancario['paidAmount']) ? trim($boletobancario['paidAmount']) : "";
} }
} }
} }
if($additionalData && is_array($additionalData)) { if ($additionalData && is_array($additionalData)) {
// check if the payment is in status manual review // check if the payment is in status manual review
$fraudManualReview = isset($additionalData['fraudManualReview']) ? $additionalData['fraudManualReview'] : ""; $fraudManualReview = isset($additionalData['fraudManualReview']) ?
if($fraudManualReview == "true") { $additionalData['fraudManualReview'] : "";
if ($fraudManualReview == "true") {
$this->_fraudManualReview = true; $this->_fraudManualReview = true;
} else { } else {
$this->_fraudManualReview = false; $this->_fraudManualReview = false;
} }
// modification.action is it for JSON // modification.action is it for JSON
$modificationActionJson = isset($additionalData['modification.action']) ? $additionalData['modification.action'] : null; $modificationActionJson = isset($additionalData['modification.action']) ?
if($modificationActionJson != "") { $additionalData['modification.action'] : null;
if ($modificationActionJson != "") {
$this->_modificationResult = $modificationActionJson; $this->_modificationResult = $modificationActionJson;
} }
$modification = isset($additionalData['modification']) ? $additionalData['modification'] : null; $modification = isset($additionalData['modification']) ? $additionalData['modification'] : null;
if($modification && is_array($modification)) { if ($modification && is_array($modification)) {
$this->_modificationResult = isset($modification['action']) ? trim($modification['action']) : ""; $this->_modificationResult = isset($modification['action']) ? trim($modification['action']) : "";
} }
$additionalData2 = isset($additionalData['additionalData']) ? $additionalData['additionalData'] : null; $additionalData2 = isset($additionalData['additionalData']) ? $additionalData['additionalData'] : null;
if($additionalData2 && is_array($additionalData2)) { if ($additionalData2 && is_array($additionalData2)) {
$this->_klarnaReservationNumber = isset($additionalData2['acquirerReference']) ? trim($additionalData2['acquirerReference']) : ""; $this->_klarnaReservationNumber = isset($additionalData2['acquirerReference']) ? trim($additionalData2['acquirerReference']) : "";
} }
} }
...@@ -303,7 +361,11 @@ class Cron ...@@ -303,7 +361,11 @@ class Cron
return $this->_order->getPayment()->getMethod(); return $this->_order->getPayment()->getMethod();
} }
protected function _getPaymentMethodType() { /**
* @return mixed
*/
protected function _getPaymentMethodType()
{
return $this->_order->getPayment()->getPaymentMethodType(); return $this->_order->getPayment()->getPaymentMethodType();
} }
...@@ -313,10 +375,11 @@ class Cron ...@@ -313,10 +375,11 @@ class Cron
*/ */
protected function _addStatusHistoryComment() protected function _addStatusHistoryComment()
{ {
$success_result = (strcmp($this->_success, 'true') == 0 || strcmp($this->_success, '1') == 0) ? 'true' : 'false'; $successResult = (strcmp($this->_success, 'true') == 0 ||
$success = (!empty($this->_reason)) ? "$success_result <br />reason:$this->_reason" : $success_result; strcmp($this->_success, '1') == 0) ? 'true' : 'false';
$success = (!empty($this->_reason)) ? "$successResult <br />reason:$this->_reason" : $successResult;
if($this->_eventCode == Notification::REFUND || $this->_eventCode == Notification::CAPTURE) { if ($this->_eventCode == Notification::REFUND || $this->_eventCode == Notification::CAPTURE) {
$currency = $this->_order->getOrderCurrencyCode(); $currency = $this->_order->getOrderCurrencyCode();
...@@ -324,48 +387,61 @@ class Cron ...@@ -324,48 +387,61 @@ class Cron
$amount = $this->_value; $amount = $this->_value;
$orderAmount = (int) $this->_adyenHelper->formatAmount($this->_order->getGrandTotal(), $currency); $orderAmount = (int) $this->_adyenHelper->formatAmount($this->_order->getGrandTotal(), $currency);
$this->_adyenLogger->addAdyenNotificationCronjob('amount notification:'.$amount . ' amount order:'.$orderAmount); $this->_adyenLogger->addAdyenNotificationCronjob(
'amount notification:'.$amount . ' amount order:'.$orderAmount
);
if($amount == $orderAmount) { if ($amount == $orderAmount) {
$this->_order->setData('adyen_notification_event_code', $this->_eventCode . " : " . strtoupper($success_result)); $this->_order->setData(
'adyen_notification_event_code', $this->_eventCode . " : " . strtoupper($successResult)
);
} else { } else {
$this->_order->setData('adyen_notification_event_code', "(PARTIAL) " . $this->_eventCode . " : " . strtoupper($success_result)); $this->_order->setData(
'adyen_notification_event_code', "(PARTIAL) " .
$this->_eventCode . " : " . strtoupper($successResult)
);
} }
} else { } else {
$this->_order->setData('adyen_notification_event_code', $this->_eventCode . " : " . strtoupper($success_result)); $this->_order->setData(
'adyen_notification_event_code', $this->_eventCode . " : " . strtoupper($successResult)
);
} }
// if payment method is klarna or openinvoice/afterpay show the reservartion number // if payment method is klarna or openinvoice/afterpay show the reservartion number
if(($this->_paymentMethod == "klarna" || $this->_paymentMethod == "afterpay_default" || $this->_paymentMethod == "openinvoice") && ($this->_klarnaReservationNumber != null && $this->_klarnaReservationNumber != "")) { if (($this->_paymentMethod == "klarna" || $this->_paymentMethod == "afterpay_default" ||
$this->_paymentMethod == "openinvoice") && ($this->_klarnaReservationNumber != null &&
$this->_klarnaReservationNumber != "")) {
$klarnaReservationNumberText = "<br /> reservationNumber: " . $this->_klarnaReservationNumber; $klarnaReservationNumberText = "<br /> reservationNumber: " . $this->_klarnaReservationNumber;
} else { } else {
$klarnaReservationNumberText = ""; $klarnaReservationNumberText = "";
} }
if($this->_boletoPaidAmount != null && $this->_boletoPaidAmount != "") { if ($this->_boletoPaidAmount != null && $this->_boletoPaidAmount != "") {
$boletoPaidAmountText = "<br /> Paid amount: " . $this->_boletoPaidAmount; $boletoPaidAmountText = "<br /> Paid amount: " . $this->_boletoPaidAmount;
} else { } else {
$boletoPaidAmountText = ""; $boletoPaidAmountText = "";
} }
$type = 'Adyen HTTP Notification(s):'; $type = 'Adyen HTTP Notification(s):';
$comment = __('%1 <br /> eventCode: %2 <br /> pspReference: %3 <br /> paymentMethod: %4 <br /> success: %5 %6 %7', $type, $this->_eventCode, $this->_pspReference, $this->_paymentMethod, $success, $klarnaReservationNumberText, $boletoPaidAmountText); $comment = __('%1 <br /> eventCode: %2 <br /> pspReference: %3 <br /> paymentMethod: %4 <br />' .
' success: %5 %6 %7', $type, $this->_eventCode, $this->_pspReference, $this->_paymentMethod,
$success, $klarnaReservationNumberText, $boletoPaidAmountText);
// If notification is pending status and pending status is set add the status change to the comment history // If notification is pending status and pending status is set add the status change to the comment history
if($this->_eventCode == Notification::PENDING) if ($this->_eventCode == Notification::PENDING) {
{
$pendingStatus = $this->_getConfigData('pending_status', 'adyen_abstract', $this->_order->getStoreId()); $pendingStatus = $this->_getConfigData('pending_status', 'adyen_abstract', $this->_order->getStoreId());
if($pendingStatus != "") { if ($pendingStatus != "") {
$this->_order->addStatusHistoryComment($comment, $pendingStatus); $this->_order->addStatusHistoryComment($comment, $pendingStatus);
$this->_adyenLogger->addAdyenNotificationCronjob('Created comment history for this notification with status change to: ' . $pendingStatus); $this->_adyenLogger->addAdyenNotificationCronjob(
'Created comment history for this notification with status change to: ' . $pendingStatus
);
return; return;
} }
} }
// if manual review is accepted and a status is selected. Change the status through this comment history item // if manual review is accepted and a status is selected. Change the status through this comment history item
if($this->_eventCode == Notification::MANUAL_REVIEW_ACCEPT if ($this->_eventCode == Notification::MANUAL_REVIEW_ACCEPT
&& $this->_getFraudManualReviewAcceptStatus() != "") && $this->_getFraudManualReviewAcceptStatus() != "") {
{
$manualReviewAcceptStatus = $this->_getFraudManualReviewAcceptStatus(); $manualReviewAcceptStatus = $this->_getFraudManualReviewAcceptStatus();
$this->_order->addStatusHistoryComment($comment, $manualReviewAcceptStatus); $this->_order->addStatusHistoryComment($comment, $manualReviewAcceptStatus);
$this->_adyenLogger->addAdyenNotificationCronjob('Created comment history for this notification with status change to: ' . $manualReviewAcceptStatus); $this->_adyenLogger->addAdyenNotificationCronjob('Created comment history for this notification with status change to: ' . $manualReviewAcceptStatus);
...@@ -376,6 +452,9 @@ class Cron ...@@ -376,6 +452,9 @@ class Cron
$this->_adyenLogger->addAdyenNotificationCronjob('Created comment history for this notification'); $this->_adyenLogger->addAdyenNotificationCronjob('Created comment history for this notification');
} }
/**
* @param $notification
*/
protected function _updateAdyenAttributes($notification) protected function _updateAdyenAttributes($notification)
{ {
$this->_adyenLogger->addAdyenNotificationCronjob('Updating the Adyen attributes of the order'); $this->_adyenLogger->addAdyenNotificationCronjob('Updating the Adyen attributes of the order');
...@@ -385,10 +464,16 @@ class Cron ...@@ -385,10 +464,16 @@ class Cron
if ($this->_eventCode == Notification::AUTHORISATION if ($this->_eventCode == Notification::AUTHORISATION
|| $this->_eventCode == Notification::HANDLED_EXTERNALLY || $this->_eventCode == Notification::HANDLED_EXTERNALLY
|| ($this->_eventCode == Notification::CAPTURE && $_paymentCode == "adyen_pos")) || ($this->_eventCode == Notification::CAPTURE && $_paymentCode == "adyen_pos")) {
{
// if current notification is authorisation : false and the previous notification was authorisation : true do not update pspreference /*
if (strcmp($this->_success, 'false') == 0 || strcmp($this->_success, '0') == 0 || strcmp($this->_success, '') == 0) { * if current notification is authorisation : false and
* the previous notification was authorisation : true do not update pspreference
*/
if (strcmp($this->_success, 'false') == 0 ||
strcmp($this->_success, '0') == 0 ||
strcmp($this->_success, '') == 0) {
$previousAdyenEventCode = $this->_order->getData('adyen_notification_event_code'); $previousAdyenEventCode = $this->_order->getData('adyen_notification_event_code');
if ($previousAdyenEventCode != "AUTHORISATION : TRUE") { if ($previousAdyenEventCode != "AUTHORISATION : TRUE") {
$this->_updateOrderPaymentWithAdyenAttributes($additionalData); $this->_updateOrderPaymentWithAdyenAttributes($additionalData);
...@@ -399,6 +484,9 @@ class Cron ...@@ -399,6 +484,9 @@ class Cron
} }
} }
/**
* @param $additionalData
*/
protected function _updateOrderPaymentWithAdyenAttributes($additionalData) protected function _updateOrderPaymentWithAdyenAttributes($additionalData)
{ {
if ($additionalData && is_array($additionalData)) { if ($additionalData && is_array($additionalData)) {
...@@ -407,7 +495,8 @@ class Cron ...@@ -407,7 +495,8 @@ class Cron
$totalFraudScore = (isset($additionalData['totalFraudScore'])) ? $additionalData['totalFraudScore'] : ""; $totalFraudScore = (isset($additionalData['totalFraudScore'])) ? $additionalData['totalFraudScore'] : "";
$ccLast4 = (isset($additionalData['cardSummary'])) ? $additionalData['cardSummary'] : ""; $ccLast4 = (isset($additionalData['cardSummary'])) ? $additionalData['cardSummary'] : "";
$refusalReasonRaw = (isset($additionalData['refusalReasonRaw'])) ? $additionalData['refusalReasonRaw'] : ""; $refusalReasonRaw = (isset($additionalData['refusalReasonRaw'])) ? $additionalData['refusalReasonRaw'] : "";
$acquirerReference = (isset($additionalData['acquirerReference'])) ? $additionalData['acquirerReference'] : ""; $acquirerReference = (isset($additionalData['acquirerReference'])) ?
$additionalData['acquirerReference'] : "";
$authCode = (isset($additionalData['authCode'])) ? $additionalData['authCode'] : ""; $authCode = (isset($additionalData['authCode'])) ? $additionalData['authCode'] : "";
} }
...@@ -420,7 +509,9 @@ class Cron ...@@ -420,7 +509,9 @@ class Cron
$this->_order->getPayment()->setAdditionalInformation('pspReference', $this->_pspReference); $this->_order->getPayment()->setAdditionalInformation('pspReference', $this->_pspReference);
if ($this->_klarnaReservationNumber != "") { if ($this->_klarnaReservationNumber != "") {
$this->_order->getPayment()->setAdditionalInformation('adyen_klarna_number', $this->_klarnaReservationNumber); $this->_order->getPayment()->setAdditionalInformation(
'adyen_klarna_number', $this->_klarnaReservationNumber
);
} }
if (isset($ccLast4) && $ccLast4 != "") { if (isset($ccLast4) && $ccLast4 != "") {
// this field is column in db by core // this field is column in db by core
...@@ -458,10 +549,10 @@ class Cron ...@@ -458,10 +549,10 @@ class Cron
{ {
$result = ""; $result = "";
if($reason != "") { if ($reason != "") {
$reasonArray = explode(":", $reason); $reasonArray = explode(":", $reason);
if($reasonArray != null && is_array($reasonArray)) { if ($reasonArray != null && is_array($reasonArray)) {
if(isset($reasonArray[1])) { if (isset($reasonArray[1])) {
$result = $reasonArray[1]; $result = $reasonArray[1];
} }
} }
...@@ -470,20 +561,18 @@ class Cron ...@@ -470,20 +561,18 @@ class Cron
} }
/** /**
* @param $order * @param $ignoreHasInvoice
* @return bool * @throws \Magento\Framework\Exception\LocalizedException
* @deprecate not needed already cancelled in ProcessController
*/ */
protected function _holdCancelOrder($ignoreHasInvoice) protected function _holdCancelOrder($ignoreHasInvoice)
{ {
$orderStatus = $this->_getConfigData('payment_cancelled', 'adyen_abstract', $this->_order->getStoreId()); $orderStatus = $this->_getConfigData('payment_cancelled', 'adyen_abstract', $this->_order->getStoreId());
// check if order has in invoice only cancel/hold if this is not the case // check if order has in invoice only cancel/hold if this is not the case
if ($ignoreHasInvoice || !$this->_order->hasInvoices()) { if ($ignoreHasInvoice || !$this->_order->hasInvoices()) {
$this->_order->setActionFlag($orderStatus, true); $this->_order->setActionFlag($orderStatus, true);
if($orderStatus == \Magento\Sales\Model\Order::STATE_HOLDED) { if ($orderStatus == \Magento\Sales\Model\Order::STATE_HOLDED) {
if ($this->_order->canHold()) { if ($this->_order->canHold()) {
$this->_order->hold(); $this->_order->hold();
} else { } else {
...@@ -504,7 +593,7 @@ class Cron ...@@ -504,7 +593,7 @@ class Cron
} }
/** /**
* @param $params * Process the Notification
*/ */
protected function _processNotification() protected function _processNotification()
{ {
...@@ -516,21 +605,27 @@ class Cron ...@@ -516,21 +605,27 @@ class Cron
// do nothing only inform the merchant with order comment history // do nothing only inform the merchant with order comment history
break; break;
case Notification::REFUND: case Notification::REFUND:
$ignoreRefundNotification = $this->_getConfigData('ignore_refund_notification', 'adyen_abstract', $this->_order->getStoreId()); $ignoreRefundNotification = $this->_getConfigData(
if($ignoreRefundNotification != true) { 'ignore_refund_notification', 'adyen_abstract', $this->_order->getStoreId()
);
if ($ignoreRefundNotification != true) {
$this->_refundOrder(); $this->_refundOrder();
//refund completed //refund completed
$this->_setRefundAuthorized(); $this->_setRefundAuthorized();
} else { } else {
$this->_adyenLogger->addAdyenNotificationCronjob('Setting to ignore refund notification is enabled so ignore this notification'); $this->_adyenLogger->addAdyenNotificationCronjob(
'Setting to ignore refund notification is enabled so ignore this notification'
);
} }
break; break;
case Notification::PENDING: case Notification::PENDING:
if($this->_getConfigData('send_email_bank_sepa_on_pending', 'adyen_abstract', $this->_order->getStoreId())) { if ($this->_getConfigData(
'send_email_bank_sepa_on_pending', 'adyen_abstract', $this->_order->getStoreId())
) {
// Check if payment is banktransfer or sepa if true then send out order confirmation email // Check if payment is banktransfer or sepa if true then send out order confirmation email
$isBankTransfer = $this->_isBankTransfer(); $isBankTransfer = $this->_isBankTransfer();
if($isBankTransfer || $this->_paymentMethod == 'sepadirectdebit') { if ($isBankTransfer || $this->_paymentMethod == 'sepadirectdebit') {
if(!$this->_order->getEmailSent()) { if (!$this->_order->getEmailSent()) {
$this->_orderSender->send($this->_order); $this->_orderSender->send($this->_order);
$this->_adyenLogger->addAdyenNotificationCronjob('Send orderconfirmation email to shopper'); $this->_adyenLogger->addAdyenNotificationCronjob('Send orderconfirmation email to shopper');
} }
...@@ -540,7 +635,7 @@ class Cron ...@@ -540,7 +635,7 @@ class Cron
case Notification::HANDLED_EXTERNALLY: case Notification::HANDLED_EXTERNALLY:
case Notification::AUTHORISATION: case Notification::AUTHORISATION:
// for POS don't do anything on the AUTHORIZATION // for POS don't do anything on the AUTHORIZATION
if($_paymentCode != "adyen_pos") { if ($_paymentCode != "adyen_pos") {
$this->_authorizePayment(); $this->_authorizePayment();
} }
break; break;
...@@ -548,14 +643,20 @@ class Cron ...@@ -548,14 +643,20 @@ class Cron
// don't do anything it will send a CANCEL_OR_REFUND notification when this payment is captured // don't do anything it will send a CANCEL_OR_REFUND notification when this payment is captured
break; break;
case Notification::MANUAL_REVIEW_ACCEPT: case Notification::MANUAL_REVIEW_ACCEPT:
// only process this if you are on auto capture. On manual capture you will always get Capture or CancelOrRefund notification /*
* only process this if you are on auto capture.
* On manual capture you will always get Capture or CancelOrRefund notification
*/
if ($this->_isAutoCapture()) { if ($this->_isAutoCapture()) {
$this->_setPaymentAuthorized(false); $this->_setPaymentAuthorized(false);
} }
break; break;
case Notification::CAPTURE: case Notification::CAPTURE:
if($_paymentCode != "adyen_pos") { if ($_paymentCode != "adyen_pos") {
// ignore capture if you are on auto capture (this could be called if manual review is enabled and you have a capture delay) /*
* ignore capture if you are on auto capture
* this could be called if manual review is enabled and you have a capture delay
*/
if (!$this->_isAutoCapture()) { if (!$this->_isAutoCapture()) {
$this->_setPaymentAuthorized(false, true); $this->_setPaymentAuthorized(false, true);
} }
...@@ -570,17 +671,21 @@ class Cron ...@@ -570,17 +671,21 @@ class Cron
$this->_holdCancelOrder(true); $this->_holdCancelOrder(true);
break; break;
case Notification::CANCEL_OR_REFUND: case Notification::CANCEL_OR_REFUND:
if(isset($this->_modificationResult) && $this->_modificationResult != "") { if (isset($this->_modificationResult) && $this->_modificationResult != "") {
if($this->_modificationResult == "cancel") { if ($this->_modificationResult == "cancel") {
$this->_holdCancelOrder(true); $this->_holdCancelOrder(true);
} elseif($this->_modificationResult == "refund") { } elseif ($this->_modificationResult == "refund") {
$this->_refundOrder(); $this->_refundOrder();
//refund completed //refund completed
$this->_setRefundAuthorized(); $this->_setRefundAuthorized();
} }
} else { } else {
if ($this->_order->isCanceled() || $this->_order->getState() === \Magento\Sales\Model\Order::STATE_HOLDED) { if ($this->_order->isCanceled() ||
$this->_adyenLogger->addAdyenNotificationCronjob('Order is already cancelled or holded so do nothing'); $this->_order->getState() === \Magento\Sales\Model\Order::STATE_HOLDED) {
$this->_adyenLogger->addAdyenNotificationCronjob(
'Order is already cancelled or holded so do nothing'
);
} else if ($this->_order->canCancel() || $this->_order->canHold()) { } else if ($this->_order->canCancel() || $this->_order->canHold()) {
$this->_adyenLogger->addAdyenNotificationCronjob('try to cancel the order'); $this->_adyenLogger->addAdyenNotificationCronjob('try to cancel the order');
$this->_holdCancelOrder(true); $this->_holdCancelOrder(true);
...@@ -633,43 +738,53 @@ class Cron ...@@ -633,43 +738,53 @@ class Cron
$customerReference = $billingAgreement->getCustomerReference(); $customerReference = $billingAgreement->getCustomerReference();
$storeId = $billingAgreement->getStoreId(); $storeId = $billingAgreement->getStoreId();
// for quest checkout users we can't save this in the billing agreement because it is linked to customer /*
if($customerReference && $storeId) { * for quest checkout users we can't save this in the billing agreement
* because it is linked to customer
*/
if ($customerReference && $storeId) {
$listRecurringContracts = null; $listRecurringContracts = null;
try { try {
$listRecurringContracts = $this->_adyenPaymentRequest->getRecurringContractsForShopper($customerReference, $storeId); $listRecurringContracts = $this->_adyenPaymentRequest->getRecurringContractsForShopper(
$customerReference, $storeId
);
} catch(\Exception $exception) { } catch(\Exception $exception) {
$this->_adyenLogger->addAdyenNotificationCronjob($exception->getMessage()); $this->_adyenLogger->addAdyenNotificationCronjob($exception->getMessage());
} }
$contractDetail = null; $contractDetail = null;
// get currenct Contract details and get list of all current ones // get currenct Contract details and get list of all current ones
$recurringReferencesList = array(); $recurringReferencesList = [];
if($listRecurringContracts) { if ($listRecurringContracts) {
foreach ($listRecurringContracts as $rc) { foreach ($listRecurringContracts as $rc) {
$recurringReferencesList[] = $rc['recurringDetailReference']; $recurringReferencesList[] = $rc['recurringDetailReference'];
if (isset($rc['recurringDetailReference']) && $rc['recurringDetailReference'] == $recurringDetailReference) { if (isset($rc['recurringDetailReference']) &&
$rc['recurringDetailReference'] == $recurringDetailReference) {
$contractDetail = $rc; $contractDetail = $rc;
} }
} }
} }
if($contractDetail != null) { if ($contractDetail != null) {
// update status of all the current saved agreements in magento // update status of all the current saved agreements in magento
$billingAgreements = $this->_billingAgreementCollectionFactory->create(); $billingAgreements = $this->_billingAgreementCollectionFactory->create();
$billingAgreements->addFieldToFilter('customer_id', $customerReference); $billingAgreements->addFieldToFilter('customer_id', $customerReference);
// get collection // get collection
foreach($billingAgreements as $updateBillingAgreement) { foreach ($billingAgreements as $updateBillingAgreement) {
if(!in_array($updateBillingAgreement->getReferenceId(), $recurringReferencesList)) { if (!in_array($updateBillingAgreement->getReferenceId(), $recurringReferencesList)) {
$updateBillingAgreement->setStatus(\Adyen\Payment\Model\Billing\Agreement::STATUS_CANCELED); $updateBillingAgreement->setStatus(
\Adyen\Payment\Model\Billing\Agreement::STATUS_CANCELED
);
$updateBillingAgreement->save(); $updateBillingAgreement->save();
} else { } else {
$updateBillingAgreement->setStatus(\Adyen\Payment\Model\Billing\Agreement::STATUS_ACTIVE); $updateBillingAgreement->setStatus(
\Adyen\Payment\Model\Billing\Agreement::STATUS_ACTIVE
);
$updateBillingAgreement->save(); $updateBillingAgreement->save();
} }
} }
...@@ -689,22 +804,33 @@ class Cron ...@@ -689,22 +804,33 @@ class Cron
} }
}else { } else {
$this->_adyenLogger->addAdyenNotificationCronjob('Failed to create billing agreement for this order (listRecurringCall did not contain contract)'); $this->_adyenLogger->addAdyenNotificationCronjob(
$this->_adyenLogger->addAdyenNotificationCronjob(printf('recurringDetailReference in notification is %1', $recurringDetailReference)); 'Failed to create billing agreement for this order ' .
$this->_adyenLogger->addAdyenNotificationCronjob(printf('CustomerReference is: %1 and storeId is %2', $customerReference, $storeId)); '(listRecurringCall did not contain contract)'
$this->_adyenLogger->addAdyenNotificationCronjob( $listRecurringContracts); );
$message = __('Failed to create billing agreement for this order (listRecurringCall did not contain contract)'); $this->_adyenLogger->addAdyenNotificationCronjob(
printf('recurringDetailReference in notification is %1', $recurringDetailReference)
);
$this->_adyenLogger->addAdyenNotificationCronjob(
printf('CustomerReference is: %1 and storeId is %2', $customerReference, $storeId)
);
$this->_adyenLogger->addAdyenNotificationCronjob($listRecurringContracts);
$message = __(
'Failed to create billing agreement for this order ' .
'(listRecurringCall did not contain contract)'
);
} }
$comment = $this->_order->addStatusHistoryComment($message); $comment = $this->_order->addStatusHistoryComment($message);
$this->_order->addRelatedObject($comment); $this->_order->addRelatedObject($comment);
} }
} }
break; break;
default: default:
$this->_adyenLogger->addAdyenNotificationCronjob(sprintf('This notification event: %s is not supported so will be ignored', $this->_eventCode)); $this->_adyenLogger->addAdyenNotificationCronjob(
sprintf('This notification event: %s is not supported so will be ignored', $this->_eventCode)
);
break; break;
} }
} }
...@@ -717,24 +843,29 @@ class Cron ...@@ -717,24 +843,29 @@ class Cron
{ {
$this->_adyenLogger->addAdyenNotificationCronjob('Refunding the order'); $this->_adyenLogger->addAdyenNotificationCronjob('Refunding the order');
// Don't create a credit memo if refund is initialize in Magento because in this case the credit memo already exists /*
* Don't create a credit memo if refund is initialize in Magento
* because in this case the credit memo already exists
*/
$lastTransactionId = $this->_order->getPayment()->getLastTransId(); $lastTransactionId = $this->_order->getPayment()->getLastTransId();
if($lastTransactionId != $this->_pspReference) { if ($lastTransactionId != $this->_pspReference) {
// refund is done through adyen backoffice so create an invoice // refund is done through adyen backoffice so create an invoice
$order = $this->_order; $order = $this->_order;
if ($order->canCreditmemo()) { if ($order->canCreditmemo()) {
// there is a bug in this function of Magento see #2656 magento\magento2 repo // there is a bug in this function of Magento see #2656 magento\magento2 repo
// $amount = $this->_adyenHelper->originalAmount($this->_value, $currency); // $amount = $this->_adyenHelper->originalAmount($this->_value, $currency);
// $order->getPayment()->registerRefundNotification($amount); // $order->getPayment()->registerRefundNotification($amount);
$this->_adyenLogger->addAdyenNotificationCronjob('Please create your credit memo inside magentos'); $this->_adyenLogger->addAdyenNotificationCronjob('Please create your credit memo inside magentos');
} else { } else {
$this->_adyenLogger->addAdyenNotificationCronjob('Could not create a credit memo for order'); $this->_adyenLogger->addAdyenNotificationCronjob('Could not create a credit memo for order');
} }
} else { } else {
$this->_adyenLogger->addAdyenNotificationCronjob('Did not create a credit memo for this order becasue refund is done through Magento'); $this->_adyenLogger->addAdyenNotificationCronjob(
'Did not create a credit memo for this order becasue refund is done through Magento'
);
} }
} }
...@@ -743,12 +874,14 @@ class Cron ...@@ -743,12 +874,14 @@ class Cron
*/ */
protected function _setRefundAuthorized() protected function _setRefundAuthorized()
{ {
$this->_adyenLogger->addAdyenNotificationCronjob('Status update to default status or refund_authorized status if this is set'); $this->_adyenLogger->addAdyenNotificationCronjob(
'Status update to default status or refund_authorized status if this is set'
);
$this->_order->addStatusHistoryComment(__('Adyen Refund Successfully completed')); $this->_order->addStatusHistoryComment(__('Adyen Refund Successfully completed'));
} }
/** /**
* * authorize payment
*/ */
protected function _authorizePayment() protected function _authorizePayment()
{ {
...@@ -756,75 +889,90 @@ class Cron ...@@ -756,75 +889,90 @@ class Cron
$fraudManualReviewStatus = $this->_getFraudManualReviewStatus(); $fraudManualReviewStatus = $this->_getFraudManualReviewStatus();
// If manual review is active and a seperate status is used then ignore the pre authorized status // If manual review is active and a seperate status is used then ignore the pre authorized status
if($this->_fraudManualReview != true || $fraudManualReviewStatus == "") { if ($this->_fraudManualReview != true || $fraudManualReviewStatus == "") {
$this->_setPrePaymentAuthorized(); $this->_setPrePaymentAuthorized();
} else { } else {
$this->_adyenLogger->addAdyenNotificationCronjob('Ignore the pre authorized status because the order is under manual review and use the Manual review status'); $this->_adyenLogger->addAdyenNotificationCronjob(
'Ignore the pre authorized status because the order is ' .
'under manual review and use the Manual review status'
);
} }
$this->_prepareInvoice(); $this->_prepareInvoice();
$_paymentCode = $this->_paymentMethodCode(); $_paymentCode = $this->_paymentMethodCode();
// for boleto confirmation mail is send on order creation // for boleto confirmation mail is send on order creation
if($this->_paymentMethod != "adyen_boleto") { if ($this->_paymentMethod != "adyen_boleto") {
// send order confirmation mail after invoice creation so merchant can add invoicePDF to this mail // send order confirmation mail after invoice creation so merchant can add invoicePDF to this mail
if(!$this->_order->getEmailSent()) { if (!$this->_order->getEmailSent()) {
$this->_orderSender->send($this->_order); $this->_orderSender->send($this->_order);
$this->_adyenLogger->addAdyenNotificationCronjob('Send orderconfirmation email to shopper'); $this->_adyenLogger->addAdyenNotificationCronjob('Send orderconfirmation email to shopper');
} }
} }
if(($this->_paymentMethod == "c_cash" && $this->_getConfigData('create_shipment', 'adyen_cash', $this->_order->getStoreId())) || ($this->_getConfigData('create_shipment', 'adyen_pos', $this->_order->getStoreId()) && $_paymentCode == "adyen_pos")) if (($this->_paymentMethod == "c_cash" &&
{ $this->_getConfigData('create_shipment', 'adyen_cash', $this->_order->getStoreId())) ||
($this->_getConfigData('create_shipment', 'adyen_pos', $this->_order->getStoreId()) &&
$_paymentCode == "adyen_pos")) {
$this->_createShipment(); $this->_createShipment();
} }
} }
/**
* Set status on authorisation
*/
private function _setPrePaymentAuthorized() private function _setPrePaymentAuthorized()
{ {
$status = $this->_getConfigData('payment_pre_authorized', 'adyen_abstract', $this->_order->getStoreId()); $status = $this->_getConfigData('payment_pre_authorized', 'adyen_abstract', $this->_order->getStoreId());
// only do this if status in configuration is set // only do this if status in configuration is set
if(!empty($status)) { if (!empty($status)) {
$this->_order->addStatusHistoryComment(__('Payment is authorised waiting for capture'), $status); $this->_order->addStatusHistoryComment(__('Payment is authorised waiting for capture'), $status);
$this->_adyenLogger->addAdyenNotificationCronjob('Order status is changed to Pre-authorised status, status is ' . $status); $this->_adyenLogger->addAdyenNotificationCronjob(
'Order status is changed to Pre-authorised status, status is ' . $status
);
} else { } else {
$this->_adyenLogger->addAdyenNotificationCronjob('No pre-authorised status is used so ignore'); $this->_adyenLogger->addAdyenNotificationCronjob('No pre-authorised status is used so ignore');
} }
} }
/** /**
* @param $order * @throws Exception
*/ */
protected function _prepareInvoice() protected function _prepareInvoice()
{ {
$this->_adyenLogger->addAdyenNotificationCronjob('Prepare invoice for order'); $this->_adyenLogger->addAdyenNotificationCronjob('Prepare invoice for order');
$payment = $this->_order->getPayment()->getMethodInstance();
//Set order state to new because with order state payment_review it is not possible to create an invoice //Set order state to new because with order state payment_review it is not possible to create an invoice
if (strcmp($this->_order->getState(), \Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW) == 0) { if (strcmp($this->_order->getState(), \Magento\Sales\Model\Order::STATE_PAYMENT_REVIEW) == 0) {
$this->_order->setState(\Magento\Sales\Model\Order::STATE_NEW); $this->_order->setState(\Magento\Sales\Model\Order::STATE_NEW);
} }
//capture mode //capture mode
if (!$this->_isAutoCapture()) { if (!$this->_isAutoCapture()) {
$this->_order->addStatusHistoryComment(__('Capture Mode set to Manual')); $this->_order->addStatusHistoryComment(__('Capture Mode set to Manual'));
$this->_adyenLogger->addAdyenNotificationCronjob('Capture mode is set to Manual'); $this->_adyenLogger->addAdyenNotificationCronjob('Capture mode is set to Manual');
// show message if order is in manual review // show message if order is in manual review
if($this->_fraudManualReview) { if ($this->_fraudManualReview) {
// check if different status is selected // check if different status is selected
$fraudManualReviewStatus = $this->_getFraudManualReviewStatus(); $fraudManualReviewStatus = $this->_getFraudManualReviewStatus();
if($fraudManualReviewStatus != "") { if ($fraudManualReviewStatus != "") {
$status = $fraudManualReviewStatus; $status = $fraudManualReviewStatus;
$comment = "Adyen Payment is in Manual Review check the Adyen platform"; $comment = "Adyen Payment is in Manual Review check the Adyen platform";
$this->_order->addStatusHistoryComment(__($comment), $status); $this->_order->addStatusHistoryComment(__($comment), $status);
} }
} }
$createPendingInvoice = (bool) $this->_getConfigData('create_pending_invoice', 'adyen_abstract', $this->_order->getStoreId()); $createPendingInvoice = (bool) $this->_getConfigData(
if(!$createPendingInvoice) { 'create_pending_invoice', 'adyen_abstract', $this->_order->getStoreId()
$this->_adyenLogger->addAdyenNotificationCronjob('Setting pending invoice is off so don\'t create an invoice wait for the capture notification'); );
if (!$createPendingInvoice) {
$this->_adyenLogger->addAdyenNotificationCronjob(
'Setting pending invoice is off so don\'t create an invoice wait for the capture notification'
);
return; return;
} }
} }
...@@ -833,7 +981,7 @@ class Cron ...@@ -833,7 +981,7 @@ class Cron
$orderCurrencyCode = $this->_order->getOrderCurrencyCode(); $orderCurrencyCode = $this->_order->getOrderCurrencyCode();
$orderAmount = (int) $this->_adyenHelper->formatAmount($this->_order->getGrandTotal(), $orderCurrencyCode); $orderAmount = (int) $this->_adyenHelper->formatAmount($this->_order->getGrandTotal(), $orderCurrencyCode);
if($this->_isTotalAmount($orderAmount)) { if ($this->_isTotalAmount($orderAmount)) {
$this->_createInvoice(); $this->_createInvoice();
} else { } else {
$this->_adyenLogger->addAdyenNotificationCronjob('This is a partial AUTHORISATION'); $this->_adyenLogger->addAdyenNotificationCronjob('This is a partial AUTHORISATION');
...@@ -841,8 +989,11 @@ class Cron ...@@ -841,8 +989,11 @@ class Cron
// Check if this is the first partial authorisation or if there is already been an authorisation // Check if this is the first partial authorisation or if there is already been an authorisation
$paymentObj = $this->_order->getPayment(); $paymentObj = $this->_order->getPayment();
$authorisationAmount = $paymentObj->getAdyenAuthorisationAmount(); $authorisationAmount = $paymentObj->getAdyenAuthorisationAmount();
if($authorisationAmount != "") { if ($authorisationAmount != "") {
$this->_adyenLogger->addAdyenNotificationCronjob('There is already a partial AUTHORISATION received check if this combined with the previous amounts match the total amount of the order'); $this->_adyenLogger->addAdyenNotificationCronjob(
'There is already a partial AUTHORISATION received check if this combined with the ' .
'previous amounts match the total amount of the order'
);
$authorisationAmount = (int) $authorisationAmount; $authorisationAmount = (int) $authorisationAmount;
$currentValue = (int) $this->_value; $currentValue = (int) $this->_value;
$totalAuthorisationAmount = $authorisationAmount + $currentValue; $totalAuthorisationAmount = $authorisationAmount + $currentValue;
...@@ -850,59 +1001,88 @@ class Cron ...@@ -850,59 +1001,88 @@ class Cron
// update amount in column // update amount in column
$paymentObj->setAdyenAuthorisationAmount($totalAuthorisationAmount); $paymentObj->setAdyenAuthorisationAmount($totalAuthorisationAmount);
if($totalAuthorisationAmount == $orderAmount) { if ($totalAuthorisationAmount == $orderAmount) {
$this->_adyenLogger->addAdyenNotificationCronjob('The full amount is paid. This is the latest AUTHORISATION notification. Create the invoice'); $this->_adyenLogger->addAdyenNotificationCronjob(
'The full amount is paid. This is the latest AUTHORISATION notification. Create the invoice'
);
$this->_createInvoice(); $this->_createInvoice();
} else { } else {
// this can be multiple times so use envenData as unique key // this can be multiple times so use envenData as unique key
$this->_adyenLogger->addAdyenNotificationCronjob('The full amount is not reached. Wait for the next AUTHORISATION notification. The current amount that is authorized is:' . $totalAuthorisationAmount); $this->_adyenLogger->addAdyenNotificationCronjob(
'The full amount is not reached. Wait for the next AUTHORISATION notification. ' .
'The current amount that is authorized is:' . $totalAuthorisationAmount
);
} }
} else { } else {
$this->_adyenLogger->addAdyenNotificationCronjob('This is the first partial AUTHORISATION save this into the adyen_authorisation_amount field'); $this->_adyenLogger->addAdyenNotificationCronjob(
'This is the first partial AUTHORISATION save this into the adyen_authorisation_amount field'
);
$paymentObj->setAdyenAuthorisationAmount($this->_value); $paymentObj->setAdyenAuthorisationAmount($this->_value);
} }
} }
} }
/** /**
* @param $order
* @return bool * @return bool
*/ */
protected function _isAutoCapture() protected function _isAutoCapture()
{ {
// validate if payment methods allowes manual capture // validate if payment methods allowes manual capture
if($this->_manualCaptureAllowed()) if ($this->_manualCaptureAllowed()) {
{
$captureMode = trim($this->_getConfigData('capture_mode', 'adyen_abstract', $this->_order->getStoreId())); $captureMode = trim($this->_getConfigData('capture_mode', 'adyen_abstract', $this->_order->getStoreId()));
$sepaFlow = trim($this->_getConfigData('sepa_flow', 'adyen_abstract', $this->_order->getStoreId())); $sepaFlow = trim($this->_getConfigData('sepa_flow', 'adyen_abstract', $this->_order->getStoreId()));
$_paymentCode = $this->_paymentMethodCode(); $_paymentCode = $this->_paymentMethodCode();
$captureModeOpenInvoice = $this->_getConfigData('auto_capture_openinvoice', 'adyen_abstract', $this->_order->getStoreId()); $captureModeOpenInvoice = $this->_getConfigData(
$captureModePayPal = trim($this->_getConfigData('paypal_capture_mode', 'adyen_abstract', $this->_order->getStoreId())); 'auto_capture_openinvoice', 'adyen_abstract', $this->_order->getStoreId()
);
// if you are using authcap the payment method is manual. There will be a capture send to indicate if payment is succesfull $captureModePayPal = trim($this->_getConfigData(
if(($_paymentCode == "adyen_sepa" || $this->_paymentMethod == "sepadirectdebit") && $sepaFlow == "authcap") { 'paypal_capture_mode', 'adyen_abstract', $this->_order->getStoreId())
$this->_adyenLogger->addAdyenNotificationCronjob('Manual Capture is applied for sepa because it is in authcap flow'); );
/*
* if you are using authcap the payment method is manual.
* There will be a capture send to indicate if payment is successful
*/
if (($_paymentCode == "adyen_sepa" || $this->_paymentMethod == "sepadirectdebit") &&
$sepaFlow == "authcap") {
$this->_adyenLogger->addAdyenNotificationCronjob(
'Manual Capture is applied for sepa because it is in authcap flow'
);
return false; return false;
} }
// payment method ideal, cash adyen_boleto or adyen_pos has direct capture // payment method ideal, cash adyen_boleto or adyen_pos has direct capture
if ($_paymentCode == "adyen_pos" || (($_paymentCode == "adyen_sepa" || $this->_paymentMethod == "sepadirectdebit") && $sepaFlow != "authcap")) { if ($_paymentCode == "adyen_pos" || (($_paymentCode == "adyen_sepa" ||
$this->_adyenLogger->addAdyenNotificationCronjob('This payment method does not allow manual capture.(2) paymentCode:' . $_paymentCode . ' paymentMethod:' . $this->_paymentMethod); $this->_paymentMethod == "sepadirectdebit") && $sepaFlow != "authcap")) {
$this->_adyenLogger->addAdyenNotificationCronjob(
'This payment method does not allow manual capture.(2) paymentCode:' .
$_paymentCode . ' paymentMethod:' . $this->_paymentMethod
);
return true; return true;
} }
// if auto capture mode for openinvoice is turned on then use auto capture // if auto capture mode for openinvoice is turned on then use auto capture
if ($captureModeOpenInvoice == true && (strcmp($this->_paymentMethod, 'openinvoice') === 0 || strcmp($this->_paymentMethod, 'afterpay_default') === 0 || strcmp($this->_paymentMethod, 'klarna') === 0)) { if ($captureModeOpenInvoice == true &&
$this->_adyenLogger->addAdyenNotificationCronjob('This payment method is configured to be working as auto capture '); (strcmp($this->_paymentMethod, 'openinvoice') === 0 ||
strcmp($this->_paymentMethod, 'afterpay_default') === 0 ||
strcmp($this->_paymentMethod, 'klarna') === 0)) {
$this->_adyenLogger->addAdyenNotificationCronjob(
'This payment method is configured to be working as auto capture '
);
return true; return true;
} }
// if PayPal capture modues is different from the default use this one // if PayPal capture modues is different from the default use this one
if(strcmp($this->_paymentMethod, 'paypal' ) === 0 && $captureModePayPal != "") { if (strcmp($this->_paymentMethod, 'paypal' ) === 0 && $captureModePayPal != "") {
if(strcmp($captureModePayPal, 'auto') === 0 ) { if (strcmp($captureModePayPal, 'auto') === 0 ) {
$this->_adyenLogger->addAdyenNotificationCronjob('This payment method is paypal and configured to work as auto capture'); $this->_adyenLogger->addAdyenNotificationCronjob(
'This payment method is paypal and configured to work as auto capture'
);
return true; return true;
} elseif(strcmp($captureModePayPal, 'manual') === 0 ) { } elseif (strcmp($captureModePayPal, 'manual') === 0 ) {
$this->_adyenLogger->addAdyenNotificationCronjob('This payment method is paypal and configured to work as manual capture'); $this->_adyenLogger->addAdyenNotificationCronjob(
'This payment method is paypal and configured to work as manual capture'
);
return false; return false;
} }
} }
...@@ -910,8 +1090,15 @@ class Cron ...@@ -910,8 +1090,15 @@ class Cron
$this->_adyenLogger->addAdyenNotificationCronjob('Capture mode for this payment is set to manual'); $this->_adyenLogger->addAdyenNotificationCronjob('Capture mode for this payment is set to manual');
return false; return false;
} }
//online capture after delivery, use Magento backend to online invoice (if the option auto capture mode for openinvoice is not set)
if (strcmp($this->_paymentMethod, 'openinvoice') === 0 || strcmp($this->_paymentMethod, 'afterpay_default') === 0 || strcmp($this->_paymentMethod, 'klarna') === 0) { /*
* online capture after delivery, use Magento backend to online invoice
* (if the option auto capture mode for openinvoice is not set)
*/
if (strcmp($this->_paymentMethod, 'openinvoice') === 0 ||
strcmp($this->_paymentMethod, 'afterpay_default') === 0 ||
strcmp($this->_paymentMethod, 'klarna') === 0) {
$this->_adyenLogger->addAdyenNotificationCronjob('Capture mode for klarna is by default set to manual'); $this->_adyenLogger->addAdyenNotificationCronjob('Capture mode for klarna is by default set to manual');
return false; return false;
} }
...@@ -930,6 +1117,8 @@ class Cron ...@@ -930,6 +1117,8 @@ class Cron
/** /**
* Validate if this payment methods allows manual capture * Validate if this payment methods allows manual capture
* This is a default can be forced differently to overrule on acquirer level * This is a default can be forced differently to overrule on acquirer level
*
* @return bool|null
*/ */
protected function _manualCaptureAllowed() protected function _manualCaptureAllowed()
{ {
...@@ -958,7 +1147,7 @@ class Cron ...@@ -958,7 +1147,7 @@ class Cron
break; break;
default: default:
// To be sure check if it payment method starts with afterpay_ then manualCapture is allowed // To be sure check if it payment method starts with afterpay_ then manualCapture is allowed
if(strlen($this->_paymentMethod) >= 9 && substr($this->_paymentMethod, 0, 9) == "afterpay_") { if (strlen($this->_paymentMethod) >= 9 && substr($this->_paymentMethod, 0, 9) == "afterpay_") {
$manualCaptureAllowed = true; $manualCaptureAllowed = true;
} }
$manualCaptureAllowed = false; $manualCaptureAllowed = false;
...@@ -968,11 +1157,10 @@ class Cron ...@@ -968,11 +1157,10 @@ class Cron
} }
/** /**
* @param $paymentMethod
* @return bool * @return bool
*/ */
protected function _isBankTransfer() { protected function _isBankTransfer() {
if(strlen($this->_paymentMethod) >= 12 && substr($this->_paymentMethod, 0, 12) == "bankTransfer") { if (strlen($this->_paymentMethod) >= 12 && substr($this->_paymentMethod, 0, 12) == "bankTransfer") {
$isBankTransfer = true; $isBankTransfer = true;
} else { } else {
$isBankTransfer = false; $isBankTransfer = false;
...@@ -980,39 +1168,58 @@ class Cron ...@@ -980,39 +1168,58 @@ class Cron
return $isBankTransfer; return $isBankTransfer;
} }
/**
* @return mixed
*/
protected function _getFraudManualReviewStatus() protected function _getFraudManualReviewStatus()
{ {
return $this->_getConfigData('fraud_manual_review_status', 'adyen_abstract', $this->_order->getStoreId()); return $this->_getConfigData('fraud_manual_review_status', 'adyen_abstract', $this->_order->getStoreId());
} }
/**
* @return mixed
*/
protected function _getFraudManualReviewAcceptStatus() protected function _getFraudManualReviewAcceptStatus()
{ {
return $this->_getConfigData('fraud_manual_review_accept_status', 'adyen_abstract', $this->_order->getStoreId()); return $this->_getConfigData(
'fraud_manual_review_accept_status', 'adyen_abstract', $this->_order->getStoreId()
);
} }
protected function _isTotalAmount($orderAmount) { /**
* @param $orderAmount
$this->_adyenLogger->addAdyenNotificationCronjob('Validate if AUTHORISATION notification has the total amount of the order'); * @return bool
*/
protected function _isTotalAmount($orderAmount)
{
$this->_adyenLogger->addAdyenNotificationCronjob(
'Validate if AUTHORISATION notification has the total amount of the order'
);
$value = (int)$this->_value; $value = (int)$this->_value;
if($value == $orderAmount) { if ($value == $orderAmount) {
$this->_adyenLogger->addAdyenNotificationCronjob('AUTHORISATION has the full amount'); $this->_adyenLogger->addAdyenNotificationCronjob('AUTHORISATION has the full amount');
return true; return true;
} else { } else {
$this->_adyenLogger->addAdyenNotificationCronjob('This is a partial AUTHORISATION, the amount is ' . $this->_value); $this->_adyenLogger->addAdyenNotificationCronjob(
'This is a partial AUTHORISATION, the amount is ' . $this->_value
);
return false; return false;
} }
} }
/**
* @throws Exception
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function _createInvoice() protected function _createInvoice()
{ {
$this->_adyenLogger->addAdyenNotificationCronjob('Creating invoice for order'); $this->_adyenLogger->addAdyenNotificationCronjob('Creating invoice for order');
if ($this->_order->canInvoice()) { if ($this->_order->canInvoice()) {
/* We do not use this inside a transaction because order->save() is always done on the end of the notification /* We do not use this inside a transaction because order->save()
* is always done on the end of the notification
* and it could result in a deadlock see https://github.com/Adyen/magento/issues/334 * and it could result in a deadlock see https://github.com/Adyen/magento/issues/334
*/ */
try { try {
...@@ -1024,13 +1231,15 @@ class Cron ...@@ -1024,13 +1231,15 @@ class Cron
$autoCapture = $this->_isAutoCapture(); $autoCapture = $this->_isAutoCapture();
$createPendingInvoice = (bool) $this->_getConfigData('create_pending_invoice', 'adyen_abstract', $this->_order->getStoreId()); $createPendingInvoice = (bool) $this->_getConfigData(
'create_pending_invoice', 'adyen_abstract', $this->_order->getStoreId()
);
if((!$autoCapture) && ($createPendingInvoice)) { if ((!$autoCapture) && ($createPendingInvoice)) {
// if amount is zero create a offline invoice // if amount is zero create a offline invoice
$value = (int)$this->_value; $value = (int)$this->_value;
if($value == 0) { if ($value == 0) {
$invoice->setRequestedCaptureCase(\Magento\Sales\Model\Order\Invoice::CAPTURE_OFFLINE); $invoice->setRequestedCaptureCase(\Magento\Sales\Model\Order\Invoice::CAPTURE_OFFLINE);
} else { } else {
$invoice->setRequestedCaptureCase(\Magento\Sales\Model\Order\Invoice::NOT_CAPTURE); $invoice->setRequestedCaptureCase(\Magento\Sales\Model\Order\Invoice::NOT_CAPTURE);
...@@ -1042,16 +1251,20 @@ class Cron ...@@ -1042,16 +1251,20 @@ class Cron
} }
$invoice->save(); $invoice->save();
$this->_adyenLogger->addAdyenNotificationCronjob('Created invoice'); $this->_adyenLogger->addAdyenNotificationCronjob('Created invoice');
} catch (Exception $e) { } catch (Exception $e) {
$this->_adyenLogger->addAdyenNotificationCronjob('Error saving invoice. The error message is: ' . $e->getMessage()); $this->_adyenLogger->addAdyenNotificationCronjob(
'Error saving invoice. The error message is: ' . $e->getMessage()
);
throw new Exception(sprintf('Error saving invoice. The error message is:', $e->getMessage())); throw new Exception(sprintf('Error saving invoice. The error message is:', $e->getMessage()));
} }
$this->_setPaymentAuthorized(); $this->_setPaymentAuthorized();
$invoiceAutoMail = (bool) $this->_getConfigData('send_invoice_update_mail', 'adyen_abstract', $this->_order->getStoreId()); $invoiceAutoMail = (bool) $this->_getConfigData(
'send_invoice_update_mail', 'adyen_abstract', $this->_order->getStoreId()
);
if ($invoiceAutoMail) { if ($invoiceAutoMail) {
$invoice->sendEmail(); $invoice->sendEmail();
} }
...@@ -1061,7 +1274,9 @@ class Cron ...@@ -1061,7 +1274,9 @@ class Cron
} }
/** /**
* * @param bool $manualReviewComment
* @param bool $createInvoice
* @throws Exception
*/ */
protected function _setPaymentAuthorized($manualReviewComment = true, $createInvoice = false) protected function _setPaymentAuthorized($manualReviewComment = true, $createInvoice = false)
{ {
...@@ -1073,44 +1288,49 @@ class Cron ...@@ -1073,44 +1288,49 @@ class Cron
$orderAmount = (int) $this->_adyenHelper->formatAmount($this->_order->getGrandTotal(), $currency); $orderAmount = (int) $this->_adyenHelper->formatAmount($this->_order->getGrandTotal(), $currency);
// create invoice for the capture notification if you are on manual capture // create invoice for the capture notification if you are on manual capture
if($createInvoice == true && $amount == $orderAmount) { if ($createInvoice == true && $amount == $orderAmount) {
$this->_adyenLogger->addAdyenNotificationCronjob('amount notification:'.$amount . ' amount order:'.$orderAmount); $this->_adyenLogger->addAdyenNotificationCronjob(
'amount notification:'.$amount . ' amount order:'.$orderAmount
);
$this->_createInvoice(); $this->_createInvoice();
} }
// if you have capture on shipment enabled don't set update the status of the payment // if you have capture on shipment enabled don't set update the status of the payment
$captureOnShipment = $this->_getConfigData('capture_on_shipment', 'adyen_abstract', $this->_order->getStoreId()); $captureOnShipment = $this->_getConfigData(
if(!$captureOnShipment) { 'capture_on_shipment', 'adyen_abstract', $this->_order->getStoreId()
);
if (!$captureOnShipment) {
$status = $this->_getConfigData('payment_authorized', 'adyen_abstract', $this->_order->getStoreId()); $status = $this->_getConfigData('payment_authorized', 'adyen_abstract', $this->_order->getStoreId());
} }
// virtual order can have different status // virtual order can have different status
if($this->_order->getIsVirtual()) { if ($this->_order->getIsVirtual()) {
$this->_adyenLogger->addAdyenNotificationCronjob('Product is a virtual product'); $this->_adyenLogger->addAdyenNotificationCronjob('Product is a virtual product');
$virtual_status = $this->_getConfigData('payment_authorized_virtual'); $virtualStatus = $this->_getConfigData('payment_authorized_virtual');
if($virtual_status != "") { if ($virtualStatus != "") {
$status = $virtual_status; $status = $virtualStatus;
} }
} }
// check for boleto if payment is totally paid // check for boleto if payment is totally paid
if($this->_paymentMethodCode() == "adyen_boleto") { if ($this->_paymentMethodCode() == "adyen_boleto") {
// check if paid amount is the same as orginal amount // check if paid amount is the same as orginal amount
$orginalAmount = $this->_boletoOriginalAmount; $orginalAmount = $this->_boletoOriginalAmount;
$paidAmount = $this->_boletoPaidAmount; $paidAmount = $this->_boletoPaidAmount;
if($orginalAmount != $paidAmount) { if ($orginalAmount != $paidAmount) {
// not the full amount is paid. Check if it is underpaid or overpaid // not the full amount is paid. Check if it is underpaid or overpaid
// strip the BRL of the string // strip the BRL of the string
$orginalAmount = str_replace("BRL", "", $orginalAmount); $orginalAmount = str_replace("BRL", "", $orginalAmount);
$orginalAmount = floatval(trim($orginalAmount)); $orginalAmount = floatval(trim($orginalAmount));
$paidAmount = str_replace("BRL", "", $paidAmount); $paidAmount = str_replace("BRL", "", $paidAmount);
$paidAmount = floatval(trim($paidAmount)); $paidAmount = floatval(trim($paidAmount));
if($paidAmount > $orginalAmount) { if ($paidAmount > $orginalAmount) {
$overpaidStatus = $this->_getConfigData('order_overpaid_status', 'adyen_boleto'); $overpaidStatus = $this->_getConfigData('order_overpaid_status', 'adyen_boleto');
// check if there is selected a status if not fall back to the default // check if there is selected a status if not fall back to the default
$status = (!empty($overpaidStatus)) ? $overpaidStatus : $status; $status = (!empty($overpaidStatus)) ? $overpaidStatus : $status;
...@@ -1125,10 +1345,10 @@ class Cron ...@@ -1125,10 +1345,10 @@ class Cron
$comment = "Adyen Payment Successfully completed"; $comment = "Adyen Payment Successfully completed";
// if manual review is true use the manual review status if this is set // if manual review is true use the manual review status if this is set
if($manualReviewComment == true && $this->_fraudManualReview) { if ($manualReviewComment == true && $this->_fraudManualReview) {
// check if different status is selected // check if different status is selected
$fraudManualReviewStatus = $this->_getFraudManualReviewStatus(); $fraudManualReviewStatus = $this->_getFraudManualReviewStatus();
if($fraudManualReviewStatus != "") { if ($fraudManualReviewStatus != "") {
$status = $fraudManualReviewStatus; $status = $fraudManualReviewStatus;
$comment = "Adyen Payment is in Manual Review check the Adyen platform"; $comment = "Adyen Payment is in Manual Review check the Adyen platform";
} }
...@@ -1136,21 +1356,26 @@ class Cron ...@@ -1136,21 +1356,26 @@ class Cron
$status = (!empty($status)) ? $status : $this->_order->getStatus(); $status = (!empty($status)) ? $status : $this->_order->getStatus();
$this->_order->addStatusHistoryComment(__($comment), $status); $this->_order->addStatusHistoryComment(__($comment), $status);
$this->_adyenLogger->addAdyenNotificationCronjob('Order status is changed to authorised status, status is ' . $status); $this->_adyenLogger->addAdyenNotificationCronjob(
'Order status is changed to authorised status, status is ' . $status
);
} }
/** /**
* Create shipment
* *
* @throws bool
*/ */
protected function _createShipment() { protected function _createShipment()
{
$this->_adyenLogger->addAdyenNotificationCronjob('Creating shipment for order'); $this->_adyenLogger->addAdyenNotificationCronjob('Creating shipment for order');
// create shipment for cash payment // create shipment for cash payment
$payment = $this->_order->getPayment()->getMethodInstance(); $payment = $this->_order->getPayment()->getMethodInstance();
if($this->_order->canShip()) if ($this->_order->canShip()) {
{ $itemQty = [];
$itemQty = array();
$shipment = $this->_order->prepareShipment($itemQty); $shipment = $this->_order->prepareShipment($itemQty);
if($shipment) { if ($shipment) {
$shipment->register(); $shipment->register();
$shipment->getOrder()->setIsInProcess(true); $shipment->getOrder()->setIsInProcess(true);
$comment = __('Shipment created by Adyen'); $comment = __('Shipment created by Adyen');
...@@ -1169,13 +1394,12 @@ class Cron ...@@ -1169,13 +1394,12 @@ class Cron
} }
} }
/** /**
* Retrieve information from payment configuration * Retrieve information from payment configuration
* *
* @param string $field * @param $field
* @param int|string|null|\Magento\Store\Model\Store $storeId * @param string $paymentMethodCode
* * @param $storeId
* @return mixed * @return mixed
*/ */
protected function _getConfigData($field, $paymentMethodCode = 'adyen_cc', $storeId) protected function _getConfigData($field, $paymentMethodCode = 'adyen_cc', $storeId)
...@@ -1183,6 +1407,4 @@ class Cron ...@@ -1183,6 +1407,4 @@ class Cron
$path = 'payment/' . $paymentMethodCode . '/' . $field; $path = 'payment/' . $paymentMethodCode . '/' . $field;
return $this->_scopeConfig->getValue($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId); return $this->_scopeConfig->getValue($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
} }
} }
\ No newline at end of file
...@@ -42,18 +42,23 @@ class AdyenAbstract extends \Magento\Payment\Model\Method\AbstractMethod impleme ...@@ -42,18 +42,23 @@ class AdyenAbstract extends \Magento\Payment\Model\Method\AbstractMethod impleme
* @var bool * @var bool
*/ */
protected $_isGateway = false; protected $_isGateway = false;
/**
* @var bool
*/
protected $_canAuthorize = false; protected $_canAuthorize = false;
/**
* @var bool
*/
protected $_isInitializeNeeded = false; protected $_isInitializeNeeded = false;
/** /**
* Post request to gateway and return response * Post request to gateway and return response
* *
* @param Object $request * @param DataObject $request
* @param ConfigInterface $config * @param ConfigInterface $config
*
* @return DataObject
*
* @throws \Exception
*/ */
public function postRequest(DataObject $request, ConfigInterface $config) public function postRequest(DataObject $request, ConfigInterface $config)
{ {
......
...@@ -40,11 +40,35 @@ class Cc extends \Magento\Payment\Model\Method\Cc ...@@ -40,11 +40,35 @@ class Cc extends \Magento\Payment\Model\Method\Cc
* @var bool * @var bool
*/ */
protected $_canAuthorize = true; protected $_canAuthorize = true;
/**
* @var bool
*/
protected $_canCapture = true; protected $_canCapture = true;
/**
* @var bool
*/
protected $_canCapturePartial = true; protected $_canCapturePartial = true;
/**
* @var bool
*/
protected $_canCaptureOnce = true; protected $_canCaptureOnce = true;
/**
* @var bool
*/
protected $_canRefund = true; protected $_canRefund = true;
/**
* @var bool
*/
protected $_canRefundInvoicePartial = true; protected $_canRefundInvoicePartial = true;
/**
* @var bool
*/
protected $_isGateway = true; protected $_isGateway = true;
/** /**
...@@ -56,22 +80,16 @@ class Cc extends \Magento\Payment\Model\Method\Cc ...@@ -56,22 +80,16 @@ class Cc extends \Magento\Payment\Model\Method\Cc
* @var string * @var string
*/ */
protected $_formBlockType = 'Adyen\Payment\Block\Form\Cc'; protected $_formBlockType = 'Adyen\Payment\Block\Form\Cc';
protected $_infoBlockType = 'Adyen\Payment\Block\Info\Cc';
/** /**
* @var \Adyen\Payment\Model\Api\PaymentRequest * @var string
*/
protected $_paymentRequest;
/**
* @var \Adyen\Payment\Logger\AdyenLogger
*/ */
protected $_adyenLogger; protected $_infoBlockType = 'Adyen\Payment\Block\Info\Cc';
/** /**
* @var \Magento\Checkout\Model\Session * @var \Adyen\Payment\Model\Api\PaymentRequest
*/ */
protected $_checkoutSession; protected $_paymentRequest;
/** /**
* @var \Magento\Framework\UrlInterface * @var \Magento\Framework\UrlInterface
...@@ -91,9 +109,10 @@ class Cc extends \Magento\Payment\Model\Method\Cc ...@@ -91,9 +109,10 @@ class Cc extends \Magento\Payment\Model\Method\Cc
protected $_request; protected $_request;
/** /**
* Cc constructor.
*
* @param \Magento\Framework\App\RequestInterface $request
* @param \Adyen\Payment\Model\Api\PaymentRequest $paymentRequest * @param \Adyen\Payment\Model\Api\PaymentRequest $paymentRequest
* @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger
* @param \Magento\Checkout\Model\Session $checkoutSession
* @param \Magento\Framework\UrlInterface $urlBuilder * @param \Magento\Framework\UrlInterface $urlBuilder
* @param \Adyen\Payment\Helper\Data $adyenHelper * @param \Adyen\Payment\Helper\Data $adyenHelper
* @param \Magento\Framework\Model\Context $context * @param \Magento\Framework\Model\Context $context
...@@ -108,13 +127,10 @@ class Cc extends \Magento\Payment\Model\Method\Cc ...@@ -108,13 +127,10 @@ class Cc extends \Magento\Payment\Model\Method\Cc
* @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource * @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource
* @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection * @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection
* @param array $data * @param array $data
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/ */
public function __construct( public function __construct(
\Magento\Framework\App\RequestInterface $request, \Magento\Framework\App\RequestInterface $request,
\Adyen\Payment\Model\Api\PaymentRequest $paymentRequest, \Adyen\Payment\Model\Api\PaymentRequest $paymentRequest,
\Adyen\Payment\Logger\AdyenLogger $adyenLogger,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Framework\UrlInterface $urlBuilder, \Magento\Framework\UrlInterface $urlBuilder,
\Adyen\Payment\Helper\Data $adyenHelper, \Adyen\Payment\Helper\Data $adyenHelper,
\Magento\Framework\Model\Context $context, \Magento\Framework\Model\Context $context,
...@@ -145,15 +161,21 @@ class Cc extends \Magento\Payment\Model\Method\Cc ...@@ -145,15 +161,21 @@ class Cc extends \Magento\Payment\Model\Method\Cc
$data $data
); );
$this->_paymentRequest = $paymentRequest; $this->_paymentRequest = $paymentRequest;
$this->_adyenLogger = $adyenLogger;
$this->_checkoutSession = $checkoutSession;
$this->_urlBuilder = $urlBuilder; $this->_urlBuilder = $urlBuilder;
$this->_adyenHelper = $adyenHelper; $this->_adyenHelper = $adyenHelper;
$this->_request = $request; $this->_request = $request;
} }
/**
* @var string
*/
protected $_paymentMethodType = 'api'; protected $_paymentMethodType = 'api';
public function getPaymentMethodType() {
/**
* @return string
*/
public function getPaymentMethodType()
{
return $this->_paymentMethodType; return $this->_paymentMethodType;
} }
...@@ -167,20 +189,29 @@ class Cc extends \Magento\Payment\Model\Method\Cc ...@@ -167,20 +189,29 @@ class Cc extends \Magento\Payment\Model\Method\Cc
public function assignData(\Magento\Framework\DataObject $data) public function assignData(\Magento\Framework\DataObject $data)
{ {
parent::assignData($data); parent::assignData($data);
$infoInstance = $this->getInfoInstance();
$infoInstance->setCcType($data['cc_type']); if (!$data instanceof \Magento\Framework\DataObject) {
$data = new \Magento\Framework\DataObject($data);
}
if($this->_adyenHelper->getAdyenCcConfigDataFlag('cse_enabled')) { $additionalData = $data->getAdditionalData();
if(isset($data['encrypted_data'])) { $infoInstance = $this->getInfoInstance();
$infoInstance->setAdditionalInformation('encrypted_data', $data['encrypted_data']);
if (isset($additionalData['cc_type'])) {
$infoInstance->setCcType($additionalData['cc_type']);
}
if ($this->_adyenHelper->getAdyenCcConfigDataFlag('cse_enabled')) {
if (isset($additionalData['encrypted_data'])) {
$infoInstance->setAdditionalInformation('encrypted_data', $additionalData['encrypted_data']);
} else { } else {
throw new \Magento\Framework\Exception\LocalizedException(__('Card encryption failed')); throw new \Magento\Framework\Exception\LocalizedException(__('Card encryption failed'));
} }
} }
// save value remember details checkbox // save value remember details checkbox
$infoInstance->setAdditionalInformation('store_cc', $data['store_cc']); if (isset($additionalData['store_cc'])) {
$infoInstance->setAdditionalInformation('store_cc', $additionalData['store_cc']);
}
return $this; return $this;
} }
...@@ -191,7 +222,7 @@ class Cc extends \Magento\Payment\Model\Method\Cc ...@@ -191,7 +222,7 @@ class Cc extends \Magento\Payment\Model\Method\Cc
* @return $this * @return $this
* @throws \Magento\Framework\Exception\LocalizedException * @throws \Magento\Framework\Exception\LocalizedException
* @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.NPathComplexity)authorize
*/ */
public function validate() public function validate()
{ {
...@@ -199,6 +230,12 @@ class Cc extends \Magento\Payment\Model\Method\Cc ...@@ -199,6 +230,12 @@ class Cc extends \Magento\Payment\Model\Method\Cc
return $this; return $this;
} }
/**
* @param \Magento\Payment\Model\InfoInterface $payment
* @param float $amount
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function authorize(\Magento\Payment\Model\InfoInterface $payment, $amount) public function authorize(\Magento\Payment\Model\InfoInterface $payment, $amount)
{ {
if (!$this->canAuthorize()) { if (!$this->canAuthorize()) {
...@@ -221,6 +258,12 @@ class Cc extends \Magento\Payment\Model\Method\Cc ...@@ -221,6 +258,12 @@ class Cc extends \Magento\Payment\Model\Method\Cc
return $this; return $this;
} }
/**
* @param \Magento\Sales\Model\Order\Payment $payment
* @param $amount
* @param $request
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function _processRequest(\Magento\Sales\Model\Order\Payment $payment, $amount, $request) protected function _processRequest(\Magento\Sales\Model\Order\Payment $payment, $amount, $request)
{ {
switch ($request) { switch ($request) {
...@@ -236,13 +279,17 @@ class Cc extends \Magento\Payment\Model\Method\Cc ...@@ -236,13 +279,17 @@ class Cc extends \Magento\Payment\Model\Method\Cc
} }
} }
/**
* @param \Magento\Payment\Model\InfoInterface $payment
* @param $response
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function _processResponse(\Magento\Payment\Model\InfoInterface $payment, $response) protected function _processResponse(\Magento\Payment\Model\InfoInterface $payment, $response)
{ {
$payment->setAdditionalInformation('3dActive', false); $payment->setAdditionalInformation('3dActive', false);
switch ($response['resultCode']) { switch ($response['resultCode']) {
case "Authorised": case "Authorised":
//$this->_addStatusHistory($payment, $responseCode, $pspReference, $this->_getConfigData('order_status'));
$this->_addStatusHistory($payment, $response['resultCode'], $response['pspReference']); $this->_addStatusHistory($payment, $response['resultCode'], $response['pspReference']);
$payment->setAdditionalInformation('pspReference', $response['pspReference']); $payment->setAdditionalInformation('pspReference', $response['pspReference']);
break; break;
...@@ -250,10 +297,10 @@ class Cc extends \Magento\Payment\Model\Method\Cc ...@@ -250,10 +297,10 @@ class Cc extends \Magento\Payment\Model\Method\Cc
// 3d is active so set the param to true checked in Controller/Validate3d // 3d is active so set the param to true checked in Controller/Validate3d
$payment->setAdditionalInformation('3dActive', true); $payment->setAdditionalInformation('3dActive', true);
$issuerUrl = $response['issuerUrl']; $issuerUrl = $response['issuerUrl'];
$PaReq = $response['paRequest']; $paReq = $response['paRequest'];
$md = $response['md']; $md = $response['md'];
if(!empty($PaReq) && !empty($md) && !empty($issuerUrl)) { if (!empty($paReq) && !empty($md) && !empty($issuerUrl)) {
$payment->setAdditionalInformation('issuerUrl', $response['issuerUrl']); $payment->setAdditionalInformation('issuerUrl', $response['issuerUrl']);
$payment->setAdditionalInformation('paRequest', $response['paRequest']); $payment->setAdditionalInformation('paRequest', $response['paRequest']);
$payment->setAdditionalInformation('md', $response['md']); $payment->setAdditionalInformation('md', $response['md']);
...@@ -263,7 +310,7 @@ class Cc extends \Magento\Payment\Model\Method\Cc ...@@ -263,7 +310,7 @@ class Cc extends \Magento\Payment\Model\Method\Cc
break; break;
case "Refused": case "Refused":
// refusalReason // refusalReason
if($response['refusalReason']) { if ($response['refusalReason']) {
$refusalReason = $response['refusalReason']; $refusalReason = $response['refusalReason'];
switch($refusalReason) { switch($refusalReason) {
...@@ -298,22 +345,32 @@ class Cc extends \Magento\Payment\Model\Method\Cc ...@@ -298,22 +345,32 @@ class Cc extends \Magento\Payment\Model\Method\Cc
} }
} }
/**
* @param $payment
* @param $responseCode
* @param $pspReference
* @return $this
*/
protected function _addStatusHistory($payment, $responseCode, $pspReference) protected function _addStatusHistory($payment, $responseCode, $pspReference)
{ {
$type = 'Adyen Result URL response:'; $type = 'Adyen Result URL response:';
$comment = __('%1 <br /> authResult: %2 <br /> pspReference: %3 <br /> paymentMethod: %4', $type, $responseCode, $pspReference, ""); $comment = __('%1 <br /> authResult: %2 <br /> pspReference: %3 <br /> paymentMethod: %4',
$type, $responseCode, $pspReference, "");
$payment->getOrder()->setAdyenResulturlEventCode($responseCode); $payment->getOrder()->setAdyenResulturlEventCode($responseCode);
$payment->getOrder()->addStatusHistoryComment($comment); $payment->getOrder()->addStatusHistoryComment($comment);
return $this; return $this;
} }
/* /**
* Called by validate3d controller when cc payment has 3D secure * Called by validate3d controller when cc payment has 3D secure
*
* @param $payment
* @return mixed
* @throws \Magento\Framework\Exception\LocalizedException
*/ */
public function authorise3d($payment) public function authorise3d($payment)
{ {
$response = $this->_paymentRequest->authorise3d($payment); $response = $this->_paymentRequest->authorise3d($payment);
$responseCode = $response['resultCode']; $responseCode = $response['resultCode'];
return $responseCode; return $responseCode;
...@@ -328,7 +385,7 @@ class Cc extends \Magento\Payment\Model\Method\Cc ...@@ -328,7 +385,7 @@ class Cc extends \Magento\Payment\Model\Method\Cc
*/ */
public function getCheckoutRedirectUrl() public function getCheckoutRedirectUrl()
{ {
return $this->_urlBuilder->getUrl('adyen/process/validate3d/',['_secure' => $this->_getRequest()->isSecure()]); return $this->_urlBuilder->getUrl('adyen/process/validate3d/', ['_secure' => $this->_getRequest()->isSecure()]);
} }
/** /**
...@@ -336,6 +393,8 @@ class Cc extends \Magento\Payment\Model\Method\Cc ...@@ -336,6 +393,8 @@ class Cc extends \Magento\Payment\Model\Method\Cc
* *
* @param \Magento\Payment\Model\InfoInterface $payment * @param \Magento\Payment\Model\InfoInterface $payment
* @param float $amount * @param float $amount
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
*/ */
public function capture(\Magento\Payment\Model\InfoInterface $payment, $amount) public function capture(\Magento\Payment\Model\InfoInterface $payment, $amount)
{ {
...@@ -343,26 +402,27 @@ class Cc extends \Magento\Payment\Model\Method\Cc ...@@ -343,26 +402,27 @@ class Cc extends \Magento\Payment\Model\Method\Cc
$this->_paymentRequest->capture($payment, $amount); $this->_paymentRequest->capture($payment, $amount);
return $this; return $this;
} }
/** /**
* Refund specified amount for payment * Refund specified amount for payment
* *
* @param \Magento\Framework\DataObject|InfoInterface $payment * @param \Magento\Payment\Model\InfoInterface $payment
* @param float $amount * @param float $amount
* @return $this * @return $this
* @throws \Magento\Framework\Exception\LocalizedException * @throws \Magento\Framework\Exception\LocalizedException
* @api
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/ */
public function refund(\Magento\Payment\Model\InfoInterface $payment, $amount) public function refund(\Magento\Payment\Model\InfoInterface $payment, $amount)
{ {
parent::refund($payment, $amount); parent::refund($payment, $amount);
$order = $payment->getOrder(); $order = $payment->getOrder();
// if amount is a full refund send a refund/cancelled request so if it is not captured yet it will cancel the order /*
* if amount is a full refund send a refund/cancelled request so
* if it is not captured yet it will cancel the order
*/
$grandTotal = $order->getGrandTotal(); $grandTotal = $order->getGrandTotal();
if($grandTotal == $amount) { if ($grandTotal == $amount) {
$this->_paymentRequest->cancelOrRefund($payment); $this->_paymentRequest->cancelOrRefund($payment);
} else { } else {
$this->_paymentRequest->refund($payment, $amount); $this->_paymentRequest->refund($payment, $amount);
......
...@@ -49,22 +49,52 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -49,22 +49,52 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
protected $_infoBlockType = 'Adyen\Payment\Block\Info\Hpp'; protected $_infoBlockType = 'Adyen\Payment\Block\Info\Hpp';
/** /**
* Payment Method feature * Payment Method feature
* *
* @var bool * @var bool
*/ */
protected $_canAuthorize = true; protected $_canAuthorize = true;
/**
* @var bool
*/
protected $_canCapture = true; protected $_canCapture = true;
/**
* @var bool
*/
protected $_canCapturePartial = true; protected $_canCapturePartial = true;
/**
* @var bool
*/
protected $_canCaptureOnce = true; protected $_canCaptureOnce = true;
/**
* @var bool
*/
protected $_canRefund = true; protected $_canRefund = true;
/**
* @var bool
*/
protected $_canRefundInvoicePartial = true; protected $_canRefundInvoicePartial = true;
/**
* @var bool
*/
protected $_isGateway = true; protected $_isGateway = true;
/**
* @var bool
*/
protected $_isInitializeNeeded = true; protected $_isInitializeNeeded = true;
protected $_canUseInternal = false;
/**
* @var bool
*/
protected $_canUseInternal = false;
/** /**
* @var \Adyen\Payment\Model\Api\PaymentRequest * @var \Adyen\Payment\Model\Api\PaymentRequest
...@@ -98,6 +128,8 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -98,6 +128,8 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
protected $_adyenLogger; protected $_adyenLogger;
/** /**
* Hpp constructor.
* @param \Magento\Framework\App\RequestInterface $request
* @param \Adyen\Payment\Model\Api\PaymentRequest $paymentRequest * @param \Adyen\Payment\Model\Api\PaymentRequest $paymentRequest
* @param \Magento\Framework\UrlInterface $urlBuilder * @param \Magento\Framework\UrlInterface $urlBuilder
* @param \Adyen\Payment\Helper\Data $adyenHelper * @param \Adyen\Payment\Helper\Data $adyenHelper
...@@ -114,7 +146,6 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -114,7 +146,6 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
* @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource * @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource
* @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection * @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection
* @param array $data * @param array $data
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/ */
public function __construct( public function __construct(
\Magento\Framework\App\RequestInterface $request, \Magento\Framework\App\RequestInterface $request,
...@@ -156,11 +187,24 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -156,11 +187,24 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
$this->_request = $request; $this->_request = $request;
} }
/**
* @var string
*/
protected $_paymentMethodType = 'hpp'; protected $_paymentMethodType = 'hpp';
public function getPaymentMethodType() {
/**
* @return string
*/
public function getPaymentMethodType()
{
return $this->_paymentMethodType; return $this->_paymentMethodType;
} }
/**
* @param string $paymentAction
* @param object $stateObject
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function initialize($paymentAction, $stateObject) public function initialize($paymentAction, $stateObject)
{ {
/* /*
...@@ -171,9 +215,9 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -171,9 +215,9 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
$order = $payment->getOrder(); $order = $payment->getOrder();
$order->setCanSendNewEmailFlag(false); $order->setCanSendNewEmailFlag(false);
$state = \Magento\Sales\Model\Order::STATE_NEW; $stateObject->setState(\Magento\Sales\Model\Order::STATE_NEW);
$stateObject->setState($state);
$stateObject->setStatus($this->_adyenHelper->getAdyenAbstractConfigData('order_status')); $stateObject->setStatus($this->_adyenHelper->getAdyenAbstractConfigData('order_status'));
$stateObject->setIsNotified(false);
} }
/** /**
...@@ -186,17 +230,23 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -186,17 +230,23 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
public function assignData(\Magento\Framework\DataObject $data) public function assignData(\Magento\Framework\DataObject $data)
{ {
parent::assignData($data); parent::assignData($data);
if (!$data instanceof \Magento\Framework\DataObject) {
$data = new \Magento\Framework\DataObject($data);
}
$additionalData = $data->getAdditionalData();
$infoInstance = $this->getInfoInstance(); $infoInstance = $this->getInfoInstance();
if(isset($data['brand_code'])) { if (isset($additionalData['brand_code'])) {
$infoInstance->setAdditionalInformation('brand_code', $data['brand_code']); $infoInstance->setAdditionalInformation('brand_code', $additionalData['brand_code']);
} }
if(isset($data['issuer_id'])) { if (isset($additionalData['issuer_id'])) {
$infoInstance->setAdditionalInformation('issuer_id', $data['issuer_id']); $infoInstance->setAdditionalInformation('issuer_id', $additionalData['issuer_id']);
} }
$this->_adyenLogger->debug(print_r($data,1)); $this->_adyenLogger->debug(print_r($data, 1));
return $this; return $this;
} }
...@@ -210,7 +260,7 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -210,7 +260,7 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
*/ */
public function getCheckoutRedirectUrl() public function getCheckoutRedirectUrl()
{ {
return $this->_urlBuilder->getUrl('adyen/process/redirect',['_secure' => $this->_getRequest()->isSecure()]); return $this->_urlBuilder->getUrl('adyen/process/redirect', ['_secure' => $this->_getRequest()->isSecure()]);
} }
/** /**
...@@ -223,16 +273,11 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -223,16 +273,11 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
return $this->_request; return $this->_request;
} }
/** /**
* Post request to gateway and return response * Post request to gateway and return response
* *
* @param Object $request * @param DataObject $request
* @param ConfigInterface $config * @param ConfigInterface $config
*
* @return Object
*
* @throws \Exception
*/ */
public function postRequest(DataObject $request, ConfigInterface $config) public function postRequest(DataObject $request, ConfigInterface $config)
{ {
...@@ -271,6 +316,10 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -271,6 +316,10 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
return $url; return $url;
} }
/**
* @return array
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getFormFields() public function getFormFields()
{ {
$paymentInfo = $this->getInfoInstance(); $paymentInfo = $this->getInfoInstance();
...@@ -291,7 +340,6 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -291,7 +340,6 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
$countryCode = trim($this->getConfigData('country_code')); $countryCode = trim($this->getConfigData('country_code'));
$countryCode = (!empty($countryCode)) ? $countryCode : false; $countryCode = (!empty($countryCode)) ? $countryCode : false;
// if directory lookup is enabled use the billingadress as countrycode // if directory lookup is enabled use the billingadress as countrycode
if ($countryCode == false) { if ($countryCode == false) {
if ($order->getBillingAddress() && $order->getBillingAddress()->getCountryId() != "") { if ($order->getBillingAddress() && $order->getBillingAddress()->getCountryId() != "") {
...@@ -299,8 +347,7 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -299,8 +347,7 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
} }
} }
$formFields = array(); $formFields = [];
$formFields['merchantAccount'] = $merchantAccount; $formFields['merchantAccount'] = $merchantAccount;
$formFields['merchantReference'] = $realOrderId; $formFields['merchantReference'] = $realOrderId;
$formFields['paymentAmount'] = (int)$amount; $formFields['paymentAmount'] = (int)$amount;
...@@ -314,60 +361,66 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -314,60 +361,66 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
$formFields['countryCode'] = $countryCode; $formFields['countryCode'] = $countryCode;
$formFields['shopperIP'] = $shopperIP; $formFields['shopperIP'] = $shopperIP;
$formFields['browserInfo'] = $browserInfo; $formFields['browserInfo'] = $browserInfo;
$formFields['sessionValidity'] = date( $formFields['sessionValidity'] = date(
DATE_ATOM, DATE_ATOM,
mktime(date("H") + 1, date("i"), date("s"), date("m"), date("j"), date("Y")) mktime(date("H") + 1, date("i"), date("s"), date("m"), date("j"), date("Y"))
); );
$formFields['shopperEmail'] = $shopperEmail; $formFields['shopperEmail'] = $shopperEmail;
// recurring // recurring
$recurringType = trim($this->_adyenHelper->getAdyenAbstractConfigData('recurring_type')); $recurringType = trim($this->_adyenHelper->getAdyenAbstractConfigData('recurring_type'));
$formFields['recurringContract'] = $recurringType; $formFields['recurringContract'] = $recurringType;
$formFields['shopperReference'] = (!empty($customerId)) ? $customerId : self::GUEST_ID . $realOrderId; $formFields['shopperReference'] = (!empty($customerId)) ? $customerId : self::GUEST_ID . $realOrderId;
//blocked methods //blocked methods
$formFields['blockedMethods'] = ""; $formFields['blockedMethods'] = "";
$baseUrl = $this->storeManager->getStore($this->getStore()) $baseUrl = $this->storeManager->getStore($this->getStore())
->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK); ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK);
$formFields['resURL'] = $baseUrl . 'adyen/process/result';
$hmacKey = $this->_adyenHelper->getHmac(); $formFields['resURL'] = $baseUrl . 'adyen/process/result';
$hmacKey = $this->_adyenHelper->getHmac();
$brandCode = $order->getPayment()->getAdditionalInformation("brand_code"); $brandCode = $order->getPayment()->getAdditionalInformation("brand_code");
if($brandCode) { if ($brandCode) {
$formFields['brandCode'] = $brandCode; $formFields['brandCode'] = $brandCode;
} }
$issuerId = $order->getPayment()->getAdditionalInformation("issuer_id"); $issuerId = $order->getPayment()->getAdditionalInformation("issuer_id");
if($issuerId) { if ($issuerId) {
$formFields['issuerId'] = $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);
// Generate the signing data string // Generate the signing data string
$signData = implode(":",array_map(array($this, 'escapeString'),array_merge(array_keys($formFields), array_values($formFields)))); $signData = implode(":", array_map([$this, 'escapeString'],
array_merge(array_keys($formFields), array_values($formFields))));
$merchantSig = base64_encode(hash_hmac('sha256',$signData,pack("H*" , $hmacKey),true)); $merchantSig = base64_encode(hash_hmac('sha256', $signData, pack("H*", $hmacKey), true));
$formFields['merchantSig'] = $merchantSig; $formFields['merchantSig'] = $merchantSig;
$this->_adyenLogger->debug(print_r($formFields, true)); $this->_adyenLogger->debug(print_r($formFields, true));
return $formFields; return $formFields;
} }
/* /**
* @desc The character escape function is called from the array_map function in _signRequestParams * The character escape function is called from the array_map function in _signRequestParams
* $param $val *
* return string * @param $val
*/ * @return mixed
*/
protected function escapeString($val) protected function escapeString($val)
{ {
return str_replace(':','\\:',str_replace('\\','\\\\',$val)); return str_replace(':', '\\:', str_replace('\\', '\\\\', $val));
} }
public function getPaymentMethodSelectionOnAdyen() { /**
* @return mixed
*/
public function getPaymentMethodSelectionOnAdyen()
{
return $this->getConfigData('payment_selection_on_adyen'); return $this->getConfigData('payment_selection_on_adyen');
} }
...@@ -376,6 +429,8 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -376,6 +429,8 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
* *
* @param \Magento\Payment\Model\InfoInterface $payment * @param \Magento\Payment\Model\InfoInterface $payment
* @param float $amount * @param float $amount
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
*/ */
public function capture(\Magento\Payment\Model\InfoInterface $payment, $amount) public function capture(\Magento\Payment\Model\InfoInterface $payment, $amount)
{ {
...@@ -383,16 +438,14 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -383,16 +438,14 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
$this->_paymentRequest->capture($payment, $amount); $this->_paymentRequest->capture($payment, $amount);
return $this; return $this;
} }
/** /**
* Refund specified amount for payment * Refund specified amount for payment
* *
* @param \Magento\Framework\DataObject|InfoInterface $payment * @param \Magento\Payment\Model\InfoInterface $payment
* @param float $amount * @param float $amount
* @return $this * @return $this
* @throws \Magento\Framework\Exception\LocalizedException * @throws \Magento\Framework\Exception\LocalizedException
* @api
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/ */
public function refund(\Magento\Payment\Model\InfoInterface $payment, $amount) public function refund(\Magento\Payment\Model\InfoInterface $payment, $amount)
{ {
...@@ -402,16 +455,18 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -402,16 +455,18 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
$pspReference = $payment->getAdyenPspReference(); $pspReference = $payment->getAdyenPspReference();
$order = $payment->getOrder(); $order = $payment->getOrder();
// if amount is a full refund send a refund/cancelled request so if it is not captured yet it will cancel the order
/*
* if amount is a full refund send a refund/cancelled request
* so if it is not captured yet it will cancel the order
*/
$grandTotal = $order->getGrandTotal(); $grandTotal = $order->getGrandTotal();
if($grandTotal == $amount) { if ($grandTotal == $amount) {
$this->_paymentRequest->cancelOrRefund($payment); $this->_paymentRequest->cancelOrRefund($payment);
} else { } else {
$this->_paymentRequest->refund($payment, $amount); $this->_paymentRequest->refund($payment, $amount);
} }
return $this; return $this;
} }
} }
\ No newline at end of file
...@@ -43,8 +43,11 @@ class Oneclick extends \Adyen\Payment\Model\Method\Cc ...@@ -43,8 +43,11 @@ class Oneclick extends \Adyen\Payment\Model\Method\Cc
* @var string * @var string
*/ */
protected $_formBlockType = 'Adyen\Payment\Block\Form\Oneclick'; protected $_formBlockType = 'Adyen\Payment\Block\Form\Oneclick';
protected $_infoBlockType = 'Adyen\Payment\Block\Info\Oneclick';
/**
* @var string
*/
protected $_infoBlockType = 'Adyen\Payment\Block\Info\Oneclick';
/** /**
* Payment Method not ready for internal use * Payment Method not ready for internal use
...@@ -63,18 +66,25 @@ class Oneclick extends \Adyen\Payment\Model\Method\Cc ...@@ -63,18 +66,25 @@ class Oneclick extends \Adyen\Payment\Model\Method\Cc
public function assignData(\Magento\Framework\DataObject $data) public function assignData(\Magento\Framework\DataObject $data)
{ {
parent::assignData($data); parent::assignData($data);
if (!$data instanceof \Magento\Framework\DataObject) {
$data = new \Magento\Framework\DataObject($data);
}
$additionalData = $data->getAdditionalData();
$infoInstance = $this->getInfoInstance(); $infoInstance = $this->getInfoInstance();
// get from variant magento code for creditcard type and set this in ccType // get from variant magento code for creditcard type and set this in ccType
$variant = $data['variant']; $variant = $additionalData['variant'];
$ccType = $this->_adyenHelper->getMagentoCreditCartType($variant); $ccType = $this->_adyenHelper->getMagentoCreditCartType($variant);
$infoInstance->setCcType($ccType); $infoInstance->setCcType($ccType);
// save value remember details checkbox // save value remember details checkbox
$infoInstance->setAdditionalInformation('recurring_detail_reference', $data['recurring_detail_reference']); $infoInstance->setAdditionalInformation('recurring_detail_reference',
$additionalData['recurring_detail_reference']);
$recurringPaymentType = $this->_adyenHelper->getAdyenOneclickConfigData('recurring_payment_type'); $recurringPaymentType = $this->_adyenHelper->getAdyenOneclickConfigData('recurring_payment_type');
if($recurringPaymentType == \Adyen\Payment\Model\RecurringType::ONECLICK) { if ($recurringPaymentType == \Adyen\Payment\Model\RecurringType::ONECLICK) {
$customerInteraction = true; $customerInteraction = true;
} else { } else {
$customerInteraction = false; $customerInteraction = false;
...@@ -85,12 +95,16 @@ class Oneclick extends \Adyen\Payment\Model\Method\Cc ...@@ -85,12 +95,16 @@ class Oneclick extends \Adyen\Payment\Model\Method\Cc
return $this; return $this;
} }
/**
* @param \Adyen\Payment\Model\Billing\Agreement $agreement
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function updateBillingAgreementStatus(\Adyen\Payment\Model\Billing\Agreement $agreement) public function updateBillingAgreementStatus(\Adyen\Payment\Model\Billing\Agreement $agreement)
{ {
$targetStatus = $agreement->getStatus(); $targetStatus = $agreement->getStatus();
if($targetStatus == \Magento\Paypal\Model\Billing\Agreement::STATUS_CANCELED) { if ($targetStatus == \Magento\Paypal\Model\Billing\Agreement::STATUS_CANCELED) {
try { try {
$this->_paymentRequest->disableRecurringContract( $this->_paymentRequest->disableRecurringContract(
$agreement->getReferenceId(), $agreement->getReferenceId(),
...@@ -102,5 +116,4 @@ class Oneclick extends \Adyen\Payment\Model\Method\Cc ...@@ -102,5 +116,4 @@ class Oneclick extends \Adyen\Payment\Model\Method\Cc
} }
return $this; return $this;
} }
} }
\ No newline at end of file
...@@ -55,15 +55,46 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -55,15 +55,46 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
* @var bool * @var bool
*/ */
protected $_canAuthorize = true; protected $_canAuthorize = true;
/**
* @var bool
*/
protected $_canCapture = true; protected $_canCapture = true;
/**
* @var bool
*/
protected $_canCapturePartial = true; protected $_canCapturePartial = true;
/**
* @var bool
*/
protected $_canCaptureOnce = true; protected $_canCaptureOnce = true;
/**
* @var bool
*/
protected $_canRefund = true; protected $_canRefund = true;
/**
* @var bool
*/
protected $_canRefundInvoicePartial = true; protected $_canRefundInvoicePartial = true;
/**
* @var bool
*/
protected $_isGateway = true; protected $_isGateway = true;
/**
* @var bool
*/
protected $_isInitializeNeeded = true; protected $_isInitializeNeeded = true;
protected $_canUseInternal = false;
/**
* @var bool
*/
protected $_canUseInternal = false;
/** /**
* @var \Adyen\Payment\Model\Api\PaymentRequest * @var \Adyen\Payment\Model\Api\PaymentRequest
...@@ -75,7 +106,6 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -75,7 +106,6 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
*/ */
protected $_adyenHelper; protected $_adyenHelper;
/** /**
* @var \Magento\Store\Model\StoreManagerInterface * @var \Magento\Store\Model\StoreManagerInterface
*/ */
...@@ -104,6 +134,17 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -104,6 +134,17 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
protected $_currencyFactory; protected $_currencyFactory;
/** /**
* Request object
*
* @var \Magento\Framework\App\RequestInterface
*/
protected $_request;
/**
* Pos constructor.
*
* @param \Magento\Directory\Model\CurrencyFactory $currencyFactory
* @param \Magento\Framework\App\RequestInterface $request
* @param \Adyen\Payment\Model\Api\PaymentRequest $paymentRequest * @param \Adyen\Payment\Model\Api\PaymentRequest $paymentRequest
* @param \Magento\Framework\UrlInterface $urlBuilder * @param \Magento\Framework\UrlInterface $urlBuilder
* @param \Adyen\Payment\Helper\Data $adyenHelper * @param \Adyen\Payment\Helper\Data $adyenHelper
...@@ -120,7 +161,6 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -120,7 +161,6 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
* @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource * @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource
* @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection * @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection
* @param array $data * @param array $data
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/ */
public function __construct( public function __construct(
\Magento\Directory\Model\CurrencyFactory $currencyFactory, \Magento\Directory\Model\CurrencyFactory $currencyFactory,
...@@ -164,11 +204,24 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -164,11 +204,24 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
$this->_currencyFactory = $currencyFactory; $this->_currencyFactory = $currencyFactory;
} }
/**
* @var string
*/
protected $_paymentMethodType = 'hpp'; protected $_paymentMethodType = 'hpp';
public function getPaymentMethodType() {
/**
* @return string
*/
public function getPaymentMethodType()
{
return $this->_paymentMethodType; return $this->_paymentMethodType;
} }
/**
* @param string $paymentAction
* @param object $stateObject
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function initialize($paymentAction, $stateObject) public function initialize($paymentAction, $stateObject)
{ {
/* /*
...@@ -179,9 +232,9 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -179,9 +232,9 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
$order = $payment->getOrder(); $order = $payment->getOrder();
$order->setCanSendNewEmailFlag(false); $order->setCanSendNewEmailFlag(false);
$state = \Magento\Sales\Model\Order::STATE_NEW; $stateObject->setState(\Magento\Sales\Model\Order::STATE_NEW);
$stateObject->setState($state);
$stateObject->setStatus($this->_adyenHelper->getAdyenAbstractConfigData('order_status')); $stateObject->setStatus($this->_adyenHelper->getAdyenAbstractConfigData('order_status'));
$stateObject->setIsNotified(false);
} }
/** /**
...@@ -194,7 +247,6 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -194,7 +247,6 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
public function assignData(\Magento\Framework\DataObject $data) public function assignData(\Magento\Framework\DataObject $data)
{ {
parent::assignData($data); parent::assignData($data);
$infoInstance = $this->getInfoInstance();
return $this; return $this;
} }
...@@ -207,7 +259,7 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -207,7 +259,7 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
*/ */
public function getCheckoutRedirectUrl() public function getCheckoutRedirectUrl()
{ {
return $this->_urlBuilder->getUrl('adyen/process/redirectPos',['_secure' => $this->_getRequest()->isSecure()]); return $this->_urlBuilder->getUrl('adyen/process/redirectPos', ['_secure' => $this->_getRequest()->isSecure()]);
} }
/** /**
...@@ -220,23 +272,21 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -220,23 +272,21 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
return $this->_request; return $this->_request;
} }
/** /**
* Post request to gateway and return response * Post request to gateway and return response
* *
* @param Object $request * @param DataObject $request
* @param ConfigInterface $config * @param ConfigInterface $config
*
* @return Object
*
* @throws \Exception
*/ */
public function postRequest(DataObject $request, ConfigInterface $config) public function postRequest(DataObject $request, ConfigInterface $config)
{ {
// Implement postRequest() method. // Implement postRequest() method.
} }
/**
* @return string
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getLaunchLink() public function getLaunchLink()
{ {
$paymentInfo = $this->getInfoInstance(); $paymentInfo = $this->getInfoInstance();
...@@ -247,7 +297,8 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -247,7 +297,8 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
$amount = $this->_adyenHelper->formatAmount($order->getGrandTotal(), $orderCurrencyCode); $amount = $this->_adyenHelper->formatAmount($order->getGrandTotal(), $orderCurrencyCode);
$shopperEmail = $order->getCustomerEmail(); $shopperEmail = $order->getCustomerEmail();
$customerId = $order->getCustomerId(); $customerId = $order->getCustomerId();
$callbackUrl = $this->_urlBuilder->getUrl('adyen/process/resultpos',['_secure' => $this->_getRequest()->isSecure()]); $callbackUrl = $this->_urlBuilder->getUrl('adyen/process/resultpos',
['_secure' => $this->_getRequest()->isSecure()]);
$addReceiptOrderLines = $this->_adyenHelper->getAdyenPosConfigData("add_receipt_order_lines"); $addReceiptOrderLines = $this->_adyenHelper->getAdyenPosConfigData("add_receipt_order_lines");
$recurringContract = $this->_adyenHelper->getAdyenPosConfigData('recurring_type'); $recurringContract = $this->_adyenHelper->getAdyenPosConfigData('recurring_type');
$currencyCode = $orderCurrencyCode; $currencyCode = $orderCurrencyCode;
...@@ -257,47 +308,54 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -257,47 +308,54 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
$shopperEmail = $shopperEmail; $shopperEmail = $shopperEmail;
$recurringParams = ""; $recurringParams = "";
if($order->getPayment()->getAdditionalInformation("store_cc") != "") { if ($order->getPayment()->getAdditionalInformation("store_cc") != "") {
$recurringParams = "&recurringContract=".urlencode($recurringContract)."&shopperReference=".urlencode($shopperReference). "&shopperEmail=".urlencode($shopperEmail); $recurringParams = "&recurringContract=" . urlencode($recurringContract) . "&shopperReference=" .
urlencode($shopperReference) . "&shopperEmail=" . urlencode($shopperEmail);
} }
$receiptOrderLines = ""; $receiptOrderLines = "";
if($addReceiptOrderLines) { if ($addReceiptOrderLines) {
$orderLines = base64_encode($this->getReceiptOrderLines($order)); $orderLines = base64_encode($this->getReceiptOrderLines($order));
$receiptOrderLines = "&receiptOrderLines=" . urlencode($orderLines); $receiptOrderLines = "&receiptOrderLines=" . urlencode($orderLines);
} }
// extra parameters so that you alway's return these paramters from the application // extra parameters so that you alway's return these paramters from the application
$extra_paramaters = urlencode("/?originalCustomCurrency=".$currencyCode."&originalCustomAmount=".$paymentAmount. "&originalCustomMerchantReference=".$merchantReference . "&originalCustomSessionId=".session_id()); $extraParamaters = urlencode("/?originalCustomCurrency=".$currencyCode."&originalCustomAmount=".
$launchlink = "adyen://payment?sessionId=".session_id()."&amount=".$paymentAmount."&currency=".$currencyCode."&merchantReference=".$merchantReference. $recurringParams . $receiptOrderLines . "&callback=".$callbackUrl . $extra_paramaters; $paymentAmount. "&originalCustomMerchantReference=".
$merchantReference . "&originalCustomSessionId=".session_id());
$launchlink = "adyen://payment?sessionId=".session_id()."&amount=".$paymentAmount.
"&currency=".$currencyCode."&merchantReference=".$merchantReference. $recurringParams .
$receiptOrderLines . "&callback=".$callbackUrl . $extraParamaters;
$this->_adyenLogger->debug(print_r($launchlink, true)); $this->_adyenLogger->debug(print_r($launchlink, true));
return $launchlink; return $launchlink;
} }
private function getReceiptOrderLines($order) { /**
* @param $order
* @return string
*/
private function getReceiptOrderLines(\Magento\Sales\Model\Order $order) {
$myReceiptOrderLines = ""; $myReceiptOrderLines = "";
// temp
$currency = $order->getOrderCurrencyCode(); $currency = $order->getOrderCurrencyCode();
$formattedAmountValue = $this->_currencyFactory->create()->format( $formattedAmountValue = $this->_currencyFactory->create()->format(
$order->getGrandTotal(), $order->getGrandTotal(),
array('display'=>\Magento\Framework\Currency::NO_SYMBOL), ['display'=>\Magento\Framework\Currency::NO_SYMBOL],
false false
); );
$taxAmount = $order->getTaxAmount(); $taxAmount = $order->getTaxAmount();
$formattedTaxAmount = $this->_currencyFactory->create()->format( $formattedTaxAmount = $this->_currencyFactory->create()->format(
$taxAmount, $taxAmount,
array('display'=>\Magento\Framework\Currency::NO_SYMBOL), ['display'=>\Magento\Framework\Currency::NO_SYMBOL],
false false
); );
$paymentAmount = "1000";
$myReceiptOrderLines .= "---||C\n". $myReceiptOrderLines .= "---||C\n".
"====== YOUR ORDER DETAILS ======||CB\n". "====== YOUR ORDER DETAILS ======||CB\n".
"---||C\n". "---||C\n".
...@@ -305,53 +363,57 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -305,53 +363,57 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
foreach ($order->getItemsCollection() as $item) { foreach ($order->getItemsCollection() as $item) {
//skip dummies //skip dummies
if ($item->isDummy()) continue; if ($item->isDummy()) {
continue;
};
$singlePriceFormat = $this->_currencyFactory->create()->format( $singlePriceFormat = $this->_currencyFactory->create()->format(
$item->getPriceInclTax(), $item->getPriceInclTax(),
array('display'=>\Magento\Framework\Currency::NO_SYMBOL), ['display'=>\Magento\Framework\Currency::NO_SYMBOL],
false false
); );
$itemAmount = $item->getPriceInclTax() * (int) $item->getQtyOrdered(); $itemAmount = $item->getPriceInclTax() * (int) $item->getQtyOrdered();
$itemAmountFormat = $this->_currencyFactory->create()->format( $itemAmountFormat = $this->_currencyFactory->create()->format(
$itemAmount, $itemAmount,
array('display'=>\Magento\Framework\Currency::NO_SYMBOL), ['display'=>\Magento\Framework\Currency::NO_SYMBOL],
false false
); );
$myReceiptOrderLines .= " " . (int) $item->getQtyOrdered() . " " . trim(substr($item->getName(),0, 25)) . "| " . $currency . " " . $singlePriceFormat . " " . $currency . " " . $itemAmountFormat . "|\n"; $myReceiptOrderLines .= " " . (int) $item->getQtyOrdered() . " " . trim(substr($item->getName(), 0, 25)) .
"| " . $currency . " " . $singlePriceFormat . " " . $currency . " " . $itemAmountFormat . "|\n";
} }
//discount cost //discount cost
if($order->getDiscountAmount() > 0 || $order->getDiscountAmount() < 0) if ($order->getDiscountAmount() > 0 || $order->getDiscountAmount() < 0) {
{
$discountAmountFormat = $this->_currencyFactory->create()->format( $discountAmountFormat = $this->_currencyFactory->create()->format(
$order->getDiscountAmount(), $order->getDiscountAmount(),
array('display'=>\Magento\Framework\Currency::NO_SYMBOL), ['display'=>\Magento\Framework\Currency::NO_SYMBOL],
false false
); );
$myReceiptOrderLines .= " " . 1 . " " . $this->__('Total Discount') . "| " . $currency . " " . $discountAmountFormat ."|\n"; $myReceiptOrderLines .= " " . 1 . " " . $this->__('Total Discount') . "| " .
$currency . " " . $discountAmountFormat ."|\n";
} }
//shipping cost //shipping cost
if($order->getShippingAmount() > 0 || $order->getShippingTaxAmount() > 0) if ($order->getShippingAmount() > 0 || $order->getShippingTaxAmount() > 0) {
{
$shippingAmountFormat = $this->_currencyFactory->create()->format( $shippingAmountFormat = $this->_currencyFactory->create()->format(
$order->getShippingAmount(), $order->getShippingAmount(),
array('display'=>\Magento\Framework\Currency::NO_SYMBOL), ['display'=>\Magento\Framework\Currency::NO_SYMBOL],
false false
); );
$myReceiptOrderLines .= " " . 1 . " " . $order->getShippingDescription() . "| " . $currency . " " . $shippingAmountFormat ."|\n"; $myReceiptOrderLines .= " " . 1 . " " . $order->getShippingDescription() . "| " .
$currency . " " . $shippingAmountFormat ."|\n";
} }
if($order->getPaymentFeeAmount() > 0) { if ($order->getPaymentFeeAmount() > 0) {
$paymentFeeAmount = $this->_currencyFactory->create()->format( $paymentFeeAmount = $this->_currencyFactory->create()->format(
$order->getPaymentFeeAmount(), $order->getPaymentFeeAmount(),
array('display'=>\Magento\Framework\Currency::NO_SYMBOL), ['display'=>\Magento\Framework\Currency::NO_SYMBOL],
false false
); );
$myReceiptOrderLines .= " " . 1 . " " . $this->__('Payment Fee') . "| " . $currency . " " . $paymentFeeAmount ."|\n"; $myReceiptOrderLines .= " " . 1 . " " . $this->__('Payment Fee') . "| " .
$currency . " " . $paymentFeeAmount ."|\n";
} }
...@@ -360,22 +422,24 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -360,22 +422,24 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
"|Tax: ".$currency." ".$formattedTaxAmount."|B\n". "|Tax: ".$currency." ".$formattedTaxAmount."|B\n".
"||C\n"; "||C\n";
//Cool new header for card details section! Default location is After Header so simply add to Order Details as separator /*
* New header for card details section!
* Default location is After Header so simply add to Order Details as separator
*/
$myReceiptOrderLines .= "---||C\n". $myReceiptOrderLines .= "---||C\n".
"====== YOUR PAYMENT DETAILS ======||CB\n". "====== YOUR PAYMENT DETAILS ======||CB\n".
"---||C\n"; "---||C\n";
return $myReceiptOrderLines; return $myReceiptOrderLines;
} }
/** /**
* Capture on Adyen * Capture on Adyen
* *
* @param \Magento\Payment\Model\InfoInterface $payment * @param \Magento\Payment\Model\InfoInterface $payment
* @param float $amount * @param float $amount
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
*/ */
public function capture(\Magento\Payment\Model\InfoInterface $payment, $amount) public function capture(\Magento\Payment\Model\InfoInterface $payment, $amount)
{ {
...@@ -383,29 +447,28 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -383,29 +447,28 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
$this->_paymentRequest->capture($payment, $amount); $this->_paymentRequest->capture($payment, $amount);
return $this; return $this;
} }
/** /**
* Refund specified amount for payment * Refund specified amount for payment
* *
* @param \Magento\Framework\DataObject|InfoInterface $payment * @param \Magento\Payment\Model\InfoInterface $payment
* @param float $amount * @param float $amount
* @return $this * @return $this
* @throws \Magento\Framework\Exception\LocalizedException * @throws \Magento\Framework\Exception\LocalizedException
* @api
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/ */
public function refund(\Magento\Payment\Model\InfoInterface $payment, $amount) public function refund(\Magento\Payment\Model\InfoInterface $payment, $amount)
{ {
parent::refund($payment, $amount); parent::refund($payment, $amount);
// get pspReference
$pspReference = $payment->getAdyenPspReference();
$order = $payment->getOrder(); $order = $payment->getOrder();
// if amount is a full refund send a refund/cancelled request so if it is not captured yet it will cancel the order
/*
* if amount is a full refund send a refund/cancelled request
* so if it is not captured yet it will cancel the order
*/
$grandTotal = $order->getGrandTotal(); $grandTotal = $order->getGrandTotal();
if($grandTotal == $amount) { if ($grandTotal == $amount) {
$this->_paymentRequest->cancelOrRefund($payment); $this->_paymentRequest->cancelOrRefund($payment);
} else { } else {
$this->_paymentRequest->refund($payment, $amount); $this->_paymentRequest->refund($payment, $amount);
...@@ -413,5 +476,4 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa ...@@ -413,5 +476,4 @@ class Pos extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
return $this; return $this;
} }
} }
\ No newline at end of file
<?php
/**
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Payment module (https://www.adyen.com/)
*
* Copyright (c) 2015 Adyen BV (https://www.adyen.com/)
* See LICENSE.txt for license details.
*
* Author: Adyen <magento@adyen.com>
*/
namespace Adyen\Payment\Model\Method;
/**
* Class Sepa
* @package Adyen\Payment\Model\Method
*/
class Sepa extends \Magento\Payment\Model\Method\AbstractMethod
{
const METHOD_CODE = 'adyen_sepa';
/**
* @var string
*/
protected $_code = self::METHOD_CODE;
/**
* @var \Adyen\Payment\Model\Api\PaymentRequest
*/
protected $_paymentRequest;
/**
* @var \Magento\Framework\UrlInterface
*/
protected $_urlBuilder;
/**
* Request object
*
* @var \Magento\Framework\App\RequestInterface
*/
protected $_request;
/**
* Payment Method feature
*
* @var bool
*/
protected $_canAuthorize = true;
/**
* @var bool
*/
protected $_canCapture = true;
/**
* @var bool
*/
protected $_canCapturePartial = true;
/**
* @var bool
*/
protected $_canCaptureOnce = true;
/**
* @var bool
*/
protected $_canRefund = true;
/**
* @var bool
*/
protected $_canRefundInvoicePartial = true;
/**
* @var bool
*/
protected $_isGateway = true;
/**
* @var bool
*/
protected $_canUseInternal = true;
/**
* Sepa constructor.
* @param \Magento\Framework\App\RequestInterface $request
* @param \Adyen\Payment\Model\Api\PaymentRequest $paymentRequest
* @param \Magento\Framework\UrlInterface $urlBuilder
* @param \Magento\Framework\Model\Context $context
* @param \Magento\Framework\Registry $registry
* @param \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory
* @param \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory
* @param \Magento\Payment\Helper\Data $paymentData
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
* @param \Magento\Payment\Model\Method\Logger $logger
* @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource
* @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection
* @param array $data
*/
public function __construct(
\Magento\Framework\App\RequestInterface $request,
\Adyen\Payment\Model\Api\PaymentRequest $paymentRequest,
\Magento\Framework\UrlInterface $urlBuilder,
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory,
\Magento\Framework\Api\AttributeValueFactory $customAttributeFactory,
\Magento\Payment\Helper\Data $paymentData,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Payment\Model\Method\Logger $logger,
\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
array $data = []
) {
parent::__construct(
$context,
$registry,
$extensionFactory,
$customAttributeFactory,
$paymentData,
$scopeConfig,
$logger,
$resource,
$resourceCollection,
$data
);
$this->_paymentRequest = $paymentRequest;
$this->_urlBuilder = $urlBuilder;
$this->_request = $request;
}
/**
* 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);
if (!$data instanceof \Magento\Framework\DataObject) {
$data = new \Magento\Framework\DataObject($data);
}
$additionalData = $data->getAdditionalData();
$infoInstance = $this->getInfoInstance();
$infoInstance->setAdditionalInformation('account_name', $additionalData['account_name']);
$infoInstance->setAdditionalInformation('iban', $additionalData['iban']);
$infoInstance->setAdditionalInformation('country', $additionalData['country']);
$infoInstance->setAdditionalInformation('accept_sepa', $additionalData['accept_sepa']);
}
/**
* Validate payment method information object
*
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)authorize
*/
public function validate()
{
$infoInstance = $this->getInfoInstance();
$iban = $infoInstance->getAdditionalInformation('iban');
if (empty($iban) || !$this->validateIban($iban)) {
throw new \Magento\Framework\Exception\LocalizedException(__('Invalid Iban number.'));
}
return $this;
}
/**
* Validate IBAN
*
* @param $iban
* @return bool
*/
public function validateIban($iban)
{
$iban = strtolower(str_replace(' ', '', $iban));
$countries = ['al'=>28,'ad'=>24,'at'=>20,'az'=>28,'bh'=>22,'be'=>16,'ba'=>20,'br'=>29,'bg'=>22,'cr'=>21,
'hr'=>21,'cy'=>28,'cz'=>24,'dk'=>18,'do'=>28,'ee'=>20,'fo'=>18,'fi'=>18,'fr'=>27,'ge'=>22,
'de'=>22,'gi'=>23,'gr'=>27,'gl'=>18,'gt'=>28,'hu'=>28,'is'=>26,'ie'=>22,'il'=>23,'it'=>27,
'jo'=>30,'kz'=>20,'kw'=>30,'lv'=>21,'lb'=>28,'li'=>21,'lt'=>20,'lu'=>20,'mk'=>19,'mt'=>31,
'mr'=>27,'mu'=>30,'mc'=>27,'md'=>24, 'me'=>22,'nl'=>18,'no'=>15,'pk'=>24,'ps'=>29,'pl'=>28,
'pt'=>25,'qa'=>29,'ro'=>24, 'sm'=>27,'sa'=>24,'rs'=>22,'sk'=>24,'si'=>19,'es'=>24,'se'=>24,
'ch'=>21,'tn'=>24,'tr'=>26,'ae'=>23,'gb'=>22,'vg'=>24];
$chars = ['a'=>10,'b'=>11,'c'=>12,'d'=>13,'e'=>14,'f'=>15,'g'=>16,'h'=>17,'i'=>18,'j'=>19,'k'=>20,'l'=>21,
'm'=>22,'n'=>23,'o'=>24,'p'=>25,'q'=>26,'r'=>27,'s'=>28,'t'=>29,'u'=>30,'v'=>31,'w'=>32,'x'=>33,
'y'=>34,'z'=>35];
if (isset($countries[substr($iban, 0, 2)]) && strlen($iban) == $countries[substr($iban, 0, 2)]) {
$movedChar = substr($iban, 4).substr($iban, 0, 4);
$movedCharArray = str_split($movedChar);
$newString = "";
foreach ($movedChar AS $key => $value) {
if (!is_numeric($movedCharArray[$key])) {
$movedChar[$key] = $chars[$movedChar[$key]];
}
$newString .= $movedCharArray[$key];
}
if (bcmod($newString, '97') == 1) {
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* @param \Magento\Payment\Model\InfoInterface $payment
* @param float $amount
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function authorize(\Magento\Payment\Model\InfoInterface $payment, $amount)
{
if (!$this->canAuthorize()) {
throw new \Magento\Framework\Exception\LocalizedException(__('The authorize action is not available.'));
}
/*
* do not send order confirmation mail after order creation wait for
* Adyen AUTHORIISATION notification
*/
$order = $payment->getOrder();
$order->setCanSendNewEmailFlag(false);
// do not let magento set status to processing
$payment->setLastTransId($this->getTransactionId())->setIsTransactionPending(true);
// DO authorisation
$this->_processRequest($payment, $amount, "authorise");
return $this;
}
/**
* @param \Magento\Sales\Model\Order\Payment $payment
* @param $amount
* @param $request
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function _processRequest(\Magento\Sales\Model\Order\Payment $payment, $amount, $request)
{
switch ($request) {
case "authorise":
$response = $this->_paymentRequest->fullApiRequest($payment, $this->_code);
break;
}
if (!empty($response)) {
$this->_processResponse($payment, $response);
} else {
throw new \Magento\Framework\Exception\LocalizedException(__('Empty result.'));
}
}
/**
* @param \Magento\Payment\Model\InfoInterface $payment
* @param $response
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function _processResponse(\Magento\Payment\Model\InfoInterface $payment, $response)
{
$payment->setAdditionalInformation('3dActive', false);
switch ($response['resultCode']) {
case "Authorised":
$this->_addStatusHistory($payment, $response['resultCode'], $response['pspReference']);
$payment->setAdditionalInformation('pspReference', $response['pspReference']);
break;
case "Refused":
$errorMsg = __('The payment is REFUSED.');
$this->_logger->critical($errorMsg);
throw new \Magento\Framework\Exception\LocalizedException(__($errorMsg));
break;
}
}
/**
* @param $payment
* @param $responseCode
* @param $pspReference
* @return $this
*/
protected function _addStatusHistory($payment, $responseCode, $pspReference)
{
$type = 'Adyen Result URL response:';
$comment = __('%1 <br /> authResult: %2 <br /> pspReference: %3 <br /> paymentMethod: %4',
$type, $responseCode, $pspReference, "");
$payment->getOrder()->setAdyenResulturlEventCode($responseCode);
$payment->getOrder()->addStatusHistoryComment($comment);
return $this;
}
/**
* Checkout redirect URL getter for onepage checkout (hardcode)
*
* @see \Magento\Checkout\Controller\Onepage::savePaymentAction()
* @see \Magento\Quote\Model\Quote\Payment::getCheckoutRedirectUrl()
* @return string
*/
public function getCheckoutRedirectUrl()
{
return $this->_urlBuilder->getUrl('checkout/onepage/success/',
['_secure' => $this->_getRequest()->isSecure()]);
}
/**
* Retrieve request object
*
* @return \Magento\Framework\App\RequestInterface
*/
protected function _getRequest()
{
return $this->_request;
}
}
\ No newline at end of file
...@@ -50,6 +50,15 @@ class Notification extends \Magento\Framework\Model\AbstractModel ...@@ -50,6 +50,15 @@ class Notification extends \Magento\Framework\Model\AbstractModel
const REPORT_AVAILABLE = "REPORT_AVAILABLE"; const REPORT_AVAILABLE = "REPORT_AVAILABLE";
const ORDER_CLOSED = "ORDER_CLOSED"; const ORDER_CLOSED = "ORDER_CLOSED";
/**
* Notification constructor.
*
* @param \Magento\Framework\Model\Context $context
* @param \Magento\Framework\Registry $registry
* @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource
* @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection
* @param array $data
*/
public function __construct( public function __construct(
\Magento\Framework\Model\Context $context, \Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry, \Magento\Framework\Registry $registry,
...@@ -60,7 +69,6 @@ class Notification extends \Magento\Framework\Model\AbstractModel ...@@ -60,7 +69,6 @@ class Notification extends \Magento\Framework\Model\AbstractModel
parent::__construct($context, $registry, $resource, $resourceCollection, $data); parent::__construct($context, $registry, $resource, $resourceCollection, $data);
} }
/** /**
* Initialize resource model * Initialize resource model
* *
...@@ -73,12 +81,14 @@ class Notification extends \Magento\Framework\Model\AbstractModel ...@@ -73,12 +81,14 @@ class Notification extends \Magento\Framework\Model\AbstractModel
/** /**
* Check if the Adyen Notification is already stored in the system * Check if the Adyen Notification is already stored in the system
*
* @param $pspReference * @param $pspReference
* @param $event * @param $eventCode
* @param $success * @param $success
* @return bool true if the notification is a duplicate * @return bool (true if the notification is a duplicate)
*/ */
public function isDuplicate($pspReference, $eventCode, $success) { public function isDuplicate($pspReference, $eventCode, $success)
{
$result = $this->getResource()->getNotification($pspReference, $eventCode, $success); $result = $this->getResource()->getNotification($pspReference, $eventCode, $success);
return (empty($result)) ? false : true; return (empty($result)) ? false : true;
} }
...@@ -263,17 +273,14 @@ class Notification extends \Magento\Framework\Model\AbstractModel ...@@ -263,17 +273,14 @@ class Notification extends \Magento\Framework\Model\AbstractModel
} }
/** /**
* Sets Reason. * @param $live
*
* @param string $reason
* @return $this * @return $this
*/ */
public function setLive($live) public function setLive($live)
{ {
return $this->setData(self::LIVE, $live); return $this->setData(self::LIVE, $live);
} }
/** /**
* Gets the AdditionalData for the notification. * Gets the AdditionalData for the notification.
* *
...@@ -357,6 +364,4 @@ class Notification extends \Magento\Framework\Model\AbstractModel ...@@ -357,6 +364,4 @@ class Notification extends \Magento\Framework\Model\AbstractModel
{ {
return $this->setData(self::UPDATED_AT, $timestamp); return $this->setData(self::UPDATED_AT, $timestamp);
} }
} }
\ No newline at end of file
...@@ -30,14 +30,19 @@ class RecurringType { ...@@ -30,14 +30,19 @@ class RecurringType {
const ONECLICK_RECURRING = 'ONECLICK,RECURRING'; const ONECLICK_RECURRING = 'ONECLICK,RECURRING';
const RECURRING = 'RECURRING'; const RECURRING = 'RECURRING';
/**
* @var array
*/
protected $_allowedRecurringTypesForListRecurringCall = [ protected $_allowedRecurringTypesForListRecurringCall = [
self::ONECLICK, self::ONECLICK,
self::RECURRING self::RECURRING
]; ];
/**
* @return array
*/
public function getAllowedRecurringTypesForListRecurringCall() public function getAllowedRecurringTypesForListRecurringCall()
{ {
return $this->_allowedRecurringTypesForListRecurringCall; return $this->_allowedRecurringTypesForListRecurringCall;
} }
} }
\ No newline at end of file
...@@ -26,13 +26,17 @@ namespace Adyen\Payment\Model\Resource; ...@@ -26,13 +26,17 @@ namespace Adyen\Payment\Model\Resource;
class Notification extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb class Notification extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{ {
/**
* Construct
*/
public function _construct() public function _construct()
{ {
$this->_init('adyen_notification', 'entity_id'); $this->_init('adyen_notification', 'entity_id');
} }
/** /**
* @desc get Notification for duplicate check * Get Notification for duplicate check
*
* @param $pspReference * @param $pspReference
* @param $eventCode * @param $eventCode
* @param $success * @param $success
...@@ -47,5 +51,4 @@ class Notification extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb ...@@ -47,5 +51,4 @@ class Notification extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
->where('notification.success=?', $success); ->where('notification.success=?', $success);
return $this->getConnection()->fetchAll($select); return $this->getConnection()->fetchAll($select);
} }
} }
\ No newline at end of file
...@@ -25,9 +25,11 @@ namespace Adyen\Payment\Model\Resource\Notification; ...@@ -25,9 +25,11 @@ namespace Adyen\Payment\Model\Resource\Notification;
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{ {
/**
* Construct
*/
public function _construct() public function _construct()
{ {
$this->_init('Adyen\Payment\Model\Notification', 'Adyen\Payment\Model\Resource\Notification'); $this->_init('Adyen\Payment\Model\Notification', 'Adyen\Payment\Model\Resource\Notification');
} }
} }
\ No newline at end of file
...@@ -46,7 +46,8 @@ class InstallSchema implements InstallSchemaInterface ...@@ -46,7 +46,8 @@ class InstallSchema implements InstallSchemaInterface
$table = $installer->getConnection() $table = $installer->getConnection()
->newTable($installer->getTable('adyen_notification')) ->newTable($installer->getTable('adyen_notification'))
->addColumn('entity_id', Table::TYPE_SMALLINT, null,['identity' => true, 'nullable' => false, 'primary' => true],'Entity ID') ->addColumn('entity_id', Table::TYPE_SMALLINT, null, ['identity' => true,
'nullable' => false, 'primary' => true], 'Entity ID')
->addColumn('pspreference', Table::TYPE_TEXT, 255, ['nullable' => true], 'Pspreference') ->addColumn('pspreference', Table::TYPE_TEXT, 255, ['nullable' => true], 'Pspreference')
->addColumn('merchant_reference', Table::TYPE_TEXT, 255, ['nullable' => true], 'Merchant Reference') ->addColumn('merchant_reference', Table::TYPE_TEXT, 255, ['nullable' => true], 'Merchant Reference')
->addColumn('event_code', Table::TYPE_TEXT, 255, ['nullable' => true], 'Event Code') ->addColumn('event_code', Table::TYPE_TEXT, 255, ['nullable' => true], 'Event Code')
...@@ -58,8 +59,10 @@ class InstallSchema implements InstallSchemaInterface ...@@ -58,8 +59,10 @@ class InstallSchema implements InstallSchemaInterface
->addColumn('live', Table::TYPE_TEXT, 255, ['nullable' => true], 'Send from Live platform of adyen?') ->addColumn('live', Table::TYPE_TEXT, 255, ['nullable' => true], 'Send from Live platform of adyen?')
->addColumn('additional_data', Table::TYPE_TEXT, null, ['nullable' => true], 'AdditionalData') ->addColumn('additional_data', Table::TYPE_TEXT, null, ['nullable' => true], 'AdditionalData')
->addColumn('done', Table::TYPE_BOOLEAN, null, ['nullable' => false, 'default' => 0], 'done') ->addColumn('done', Table::TYPE_BOOLEAN, null, ['nullable' => false, 'default' => 0], 'done')
->addColumn('created_at', Table::TYPE_TIMESTAMP, null, ['nullable' => false, 'default' => Table::TIMESTAMP_INIT], 'Created At') ->addColumn('created_at', Table::TYPE_TIMESTAMP, null, ['nullable' => false,
->addColumn('updated_at', Table::TYPE_TIMESTAMP, null, ['nullable' => false, 'default' => Table::TIMESTAMP_INIT_UPDATE],'Updated At') 'default' => Table::TIMESTAMP_INIT], 'Created At')
->addColumn('updated_at', Table::TYPE_TIMESTAMP, null, ['nullable' => false,
'default' => Table::TIMESTAMP_INIT_UPDATE], 'Updated At')
->addIndex($installer->getIdxName('adyen_notification', ['pspreference']), ['pspreference']) ->addIndex($installer->getIdxName('adyen_notification', ['pspreference']), ['pspreference'])
->addIndex($installer->getIdxName('adyen_notification', ['event_code']), ['event_code']) ->addIndex($installer->getIdxName('adyen_notification', ['event_code']), ['event_code'])
->addIndex( ->addIndex(
...@@ -107,7 +110,6 @@ class InstallSchema implements InstallSchemaInterface ...@@ -107,7 +110,6 @@ class InstallSchema implements InstallSchemaInterface
$connection->addColumn($orderTable, $name, $definition); $connection->addColumn($orderTable, $name, $definition);
} }
$installer->endSetup(); $installer->endSetup();
} }
} }
\ No newline at end of file
...@@ -48,12 +48,13 @@ class UpgradeSchema implements UpgradeSchemaInterface ...@@ -48,12 +48,13 @@ class UpgradeSchema implements UpgradeSchemaInterface
$this->updateSchemaVersion1002($setup); $this->updateSchemaVersion1002($setup);
} }
$setup->endSetup(); $setup->endSetup();
} }
/**
public function updateSchemaVersion1001($setup) * @param SchemaSetupInterface $setup
*/
public function updateSchemaVersion1001(SchemaSetupInterface $setup)
{ {
$connection = $setup->getConnection(); $connection = $setup->getConnection();
...@@ -64,7 +65,12 @@ class UpgradeSchema implements UpgradeSchemaInterface ...@@ -64,7 +65,12 @@ class UpgradeSchema implements UpgradeSchemaInterface
'nullable' => true, 'nullable' => true,
'comment' => 'Adyen Notification event code success flag' 'comment' => 'Adyen Notification event code success flag'
]; ];
$connection->addColumn($setup->getTable('sales_order'), 'adyen_notification_event_code_success', $adyenNotificationEventCodeSuccessColumn);
$connection->addColumn(
$setup->getTable('sales_order'),
'adyen_notification_event_code_success',
$adyenNotificationEventCodeSuccessColumn
);
// add column to order_payment to save Adyen PspReference // add column to order_payment to save Adyen PspReference
$pspReferenceColumn = [ $pspReferenceColumn = [
...@@ -76,8 +82,11 @@ class UpgradeSchema implements UpgradeSchemaInterface ...@@ -76,8 +82,11 @@ class UpgradeSchema implements UpgradeSchemaInterface
$connection->addColumn($setup->getTable('sales_order_payment'), 'adyen_psp_reference', $pspReferenceColumn); $connection->addColumn($setup->getTable('sales_order_payment'), 'adyen_psp_reference', $pspReferenceColumn);
} }
public function updateSchemaVersion1002($setup) /**
* @param SchemaSetupInterface $setup
*/
public function updateSchemaVersion1002(SchemaSetupInterface $setup)
{ {
$connection = $setup->getConnection(); $connection = $setup->getConnection();
...@@ -87,7 +96,8 @@ class UpgradeSchema implements UpgradeSchemaInterface ...@@ -87,7 +96,8 @@ class UpgradeSchema implements UpgradeSchemaInterface
'nullable' => true, 'nullable' => true,
'comment' => 'Agreement Data' 'comment' => 'Agreement Data'
]; ];
$connection->addColumn($setup->getTable('paypal_billing_agreement'), 'agreement_data', $adyenAgreementDataColumn); $connection->addColumn(
$setup->getTable('paypal_billing_agreement'), 'agreement_data', $adyenAgreementDataColumn
);
} }
} }
\ No newline at end of file
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
"name": "adyen/module-payment", "name": "adyen/module-payment",
"description": "Official Magento2 Plugin to connect to Payment Service Provider Adyen.", "description": "Official Magento2 Plugin to connect to Payment Service Provider Adyen.",
"type": "magento2-module", "type": "magento2-module",
"version": "1.2.1", "version": "1.3.0",
"license": [ "license": [
"OSL-3.0", "OSL-3.0",
"AFL-3.0" "AFL-3.0"
......
...@@ -40,6 +40,7 @@ ...@@ -40,6 +40,7 @@
<include path="Adyen_Payment::system/adyen_cc.xml"/> <include path="Adyen_Payment::system/adyen_cc.xml"/>
<include path="Adyen_Payment::system/adyen_oneclick.xml"/> <include path="Adyen_Payment::system/adyen_oneclick.xml"/>
<include path="Adyen_Payment::system/adyen_hpp.xml"/> <include path="Adyen_Payment::system/adyen_hpp.xml"/>
<include path="Adyen_Payment::system/adyen_sepa.xml"/>
<include path="Adyen_Payment::system/adyen_pos.xml"/> <include path="Adyen_Payment::system/adyen_pos.xml"/>
</group> </group>
<group id="test" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1"> <group id="test" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1">
......
...@@ -62,6 +62,18 @@ ...@@ -62,6 +62,18 @@
<depends><field id="cse_enabled">1</field></depends> <depends><field id="cse_enabled">1</field></depends>
<config_path>payment/adyen_cc/cse_publickey_live</config_path> <config_path>payment/adyen_cc/cse_publickey_live</config_path>
</field> </field>
<group id="adyen_cc_advanced_settings" translate="label" showInDefault="1" showInWebsite="1" sortOrder="150">
<label>Advanced Settings</label>
<frontend_model>Magento\Config\Block\System\Config\Form\Fieldset</frontend_model>
<field id="enable_moto" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Enable MOTO</label>
<tooltip><![CDATA[Important you have to activate MOTO for your account contact magento@adyen.com.]]></tooltip>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<config_path>payment/adyen_cc/enable_moto</config_path>
</field>
</group>
<group id="adyen_cc_country_specific" translate="label" showInDefault="1" showInWebsite="1" sortOrder="200"> <group id="adyen_cc_country_specific" translate="label" showInDefault="1" showInWebsite="1" sortOrder="200">
<label>Country Specific Settings</label> <label>Country Specific Settings</label>
<frontend_model>Magento\Config\Block\System\Config\Form\Fieldset</frontend_model> <frontend_model>Magento\Config\Block\System\Config\Form\Fieldset</frontend_model>
......
<?xml version="1.0"?>
<!--
/**
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Payment module (https://www.adyen.com/)
*
* Copyright (c) 2015 Adyen BV (https://www.adyen.com/)
* See LICENSE.txt for license details.
*
* Author: Adyen <magento@adyen.com>
*/
-->
<include xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_include.xsd">
<group id="adyen_sepa" translate="label" type="text" sortOrder="250" showInDefault="1" showInWebsite="1" showInStore="1">
<label><![CDATA[SEPA integration]]></label>
<frontend_model>Magento\Paypal\Block\Adminhtml\System\Config\Fieldset\Payment</frontend_model>
<fieldset_css>adyen-method-adyen-cc</fieldset_css>
<comment>Process SEPA transactions</comment>
<field id="active" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Enabled</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
<config_path>payment/adyen_sepa/active</config_path>
</field>
<field id="title" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Title</label>
<config_path>payment/adyen_sepa/title</config_path>
</field>
<field id="sort_order" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="0">
<label>Sort Order</label>
<frontend_class>validate-number</frontend_class>
<config_path>payment/adyen_sepa/sort_order</config_path>
</field>
<group id="adyen_sepa_country_specific" translate="label" showInDefault="1" showInWebsite="1" sortOrder="210">
<label>Country Specific Settings</label>
<frontend_model>Magento\Config\Block\System\Config\Form\Fieldset</frontend_model>
<field id="allowspecific" translate="label" type="allowspecific" sortOrder="40" showInDefault="1" showInWebsite="1" showInStore="0">
<label>Payment from Applicable Countries</label>
<source_model>Magento\Payment\Model\Config\Source\Allspecificcountries</source_model>
<config_path>payment/adyen_sepa/allowspecific</config_path>
</field>
<field id="specificcountry" translate="label" type="multiselect" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="0">
<label>Payment from Specific Countries</label>
<source_model>Magento\Directory\Model\Config\Source\Country</source_model>
<can_be_empty>1</can_be_empty>
<config_path>payment/adyen_sepa/specificcountry</config_path>
</field>
</group>
</group>
</include>
\ No newline at end of file
...@@ -45,6 +45,7 @@ ...@@ -45,6 +45,7 @@
<cctypes>AE,VI,MC,DI</cctypes> <cctypes>AE,VI,MC,DI</cctypes>
<useccv>1</useccv> <useccv>1</useccv>
<cse_enabled>1</cse_enabled> <cse_enabled>1</cse_enabled>
<enable_moto>0</enable_moto>
<payment_action>authorize</payment_action> <payment_action>authorize</payment_action>
<group>adyen</group> <group>adyen</group>
</adyen_cc> </adyen_cc>
...@@ -64,24 +65,35 @@ ...@@ -64,24 +65,35 @@
<model>Adyen\Payment\Model\Method\Hpp</model> <model>Adyen\Payment\Model\Method\Hpp</model>
<order_status>pending</order_status> <order_status>pending</order_status>
<title>Adyen HPP</title> <title>Adyen HPP</title>
<payment_selection_on_adyen>1</payment_selection_on_adyen> <payment_selection_on_adyen>0</payment_selection_on_adyen>
<payment_routine>single</payment_routine> <payment_routine>single</payment_routine>
<delivery_days>5</delivery_days> <delivery_days>5</delivery_days>
<allowspecific>0</allowspecific> <allowspecific>0</allowspecific>
<sort_order>3</sort_order> <sort_order>3</sort_order>
<place_order_url>adyen/process/redirect</place_order_url> <place_order_url>adyen/process/redirect</place_order_url>
<order_place_redirect_url>adyen/process/redirect</order_place_redirect_url> <order_place_redirect_url>adyen/process/redirect</order_place_redirect_url>
<payment_action>order</payment_action>
<group>adyen</group> <group>adyen</group>
</adyen_hpp> </adyen_hpp>
<adyen_sepa>
<active>0</active>
<model>Adyen\Payment\Model\Method\Sepa</model>
<title>Sepa Direct Debit</title>
<allowspecific>0</allowspecific>
<sort_order>4</sort_order>
<payment_action>authorize</payment_action>
<group>adyen</group>
</adyen_sepa>
<adyen_pos> <adyen_pos>
<active>0</active> <active>0</active>
<model>Adyen\Payment\Model\Method\Pos</model> <model>Adyen\Payment\Model\Method\Pos</model>
<order_status>pending</order_status> <order_status>pending</order_status>
<title>Adyen POS</title> <title>Adyen POS</title>
<allowspecific>0</allowspecific> <allowspecific>0</allowspecific>
<sort_order>4</sort_order> <sort_order>5</sort_order>
<place_order_url>adyen/process/redirect</place_order_url> <place_order_url>adyen/process/redirect</place_order_url>
<order_place_redirect_url>adyen/process/redirect</order_place_redirect_url> <order_place_redirect_url>adyen/process/redirect</order_place_redirect_url>
<payment_action>order</payment_action>
<group>adyen</group> <group>adyen</group>
</adyen_pos> </adyen_pos>
</payment> </payment>
......
...@@ -31,6 +31,7 @@ ...@@ -31,6 +31,7 @@
<item name="adyen_cc_config_provider" xsi:type="object">Adyen\Payment\Model\AdyenCcConfigProvider</item> <item name="adyen_cc_config_provider" xsi:type="object">Adyen\Payment\Model\AdyenCcConfigProvider</item>
<item name="adyen_oneclick_config_provider" xsi:type="object">Adyen\Payment\Model\AdyenOneclickConfigProvider</item> <item name="adyen_oneclick_config_provider" xsi:type="object">Adyen\Payment\Model\AdyenOneclickConfigProvider</item>
<item name="adyen_hpp_config_provider" xsi:type="object">Adyen\Payment\Model\AdyenHppConfigProvider</item> <item name="adyen_hpp_config_provider" xsi:type="object">Adyen\Payment\Model\AdyenHppConfigProvider</item>
<item name="adyen_sepa_config_provider" xsi:type="object">Adyen\Payment\Model\AdyenSepaConfigProvider</item>
</argument> </argument>
</arguments> </arguments>
</type> </type>
......
...@@ -24,7 +24,7 @@ ...@@ -24,7 +24,7 @@
--> -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Adyen_Payment" setup_version="1.2.1"> <module name="Adyen_Payment" setup_version="1.3.0">
<sequence> <sequence>
<module name="Magento_Sales"/> <module name="Magento_Sales"/>
<module name="Magento_Quote"/> <module name="Magento_Quote"/>
......
...@@ -36,9 +36,6 @@ ...@@ -36,9 +36,6 @@
<method name="adyen_hpp"> <method name="adyen_hpp">
<allow_multiple_address>1</allow_multiple_address> <allow_multiple_address>1</allow_multiple_address>
</method> </method>
<method name="test">
<allow_multiple_address>1</allow_multiple_address>
</method>
</methods> </methods>
</payment> </payment>
......
...@@ -55,6 +55,9 @@ ...@@ -55,6 +55,9 @@
<item name="adyen_hpp" xsi:type="array"> <item name="adyen_hpp" xsi:type="array">
<item name="isBillingAddressRequired" xsi:type="boolean">true</item> <item name="isBillingAddressRequired" xsi:type="boolean">true</item>
</item> </item>
<item name="adyen_sepa" xsi:type="array">
<item name="isBillingAddressRequired" xsi:type="boolean">true</item>
</item>
</item> </item>
</item> </item>
</item> </item>
......
...@@ -53,6 +53,9 @@ ...@@ -53,6 +53,9 @@
background-position: 0 -1819px; background-position: 0 -1819px;
} }
.checkout-payment-method .payment-method-title label div.adyen-sprite.adyen_sepa {
background-position: 0 -1910px;
}
......
...@@ -44,6 +44,10 @@ define( ...@@ -44,6 +44,10 @@ define(
type: 'adyen_hpp', type: 'adyen_hpp',
component: 'Adyen_Payment/js/view/payment/method-renderer/adyen-hpp-method' component: 'Adyen_Payment/js/view/payment/method-renderer/adyen-hpp-method'
}, },
{
type: 'adyen_sepa',
component: 'Adyen_Payment/js/view/payment/method-renderer/adyen-sepa-method'
},
{ {
type: 'adyen_pos', type: 'adyen_pos',
component: 'Adyen_Payment/js/view/payment/method-renderer/adyen-pos-method' component: 'Adyen_Payment/js/view/payment/method-renderer/adyen-pos-method'
......
...@@ -34,11 +34,6 @@ define( ...@@ -34,11 +34,6 @@ define(
function (_, $, Component, placeOrderAction, $t, additionalValidators, adyenEncrypt) { function (_, $, Component, placeOrderAction, $t, additionalValidators, adyenEncrypt) {
'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',
...@@ -64,8 +59,6 @@ define( ...@@ -64,8 +59,6 @@ define(
]); ]);
return this; return this;
}, },
placeOrderHandler: null,
validateHandler: null,
setPlaceOrderHandler: function(handler) { setPlaceOrderHandler: function(handler) {
this.placeOrderHandler = handler; this.placeOrderHandler = handler;
}, },
......
...@@ -29,9 +29,10 @@ define( ...@@ -29,9 +29,10 @@ define(
'Adyen_Payment/js/action/set-payment-method', 'Adyen_Payment/js/action/set-payment-method',
'Magento_Checkout/js/action/select-payment-method', 'Magento_Checkout/js/action/select-payment-method',
'Magento_Checkout/js/model/quote', 'Magento_Checkout/js/model/quote',
'Magento_Checkout/js/checkout-data' 'Magento_Checkout/js/checkout-data',
'Magento_Checkout/js/model/payment/additional-validators'
], ],
function (ko, $, Component, setPaymentMethodAction, selectPaymentMethodAction,quote, checkoutData) { function (ko, $, Component, setPaymentMethodAction, selectPaymentMethodAction, quote, checkoutData, additionalValidators) {
'use strict'; 'use strict';
var brandCode = ko.observable(null); var brandCode = ko.observable(null);
var paymentMethod = ko.observable(null); var paymentMethod = ko.observable(null);
...@@ -64,6 +65,9 @@ define( ...@@ -64,6 +65,9 @@ define(
'issuerId': ko.observable(null), 'issuerId': ko.observable(null),
getCode: function() { getCode: function() {
return self.item.method; return self.item.method;
},
validate: function () {
return self.validate();
} }
} }
} else { } else {
...@@ -73,6 +77,9 @@ define( ...@@ -73,6 +77,9 @@ define(
'method': self.item.method, 'method': self.item.method,
getCode: function() { getCode: function() {
return self.item.method; return self.item.method;
},
validate: function () {
return self.validate();
} }
} }
} }
...@@ -82,37 +89,43 @@ define( ...@@ -82,37 +89,43 @@ define(
}, },
/** Redirect to adyen */ /** Redirect to adyen */
continueToAdyen: function () { continueToAdyen: function () {
//update payment method information if additional data was changed if (this.validate() && additionalValidators.validate()) {
this.selectPaymentMethod(); //update payment method information if additional data was changed
setPaymentMethodAction(); this.selectPaymentMethod();
return false; setPaymentMethodAction();
return false;
}
}, },
continueToAdyenBrandCode: function() { continueToAdyenBrandCode: function() {
// set payment method to adyen_hpp // set payment method to adyen_hpp
var self = this; var self = this;
// for ideal add brand_code in request if (this.validate() && additionalValidators.validate()) {
if(brandCode() == "ideal") {
var data = { // for ideal add brand_code in request
"method": self.method, if(brandCode() == "ideal") {
"po_number": null, var data = {
"additional_data": { "method": self.method,
issuer_id: this.issuerId(), "po_number": null,
brand_code: self.value "additional_data": {
} issuer_id: this.issuerId(),
}; brand_code: self.value
} else { }
var data = { };
"method": self.method, } else {
"po_number": null, var data = {
"additional_data": { "method": self.method,
brand_code: self.value "po_number": null,
} "additional_data": {
}; brand_code: self.value
}
};
}
selectPaymentMethodAction(data);
setPaymentMethodAction();
} }
selectPaymentMethodAction(data);
setPaymentMethodAction();
return false; return false;
}, },
selectPaymentMethodBrandCode: function() { selectPaymentMethodBrandCode: function() {
...@@ -151,6 +164,9 @@ define( ...@@ -151,6 +164,9 @@ define(
}), }),
isPaymentMethodSelectionOnAdyen: function() { isPaymentMethodSelectionOnAdyen: function() {
return window.checkoutConfig.payment.adyenHpp.isPaymentMethodSelectionOnAdyen; return window.checkoutConfig.payment.adyenHpp.isPaymentMethodSelectionOnAdyen;
},
validate: function () {
return true;
} }
}); });
} }
......
...@@ -25,9 +25,10 @@ define( ...@@ -25,9 +25,10 @@ define(
[ [
'ko', 'ko',
'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/model/payment/additional-validators'
], ],
function (ko, Component, setPaymentMethodAction) { function (ko, Component, setPaymentMethodAction, additionalValidators) {
'use strict'; 'use strict';
var brandCode = ko.observable(null); var brandCode = ko.observable(null);
var paymentMethod = ko.observable(null); var paymentMethod = ko.observable(null);
...@@ -46,13 +47,18 @@ define( ...@@ -46,13 +47,18 @@ define(
}, },
/** Redirect to adyen */ /** Redirect to adyen */
continueToAdyen: function () { continueToAdyen: function () {
//update payment method information if additional data was changed if (this.validate() && additionalValidators.validate()) {
this.selectPaymentMethod(); //update payment method information if additional data was changed
setPaymentMethodAction(); this.selectPaymentMethod();
return false; setPaymentMethodAction();
return false;
}
}, },
showLogo: function() { showLogo: function() {
return window.checkoutConfig.payment.adyen.showLogo; return window.checkoutConfig.payment.adyen.showLogo;
},
validate: function () {
return true;
} }
}); });
} }
......
/**
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Payment module (https://www.adyen.com/)
*
* Copyright (c) 2015 Adyen BV (https://www.adyen.com/)
* See LICENSE.txt for license details.
*
* Author: Adyen <magento@adyen.com>
*/
/*browser:true*/
/*global define*/
define(
[
'underscore',
'jquery',
'Magento_Payment/js/view/payment/cc-form',
'Adyen_Payment/js/action/place-order',
'mage/translate',
'Magento_Checkout/js/model/payment/additional-validators'
],
function (_, $, Component, placeOrderAction, $t, additionalValidators) {
'use strict';
return Component.extend({
self: this,
defaults: {
template: 'Adyen_Payment/payment/sepa-form'
},
initObservable: function () {
this._super()
.observe([
'accountName',
'iban',
'country',
'setAcceptSepa'
]);
return this;
},
setPlaceOrderHandler: function(handler) {
this.placeOrderHandler = handler;
},
setValidateHandler: function(handler) {
this.validateHandler = handler;
},
getCode: function() {
return 'adyen_sepa';
},
getData: function() {
return {
'method': this.item.method,
'additional_data': {
'account_name': this.accountName(),
'iban': this.iban(),
'country': this.country(),
'accept_sepa': this.setAcceptSepa()
}
};
},
isActive: function() {
return true;
},
/**
* @override
*/
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);
$.when(placeOrder).fail(function(response) {
self.isPlaceOrderActionAllowed(true);
});
return true;
}
return false;
},
getControllerName: function() {
return window.checkoutConfig.payment.iframe.controllerName[this.getCode()];
},
getPlaceOrderUrl: function() {
return window.checkoutConfig.payment.iframe.placeOrderUrl[this.getCode()];
},
context: function() {
return this;
},
validate: function () {
var form = 'form[data-role=adyen-sepa-form]';
var validate = $(form).validation() && $(form).validation('isValid');
if(!validate) {
return false;
}
return true;
},
showLogo: function() {
return window.checkoutConfig.payment.adyen.showLogo;
},
getCountries: function() {
return _.map(window.checkoutConfig.payment.adyenSepa.countries, function(value, key) {
return {
'key': key,
'value': value
}
});
}
});
}
);
...@@ -233,28 +233,28 @@ ...@@ -233,28 +233,28 @@
<!-- /ko --> <!-- /ko -->
</fieldset> </fieldset>
</form>
<div class="checkout-agreements-block"> <div class="checkout-agreements-block">
<!-- ko foreach: $parent.getRegion('before-place-order') --> <!-- ko foreach: $parent.getRegion('before-place-order') -->
<!-- ko template: getTemplate() --><!-- /ko --> <!-- ko template: getTemplate() --><!-- /ko -->
<!--/ko--> <!--/ko-->
</div> </div>
<div class="actions-toolbar"> <div class="actions-toolbar">
<div class="primary"> <div class="primary">
<button class="action primary checkout" <button class="action primary checkout"
type="submit" type="submit"
data-bind=" data-bind="
click: placeOrder, click: placeOrder,
attr: {title: $t('Place Order')}, attr: {title: $t('Place Order')},
enable: (getCode() == isChecked()), enable: (getCode() == isChecked()),
css: {disabled: !isPlaceOrderActionAllowed()} css: {disabled: !isPlaceOrderActionAllowed()}
" "
disabled> disabled>
<span data-bind="text: $t('Place Order')"></span> <span data-bind="text: $t('Place Order')"></span>
</button> </button>
</div>
</div> </div>
</form> </div>
</div> </div>
</div> </div>
<!--
/**
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Payment module (https://www.adyen.com/)
*
* Copyright (c) 2015 Adyen BV (https://www.adyen.com/)
* See LICENSE.txt for license details.
*
* Author: Adyen <magento@adyen.com>
*/
-->
<div class="payment-method" data-bind="css: {'_active': (getCode() == isChecked())}">
<div class="payment-method-title field choice">
<input type="radio"
name="payment[method]"
class="radio"
data-bind="attr: {'id': getCode()}, value: getCode(), checked: isChecked, click: selectPaymentMethod, visible: isRadioButtonVisible()"/>
<label data-bind="attr: {'for': getCode()}" class="label">
<!-- ko if: showLogo() -->
<div data-bind="attr: { 'class': 'adyen-sprite ' + getCode() }"></div>
<!--/ko-->
<span data-bind="text: getTitle()"></span>
</label>
</div>
<div class="payment-method-content">
<div class="payment-method-billing-address">
<!-- ko foreach: $parent.getRegion(getBillingAddressFormName()) -->
<!-- ko template: getTemplate() --><!-- /ko -->
<!--/ko-->
</div>
<form class="form" id="adyen-sepa-form" data-role="adyen-sepa-form" action="#" method="post" data-bind="mageInit: {
'transparent':{
'context': context(),
'controller': getControllerName(),
'orderSaveUrl':getPlaceOrderUrl(),
}, 'validation':[]}">
<fieldset data-bind="attr: {class: 'fieldset payment items adyen_sepa ' + getCode(), id: 'payment_form_' + getCode()}">
<!-- ko if: (isShowLegend())-->
<legend class="legend">
<span><!-- ko text: $t('Sepa Information')--><!-- /ko --></span>
</legend><br />
<!-- /ko -->
<div class="field accountname type required">
<label data-bind="attr: {for: getCode() + '_account_name'}" class="label">
<span><!-- ko text: $t('Bank account holder name')--><!-- /ko --></span>
</label>
<div class="control">
<input type="text"
class="input-text"
name="payment[account_name]"
autocomplete="off"
data-bind="attr: {id: getCode() + '_account_name', 'data-container': getCode() + '-account-name', 'data-validate': JSON.stringify({required:true})},
enable: isActive($parents),
value: accountName"
data-validate="{required:true}">
</input>
</div>
</div>
<div class="field iban type required">
<label data-bind="attr: {for: getCode() + '_iban'}" class="label">
<span><!-- ko text: $t('IBAN')--><!-- /ko --></span>
</label>
<div class="control">
<input type="text"
class="input-text"
name="payment[iban]"
autocomplete="off"
data-bind="attr: {id: getCode() + '_iban', 'data-container': getCode() + '-iban', 'data-validate': JSON.stringify({required:true})},
enable: isActive($parents),
value: iban"
data-validate="{required:true}">
</input>
</div>
</div>
<div class="field country type required">
<label data-bind="attr: {for: getCode() + '_country'}" class="label">
<span><!-- ko text: $t('Country')--><!-- /ko --></span>
</label>
<div class="control">
<select class="select select-country"
name="payment[country]"
data-bind="attr: {id: getCode() + '_country', 'data-container': getCode() + '-country', 'data-validate': JSON.stringify({required:true})},
enable: isActive($parents),
options: getCountries(),
optionsValue: 'key',
optionsText: 'value',
optionsCaption: $t('Select your country'),
value: country"
data-validate="{required:true}">
</select>
</div>
</div>
<div class="field choice required">
<input type="checkbox"
name="payment[accept_sepa]"
autocomplete="off"
class="checkbox"
data-bind="attr: {id: getCode() + '_accept_sepa', title: $t('I agree that the above amount will be debited from my bank account.')}, checked: setAcceptSepa"
data-validate="{required:true}"
/>
<label data-bind="attr: {for: getCode() + '_accept_sepa'}" class="label">
<span><!-- ko text: $t('I agree that the above amount will be debited from my bank account.')--><!-- /ko --></span>
</label>
</div>
</fieldset>
</form>
<div class="checkout-agreements-block">
<!-- ko foreach: $parent.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: placeOrder,
attr: {title: $t('Place Order')},
enable: (getCode() == isChecked()),
css: {disabled: !isPlaceOrderActionAllowed()}
"
disabled>
<span data-bind="text: $t('Place Order')"></span>
</button>
</div>
</div>
</div>
</div>
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