We will be off from 27/1 (Monday) to 31/1 (Friday) (GMT +7) for our Tet Holiday (Lunar New Year) in our country

Commit ae2b85a9 authored by rikterbeek's avatar rikterbeek

#37 optimizing the code to match code standards

parent b582fae7
......@@ -30,6 +30,8 @@ class Version extends \Magento\Config\Block\System\Config\Form\Field
{
/**
* Contains list of modules
*
* @var \Magento\Framework\Module\ModuleListInterface
*/
protected $_moduleList;
......@@ -44,13 +46,14 @@ class Version extends \Magento\Config\Block\System\Config\Form\Field
\Magento\Framework\Module\ModuleListInterface $moduleList,
\Magento\Backend\Block\Template\Context $context,
array $data = []
)
{
) {
parent::__construct($context, $data);
$this->_moduleList = $moduleList;
}
/**
* Retrieve the setup version of the extension
*
* @param \Magento\Framework\Data\Form\Element\AbstractElement $element
* @return string
*/
......
......@@ -53,8 +53,12 @@ class Cc extends \Magento\Payment\Block\Form\Cc
protected $_checkoutSession;
/**
* Cc constructor.
*
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Payment\Model\Config $paymentConfig
* @param \Adyen\Payment\Helper\Data $adyenHelper
* @param \Magento\Checkout\Model\Session $checkoutSession
* @param array $data
*/
public function __construct(
......
......@@ -36,6 +36,8 @@ class AbstractInfo extends \Magento\Payment\Block\Info
/**
* Constructor
*
* AbstractInfo constructor.
* @param \Adyen\Payment\Helper\Data $adyenHelper
* @param Template\Context $context
* @param array $data
*/
......@@ -49,12 +51,19 @@ class AbstractInfo extends \Magento\Payment\Block\Info
$this->_adyenHelper = $adyenHelper;
}
/**
* @return mixed
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getAdyenPspReference()
{
return $this->getInfo()->getAdyenPspReference();
}
/**
* @return mixed
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function isDemoMode()
{
$storeId = $this->getInfo()->getOrder()->getStoreId();
......
......@@ -30,6 +30,11 @@ class Hpp extends AbstractInfo
*/
protected $_template = 'Adyen_Payment::info/adyen_hpp.phtml';
/**
* Check if Payment method selection is configured on Adyen or Magento
*
* @return mixed
*/
public function isPaymentSelectionOnAdyen()
{
return $this->_adyenHelper->getAdyenHppConfigDataFlag('payment_selection_on_adyen');
......
......@@ -40,6 +40,8 @@ class Pos extends \Magento\Payment\Block\Form
protected $_order;
/**
* Pos constructor.
*
* @param \Magento\Framework\View\Element\Template\Context $context
* @param array $data
* @param \Magento\Sales\Model\OrderFactory $orderFactory
......@@ -50,20 +52,24 @@ class Pos extends \Magento\Payment\Block\Form
array $data = [],
\Magento\Sales\Model\OrderFactory $orderFactory,
\Magento\Checkout\Model\Session $checkoutSession
)
{
) {
$this->_orderFactory = $orderFactory;
$this->_checkoutSession = $checkoutSession;
parent::__construct($context, $data);
$this->_getOrder();
}
/**
* @return $this
*/
public function _prepareLayout()
{
return parent::_prepareLayout();
}
/**
* @return string
*/
public function getLaunchLink()
{
$result = "";
......
......@@ -40,6 +40,8 @@ class Redirect extends \Magento\Payment\Block\Form
protected $_order;
/**
* Redirect constructor.
*
* @param \Magento\Framework\View\Element\Template\Context $context
* @param array $data
* @param \Magento\Sales\Model\OrderFactory $orderFactory
......@@ -50,8 +52,7 @@ class Redirect extends \Magento\Payment\Block\Form
array $data = [],
\Magento\Sales\Model\OrderFactory $orderFactory,
\Magento\Checkout\Model\Session $checkoutSession
)
{
) {
$this->_orderFactory = $orderFactory;
$this->_checkoutSession = $checkoutSession;
parent::__construct($context, $data);
......@@ -59,11 +60,17 @@ class Redirect extends \Magento\Payment\Block\Form
}
/**
* @return $this
*/
public function _prepareLayout()
{
return parent::_prepareLayout();
}
/**
* @return string
*/
public function getFormUrl()
{
$result = "";
......@@ -81,6 +88,9 @@ class Redirect extends \Magento\Payment\Block\Form
return $result;
}
/**
* @return array
*/
public function getFormFields()
{
$result = array();
......
......@@ -26,7 +26,11 @@ namespace Adyen\Payment\Block\Redirect;
class Validate3d extends \Magento\Payment\Block\Form
{
/**
* @var \Magento\Sales\Model\OrderFactory
*/
protected $_orderFactory;
/**
* @var \Magento\Checkout\Model\Session
*/
......@@ -38,6 +42,8 @@ class Validate3d extends \Magento\Payment\Block\Form
protected $_order;
/**
* Validate3d constructor.
*
* @param \Magento\Framework\View\Element\Template\Context $context
* @param array $data
* @param \Magento\Sales\Model\OrderFactory $orderFactory
......@@ -48,15 +54,13 @@ class Validate3d extends \Magento\Payment\Block\Form
array $data = [],
\Magento\Sales\Model\OrderFactory $orderFactory,
\Magento\Checkout\Model\Session $checkoutSession
)
{
) {
$this->_orderFactory = $orderFactory;
$this->_checkoutSession = $checkoutSession;
parent::__construct($context, $data);
$this->_getOrder();
}
/**
* Get order object
*
......@@ -81,21 +85,33 @@ class Validate3d extends \Magento\Payment\Block\Form
return $this->_checkoutSession;
}
/**
* @return mixed
*/
public function getIssuerUrl()
{
return $this->_order->getPayment()->getAdditionalInformation('issuerUrl');
}
/**
* @return mixed
*/
public function getPaReq()
{
return $this->_order->getPayment()->getAdditionalInformation('paRequest');
}
/**
* @return mixed
*/
public function getMd()
{
return $this->_order->getPayment()->getAdditionalInformation('md');
}
/**
* @return string
*/
public function getTermUrl()
{
return $this->getUrl('adyen/process/validate3d');
......
......@@ -36,7 +36,10 @@ class Cron extends \Magento\Framework\App\Action\Action
* @var \Magento\Framework\Controller\Result\RawFactory
*/
protected $_resultFactory;
/**
* Cron constructor.
*
* @param \Magento\Framework\App\Action\Context $context
*/
public function __construct(
......@@ -46,8 +49,9 @@ class Cron extends \Magento\Framework\App\Action\Action
$this->_objectManager = $context->getObjectManager();
$this->_resultFactory = $context->getResultFactory();
}
/**
* @throws \Magento\Framework\Exception\LocalizedException
* Process Notification from Cron
*/
public function execute()
{
......
......@@ -52,6 +52,8 @@ class Json extends \Magento\Framework\App\Action\Action
protected $_adyenLogger;
/**
* Json constructor.
*
* @param \Magento\Framework\App\Action\Context $context
* @param \Adyen\Payment\Helper\Data $adyenHelper
* @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger
......@@ -77,16 +79,19 @@ class Json extends \Magento\Framework\App\Action\Action
$notificationItems = json_decode(file_get_contents('php://input'), true);
// 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'] : "";
if($notificationMode != "" && $this->_validateNotificationMode($notificationMode))
{
foreach($notificationItems['notificationItems'] as $notificationItem)
{
$status = $this->_processNotification($notificationItem['NotificationRequestItem'], $notificationMode);
if($status != true) {
if ($notificationMode != "" && $this->_validateNotificationMode($notificationMode)) {
foreach ($notificationItems['notificationItems'] as $notificationItem) {
$status = $this->_processNotification(
$notificationItem['NotificationRequestItem'], $notificationMode
);
if ($status != true) {
$this->_return401();
return;
}
......@@ -99,13 +104,14 @@ class Json extends \Magento\Framework\App\Action\Action
->setHeader('Content-Type', 'text/html')
->setBody("[accepted]");
return;
} else
{
if($notificationMode == "") {
} else {
if ($notificationMode == "") {
$this->_return401();
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) {
throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage()));
......@@ -119,13 +125,15 @@ class Json extends \Magento\Framework\App\Action\Action
protected function _validateNotificationMode($notificationMode)
{
$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 false;
}
/**
* @desc save notification into the database for cronjob to execute notification
* save notification into the database for cronjob to execute notification
*
* @param $response
* @param $notificationMode
* @return bool
......@@ -137,7 +145,7 @@ class Json extends \Magento\Framework\App\Action\Action
if ($this->authorised($response)) {
// check if notificaiton already exists
if(!$this->_isDuplicate($response)) {
if (!$this->_isDuplicate($response)) {
try {
$notification = $this->_objectManager->create('Adyen\Payment\Model\Notification');
......@@ -192,10 +200,11 @@ class Json extends \Magento\Framework\App\Action\Action
return false;
}
/**
* @desc HTTP Authentication of the notification
* HTTP Authentication of the notification
*
* @param $response
* @return bool
*/
protected function authorised($response)
{
......@@ -209,16 +218,20 @@ class Json extends \Magento\Framework\App\Action\Action
$submitedMerchantAccount = $response['merchantAccountCode'];
if (empty($submitedMerchantAccount) && empty($internalMerchantAccount)) {
if(strtolower(substr($response['pspReference'],0,17)) == "testnotification_" || strtolower(substr($response['pspReference'],0,5)) == "test_") {
echo 'merchantAccountCode is empty in magento settings'; exit();
if (strtolower(substr($response['pspReference'], 0, 17)) == "testnotification_" ||
strtolower(substr($response['pspReference'], 0, 5)) == "test_") {
echo 'merchantAccountCode is empty in magento settings';
exit();
}
return false;
}
// validate username and password
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_") {
echo 'Authentication failed: PHP_AUTH_USER and PHP_AUTH_PW are empty. See Adyen Magento manual CGI mode'; exit();
if (strtolower(substr($response['pspReference'], 0, 17)) == "testnotification_" ||
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;
}
......@@ -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(strtolower(substr($response['pspReference'],0,17)) == "testnotification_" || strtolower(substr($response['pspReference'],0,5)) == "test_") {
if($accountCmp != 0) {
echo 'MerchantAccount in notification is not the same as in Magento settings'; 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();
if (strtolower(substr($response['pspReference'], 0, 17)) == "testnotification_" ||
strtolower(substr($response['pspReference'], 0, 5)) == "test_") {
if ($accountCmp != 0) {
echo 'MerchantAccount in notification is not the same as in Magento settings';
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;
}
/**
* $desc if notification is already saved ignore it
* If notification is already saved ignore it
*
* @param $response
* @return bool
* @return mixed
*/
protected function _isDuplicate($response)
{
......@@ -264,24 +279,29 @@ class Json extends \Magento\Framework\App\Action\Action
/**
* Fix these global variables for the CGI
*/
protected function _fixCgiHttpAuthentication() { // unsupported is $_SERVER['REMOTE_AUTHORIZATION']: as stated in manual :p
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']));
} elseif(!empty($_SERVER['HTTP_AUTHORIZATION'])){ //pcd note: standard in magento?
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
} elseif (!empty($_SERVER['REMOTE_USER'])) { //pcd note: when cgi and .htaccess modrewrite patch is executed
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode(substr($_SERVER['REMOTE_USER'], 6)));
} elseif (!empty($_SERVER['REDIRECT_REMOTE_USER'])) { //pcd note: no idea who sets this
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode(substr($_SERVER['REDIRECT_REMOTE_USER'], 6)));
protected function _fixCgiHttpAuthentication()
{
if (isset($_SERVER['REDIRECT_REMOTE_AUTHORIZATION']) &&
$_SERVER['REDIRECT_REMOTE_AUTHORIZATION'] != '') {
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
explode(':', base64_decode($_SERVER['REDIRECT_REMOTE_AUTHORIZATION']));
} elseif (!empty($_SERVER['HTTP_AUTHORIZATION'])) {
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) =
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()
{
$this->getResponse()->setHttpResponseCode(401);
}
}
\ No newline at end of file
......@@ -36,7 +36,6 @@ class Redirect extends \Magento\Framework\App\Action\Action
*/
protected $_checkoutSession;
/**
* @var \Magento\Sales\Model\Order
*/
......@@ -47,7 +46,6 @@ class Redirect extends \Magento\Framework\App\Action\Action
*/
protected $_orderFactory;
/**
* @param \Magento\Framework\App\Action\Context $context
*/
......@@ -57,7 +55,6 @@ class Redirect extends \Magento\Framework\App\Action\Action
parent::__construct($context);
}
/**
* Return checkout session object
*
......@@ -68,6 +65,9 @@ class Redirect extends \Magento\Framework\App\Action\Action
return $this->_checkoutSession;
}
/**
* Set redirect
*/
public function execute()
{
$this->_view->loadLayout();
......@@ -98,14 +98,19 @@ class Redirect extends \Magento\Framework\App\Action\Action
return $this->_objectManager->get('Magento\Checkout\Model\Session');
}
/**
* @return mixed
*/
protected function _getQuote()
{
return $this->_objectManager->get('Magento\Quote\Model\Quote');
}
/**
* @return mixed
*/
protected function _getQuoteManagement()
{
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
*/
protected $_orderFactory;
/**
* @param \Magento\Framework\App\Action\Context $context
*/
......@@ -57,7 +56,6 @@ class RedirectPos extends \Magento\Framework\App\Action\Action
parent::__construct($context);
}
/**
* Return checkout session object
*
......@@ -98,14 +96,19 @@ class RedirectPos extends \Magento\Framework\App\Action\Action
return $this->_objectManager->get('Magento\Checkout\Model\Session');
}
/**
* @return mixed
*/
protected function _getQuote()
{
return $this->_objectManager->get('Magento\Quote\Model\Quote');
}
/**
* @return mixed
*/
protected function _getQuoteManagement()
{
return $this->_objectManager->get('\Magento\Quote\Model\QuoteManagement');
}
}
\ No newline at end of file
......@@ -23,8 +23,7 @@
namespace Adyen\Payment\Controller\Process;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;
use \Adyen\Payment\Model\Notification;
class Result extends \Magento\Framework\App\Action\Action
{
......@@ -59,6 +58,8 @@ class Result extends \Magento\Framework\App\Action\Action
protected $_adyenLogger;
/**
* Result constructor.
*
* @param \Magento\Framework\App\Action\Context $context
* @param \Adyen\Payment\Helper\Data $adyenHelper
* @param \Magento\Sales\Model\OrderFactory $orderFactory
......@@ -82,12 +83,15 @@ class Result extends \Magento\Framework\App\Action\Action
parent::__construct($context);
}
/**
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function execute()
{
$response = $this->getRequest()->getParams();
$this->_adyenLogger->addAdyenResult(print_r($response, true));
if($response) {
if ($response) {
$result = $this->validateResponse($response);
if ($result) {
......@@ -104,6 +108,9 @@ class Result extends \Magento\Framework\App\Action\Action
}
}
/**
* @param $response
*/
protected function _cancel($response)
{
$session = $this->_session;
......@@ -115,24 +122,32 @@ class Result extends \Magento\Framework\App\Action\Action
$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'));
} else {
$this->messageManager->addError(__('Your payment failed, Please try again later'));
}
}
/**
* @param $response
* @return bool
* @throws \Magento\Framework\Exception\LocalizedException
*/
protected function validateResponse($response)
{
$result = true;
$this->_adyenLogger->addAdyenResult('Processing ResultUrl');
$storeId = null;
if (empty($response)) {
$this->_adyenLogger->addAdyenResult('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'));
$this->_adyenLogger->addAdyenResult(
'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
......@@ -143,7 +158,7 @@ class Result extends \Magento\Framework\App\Action\Action
$incrementId = $response['merchantReference'];
if($incrementId) {
if ($incrementId) {
$order = $this->_getOrder($incrementId);
if ($order->getId()) {
......@@ -155,9 +170,6 @@ class Result extends \Magento\Framework\App\Action\Action
return $response['handled_response'];
}
// set StoreId for retrieving debug log setting
$storeId = $order->getStoreId();
// update the order
$result = $this->_validateUpdateOrder($order, $response);
......@@ -167,17 +179,22 @@ class Result extends \Magento\Framework\App\Action\Action
]);
} 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 {
throw new \Magento\Framework\Exception\LocalizedException(__('Empty merchantReference'));
throw new \Magento\Framework\Exception\LocalizedException(
__('Empty merchantReference')
);
}
return $result;
}
/**
* @param $order
* @param $params
* @param $response
* @return bool
*/
protected function _validateUpdateOrder($order, $response)
{
......@@ -190,7 +207,9 @@ class Result extends \Magento\Framework\App\Action\Action
$pspReference = isset($response['pspReference']) ? trim($response['pspReference']) : '';
$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()
//->setStatus($status)
......@@ -201,28 +220,26 @@ class Result extends \Magento\Framework\App\Action\Action
$history->save();
// needed becuase then we need to save $order objects
// needed because then we need to save $order objects
$order->setAdyenResulturlEventCode($authResult);
switch ($authResult) {
case \Adyen\Payment\Model\Notification::AUTHORISED:
case \Adyen\Payment\Model\Notification::PENDING:
case Notification::AUTHORISED:
case Notification::PENDING:
// do nothing wait for the notification
$result = true;
$this->_adyenLogger->addAdyenResult('Do nothing wait for the notification');
break;
case \Adyen\Payment\Model\Notification::CANCELLED:
case Notification::CANCELLED:
$this->_adyenLogger->addAdyenResult('Cancel or Hold the order');
$result = false;
break;
case \Adyen\Payment\Model\Notification::REFUSED:
case Notification::REFUSED:
// if refused there will be a AUTHORIZATION : FALSE notification send only exception is idea
$this->_adyenLogger->addAdyenResult('Cancel or Hold the order');
$result = false;
break;
case \Adyen\Payment\Model\Notification::ERROR:
case Notification::ERROR:
//attempt to hold/cancel
$this->_adyenLogger->addAdyenResult('Cancel or Hold the order');
$result = false;
......@@ -236,11 +253,11 @@ class Result extends \Magento\Framework\App\Action\Action
return $result;
}
/**
* @desc Authenticate using sha1 Merchant signature
* @see success Action during checkout
* @param Varien_Object $response
* Authenticate using sha1 Merchant signature
*
* @param $response
* @return bool
*/
protected function _authenticate($response) {
......@@ -254,10 +271,10 @@ class Result extends \Magento\Framework\App\Action\Action
ksort($response, SORT_STRING);
// Generate the signing data string
$signData = implode(":",array_map(array($this, 'escapeString'),array_merge(array_keys($response), array_values($response))));
$merchantSig = base64_encode(hash_hmac('sha256',$signData,pack("H*" , $hmacKey),true));
$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));
if (strcmp($merchantSig, $merchantSigNotification) === 0) {
return true;
......@@ -265,16 +282,23 @@ class Result extends \Magento\Framework\App\Action\Action
return false;
}
/*
* @desc The character escape function is called from the array_map function in _signRequestParams
* $param $val
* return string
/**
* The character escape function is called from the array_map function in _signRequestParams
*
* @param $val
* @return mixed
*/
protected function escapeString($val)
{
return str_replace(':','\\:',str_replace('\\','\\\\',$val));
}
/**
* Get order based on increment_id
*
* @param $incrementId
* @return \Magento\Sales\Model\Order
*/
protected function _getOrder($incrementId)
{
if (!$this->_order) {
......@@ -282,5 +306,4 @@ class Result extends \Magento\Framework\App\Action\Action
}
return $this->_order;
}
}
\ No newline at end of file
......@@ -57,6 +57,8 @@ class ResultPos extends \Magento\Framework\App\Action\Action
protected $_adyenLogger;
/**
* ResultPos constructor.
*
* @param \Magento\Framework\App\Action\Context $context
* @param \Adyen\Payment\Helper\Data $adyenHelper
* @param \Magento\Sales\Model\OrderFactory $orderFactory
......@@ -80,6 +82,9 @@ class ResultPos extends \Magento\Framework\App\Action\Action
parent::__construct($context);
}
/**
* Return result
*/
public function execute()
{
$response = $this->getRequest()->getParams();
......@@ -97,23 +102,27 @@ class ResultPos extends \Magento\Framework\App\Action\Action
}
}
/**
* @param $response
* @return bool
*/
private function _validateResponse($response)
{
$result = false;
if($response != null && $response['result'] != "" && $this->_validateChecksum($response)) {
if ($response != null && $response['result'] != "" && $this->_validateChecksum($response)) {
$incrementId = $response['merchantReference'];
$responseResult = $response['result'];
if($incrementId) {
if ($incrementId) {
$order = $this->_getOrder($incrementId);
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');
......@@ -163,6 +172,12 @@ class ResultPos extends \Magento\Framework\App\Action\Action
return $result;
}
/**
* Validate checksum from result parameters
*
* @param $response
* @return bool
*/
protected function _validateChecksum($response)
{
$checksum = $response['cs'];
......@@ -171,51 +186,46 @@ class ResultPos extends \Magento\Framework\App\Action\Action
$currency = $response['originalCustomCurrency'];
$sessionId = $response['sessionId'];
// for android sessionis is with low i
if($sessionId == "") {
if ($sessionId == "") {
$sessionId = $response['sessionid'];
}
// calculate amount checksum
$amount_checksum = 0;
$amountChecksum = 0;
$amountLength = strlen($amount);
for($i=0;$i<$amountLength;$i++)
{
for ($i=0; $i<$amountLength; $i++) {
// ASCII value use ord
$checksumCalc = ord($amount[$i]) - 48;
$amount_checksum += $checksumCalc;
$amountChecksum += $checksumCalc;
}
$currency_checksum = 0;
$currencyChecksum = 0;
$currencyLength = strlen($currency);
for($i=0;$i<$currencyLength;$i++)
{
for ($i=0; $i<$currencyLength; $i++) {
$checksumCalc = ord($currency[$i]) - 64;
$currency_checksum += $checksumCalc;
$currencyChecksum += $checksumCalc;
}
$result_checksum = 0;
$resultChecksum = 0;
$resultLength = strlen($result);
for($i=0;$i<$resultLength;$i++)
{
for ($i=0; $i<$resultLength; $i++) {
$checksumCalc = ord($result[$i]) - 64;
$result_checksum += $checksumCalc;
$resultChecksum += $checksumCalc;
}
$sessionId_checksum = 0;
$sessionIdChecksum = 0;
$sessionIdLength = strlen($sessionId);
for($i=0;$i<$sessionIdLength;$i++)
{
for ($i=0; $i<$sessionIdLength; $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
if($total_result_checksum == $checksum) {
if ($totalResultChecksum == $checksum) {
$this->_adyenLogger->addAdyenResult('Checksum is valid');
return true;
}
......@@ -223,9 +233,13 @@ class ResultPos extends \Magento\Framework\App\Action\Action
return false;
}
/**
* @param $ascii
* @return int
*/
protected function _getAscii2Int($ascii)
{
if (is_numeric($ascii)){
if (is_numeric($ascii)) {
$int = ord($ascii) - 48;
} else {
$int = ord($ascii) - 64;
......@@ -233,6 +247,10 @@ class ResultPos extends \Magento\Framework\App\Action\Action
return $int;
}
/**
* @param $incrementId
* @return \Magento\Sales\Model\Order
*/
protected function _getOrder($incrementId)
{
if (!$this->_order) {
......@@ -241,6 +259,9 @@ class ResultPos extends \Magento\Framework\App\Action\Action
return $this->_order;
}
/**
* @param $response
*/
protected function _cancel($response)
{
$session = $this->_session;
......@@ -250,15 +271,15 @@ class ResultPos extends \Magento\Framework\App\Action\Action
$order = $this->_order;
if($order) {
if ($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'));
} else {
$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
protected $_adyenHelper;
/**
* Validate3d constructor.
*
* @param \Magento\Framework\App\Action\Context $context
* @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger
* @param \Adyen\Payment\Helper\Data $adyenHelper
......@@ -60,6 +62,9 @@ class Validate3d extends \Magento\Framework\App\Action\Action
$this->_adyenHelper = $adyenHelper;
}
/**
* Validate 3D secure payment
*/
public function execute()
{
$active = null;
......@@ -67,19 +72,18 @@ class Validate3d extends \Magento\Framework\App\Action\Action
// check if 3d is active
$order = $this->_getOrder();
if($order->getPayment()) {
if ($order->getPayment()) {
$active = $order->getPayment()->getAdditionalInformation('3dActive');
}
// check if 3D secure is active. If not just go to success page
if($active) {
if ($active) {
$this->_adyenLogger->addAdyenResult("3D secure is active");
// check if it is already processed
if ($this->getRequest()->isPost()) {
$this->_adyenLogger->addAdyenResult("Process 3D secure payment");
$requestMD = $this->getRequest()->getPost('MD');
$requestPaRes = $this->getRequest()->getPost('PaRes');
$md = $order->getPayment()->getAdditionalInformation('md');
......@@ -98,15 +102,16 @@ class Validate3d extends \Magento\Framework\App\Action\Action
if ($result == 'Authorised') {
$order->addStatusHistoryComment(__('3D-secure validation was successful'))->save();
$this->_redirect('checkout/onepage/success');
}
else {
} else {
$order->addStatusHistoryComment(__('3D-secure validation was unsuccessful.'))->save();
$this->_adyenHelper->cancelOrder($order);
}
}
} else {
$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->getLayout()->initMessages();
......
......@@ -36,39 +36,34 @@ class Data extends AbstractHelper
*/
protected $_encryptor;
/**
* @var \Magento\Payment\Model\Config
*/
protected $_config;
/**
* @var \Magento\Framework\Config\DataInterface
*/
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(
\Magento\Framework\App\Helper\Context $context,
\Magento\Framework\Encryption\EncryptorInterface $encryptor,
\Magento\Payment\Model\Config $config,
\Magento\Framework\Config\DataInterface $dataStorage
)
{
) {
parent::__construct($context);
$this->_encryptor = $encryptor;
$this->_config = $config;
$this->_dataStorage = $dataStorage;
}
/**
* @desc return recurring types for configuration setting
* @return array
*/
public function getRecurringTypes() {
public function getRecurringTypes()
{
return [
\Adyen\Payment\Model\RecurringType::ONECLICK => 'ONECLICK',
\Adyen\Payment\Model\RecurringType::ONECLICK_RECURRING => 'ONECLICK,RECURRING',
......@@ -80,7 +75,8 @@ class Data extends AbstractHelper
* @desc return recurring types for configuration setting
* @return array
*/
public function getModes() {
public function getModes()
{
return [
'1' => 'Test Mode',
'0' => 'Production Mode'
......@@ -157,6 +153,11 @@ class Data extends AbstractHelper
return number_format($amount, $format, '', '');
}
/**
* @param $amount
* @param $currency
* @return float
*/
public function originalAmount($amount, $currency)
{
// check the format
......@@ -206,14 +207,15 @@ class Data extends AbstractHelper
*/
public function getStreet($address)
{
if (empty($address)) return false;
if (empty($address)) {
return false;
}
$street = self::formatStreet($address->getStreet());
$streetName = $street['0'];
unset($street['0']);
// $streetNr = implode('',$street);
$streetNr = implode(' ',$street);
return (array('name' => $streetName, 'house_number' => $streetNr));
$streetNr = implode(' ', $street);
return (['name' => $streetName, 'house_number' => $streetNr]);
}
/**
......@@ -228,11 +230,11 @@ class Data extends AbstractHelper
return $street;
}
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']);
$position = $houseNumber['0']['1'];
$streeName = trim(substr($street['0'], 0, $position));
$street = array($streeName,$_houseNumber);
$streetName = trim(substr($street['0'], 0, $position));
$street = [$streetName, $_houseNumber];
}
return $street;
}
......@@ -389,7 +391,7 @@ class Data extends AbstractHelper
*/
public function getWsUsername()
{
if($this->isDemoMode()) {
if ($this->isDemoMode()) {
$wsUsername = trim($this->getAdyenAbstractConfigData('ws_username_test'));
} else {
$wsUsername = trim($this->getAdyenAbstractConfigData('ws_username_live'));
......@@ -403,7 +405,7 @@ class Data extends AbstractHelper
*/
public function getWsPassword()
{
if($this->isDemoMode()) {
if ($this->isDemoMode()) {
$wsPassword = $this->_encryptor->decrypt(trim($this->getAdyenAbstractConfigData('ws_password_test')));
} else {
$wsPassword = $this->_encryptor->decrypt(trim($this->getAdyenAbstractConfigData('ws_password_live')));
......@@ -417,7 +419,7 @@ class Data extends AbstractHelper
*/
public function getWsUrl()
{
if($this->isDemoMode()) {
if ($this->isDemoMode()) {
$url = $this->getAdyenAbstractConfigData('ws_url_test');
} else {
$url = $this->getAdyenAbstractConfigData('ws_url_live');
......@@ -441,7 +443,7 @@ class Data extends AbstractHelper
}
break;
default:
if($order->canCancel()) {
if ($order->canCancel()) {
$order->cancel()->save();
}
break;
......@@ -456,20 +458,22 @@ class Data extends AbstractHelper
*/
public function getMagentoCreditCartType($ccType)
{
$ccTypesMapper = $this->getCcTypesAltData();
if(isset($ccTypesMapper[$ccType])) {
if (isset($ccTypesMapper[$ccType])) {
$ccType = $ccTypesMapper[$ccType]['code'];
}
return $ccType;
}
/**
* @return array
*/
public function getCcTypesAltData()
{
$adyenCcTypes = $this->getAdyenCcTypes();
$types = array();
$types = [];
foreach ($adyenCcTypes as $key => $data) {
$types[$data['code_alt']] = $data;
$types[$data['code_alt']]['code'] = $key;
......@@ -477,6 +481,9 @@ class Data extends AbstractHelper
return $types;
}
/**
* @return mixed
*/
public function getAdyenCcTypes()
{
return $this->_dataStorage->get('adyen_credit_cards');
......@@ -499,6 +506,5 @@ class Data extends AbstractHelper
} else {
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
*
* @var array $levels Logging levels
*/
protected static $levels = array(
protected static $levels = [
100 => 'DEBUG',
101 => 'ADYEN_DEBUG',
200 => 'INFO',
......@@ -55,7 +55,7 @@ class AdyenLogger extends Logger
500 => 'CRITICAL',
550 => 'ALERT',
600 => 'EMERGENCY',
);
];
/**
* Adds a log record at the INFO level.
......@@ -86,7 +86,6 @@ class AdyenLogger extends Logger
return $this->addRecord(static::ADYEN_NOTIFICATION_CRONJOB, $message, $context);
}
/**
* Adds a log record.
*
......
......@@ -29,32 +29,22 @@ use Magento\Payment\Helper\Data as PaymentHelper;
class AdyenCcConfigProvider extends CcGenericConfigProvider
{
/**
* @var Config
*/
protected $config;
/**
* @var string[]
*/
protected $methodCodes = [
protected $_methodCodes = [
\Adyen\Payment\Model\Method\Cc::METHOD_CODE
];
/**
* @var \Magento\Payment\Model\Method\AbstractMethod[]
*/
protected $methods = [];
/**
* @var PaymentHelper
*/
protected $paymentHelper;
protected $_paymentHelper;
/**
* @var \Adyen\Payment\Helper\Data
*/
protected $adyenHelper;
protected $_adyenHelper;
/**
* @var AdyenGenericConfig
......@@ -62,9 +52,12 @@ class AdyenCcConfigProvider extends CcGenericConfigProvider
protected $_genericConfig;
/**
* AdyenCcConfigProvider constructor.
*
* @param \Magento\Payment\Model\CcConfig $ccConfig
* @param PaymentHelper $paymentHelper
* @param \Adyen\Payment\Helper\Data $adyenHelper
* @param AdyenGenericConfig $genericConfig
*/
public function __construct(
\Magento\Payment\Model\CcConfig $ccConfig,
......@@ -72,32 +65,35 @@ class AdyenCcConfigProvider extends CcGenericConfigProvider
\Adyen\Payment\Helper\Data $adyenHelper,
\Adyen\Payment\Model\AdyenGenericConfig $genericConfig
) {
parent::__construct($ccConfig, $paymentHelper, $this->methodCodes);
$this->adyenHelper = $adyenHelper;
parent::__construct($ccConfig, $paymentHelper, $this->_methodCodes);
$this->_paymentHelper = $paymentHelper;
$this->_adyenHelper = $adyenHelper;
$this->_genericConfig = $genericConfig;
}
/**
* @return array
*/
public function getConfig()
{
$config = parent::getConfig();
$demoMode = $this->adyenHelper->getAdyenAbstractConfigDataFlag('demo_mode');
$demoMode = $this->_adyenHelper->getAdyenAbstractConfigDataFlag('demo_mode');
if($demoMode) {
$cseKey = $this->adyenHelper->getAdyenCcConfigData('cse_publickey_test');
if ($demoMode) {
$cseKey = $this->_adyenHelper->getAdyenCcConfigData('cse_publickey_test');
} 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;
if($recurringType == "ONECLICK" || $recurringType == "ONECLICK,RECURRING") {
if ($recurringType == "ONECLICK" || $recurringType == "ONECLICK,RECURRING") {
$canCreateBillingAgreement = true;
}
$config['payment'] ['adyenCc']['cseKey'] = $cseKey;
$config['payment'] ['adyenCc']['cseEnabled'] = $cseEnabled;
$config['payment'] ['adyenCc']['cseEnabled'] = $cseEnabled;
......@@ -105,20 +101,21 @@ class AdyenCcConfigProvider extends CcGenericConfigProvider
$config['payment']['adyenCc']['canCreateBillingAgreement'] = $canCreateBillingAgreement;
// show logos turned on by default
if($this->_genericConfig->showLogos()) {
if ($this->_genericConfig->showLogos()) {
$config['payment']['adyenCc']['creditCardPaymentMethodIcon'] = $this->_getCreditCardPaymentMethodIcon();
}
return $config;
}
/**
* @return array|null
*/
protected function _getCreditCardPaymentMethodIcon()
{
$asset = $this->_genericConfig->createAsset('Adyen_Payment::images/logos/img_trans.gif');
$placeholder = $this->_genericConfig->findRelativeSourceFilePath($asset);
$icon = null;
if ($placeholder) {
list($width, $height) = getimagesize($asset->getSourceFile());
$icon = [
......@@ -127,7 +124,6 @@ class AdyenCcConfigProvider extends CcGenericConfigProvider
'height' => $height
];
}
return $icon;
}
}
\ No newline at end of file
......@@ -34,17 +34,17 @@ class AdyenGenericConfig
/**
* @var Repository
*/
protected $assetRepo;
protected $_assetRepo;
/**
* @var RequestInterface
*/
protected $request;
protected $_request;
/**
* @var \Magento\Framework\View\Asset\Source
*/
protected $assetSource;
protected $_assetSource;
/**
* @var \Adyen\Payment\Helper\Data
......@@ -52,11 +52,12 @@ class AdyenGenericConfig
protected $_adyenHelper;
/**
* @param PaymentConfig $paymentConfig
* AdyenGenericConfig constructor.
*
* @param Repository $assetRepo
* @param RequestInterface $request
* @param UrlInterface $urlBuilder
* @param LoggerInterface $logger
* @param Source $assetSource
* @param \Adyen\Payment\Helper\Data $adyenHelper
*/
public function __construct(
Repository $assetRepo,
......@@ -64,9 +65,9 @@ class AdyenGenericConfig
Source $assetSource,
\Adyen\Payment\Helper\Data $adyenHelper
) {
$this->assetRepo = $assetRepo;
$this->request = $request;
$this->assetSource = $assetSource;
$this->_assetRepo = $assetRepo;
$this->_request = $request;
$this->_assetSource = $assetSource;
$this->_adyenHelper = $adyenHelper;
}
......@@ -79,21 +80,28 @@ class AdyenGenericConfig
*/
public function createAsset($fileId, array $params = [])
{
$params = array_merge(['_secure' => $this->request->isSecure()], $params);
return $this->assetRepo->createAsset($fileId, $params);
$params = array_merge(['_secure' => $this->_request->isSecure()], $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()
{
$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 false;
}
}
\ No newline at end of file
......@@ -27,25 +27,26 @@ use Magento\Payment\Helper\Data as PaymentHelper;
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[]
*/
protected $methodCodes = [
protected $_methodCodes = [
\Adyen\Payment\Model\Method\Cc::METHOD_CODE,
\Adyen\Payment\Model\Method\Hpp::METHOD_CODE,
\Adyen\Payment\Model\Method\Oneclick::METHOD_CODE,
......@@ -54,43 +55,23 @@ class AdyenGenericConfigProvider implements ConfigProviderInterface
];
/**
* @param \Magento\Framework\Model\Context $context
* @param \Magento\Checkout\Model\Session $session
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* AdyenGenericConfigProvider constructor.
*
* @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
*/
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Checkout\Model\Session $session,
\Magento\Store\Model\StoreManagerInterface $storeManager,
PaymentHelper $paymentHelper,
\Magento\Framework\Locale\ResolverInterface $localeResolver,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Adyen\Payment\Helper\Data $adyenHelper,
\Adyen\Payment\Logger\AdyenLogger $adyenLogger,
\Adyen\Payment\Model\AdyenGenericConfig $genericConfig
) {
$this->_appState = $context->getAppState();
$this->_session = $session;
$this->_storeManager = $storeManager;
$this->_paymentHelper = $paymentHelper;
$this->_localeResolver = $localeResolver;
$this->_config = $config;
$this->_adyenHelper = $adyenHelper;
$this->_adyenLogger = $adyenLogger;
$this->_genericConfig = $genericConfig;
foreach ($this->methodCodes as $code) {
$this->methods[$code] = $this->_paymentHelper->getMethodInstance($code);
foreach ($this->_methodCodes as $code) {
$this->_methods[$code] = $this->_paymentHelper->getMethodInstance($code);
}
}
/**
* Define foreach payment methods the RedirectUrl
*
......@@ -102,8 +83,8 @@ class AdyenGenericConfigProvider implements ConfigProviderInterface
'payment' => []
];
foreach ($this->methodCodes as $code) {
if ($this->methods[$code]->isAvailable()) {
foreach ($this->_methodCodes as $code) {
if ($this->_methods[$code]->isAvailable()) {
$config['payment'][$code] = [
'redirectUrl' => $this->getMethodRedirectUrl($code)
......@@ -112,13 +93,11 @@ class AdyenGenericConfigProvider implements ConfigProviderInterface
}
// show logos turned on by default
if($this->_genericConfig->showLogos()) {
if ($this->_genericConfig->showLogos()) {
$config['payment']['adyen']['showLogo'] = true;
} else {
$config['payment']['adyen']['showLogo'] = false;
}
return $config;
}
......@@ -130,6 +109,6 @@ class AdyenGenericConfigProvider implements ConfigProviderInterface
*/
protected function getMethodRedirectUrl($code)
{
return $this->methods[$code]->getCheckoutRedirectUrl();
return $this->_methods[$code]->getCheckoutRedirectUrl();
}
}
\ No newline at end of file
This diff is collapsed.
......@@ -37,7 +37,7 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider
/**
* @var string[]
*/
protected $methodCodes = [
protected $_methodCodes = [
\Adyen\Payment\Model\Method\Oneclick::METHOD_CODE
];
......@@ -86,11 +86,18 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider
*/
protected $_genericConfig;
/**
* AdyenOneclickConfigProvider constructor.
*
* @param \Magento\Framework\Model\Context $context
* @param \Magento\Payment\Model\CcConfig $ccConfig
* @param PaymentHelper $paymentHelper
* @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(
\Magento\Framework\Model\Context $context,
......@@ -103,7 +110,7 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Adyen\Payment\Model\AdyenGenericConfig $genericConfig
) {
parent::__construct($ccConfig, $paymentHelper, $this->methodCodes);
parent::__construct($ccConfig, $paymentHelper, $this->_methodCodes);
$this->_paymentHelper = $paymentHelper;
$this->_adyenHelper = $adyenHelper;
$this->_billingAgreementCollectionFactory = $billingAgreementCollectionFactory;
......@@ -114,13 +121,16 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider
$this->_genericConfig = $genericConfig;
}
/**
* @return array
*/
public function getConfig()
{
$config = parent::getConfig();
$demoMode = $this->_adyenHelper->getAdyenAbstractConfigDataFlag('demo_mode');
if($demoMode) {
if ($demoMode) {
$cseKey = $this->_adyenHelper->getAdyenCcConfigData('cse_publickey_test');
} else {
$cseKey = $this->_adyenHelper->getAdyenCcConfigData('cse_publickey_live');
......@@ -130,26 +140,24 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider
$recurringType = $this->_adyenHelper->getAdyenAbstractConfigData('recurring_type');
$canCreateBillingAgreement = false;
if($recurringType == "ONECLICK" || $recurringType == "ONECLICK,RECURRING") {
if ($recurringType == "ONECLICK" || $recurringType == "ONECLICK,RECURRING") {
$canCreateBillingAgreement = true;
}
$config['payment'] ['adyenOneclick']['cseKey'] = $cseKey;
$config['payment'] ['adyenOneclick']['cseEnabled'] = $cseEnabled;
$config['payment'] ['adyenOneclick']['cseEnabled'] = $cseEnabled;
$config['payment']['adyenOneclick']['generationTime'] = date("c");
$config['payment']['adyenOneclick']['canCreateBillingAgreement'] = $canCreateBillingAgreement;
foreach ($this->methodCodes as $code) {
foreach ($this->_methodCodes as $code) {
if ($this->methods[$code]->isAvailable()) {
$recurringContractType = $this->_getRecurringContractType();
$config['payment'] ['adyenOneclick']['billingAgreements'] = $this->getAdyenOneclickPaymentMethods();
$config['payment'] ['adyenOneclick']['recurringContractType'] = $recurringContractType;
if($recurringContractType == \Adyen\Payment\Model\RecurringType::ONECLICK) {
if ($recurringContractType == \Adyen\Payment\Model\RecurringType::ONECLICK) {
$config['payment'] ['adyenOneclick']['hasCustomerInteraction'] = true;
} else {
$config['payment'] ['adyenOneclick']['hasCustomerInteraction'] = false;
......@@ -159,16 +167,15 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider
return $config;
}
/**
* @return array
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getAdyenOneclickPaymentMethods()
{
$billingAgreements = [];
if ($this->_customerSession->isLoggedIn()) {
$customerId = $this->_customerSession->getCustomerId();
// is admin?
if ($this->_appState->getAreaCode() === \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE) {
//retrieve storeId from quote
......@@ -190,29 +197,31 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider
$agreementData = $billingAgreement->getAgreementData();
// no agreementData and contractType then ignore
if((!is_array($agreementData)) || (!isset($agreementData['contractTypes']))) {
if ((!is_array($agreementData)) || (!isset($agreementData['contractTypes']))) {
continue;
}
// check if contractType is supporting the selected contractType for OneClick payments
$allowedContractTypes = $agreementData['contractTypes'];
if(in_array($recurringPaymentType, $allowedContractTypes)) {
if (in_array($recurringPaymentType, $allowedContractTypes)) {
// check if AgreementLabel is set and if contract has an recurringType
if($billingAgreement->getAgreementLabel()) {
if ($billingAgreement->getAgreementLabel()) {
$data = ['reference_id' => $billingAgreement->getReferenceId(),
'agreement_label' => $billingAgreement->getAgreementLabel(),
'agreement_data' => $agreementData
];
if($this->_genericConfig->showLogos()) {
if ($this->_genericConfig->showLogos()) {
$logoName = $agreementData['variant'];
// for Ideal use sepadirectdebit because it is
if($agreementData['variant'] == 'ideal') {
if ($agreementData['variant'] == 'ideal') {
$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);
$icon = null;
......@@ -225,9 +234,7 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider
];
}
$data['logo'] = $icon;
}
$billingAgreements[] = $data;
}
}
......@@ -236,6 +243,9 @@ class AdyenOneclickConfigProvider extends CcGenericConfigProvider
return $billingAgreements;
}
/**
* @return mixed
*/
protected function _getRecurringContractType()
{
return $this->_adyenHelper->getAdyenOneclickConfigData('recurring_payment_type');
......
......@@ -33,14 +33,14 @@ class AdyenSepaConfigProvider implements ConfigProviderInterface
/**
* @var string[]
*/
protected $methodCodes = [
protected $_methodCodes = [
'adyen_sepa'
];
/**
* @var \Magento\Payment\Model\Method\AbstractMethod[]
*/
protected $methods = [];
protected $_methods = [];
/**
* @var PaymentHelper
......@@ -52,25 +52,27 @@ class AdyenSepaConfigProvider implements ConfigProviderInterface
*/
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);
foreach ($this->_methodCodes as $code) {
$this->_methods[$code] = $this->_paymentHelper->getMethodInstance($code);
}
}
/**
* @return array
*/
public function getConfig()
{
$config = [
......@@ -84,60 +86,26 @@ class AdyenSepaConfigProvider implements ConfigProviderInterface
return $config;
}
/**
* @return array
*/
public function getCountries()
{
$sepaCountriesAllowed = array(
"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"
);
$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)) {
if (in_array($value, $sepaCountriesAllowed)) {
$sepaCountries[$value] = $country['label'];
}
}
return $sepaCountries;
}
}
\ No newline at end of file
This diff is collapsed.
......@@ -31,14 +31,17 @@ class Agreement extends \Magento\Paypal\Model\Billing\Agreement
*/
private $_adyenHelper;
/**
* Agreement constructor.
*
* @param \Adyen\Payment\Helper\Data $adyenHelper
* @param \Magento\Framework\Model\Context $context
* @param \Magento\Framework\Registry $registry
* @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\Data\Collection\AbstractDb|null $resourceCollection
* @param \Adyen\Payment\Helper\Data $adyenHelper
* @param array $data
*/
public function __construct(
......@@ -51,10 +54,16 @@ class Agreement extends \Magento\Paypal\Model\Billing\Agreement
\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
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;
}
......@@ -68,7 +77,10 @@ class Agreement extends \Magento\Paypal\Model\Billing\Agreement
return $this->getCustomerId();
}
/**
* @param $data
* @return $this
*/
public function parseRecurringContractData($data)
{
$this
......@@ -118,6 +130,10 @@ class Agreement extends \Magento\Paypal\Model\Billing\Agreement
return $this;
}
/**
* @param $data
* @return $this
*/
public function setAgreementData($data)
{
if (is_array($data)) {
......@@ -130,6 +146,9 @@ class Agreement extends \Magento\Paypal\Model\Billing\Agreement
return $this;
}
/**
* @return mixed
*/
public function getAgreementData()
{
return json_decode($this->getData('agreement_data'), true);
......
......@@ -28,7 +28,8 @@ namespace Adyen\Payment\Model\Config;
class Converter implements \Magento\Framework\Config\ConverterInterface
{
/**
* {@inheritdoc}
* @param \DOMDocument $source
* @return array
*/
public function convert($source)
{
......@@ -91,8 +92,6 @@ class Converter implements \Magento\Framework\Config\ConverterInterface
return $left['order'] - $right['order'];
}
/**
* Convert methods xml tree to array
*
......
......@@ -35,63 +35,4 @@ class Reader extends \Magento\Framework\Config\Reader\Filesystem
protected $_idAttributes = [
'/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;
class CaptureMode implements \Magento\Framework\Option\ArrayInterface
{
/**
* @var \Magento\Sales\Model\Order\Config
*/
protected $_orderConfig;
/**
* @var \Adyen\Payment\Helper\Data
*/
......@@ -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
*/
public function __construct(
\Magento\Sales\Model\Order\Config $orderConfig,
\Adyen\Payment\Helper\Data $adyenHelper
)
{
$this->_orderConfig = $orderConfig;
) {
$this->_adyenHelper = $adyenHelper;
}
......
......@@ -26,26 +26,19 @@ namespace Adyen\Payment\Model\Config\Source;
class DemoMode implements \Magento\Framework\Option\ArrayInterface
{
/**
* @var \Magento\Sales\Model\Order\Config
*/
protected $_orderConfig;
/**
* @var \Adyen\Payment\Helper\Data
*/
protected $_adyenHelper;
/**
* @param \Magento\Sales\Model\Order\Config $orderConfig
* DemoMode constructor.
*
* @param \Adyen\Payment\Helper\Data $adyenHelper
*/
public function __construct(
\Magento\Sales\Model\Order\Config $orderConfig,
\Adyen\Payment\Helper\Data $adyenHelper
)
{
$this->_orderConfig = $orderConfig;
) {
$this->_adyenHelper = $adyenHelper;
}
......
......@@ -26,11 +26,6 @@ namespace Adyen\Payment\Model\Config\Source;
class PaymentRoutine implements \Magento\Framework\Option\ArrayInterface
{
/**
* @var \Magento\Sales\Model\Order\Config
*/
protected $_orderConfig;
/**
* @var \Adyen\Payment\Helper\Data
*/
......@@ -41,11 +36,8 @@ class PaymentRoutine implements \Magento\Framework\Option\ArrayInterface
* @param \Adyen\Payment\Helper\Data $adyenHelper
*/
public function __construct(
\Magento\Sales\Model\Order\Config $orderConfig,
\Adyen\Payment\Helper\Data $adyenHelper
)
{
$this->_orderConfig = $orderConfig;
) {
$this->_adyenHelper = $adyenHelper;
}
......
......@@ -27,26 +27,19 @@ class RecurringPaymentType implements \Magento\Framework\Option\ArrayInterface
{
const UNDEFINED_OPTION_LABEL = 'NONE';
/**
* @var \Magento\Sales\Model\Order\Config
*/
protected $_orderConfig;
/**
* @var \Adyen\Payment\Helper\Data
*/
protected $_adyenHelper;
/**
* @param \Magento\Sales\Model\Order\Config $orderConfig
* RecurringPaymentType constructor.
*
* @param \Adyen\Payment\Helper\Data $adyenHelper
*/
public function __construct(
\Magento\Sales\Model\Order\Config $orderConfig,
\Adyen\Payment\Helper\Data $adyenHelper
)
{
$this->_orderConfig = $orderConfig;
) {
$this->_adyenHelper = $adyenHelper;
}
......@@ -58,7 +51,8 @@ class RecurringPaymentType implements \Magento\Framework\Option\ArrayInterface
$recurringTypes = $this->_adyenHelper->getRecurringTypes();
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];
}
}
......
......@@ -27,26 +27,20 @@ class RecurringType implements \Magento\Framework\Option\ArrayInterface
{
const UNDEFINED_OPTION_LABEL = 'NONE';
/**
* @var \Magento\Sales\Model\Order\Config
*/
protected $_orderConfig;
/**
* @var \Adyen\Payment\Helper\Data
*/
protected $_adyenHelper;
/**
* @param \Magento\Sales\Model\Order\Config $orderConfig
* RecurringType constructor.
*
* @param \Adyen\Payment\Helper\Data $adyenHelper
*/
public function __construct(
\Magento\Sales\Model\Order\Config $orderConfig,
\Adyen\Payment\Helper\Data $adyenHelper
)
{
$this->_orderConfig = $orderConfig;
$this->_adyenHelper = $adyenHelper;
}
......
......@@ -33,9 +33,9 @@ class RenderMode implements \Magento\Framework\Option\ArrayInterface
*/
public function toOptionArray()
{
return array(
array('value' => self::MODE_TITLE, 'label' => __('Title')),
array('value' => self::MODE_TITLE_IMAGE, 'label' => __('Logo + Title')),
);
return [
['value' => self::MODE_TITLE, 'label' => __('Title')],
['value' => self::MODE_TITLE_IMAGE, 'label' => __('Logo + Title')]
];
}
}
......@@ -33,10 +33,10 @@ class SepaFlow implements \Magento\Framework\Option\ArrayInterface
*/
public function toOptionArray()
{
return array(
array('value' => self::SEPA_FLOW_SALE, 'label' => __('Sale')),
array('value' => self::SEPA_FLOW_AUTHCAP, 'label' => __('Auth/Cap')),
);
return [
['value' => self::SEPA_FLOW_SALE, 'label' => __('Sale')],
['value' => self::SEPA_FLOW_AUTHCAP, 'label' => __('Auth/Cap')],
];
}
}
\ No newline at end of file
This diff is collapsed.
......@@ -42,18 +42,23 @@ class AdyenAbstract extends \Magento\Payment\Model\Method\AbstractMethod impleme
* @var bool
*/
protected $_isGateway = false;
/**
* @var bool
*/
protected $_canAuthorize = false;
/**
* @var bool
*/
protected $_isInitializeNeeded = false;
/**
* Post request to gateway and return response
*
* @param Object $request
* @param DataObject $request
* @param ConfigInterface $config
*
* @return DataObject
*
* @throws \Exception
*/
public function postRequest(DataObject $request, ConfigInterface $config)
{
......
This diff is collapsed.
......@@ -49,22 +49,52 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
protected $_infoBlockType = 'Adyen\Payment\Block\Info\Hpp';
/**
* 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 $_isInitializeNeeded = true;
protected $_canUseInternal = false;
/**
* @var bool
*/
protected $_canUseInternal = false;
/**
* @var \Adyen\Payment\Model\Api\PaymentRequest
......@@ -98,6 +128,8 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
protected $_adyenLogger;
/**
* Hpp constructor.
* @param \Magento\Framework\App\RequestInterface $request
* @param \Adyen\Payment\Model\Api\PaymentRequest $paymentRequest
* @param \Magento\Framework\UrlInterface $urlBuilder
* @param \Adyen\Payment\Helper\Data $adyenHelper
......@@ -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\Data\Collection\AbstractDb|null $resourceCollection
* @param array $data
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __construct(
\Magento\Framework\App\RequestInterface $request,
......@@ -156,11 +187,24 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
$this->_request = $request;
}
/**
* @var string
*/
protected $_paymentMethodType = 'hpp';
public function getPaymentMethodType() {
/**
* @return string
*/
public function getPaymentMethodType()
{
return $this->_paymentMethodType;
}
/**
* @param string $paymentAction
* @param object $stateObject
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function initialize($paymentAction, $stateObject)
{
/*
......@@ -194,15 +238,15 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
$additionalData = $data->getAdditionalData();
$infoInstance = $this->getInfoInstance();
if(isset($additionalData['brand_code'])) {
if (isset($additionalData['brand_code'])) {
$infoInstance->setAdditionalInformation('brand_code', $additionalData['brand_code']);
}
if(isset($additionalData['issuer_id'])) {
if (isset($additionalData['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;
}
......@@ -216,7 +260,7 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
*/
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()]);
}
/**
......@@ -229,16 +273,11 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
return $this->_request;
}
/**
* Post request to gateway and return response
*
* @param Object $request
* @param DataObject $request
* @param ConfigInterface $config
*
* @return Object
*
* @throws \Exception
*/
public function postRequest(DataObject $request, ConfigInterface $config)
{
......@@ -277,6 +316,10 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
return $url;
}
/**
* @return array
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getFormFields()
{
$paymentInfo = $this->getInfoInstance();
......@@ -297,7 +340,6 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
$countryCode = trim($this->getConfigData('country_code'));
$countryCode = (!empty($countryCode)) ? $countryCode : false;
// if directory lookup is enabled use the billingadress as countrycode
if ($countryCode == false) {
if ($order->getBillingAddress() && $order->getBillingAddress()->getCountryId() != "") {
......@@ -305,8 +347,7 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
}
}
$formFields = array();
$formFields = [];
$formFields['merchantAccount'] = $merchantAccount;
$formFields['merchantReference'] = $realOrderId;
$formFields['paymentAmount'] = (int)$amount;
......@@ -334,17 +375,17 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
$baseUrl = $this->storeManager->getStore($this->getStore())
->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK);
$formFields['resURL'] = $baseUrl . 'adyen/process/result';
$formFields['resURL'] = $baseUrl . 'adyen/process/result';
$hmacKey = $this->_adyenHelper->getHmac();
$brandCode = $order->getPayment()->getAdditionalInformation("brand_code");
if($brandCode) {
if ($brandCode) {
$formFields['brandCode'] = $brandCode;
}
$issuerId = $order->getPayment()->getAdditionalInformation("issuer_id");
if($issuerId) {
if ($issuerId) {
$formFields['issuerId'] = $issuerId;
}
......@@ -352,9 +393,10 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
ksort($formFields, SORT_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;
......@@ -363,17 +405,22 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
return $formFields;
}
/*
* @desc The character escape function is called from the array_map function in _signRequestParams
* $param $val
* return string
/**
* The character escape function is called from the array_map function in _signRequestParams
*
* @param $val
* @return mixed
*/
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');
}
......@@ -382,6 +429,8 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
*
* @param \Magento\Payment\Model\InfoInterface $payment
* @param float $amount
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function capture(\Magento\Payment\Model\InfoInterface $payment, $amount)
{
......@@ -393,12 +442,10 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
/**
* Refund specified amount for payment
*
* @param \Magento\Framework\DataObject|InfoInterface $payment
* @param \Magento\Payment\Model\InfoInterface $payment
* @param float $amount
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
* @api
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function refund(\Magento\Payment\Model\InfoInterface $payment, $amount)
{
......@@ -408,16 +455,18 @@ class Hpp extends \Magento\Payment\Model\Method\AbstractMethod implements Gatewa
$pspReference = $payment->getAdyenPspReference();
$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();
if($grandTotal == $amount) {
if ($grandTotal == $amount) {
$this->_paymentRequest->cancelOrRefund($payment);
} else {
$this->_paymentRequest->refund($payment, $amount);
}
return $this;
}
}
\ No newline at end of file
......@@ -43,8 +43,11 @@ class Oneclick extends \Adyen\Payment\Model\Method\Cc
* @var string
*/
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
......@@ -77,10 +80,11 @@ class Oneclick extends \Adyen\Payment\Model\Method\Cc
$infoInstance->setCcType($ccType);
// save value remember details checkbox
$infoInstance->setAdditionalInformation('recurring_detail_reference', $additionalData['recurring_detail_reference']);
$infoInstance->setAdditionalInformation('recurring_detail_reference',
$additionalData['recurring_detail_reference']);
$recurringPaymentType = $this->_adyenHelper->getAdyenOneclickConfigData('recurring_payment_type');
if($recurringPaymentType == \Adyen\Payment\Model\RecurringType::ONECLICK) {
if ($recurringPaymentType == \Adyen\Payment\Model\RecurringType::ONECLICK) {
$customerInteraction = true;
} else {
$customerInteraction = false;
......@@ -91,12 +95,16 @@ class Oneclick extends \Adyen\Payment\Model\Method\Cc
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)
{
$targetStatus = $agreement->getStatus();
if($targetStatus == \Magento\Paypal\Model\Billing\Agreement::STATUS_CANCELED) {
if ($targetStatus == \Magento\Paypal\Model\Billing\Agreement::STATUS_CANCELED) {
try {
$this->_paymentRequest->disableRecurringContract(
$agreement->getReferenceId(),
......@@ -108,5 +116,4 @@ class Oneclick extends \Adyen\Payment\Model\Method\Cc
}
return $this;
}
}
\ No newline at end of file
This diff is collapsed.
......@@ -60,14 +60,41 @@ class Sepa extends \Magento\Payment\Model\Method\AbstractMethod
* @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;
protected $_canUseInternal = true;
/**
* @var bool
*/
protected $_canUseInternal = true;
/**
* Sepa constructor.
......@@ -117,8 +144,6 @@ class Sepa extends \Magento\Payment\Model\Method\AbstractMethod
$this->_request = $request;
}
/**
* Assign data to info model instance
*
......@@ -154,44 +179,61 @@ class Sepa extends \Magento\Payment\Model\Method\AbstractMethod
{
$infoInstance = $this->getInfoInstance();
$iban = $infoInstance->getAdditionalInformation('iban');
if(empty($iban) || !$this->validateIban($iban)){
if (empty($iban) || !$this->validateIban($iban)) {
throw new \Magento\Framework\Exception\LocalizedException(__('Invalid Iban number.'));
}
return $this;
}
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($MovedCharArray AS $key => $value){
if(!is_numeric($MovedCharArray[$key])){
$MovedCharArray[$key] = $Chars[$MovedCharArray[$key]];
/**
* 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];
$newString .= $movedCharArray[$key];
}
if(bcmod($NewString, '97') == 1)
{
if (bcmod($newString, '97') == 1) {
return true;
}
else{
} else {
return false;
}
}
else{
} 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()) {
......@@ -214,6 +256,12 @@ class Sepa extends \Magento\Payment\Model\Method\AbstractMethod
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) {
......@@ -229,13 +277,17 @@ class Sepa extends \Magento\Payment\Model\Method\AbstractMethod
}
}
/**
* @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, $responseCode, $pspReference, $this->_getConfigData('order_status'));
$this->_addStatusHistory($payment, $response['resultCode'], $response['pspReference']);
$payment->setAdditionalInformation('pspReference', $response['pspReference']);
break;
......@@ -247,16 +299,22 @@ class Sepa extends \Magento\Payment\Model\Method\AbstractMethod
}
}
/**
* @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, "");
$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)
*
......@@ -266,7 +324,8 @@ class Sepa extends \Magento\Payment\Model\Method\AbstractMethod
*/
public function getCheckoutRedirectUrl()
{
return $this->_urlBuilder->getUrl('checkout/onepage/success/',['_secure' => $this->_getRequest()->isSecure()]);
return $this->_urlBuilder->getUrl('checkout/onepage/success/',
['_secure' => $this->_getRequest()->isSecure()]);
}
/**
......@@ -278,6 +337,4 @@ class Sepa extends \Magento\Payment\Model\Method\AbstractMethod
{
return $this->_request;
}
}
\ No newline at end of file
......@@ -50,6 +50,15 @@ class Notification extends \Magento\Framework\Model\AbstractModel
const REPORT_AVAILABLE = "REPORT_AVAILABLE";
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(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
......@@ -60,7 +69,6 @@ class Notification extends \Magento\Framework\Model\AbstractModel
parent::__construct($context, $registry, $resource, $resourceCollection, $data);
}
/**
* Initialize resource model
*
......@@ -73,12 +81,14 @@ class Notification extends \Magento\Framework\Model\AbstractModel
/**
* Check if the Adyen Notification is already stored in the system
*
* @param $pspReference
* @param $event
* @param $eventCode
* @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);
return (empty($result)) ? false : true;
}
......@@ -263,9 +273,7 @@ class Notification extends \Magento\Framework\Model\AbstractModel
}
/**
* Sets Reason.
*
* @param string $reason
* @param $live
* @return $this
*/
public function setLive($live)
......@@ -273,7 +281,6 @@ class Notification extends \Magento\Framework\Model\AbstractModel
return $this->setData(self::LIVE, $live);
}
/**
* Gets the AdditionalData for the notification.
*
......@@ -357,6 +364,4 @@ class Notification extends \Magento\Framework\Model\AbstractModel
{
return $this->setData(self::UPDATED_AT, $timestamp);
}
}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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