We will work on Apr 26th (Saturday) and will be off from Apr 30th (Wednesday) until May 2nd (Friday) for public holiday in our country

Cron.php 71.9 KB
Newer Older
1
<?php
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/**
 *                       ######
 *                       ######
 * ############    ####( ######  #####. ######  ############   ############
 * #############  #####( ######  #####. ######  #############  #############
 *        ######  #####( ######  #####. ######  #####  ######  #####  ######
 * ###### ######  #####( ######  #####. ######  #####  #####   #####  ######
 * ###### ######  #####( ######  #####. ######  #####          #####  ######
 * #############  #############  #############  #############  #####  ######
 *  ############   ############  #############   ############  #####  ######
 *                                      ######
 *                               #############
 *                               ############
 *
 * 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>
 */
23 24 25

namespace Adyen\Payment\Model;

26
use Magento\Framework\Api\SearchCriteriaBuilder;
27
use Magento\Framework\Webapi\Exception;
28
use Magento\Sales\Model\Order\Email\Sender\OrderSender;
29
use Magento\Sales\Model\Order\Email\Sender\InvoiceSender;
30
use Magento\Framework\App\Area;
31 32 33
use Magento\Framework\App\AreaList;
use Magento\Framework\Phrase\Renderer\Placeholder;
use Magento\Framework\Phrase;
34
use Magento\Sales\Model\OrderRepository;
35 36 37 38 39 40 41 42 43 44

class Cron
{

    /**
     * Logging instance
     * @var \Adyen\Payment\Logger\AdyenLogger
     */
    protected $_logger;

45
    /**
46
     * @var ResourceModel\Notification\CollectionFactory
47
     */
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
    protected $_notificationFactory;

    /**
     * @var \Magento\Sales\Model\OrderFactory
     */
    protected $_orderFactory;

    /**
     * @var \Magento\Sales\Model\Order
     */
    protected $_order;

    /**
     * Core store config
     *
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $_scopeConfig;

67 68 69
    /**
     * @var \Adyen\Payment\Helper\Data
     */
70 71 72 73 74 75 76
    protected $_adyenHelper;

    /**
     * @var OrderSender
     */
    protected $_orderSender;

77 78 79 80 81
    /**
     * @var InvoiceSender
     */
    protected $_invoiceSender;

rikterbeek's avatar
rikterbeek committed
82 83 84 85 86
    /**
     * @var \Magento\Framework\DB\TransactionFactory
     */
    protected $_transactionFactory;

87 88 89 90 91 92
    /**
     * @var \Adyen\Payment\Model\Billing\AgreementFactory
     */
    protected $_billingAgreementFactory;

    /**
93
     * @var ResourceModel\Billing\Agreement\CollectionFactory
94 95 96 97 98 99 100 101
     */
    protected $_billingAgreementCollectionFactory;

    /**
     * @var Api\PaymentRequest
     */
    protected $_adyenPaymentRequest;

102 103 104
    /**
     * notification attributes
     */
105
    protected $_pspReference;
106

107 108 109 110 111
    /**
     * @var
     */
    protected $_originalReference;

112 113 114
    /**
     * @var
     */
115
    protected $_merchantReference;
116

117 118 119 120 121
    /**
     * @var
     */
    protected $_acquirerReference;

122 123 124 125 126
    /**
     * @var
     */
    protected $ratepayDescriptor;

127 128 129
    /**
     * @var
     */
130
    protected $_eventCode;
131 132 133 134

    /**
     * @var
     */
135
    protected $_success;
136 137 138 139

    /**
     * @var
     */
140
    protected $_paymentMethod;
141 142 143 144

    /**
     * @var
     */
145
    protected $_reason;
146 147 148 149

    /**
     * @var
     */
150
    protected $_value;
151 152 153 154

    /**
     * @var
     */
155
    protected $_boletoOriginalAmount;
156 157 158 159

    /**
     * @var
     */
160
    protected $_boletoPaidAmount;
161 162 163 164

    /**
     * @var
     */
165
    protected $_modificationResult;
166 167 168 169

    /**
     * @var
     */
170
    protected $_klarnaReservationNumber;
171 172 173 174

    /**
     * @var
     */
175 176
    protected $_fraudManualReview;

177 178 179 180 181 182
    /**
     * @var Order\PaymentFactory
     */
    protected $_adyenOrderPaymentFactory;

    /**
183
     * @var ResourceModel\Order\Payment\CollectionFactory
184 185 186
     */
    protected $_adyenOrderPaymentCollectionFactory;

187 188 189 190 191
    /**
     * @var ResourceModel\InvoiceFactory
     */
    protected $_adyenInvoiceFactory;

192
    /**
193
     * @var AreaList
194
     */
195
    protected $_areaList;
196

Bas Maassen's avatar
Bas Maassen committed
197 198 199 200 201
    /**
     * @var \Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory
     */
    protected $_orderStatusCollection;

202 203 204 205 206 207 208 209 210 211
    /**
     * @var SearchCriteriaBuilder
     */
    private $searchCriteriaBuilder;

    /**
     * @var OrderRepository
     */
    private $orderRepository;

212 213 214 215 216
    /**
     * @var ResourceModel\Billing\Agreement
     */
    private $agreementResourceModel;

217 218 219 220 221
    /**
     * @var \Magento\Sales\Model\Order\Payment\Transaction\Builder
     */
    private $transactionBuilder;

222
    /**
223
     * Cron constructor.
224
     *
225 226
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger
227
     * @param ResourceModel\Notification\CollectionFactory $notificationFactory
228 229 230
     * @param \Magento\Sales\Model\OrderFactory $orderFactory
     * @param \Adyen\Payment\Helper\Data $adyenHelper
     * @param OrderSender $orderSender
231
     * @param InvoiceSender $invoiceSender
232
     * @param \Magento\Framework\DB\TransactionFactory $transactionFactory
233
     * @param Billing\AgreementFactory $billingAgreementFactory
234
     * @param ResourceModel\Billing\Agreement\CollectionFactory $billingAgreementCollectionFactory
235
     * @param Api\PaymentRequest $paymentRequest
236
     * @param Order\PaymentFactory $adyenOrderPaymentFactory
237
     * @param ResourceModel\Order\Payment\CollectionFactory $adyenOrderPaymentCollectionFactory
Bas Maassen's avatar
Bas Maassen committed
238
     * @param InvoiceFactory $adyenInvoiceFactory
239
     * @param AreaList $areaList
Bas Maassen's avatar
Bas Maassen committed
240
     * @param \Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory $orderStatusCollection
241 242
     * @param SearchCriteriaBuilder $searchCriteriaBuilder
     * @param OrderRepository $orderRepository
243
     * @param ResourceModel\Billing\Agreement $agreementResourceModel
244
     * @param \Magento\Sales\Model\Order\Payment\Transaction\Builder $transactionBuilder
245 246 247 248
     */
    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Adyen\Payment\Logger\AdyenLogger $adyenLogger,
249
        \Adyen\Payment\Model\ResourceModel\Notification\CollectionFactory $notificationFactory,
250 251
        \Magento\Sales\Model\OrderFactory $orderFactory,
        \Adyen\Payment\Helper\Data $adyenHelper,
rikterbeek's avatar
rikterbeek committed
252
        OrderSender $orderSender,
253
        InvoiceSender $invoiceSender,
254 255
        \Magento\Framework\DB\TransactionFactory $transactionFactory,
        \Adyen\Payment\Model\Billing\AgreementFactory $billingAgreementFactory,
256
        \Adyen\Payment\Model\ResourceModel\Billing\Agreement\CollectionFactory $billingAgreementCollectionFactory,
257 258
        \Adyen\Payment\Model\Api\PaymentRequest $paymentRequest,
        \Adyen\Payment\Model\Order\PaymentFactory $adyenOrderPaymentFactory,
259
        \Adyen\Payment\Model\ResourceModel\Order\Payment\CollectionFactory $adyenOrderPaymentCollectionFactory,
260
        \Adyen\Payment\Model\InvoiceFactory $adyenInvoiceFactory,
Bas Maassen's avatar
Bas Maassen committed
261
        AreaList $areaList,
262 263
        \Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory $orderStatusCollection,
        SearchCriteriaBuilder $searchCriteriaBuilder,
264
        OrderRepository $orderRepository,
265 266
        \Adyen\Payment\Model\ResourceModel\Billing\Agreement $agreementResourceModel,
        \Magento\Sales\Model\Order\Payment\Transaction\Builder $transactionBuilder
267
    ) {
268
        $this->_scopeConfig = $scopeConfig;
269
        $this->_adyenLogger = $adyenLogger;
270 271 272 273
        $this->_notificationFactory = $notificationFactory;
        $this->_orderFactory = $orderFactory;
        $this->_adyenHelper = $adyenHelper;
        $this->_orderSender = $orderSender;
274
        $this->_invoiceSender = $invoiceSender;
rikterbeek's avatar
rikterbeek committed
275
        $this->_transactionFactory = $transactionFactory;
276 277 278
        $this->_billingAgreementFactory = $billingAgreementFactory;
        $this->_billingAgreementCollectionFactory = $billingAgreementCollectionFactory;
        $this->_adyenPaymentRequest = $paymentRequest;
279 280
        $this->_adyenOrderPaymentFactory = $adyenOrderPaymentFactory;
        $this->_adyenOrderPaymentCollectionFactory = $adyenOrderPaymentCollectionFactory;
281
        $this->_adyenInvoiceFactory = $adyenInvoiceFactory;
282
        $this->_areaList = $areaList;
Bas Maassen's avatar
Bas Maassen committed
283
        $this->_orderStatusCollection = $orderStatusCollection;
284 285
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->orderRepository = $orderRepository;
286
        $this->agreementResourceModel = $agreementResourceModel;
287
        $this->transactionBuilder = $transactionBuilder;
288 289
    }

290 291 292 293
    /**
     * Process the notification
     * @return void
     */
294
    public function processNotification()
295 296 297
    {
        try {
            $this->execute();
Rik ter Beek's avatar
Rik ter Beek committed
298
        } catch (\Exception $e) {
299 300 301 302 303 304
            $this->_adyenLogger->addAdyenNotificationCronjob($e->getMessage() . "\n" . $e->getTraceAsString());
            throw $e;
        }
    }

    public function execute()
305
    {
306
        // needed for Magento < 2.2.0 https://github.com/magento/magento2/pull/8413
307
        $renderer = Phrase::getRenderer();
308
        if ($renderer instanceof Placeholder) {
309
            $this->_areaList->getArea(Area::AREA_CRONTAB)->load(Area::PART_TRANSLATE);
310 311
        }

312 313
        $this->_order = null;

314
        // execute notifications from 2 minute or earlier because order could not yet been created by magento
315
        $dateStart = new \DateTime();
316
        $dateStart->modify('-5 day');
317
        $dateEnd = new \DateTime();
318
        $dateEnd->modify('-1 minute');
319 320
        $dateRange = ['from' => $dateStart, 'to' => $dateEnd, 'datetime' => true];

321
        // create collection
322 323
        $notifications = $this->_notificationFactory->create();
        $notifications->addFieldToFilter('done', 0);
324
        $notifications->addFieldToFilter('processing', 0);
325 326
        $notifications->addFieldToFilter('created_at', $dateRange);

327 328
        foreach ($notifications as $notification) {
            // set Cron processing to true
329
            $this->_updateNotification($notification, true, false);
330 331
        }

332
        // loop over the notifications
333
        $count = 0;
334
        foreach ($notifications as $notification) {
335 336 337 338
            $this->_adyenLogger->addAdyenNotificationCronjob(
                sprintf("Processing notification %s", $notification->getEntityId())
            );

339 340 341 342 343 344 345 346 347
            // ignore duplicate notification
            if ($this->_isDuplicate($notification)) {
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    "This is a duplicate notification and will be ignored"
                );
                $this->_updateNotification($notification, false, true);
                ++$count;
                continue;
            }
348

349
            // log the executed notification
350
            $this->_adyenLogger->addAdyenNotificationCronjob(print_r($notification->debug(), 1));
351

352 353 354
            // get order
            $incrementId = $notification->getMerchantReference();

355 356 357 358 359 360 361 362 363 364 365
            $searchCriteria = $this->searchCriteriaBuilder
                ->addFilter('increment_id', $incrementId, 'eq')
                ->create();

            $orderList = $this->orderRepository->getList($searchCriteria)->getItems();

            /** @var \Magento\Sales\Model\Order $order */
            $order = reset($orderList);
            $this->_order = $order;

            if (!$this->_order) {
366 367 368
                // order does not exists remove from queue
                $notification->delete();
                continue;
369 370 371 372 373 374 375 376 377
            }

            // declare all variables that are needed
            $this->_declareVariables($notification);

            // add notification to comment history status is current status
            $this->_addStatusHistoryComment();

            $previousAdyenEventCode = $this->_order->getData('adyen_notification_event_code');
378

379 380
            // update order details
            $this->_updateAdyenAttributes($notification);
381 382 383

            // check if success is true of false
            if (strcmp($this->_success, 'false') == 0 || strcmp($this->_success, '0') == 0) {
384 385 386 387 388 389
                /*
                 * 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 ||
390 391
                    $this->_eventCode == Notification::ORDER_CLOSED
                ) {
392
                    $this->_adyenLogger->addAdyenNotificationCronjob('Going to cancel the order');
393 394

                    // if payment is API check, check if API result pspreference is the same as reference
395
                    if ($this->_eventCode == NOTIFICATION::AUTHORISATION && $this->_getPaymentMethodType() == 'api') {
396
                        // don't cancel the order becasue order was successfull through api
397 398 399
                        $this->_adyenLogger->addAdyenNotificationCronjob(
                            'order is not cancelled because api result was succesfull'
                        );
400
                    } else {
401 402 403 404 405 406
                        /*
                         * 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
                         */
                        if ($previousAdyenEventCode != "AUTHORISATION : TRUE" ||
407 408
                            $this->_eventCode == Notification::ORDER_CLOSED
                        ) {
409 410 411
                            $this->_holdCancelOrder(false);
                        } else {
                            $this->_order->setData('adyen_notification_event_code', $previousAdyenEventCode);
412 413 414 415
                            $this->_adyenLogger->addAdyenNotificationCronjob(
                                'order is not cancelled because previous notification 
                                was an authorisation that succeeded'
                            );
416 417 418
                        }
                    }
                } else {
419 420 421
                    $this->_adyenLogger->addAdyenNotificationCronjob(
                        'Order is already processed so ignore this notification state is:' . $this->_order->getState()
                    );
422 423 424 425 426 427
                }
            } else {
                // Notification is successful
                $this->_processNotification();
            }

428 429 430 431 432 433 434
            try {
                // set done to true
                $this->_order->save();
            } catch (\Exception $e) {
                $this->_adyenLogger->addAdyenNotificationCronjob($e->getMessage());
            }

435
            $this->_updateNotification($notification, false, true);
436 437 438 439 440 441 442 443
            $this->_adyenLogger->addAdyenNotificationCronjob(
                sprintf("Notification %s is processed", $notification->getEntityId())
            );
            ++$count;
        }

        if ($count > 0) {
            $this->_adyenLogger->addAdyenNotificationCronjob(sprintf("Cronjob updated %s notification(s)", $count));
444 445 446
        }
    }

447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
    /**
     * @param $notification
     * @param $processing
     * @param $done
     */
    protected function _updateNotification($notification, $processing, $done)
    {
        if ($done) {
            $notification->setDone(true);
        }
        $notification->setProcessing($processing);
        $notification->setUpdatedAt(new \DateTime());
        $notification->save();
    }

    /**
     * Check if the notification is already executed if so this is a duplicate and ignore this one
     *
     * @param $notification
     * @return bool
     */
    protected function _isDuplicate($notification)
    {
        return $notification->isDuplicate(
471 472 473 474 475
            $notification->getPspreference(),
            $notification->getEventCode(),
            $notification->getSuccess(),
            $notification->getOriginalReference(),
            true
476 477 478
        );
    }

479 480 481 482 483 484
    /**
     * Declare private variables for processing notification
     *
     * @param Object $notification
     * @return void
     */
485 486 487 488
    protected function _declareVariables($notification)
    {
        //  declare the common parameters
        $this->_pspReference = $notification->getPspreference();
489
        $this->_originalReference = $notification->getOriginalReference();
490 491 492 493 494 495 496 497 498 499 500
        $this->_merchantReference = $notification->getMerchantReference();
        $this->_eventCode = $notification->getEventCode();
        $this->_success = $notification->getSuccess();
        $this->_paymentMethod = $notification->getPaymentMethod();
        $this->_reason = $notification->getPaymentMethod();
        $this->_value = $notification->getAmountValue();


        $additionalData = unserialize($notification->getAdditionalData());

        // boleto data
501 502
        if ($this->_paymentMethodCode() == "adyen_boleto") {
            if ($additionalData && is_array($additionalData)) {
503
                $boletobancario = isset($additionalData['boletobancario']) ? $additionalData['boletobancario'] : null;
504 505 506 507 508
                if ($boletobancario && is_array($boletobancario)) {
                    $this->_boletoOriginalAmount =
                        isset($boletobancario['originalAmount']) ? trim($boletobancario['originalAmount']) : "";
                    $this->_boletoPaidAmount =
                        isset($boletobancario['paidAmount']) ? trim($boletobancario['paidAmount']) : "";
509 510 511 512
                }
            }
        }

513
        if ($additionalData && is_array($additionalData)) {
514
            // check if the payment is in status manual review
515 516 517
            $fraudManualReview = isset($additionalData['fraudManualReview']) ?
                $additionalData['fraudManualReview'] : "";
            if ($fraudManualReview == "true") {
518 519 520 521 522
                $this->_fraudManualReview = true;
            } else {
                $this->_fraudManualReview = false;
            }

523
            // modification.action is it for JSON
524 525 526
            $modificationActionJson = isset($additionalData['modification.action']) ?
                $additionalData['modification.action'] : null;
            if ($modificationActionJson != "") {
527 528 529
                $this->_modificationResult = $modificationActionJson;
            }

530
            $modification = isset($additionalData['modification']) ? $additionalData['modification'] : null;
531
            if ($modification && is_array($modification)) {
532
                $this->_modificationResult = isset($modification['action']) ? trim($modification['action']) : "";
533 534
            }
            $additionalData2 = isset($additionalData['additionalData']) ? $additionalData['additionalData'] : null;
535
            if ($additionalData2 && is_array($additionalData2)) {
536 537
                $this->_klarnaReservationNumber = isset($additionalData2['acquirerReference']) ? trim($additionalData2['acquirerReference']) : "";
            }
538 539 540 541
            $acquirerReference = isset($additionalData['acquirerReference']) ? $additionalData['acquirerReference'] : null;
            if ($acquirerReference != "") {
                $this->_acquirerReference = $acquirerReference;
            }
542 543 544 545
            $ratepayDescriptor = isset($additionalData['openinvoicedata.descriptor']) ? $additionalData['openinvoicedata.descriptor'] : "";
            if ($ratepayDescriptor !== "") {
                $this->ratepayDescriptor = $ratepayDescriptor;
            }
546 547 548 549 550 551 552 553 554 555 556
        }
    }

    /**
     * @return mixed
     */
    protected function _paymentMethodCode()
    {
        return $this->_order->getPayment()->getMethod();
    }

557 558 559 560 561
    /**
     * @return mixed
     */
    protected function _getPaymentMethodType()
    {
rikterbeek's avatar
rikterbeek committed
562 563 564
        return $this->_order->getPayment()->getPaymentMethodType();
    }

565 566 567 568 569 570
    /**
     * @desc order comments or history
     * @param type $order
     */
    protected function _addStatusHistoryComment()
    {
571 572 573
        $successResult = (strcmp($this->_success, 'true') == 0 ||
            strcmp($this->_success, '1') == 0) ? 'true' : 'false';
        $success = (!empty($this->_reason)) ? "$successResult <br />reason:$this->_reason" : $successResult;
574

575
        if ($this->_eventCode == Notification::REFUND || $this->_eventCode == Notification::CAPTURE) {
576 577 578 579
            $currency = $this->_order->getOrderCurrencyCode();

            // check if it is a full or partial refund
            $amount = $this->_value;
580
            $orderAmount = (int)$this->_adyenHelper->formatAmount($this->_order->getGrandTotal(), $currency);
581

582
            $this->_adyenLogger->addAdyenNotificationCronjob(
583
                'amount notification:' . $amount . ' amount order:' . $orderAmount
584
            );
585

586 587
            if ($amount == $orderAmount) {
                $this->_order->setData(
588 589
                    'adyen_notification_event_code',
                    $this->_eventCode . " : " . strtoupper($successResult)
590
                );
591
            } else {
592
                $this->_order->setData(
593 594
                    'adyen_notification_event_code',
                    "(PARTIAL) " .
595 596
                    $this->_eventCode . " : " . strtoupper($successResult)
                );
597 598
            }
        } else {
599
            $this->_order->setData(
600 601
                'adyen_notification_event_code',
                $this->_eventCode . " : " . strtoupper($successResult)
602
            );
603 604
        }

Rik ter Beek's avatar
Rik ter Beek committed
605
        // if payment method is klarna, ratepay or openinvoice/afterpay show the reservartion number
Rik ter Beek's avatar
Rik ter Beek committed
606
        if ($this->_adyenHelper->isPaymentMethodOpenInvoiceMethod($this->_paymentMethod) && !empty($this->_klarnaReservationNumber)) {
607 608 609 610 611
            $klarnaReservationNumberText = "<br /> reservationNumber: " . $this->_klarnaReservationNumber;
        } else {
            $klarnaReservationNumberText = "";
        }

612
        if ($this->_boletoPaidAmount != null && $this->_boletoPaidAmount != "") {
613 614 615 616 617 618
            $boletoPaidAmountText = "<br /> Paid amount: " . $this->_boletoPaidAmount;
        } else {
            $boletoPaidAmountText = "";
        }

        $type = 'Adyen HTTP Notification(s):';
619 620 621 622 623 624 625 626 627 628 629
        $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
        );
630 631

        // If notification is pending status and pending status is set add the status change to the comment history
632
        if ($this->_eventCode == Notification::PENDING) {
633
            $pendingStatus = $this->_getConfigData(
634 635 636
                'pending_status',
                'adyen_abstract',
                $this->_order->getStoreId()
637
            );
638
            if ($pendingStatus != "") {
639
                $this->_order->addStatusHistoryComment($comment, $pendingStatus);
640 641 642
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'Created comment history for this notification with status change to: ' . $pendingStatus
                );
643 644 645 646 647
                return;
            }
        }

        // if manual review is accepted and a status is selected. Change the status through this comment history item
648
        if ($this->_eventCode == Notification::MANUAL_REVIEW_ACCEPT
649 650
            && $this->_getFraudManualReviewAcceptStatus() != ""
        ) {
651 652
            $manualReviewAcceptStatus = $this->_getFraudManualReviewAcceptStatus();
            $this->_order->addStatusHistoryComment($comment, $manualReviewAcceptStatus);
653
            $this->_adyenLogger->addAdyenNotificationCronjob('Created comment history for this notification with status change to: ' . $manualReviewAcceptStatus);
654 655 656 657
            return;
        }

        $this->_order->addStatusHistoryComment($comment);
658
        $this->_adyenLogger->addAdyenNotificationCronjob('Created comment history for this notification');
659 660
    }

661 662 663
    /**
     * @param $notification
     */
664 665
    protected function _updateAdyenAttributes($notification)
    {
666
        $this->_adyenLogger->addAdyenNotificationCronjob('Updating the Adyen attributes of the order');
667 668 669 670 671 672

        $additionalData = unserialize($notification->getAdditionalData());
        $_paymentCode = $this->_paymentMethodCode();

        if ($this->_eventCode == Notification::AUTHORISATION
            || $this->_eventCode == Notification::HANDLED_EXTERNALLY
673
        ) {
674 675 676 677 678 679
            /*
             * 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 ||
680 681
                strcmp($this->_success, '') == 0
            ) {
682 683 684 685 686 687 688 689 690 691
                $previousAdyenEventCode = $this->_order->getData('adyen_notification_event_code');
                if ($previousAdyenEventCode != "AUTHORISATION : TRUE") {
                    $this->_updateOrderPaymentWithAdyenAttributes($additionalData);
                }
            } else {
                $this->_updateOrderPaymentWithAdyenAttributes($additionalData);
            }
        }
    }

692 693 694
    /**
     * @param $additionalData
     */
695 696 697 698 699 700 701 702
    protected function _updateOrderPaymentWithAdyenAttributes($additionalData)
    {
        if ($additionalData && is_array($additionalData)) {
            $avsResult = (isset($additionalData['avsResult'])) ? $additionalData['avsResult'] : "";
            $cvcResult = (isset($additionalData['cvcResult'])) ? $additionalData['cvcResult'] : "";
            $totalFraudScore = (isset($additionalData['totalFraudScore'])) ? $additionalData['totalFraudScore'] : "";
            $ccLast4 = (isset($additionalData['cardSummary'])) ? $additionalData['cardSummary'] : "";
            $refusalReasonRaw = (isset($additionalData['refusalReasonRaw'])) ? $additionalData['refusalReasonRaw'] : "";
703 704
            $acquirerReference = (isset($additionalData['acquirerReference'])) ?
                $additionalData['acquirerReference'] : "";
705
            $authCode = (isset($additionalData['authCode'])) ? $additionalData['authCode'] : "";
706 707
            $cardBin = (isset($additionalData['cardBin'])) ? $additionalData['cardBin'] : "";
            $expiryDate = (isset($additionalData['expiryDate'])) ? $additionalData['expiryDate'] : "";
708 709 710 711 712 713 714 715 716 717 718
        }

        // if there is no server communication setup try to get last4 digits from reason field
        if (!isset($ccLast4) || $ccLast4 == "") {
            $ccLast4 = $this->_retrieveLast4DigitsFromReason($this->_reason);
        }

        $this->_order->getPayment()->setAdyenPspReference($this->_pspReference);
        $this->_order->getPayment()->setAdditionalInformation('pspReference', $this->_pspReference);

        if ($this->_klarnaReservationNumber != "") {
719
            $this->_order->getPayment()->setAdditionalInformation(
720 721
                'adyen_klarna_number',
                $this->_klarnaReservationNumber
722
            );
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
        }
        if (isset($ccLast4) && $ccLast4 != "") {
            // this field is column in db by core
            $this->_order->getPayment()->setccLast4($ccLast4);
        }
        if (isset($avsResult) && $avsResult != "") {
            $this->_order->getPayment()->setAdditionalInformation('adyen_avs_result', $avsResult);
        }
        if (isset($cvcResult) && $cvcResult != "") {
            $this->_order->getPayment()->setAdditionalInformation('adyen_cvc_result', $cvcResult);
        }
        if ($this->_boletoPaidAmount != "") {
            $this->_order->getPayment()->setAdditionalInformation('adyen_boleto_paid_amount', $this->_boletoPaidAmount);
        }
        if (isset($totalFraudScore) && $totalFraudScore != "") {
            $this->_order->getPayment()->setAdditionalInformation('adyen_total_fraud_score', $totalFraudScore);
        }
        if (isset($refusalReasonRaw) && $refusalReasonRaw != "") {
            $this->_order->getPayment()->setAdditionalInformation('adyen_refusal_reason_raw', $refusalReasonRaw);
        }
        if (isset($acquirerReference) && $acquirerReference != "") {
            $this->_order->getPayment()->setAdditionalInformation('adyen_acquirer_reference', $acquirerReference);
        }
        if (isset($authCode) && $authCode != "") {
            $this->_order->getPayment()->setAdditionalInformation('adyen_auth_code', $authCode);
        }
749 750 751 752 753 754
        if (!empty($cardBin)) {
            $this->_order->getPayment()->setAdditionalInformation('adyen_card_bin', $cardBin);
        }
        if (!empty($expiryDate)) {
            $this->_order->getPayment()->setAdditionalInformation('adyen_expiry_date', $expiryDate);
        }
755 756
        if ($this->ratepayDescriptor !== "") {
            $this->_order->getPayment()->setAdditionalInformation(
757 758
                'adyen_ratepay_descriptor',
                $this->ratepayDescriptor
759 760
            );
        }
761 762 763 764 765 766 767 768 769 770 771
    }

    /**
     * retrieve last 4 digits of card from the reason field
     * @param $reason
     * @return string
     */
    protected function _retrieveLast4DigitsFromReason($reason)
    {
        $result = "";

772
        if ($reason != "") {
773
            $reasonArray = explode(":", $reason);
774 775
            if ($reasonArray != null && is_array($reasonArray)) {
                if (isset($reasonArray[1])) {
776 777 778 779 780 781 782
                    $result = $reasonArray[1];
                }
            }
        }
        return $result;
    }

783
    /**
784 785
     * @param $ignoreHasInvoice
     * @throws \Magento\Framework\Exception\LocalizedException
786 787 788
     */
    protected function _holdCancelOrder($ignoreHasInvoice)
    {
789
        $orderStatus = $this->_getConfigData(
790 791 792
            'payment_cancelled',
            'adyen_abstract',
            $this->_order->getStoreId()
793
        );
794 795 796

        // check if order has in invoice only cancel/hold if this is not the case
        if ($ignoreHasInvoice || !$this->_order->hasInvoices()) {
797
            if ($orderStatus == \Magento\Sales\Model\Order::STATE_HOLDED) {
798 799 800
                // Allow magento to hold order
                $this->_order->setActionFlag(\Magento\Sales\Model\Order::ACTION_FLAG_HOLD, true);

801 802 803
                if ($this->_order->canHold()) {
                    $this->_order->hold();
                } else {
804
                    $this->_adyenLogger->addAdyenNotificationCronjob('Order can not hold or is already on Hold');
805 806 807
                    return;
                }
            } else {
808 809 810
                // Allow magento to cancel order
                $this->_order->setActionFlag(\Magento\Sales\Model\Order::ACTION_FLAG_CANCEL, true);

811 812 813
                if ($this->_order->canCancel()) {
                    $this->_order->cancel();
                } else {
814
                    $this->_adyenLogger->addAdyenNotificationCronjob('Order can not be canceled');
815 816 817 818
                    return;
                }
            }
        } else {
819
            $this->_adyenLogger->addAdyenNotificationCronjob('Order has already an invoice so cannot be canceled');
820 821 822 823
        }
    }

    /**
824
     * Process the Notification
825 826 827
     */
    protected function _processNotification()
    {
828

829
        $this->_adyenLogger->addAdyenNotificationCronjob('Processing the notification');
830 831 832 833 834 835 836
        $_paymentCode = $this->_paymentMethodCode();

        switch ($this->_eventCode) {
            case Notification::REFUND_FAILED:
                // do nothing only inform the merchant with order comment history
                break;
            case Notification::REFUND:
837
                $ignoreRefundNotification = $this->_getConfigData(
838 839 840
                    'ignore_refund_notification',
                    'adyen_abstract',
                    $this->_order->getStoreId()
841 842
                );
                if ($ignoreRefundNotification != true) {
rikterbeek's avatar
rikterbeek committed
843
                    $this->_refundOrder();
844
                    //refund completed
rikterbeek's avatar
rikterbeek committed
845
                    $this->_setRefundAuthorized();
846
                } else {
847 848 849
                    $this->_adyenLogger->addAdyenNotificationCronjob(
                        'Setting to ignore refund notification is enabled so ignore this notification'
                    );
850 851 852
                }
                break;
            case Notification::PENDING:
853
                if ($this->_getConfigData(
854 855 856 857
                    'send_email_bank_sepa_on_pending',
                    'adyen_abstract',
                    $this->_order->getStoreId()
                )
858
                ) {
859
                    // Check if payment is banktransfer or sepa if true then send out order confirmation email
rikterbeek's avatar
rikterbeek committed
860
                    $isBankTransfer = $this->_isBankTransfer();
861 862
                    if ($isBankTransfer || $this->_paymentMethod == 'sepadirectdebit') {
                        if (!$this->_order->getEmailSent()) {
863
                            $this->_sendOrderMail();
864
                        }
865 866 867 868 869
                    }
                }
                break;
            case Notification::HANDLED_EXTERNALLY:
            case Notification::AUTHORISATION:
870
                $this->_authorizePayment();
871 872 873 874 875
                break;
            case Notification::MANUAL_REVIEW_REJECT:
                // don't do anything it will send a CANCEL_OR_REFUND notification when this payment is captured
                break;
            case Notification::MANUAL_REVIEW_ACCEPT:
876 877 878 879
                /*
                 * only process this if you are on auto capture.
                 * On manual capture you will always get Capture or CancelOrRefund notification
                 */
880
                if ($this->_isAutoCapture()) {
881
                    $this->_setPaymentAuthorized(false);
882 883 884
                }
                break;
            case Notification::CAPTURE:
885 886 887 888 889 890 891
                /*
                 * 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()) {
                    $this->_setPaymentAuthorized(false, true);

892
                    /*
893
                     * Add invoice in the adyen_invoice table
894
                     */
895 896 897 898 899 900 901 902 903 904
                    $invoiceCollection = $this->_order->getInvoiceCollection();
                    foreach ($invoiceCollection as $invoice) {
                        if ($invoice->getTransactionId() == $this->_pspReference) {
                            $this->_adyenInvoiceFactory->create()
                                ->setInvoiceId($invoice->getEntityId())
                                ->setPspreference($this->_pspReference)
                                ->setOriginalReference($this->_originalReference)
                                ->setAcquirerReference($this->_acquirerReference)
                                ->save();
                            $this->_adyenLogger->addAdyenNotificationCronjob('Created invoice entry in the Adyen table');
905
                        }
906 907 908
                    }
                }
                break;
909
            case Notification::OFFER_CLOSED:
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
                $previousSuccess = $this->_order->getData('adyen_notification_event_code_success');

                // Order is already Authorised
                if (!empty($previousSuccess)) {
                    $this->_adyenLogger->addAdyenNotificationCronjob("Order is already authorised, skipping OFFER_CLOSED");
                    break;
                }

                /*
                 * For cards, it can be 'visa', 'maestro',...
                 * For alternatives, it can be 'ideal', 'directEbanking',...
                 */
                $notificationPaymentMethod = $this->_paymentMethod;

                /*
                * For cards, it can be 'VI', 'MI',...
                * For alternatives, it can be 'ideal', 'directEbanking',...
                */
                $orderPaymentMethod = $this->_order->getPayment()->getCcType();

                $isOrderCc = strcmp($this->_paymentMethodCode(),
                        'adyen_cc') == 0 || strcmp($this->_paymentMethodCode(), 'adyen_oneclick') == 0;

                /*
                 * If the order was made with an Alternative payment method,
                 * continue with the cancellation only if the payment method of
                 * the notification matches the payment method of the order.
                 */
                if (!$isOrderCc && strcmp($notificationPaymentMethod, $orderPaymentMethod) !== 0) {
                    $this->_adyenLogger->addAdyenNotificationCronjob("Order is not a credit card, 
                    or the payment method in the notification does not match the payment method of the order, 
                    skipping OFFER_CLOSED");
                    break;
                }

945
                if (!$this->_order->canCancel()) {
946 947 948 949 950
                    // Move the order from PAYMENT_REVIEW to NEW, so that can be cancelled
                    $this->_order->setState(\Magento\Sales\Model\Order::STATE_NEW);
                }
                $this->_holdCancelOrder(true);
                break;
951 952 953 954 955 956
            case Notification::CAPTURE_FAILED:
            case Notification::CANCELLATION:
            case Notification::CANCELLED:
                $this->_holdCancelOrder(true);
                break;
            case Notification::CANCEL_OR_REFUND:
957 958
                if (isset($this->_modificationResult) && $this->_modificationResult != "") {
                    if ($this->_modificationResult == "cancel") {
959
                        $this->_holdCancelOrder(true);
960
                    } elseif ($this->_modificationResult == "refund") {
rikterbeek's avatar
rikterbeek committed
961
                        $this->_refundOrder();
962
                        //refund completed
rikterbeek's avatar
rikterbeek committed
963
                        $this->_setRefundAuthorized();
964 965
                    }
                } else {
966
                    if ($this->_order->isCanceled() ||
967 968
                        $this->_order->getState() === \Magento\Sales\Model\Order::STATE_HOLDED
                    ) {
969 970 971
                        $this->_adyenLogger->addAdyenNotificationCronjob(
                            'Order is already cancelled or holded so do nothing'
                        );
972
                    } else {
973 974 975 976 977 978 979 980 981 982
                        if ($this->_order->canCancel() || $this->_order->canHold()) {
                            $this->_adyenLogger->addAdyenNotificationCronjob('try to cancel the order');
                            $this->_holdCancelOrder(true);
                        } else {
                            $this->_adyenLogger->addAdyenNotificationCronjob('try to refund the order');
                            // refund
                            $this->_refundOrder();
                            //refund completed
                            $this->_setRefundAuthorized();
                        }
983 984 985
                    }
                }
                break;
986

987
            case Notification::RECURRING_CONTRACT:
988 989


990 991 992 993
                // only store billing agreements if Vault is disabled
                if (!$this->_adyenHelper->isCreditCardVaultEnabled()) {
                    // storedReferenceCode
                    $recurringDetailReference = $this->_pspReference;
994

995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
                    $storeId = $this->_order->getStoreId();
                    $customerReference = $this->_order->getCustomerId();
                    $listRecurringContracts = null;
                    $this->_adyenLogger->addAdyenNotificationCronjob(
                        __(
                            'CustomerReference is: %1 and storeId is %2 and RecurringDetailsReference is %3',
                            $customerReference,
                            $storeId,
                            $recurringDetailReference
                        )
                    );
                    try {
                        $listRecurringContracts = $this->_adyenPaymentRequest->getRecurringContractsForShopper(
                            $customerReference,
                            $storeId
1010
                        );
1011 1012 1013
                        $contractDetail = null;
                        // get current Contract details and get list of all current ones
                        $recurringReferencesList = [];
1014

1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
                        if (!$listRecurringContracts) {
                            throw new \Exception("Empty list recurring contracts");
                        }
                        // Find the reference on the list
                        foreach ($listRecurringContracts as $rc) {
                            $recurringReferencesList[] = $rc['recurringDetailReference'];
                            if (isset($rc['recurringDetailReference']) &&
                                $rc['recurringDetailReference'] == $recurringDetailReference
                            ) {
                                $contractDetail = $rc;
                            }
                        }
1027

1028 1029 1030 1031 1032
                        if ($contractDetail == null) {
                            $this->_adyenLogger->addAdyenNotificationCronjob(print_r($listRecurringContracts, 1));
                            $message = __(
                                'Failed to create billing agreement for this order ' .
                                '(listRecurringCall did not contain contract)'
1033
                            );
1034
                            throw new \Exception($message);
1035 1036
                        }

1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
                        $billingAgreements = $this->_billingAgreementCollectionFactory->create();
                        $billingAgreements->addFieldToFilter('customer_id', $customerReference);

                        // Get collection and update existing agreements

                        foreach ($billingAgreements as $updateBillingAgreement) {
                            if (!in_array($updateBillingAgreement->getReferenceId(), $recurringReferencesList)) {
                                $updateBillingAgreement->setStatus(
                                    \Adyen\Payment\Model\Billing\Agreement::STATUS_CANCELED
                                );
                            } else {
                                $updateBillingAgreement->setStatus(
                                    \Adyen\Payment\Model\Billing\Agreement::STATUS_ACTIVE
                                );
                            }
                            $updateBillingAgreement->save();
                        }
1054

1055
                        // Get or create billing agreement
1056
                        $billingAgreement = $this->_billingAgreementFactory->create();
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
                        $billingAgreement->load($recurringDetailReference, 'reference_id');
                        // check if BA exists
                        if (!($billingAgreement && $billingAgreement->getAgreementId() > 0 && $billingAgreement->isValid())) {
                            // create new
                            $this->_adyenLogger->addAdyenNotificationCronjob("Creating new Billing Agreement");
                            $this->_order->getPayment()->setBillingAgreementData(
                                [
                                    'billing_agreement_id' => $recurringDetailReference,
                                    'method_code' => $this->_order->getPayment()->getMethodCode(),
                                ]
                            );

                            $billingAgreement = $this->_billingAgreementFactory->create();
                            $billingAgreement->setStoreId($this->_order->getStoreId());
                            $billingAgreement->importOrderPayment($this->_order->getPayment());
                            $message = __('Created billing agreement #%1.', $recurringDetailReference);
                        } else {
                            $this->_adyenLogger->addAdyenNotificationCronjob("Using existing Billing Agreement");
                            $billingAgreement->setIsObjectChanged(true);
                            $message = __('Updated billing agreement #%1.', $recurringDetailReference);
                        }
1078

1079 1080 1081
                        // Populate billing agreement data
                        $billingAgreement->parseRecurringContractData($contractDetail);
                        if ($billingAgreement->isValid()) {
1082

1083 1084
                            if (!$this->agreementResourceModel->getOrderRelation($billingAgreement->getAgreementId(),
                                $this->_order->getId())) {
1085

1086 1087
                                // save into sales_billing_agreement_order
                                $billingAgreement->addOrderRelation($this->_order);
1088

1089 1090 1091 1092 1093 1094
                                // add to order to save agreement
                                $this->_order->addRelatedObject($billingAgreement);
                            }
                        } else {
                            $message = __('Failed to create billing agreement for this order.');
                            throw new \Exception($message);
1095
                        }
1096 1097
                    } catch (\Exception $exception) {
                        $message = $exception->getMessage();
1098
                    }
1099

1100 1101 1102 1103 1104 1105
                    $this->_adyenLogger->addAdyenNotificationCronjob($message);
                    $comment = $this->_order->addStatusHistoryComment($message);
                    $this->_order->addRelatedObject($comment);
                } else {
                    $this->_adyenLogger->addAdyenNotificationCronjob('Ignore recurring_contract notification because Vault feature is enabled');
                }
1106
                break;
1107
            default:
1108 1109 1110
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    sprintf('This notification event: %s is not supported so will be ignored', $this->_eventCode)
                );
1111 1112 1113 1114
                break;
        }
    }

rikterbeek's avatar
rikterbeek committed
1115 1116 1117 1118 1119 1120
    /**
     * Not implemented
     * @return bool
     */
    protected function _refundOrder()
    {
1121 1122
        $this->_adyenLogger->addAdyenNotificationCronjob('Refunding the order');

1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
        // check if it is a split payment if so save the refunded data
        if ($this->_originalReference != "") {
            $this->_adyenLogger->addAdyenNotificationCronjob('Going to update the refund to split payments table');

            $orderPayment = $this->_adyenOrderPaymentCollectionFactory
                ->create()
                ->addFieldToFilter(\Adyen\Payment\Model\Notification::PSPREFRENCE, $this->_originalReference)
                ->getFirstItem();

            if ($orderPayment->getId() > 0) {
                $currency = $this->_order->getOrderCurrencyCode();
1134
                $amountRefunded = $amountRefunded = $orderPayment->getTotalRefunded() +
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
                    $this->_adyenHelper->originalAmount($this->_value, $currency);
                $orderPayment->setUpdatedAt(new \DateTime());
                $orderPayment->setTotalRefunded($amountRefunded);
                $orderPayment->save();
                $this->_adyenLogger->addAdyenNotificationCronjob('Update the refund in the split payments table');
            } else {
                $this->_adyenLogger->addAdyenNotificationCronjob('Payment not found in split payment table');
            }
        }

1145 1146 1147 1148
        /*
         * Don't create a credit memo if refund is initialize in Magento
         * because in this case the credit memo already exists
         */
1149
        $lastTransactionId = $this->_order->getPayment()->getLastTransId();
1150
        if ($lastTransactionId != $this->_pspReference) {
1151
            // refund is done through adyen backoffice so create a credit memo
1152 1153
            $order = $this->_order;
            if ($order->canCreditmemo()) {
1154 1155 1156
                $currency = $this->_order->getOrderCurrencyCode();
                $amount = $this->_adyenHelper->originalAmount($this->_value, $currency);
                $order->getPayment()->registerRefundNotification($amount);
1157

1158
                $this->_adyenLogger->addAdyenNotificationCronjob('Created credit memo for order');
1159 1160 1161 1162
            } else {
                $this->_adyenLogger->addAdyenNotificationCronjob('Could not create a credit memo for order');
            }
        } else {
1163
            $this->_adyenLogger->addAdyenNotificationCronjob(
1164
                'Did not create a credit memo for this order because refund is done through Magento'
1165
            );
1166
        }
rikterbeek's avatar
rikterbeek committed
1167 1168 1169 1170 1171 1172 1173
    }

    /**
     * @param $order
     */
    protected function _setRefundAuthorized()
    {
1174 1175 1176
        $this->_adyenLogger->addAdyenNotificationCronjob(
            'Status update to default status or refund_authorized status if this is set'
        );
rikterbeek's avatar
rikterbeek committed
1177 1178 1179
        $this->_order->addStatusHistoryComment(__('Adyen Refund Successfully completed'));
    }

1180
    /**
1181
     * authorize payment
1182 1183 1184
     */
    protected function _authorizePayment()
    {
1185
        $this->_adyenLogger->addAdyenNotificationCronjob('Authorisation of the order');
1186 1187 1188 1189 1190

        // Set adyen_notification_event_code_success to true so that we ignore a possible OFFER_CLOSED
        if (strcmp($this->_success, 'true') == 0) {
            $this->_order->setData('adyen_notification_event_code_success', 1);
        }
1191 1192
        $fraudManualReviewStatus = $this->_getFraudManualReviewStatus();

1193
        // If manual review is active and a separate status is used then ignore the pre authorized status
1194
        if ($this->_fraudManualReview != true || $fraudManualReviewStatus == "") {
1195 1196
            $this->_setPrePaymentAuthorized();
        } else {
1197 1198 1199 1200
            $this->_adyenLogger->addAdyenNotificationCronjob(
                'Ignore the pre authorized status because the order is ' .
                'under manual review and use the Manual review status'
            );
1201 1202 1203 1204 1205 1206
        }

        $this->_prepareInvoice();
        $_paymentCode = $this->_paymentMethodCode();

        // for boleto confirmation mail is send on order creation
1207
        if ($this->_paymentMethod != "adyen_boleto") {
1208
            // send order confirmation mail after invoice creation so merchant can add invoicePDF to this mail
1209
            if (!$this->_order->getEmailSent()) {
1210
                $this->_sendOrderMail();
1211
            }
1212 1213
        }

1214 1215
        if ($this->_paymentMethod == "c_cash" &&
            $this->_getConfigData('create_shipment', 'adyen_cash', $this->_order->getStoreId())
1216
        ) {
rikterbeek's avatar
rikterbeek committed
1217
            $this->_createShipment();
1218 1219 1220
        }
    }

1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
    /**
     * Send order Mail
     *
     * @return void
     */
    private function _sendOrderMail()
    {
        try {
            $this->_orderSender->send($this->_order);
            $this->_adyenLogger->addAdyenNotificationCronjob('Send orderconfirmation email to shopper');
1231
        } catch (\Exception $exception) {
1232 1233 1234 1235 1236 1237 1238
            $this->_adyenLogger->addAdyenNotificationCronjob(
                "Exception in Send Mail in Magento. This is an issue in the the core of Magento" .
                $exception->getMessage()
            );
        }
    }

1239 1240
    /**
     * Set status on authorisation
1241 1242
     *
     * @return void
1243
     */
1244 1245
    private function _setPrePaymentAuthorized()
    {
1246
        $status = $this->_getConfigData(
1247 1248 1249
            'payment_pre_authorized',
            'adyen_abstract',
            $this->_order->getStoreId()
1250
        );
1251 1252

        // only do this if status in configuration is set
1253
        if (!empty($status)) {
rikterbeek's avatar
rikterbeek committed
1254
            $this->_order->addStatusHistoryComment(__('Payment is authorised waiting for capture'), $status);
Bas Maassen's avatar
Bas Maassen committed
1255 1256
            $this->_setState($status);

1257 1258 1259
            $this->_adyenLogger->addAdyenNotificationCronjob(
                'Order status is changed to Pre-authorised status, status is ' . $status
            );
1260
        } else {
1261
            $this->_adyenLogger->addAdyenNotificationCronjob('No pre-authorised status is used so ignore');
1262 1263 1264 1265
        }
    }

    /**
1266
     * @throws Exception
1267
     * @return void
1268 1269 1270
     */
    protected function _prepareInvoice()
    {
1271
        $this->_adyenLogger->addAdyenNotificationCronjob('Prepare invoice for order');
1272 1273 1274 1275 1276

        //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) {
            $this->_order->setState(\Magento\Sales\Model\Order::STATE_NEW);
        }
1277

1278 1279 1280 1281 1282 1283 1284 1285 1286
        $paymentObj = $this->_order->getPayment();

        // set pspReference as transactionId
        $paymentObj->setCcTransId($this->_pspReference);
        $paymentObj->setLastTransId($this->_pspReference);

        // set transaction
        $paymentObj->setTransactionId($this->_pspReference);

1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
        // Prepare transaction
        $transaction = $this->transactionBuilder->setPayment($paymentObj)
            ->setOrder($this->_order)
            ->setTransactionId($this->_pspReference)
            ->build(\Magento\Sales\Api\Data\TransactionInterface::TYPE_AUTH);

        $transaction->setIsClosed(false);

        $transaction->save();

1297 1298 1299
        //capture mode
        if (!$this->_isAutoCapture()) {
            $this->_order->addStatusHistoryComment(__('Capture Mode set to Manual'));
1300
            $this->_adyenLogger->addAdyenNotificationCronjob('Capture mode is set to Manual');
1301 1302

            // show message if order is in manual review
1303
            if ($this->_fraudManualReview) {
1304 1305
                // check if different status is selected
                $fraudManualReviewStatus = $this->_getFraudManualReviewStatus();
1306
                if ($fraudManualReviewStatus != "") {
1307 1308 1309 1310 1311 1312
                    $status = $fraudManualReviewStatus;
                    $comment = "Adyen Payment is in Manual Review check the Adyen platform";
                    $this->_order->addStatusHistoryComment(__($comment), $status);
                }
            }

1313
            $createPendingInvoice = (bool)$this->_getConfigData(
1314 1315 1316
                'create_pending_invoice',
                'adyen_abstract',
                $this->_order->getStoreId()
1317 1318 1319 1320 1321 1322
            );

            if (!$createPendingInvoice) {
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'Setting pending invoice is off so don\'t create an invoice wait for the capture notification'
                );
1323 1324 1325 1326 1327 1328
                return;
            }
        }

        // validate if amount is total amount
        $orderCurrencyCode = $this->_order->getOrderCurrencyCode();
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
        $amount = $this->_adyenHelper->originalAmount($this->_value, $orderCurrencyCode);

        // add to order payment
        $date = new \DateTime();
        $this->_adyenOrderPaymentFactory->create()
            ->setPspreference($this->_pspReference)
            ->setMerchantReference($this->_merchantReference)
            ->setPaymentId($paymentObj->getId())
            ->setPaymentMethod($this->_paymentMethod)
            ->setAmount($amount)
            ->setTotalRefunded(0)
            ->setCreatedAt($date)
            ->setUpdatedAt($date)
            ->save();


        if ($this->_isTotalAmount($paymentObj->getEntityId(), $orderCurrencyCode)) {
1346
            $this->_createInvoice();
1347
        } else {
1348 1349 1350
            $this->_adyenLogger->addAdyenNotificationCronjob(
                'This is a partial AUTHORISATION and the full amount is not reached'
            );
1351 1352 1353 1354 1355 1356 1357 1358
        }
    }

    /**
     * @return bool
     */
    protected function _isAutoCapture()
    {
Alessio Zampatti's avatar
Alessio Zampatti committed
1359
        // validate if payment methods allows manual capture
1360
        if ($this->_manualCaptureAllowed()) {
1361
            $captureMode = trim($this->_getConfigData(
1362 1363 1364 1365
                'capture_mode',
                'adyen_abstract',
                $this->_order->getStoreId()
            ));
1366
            $sepaFlow = trim($this->_getConfigData(
1367 1368 1369 1370
                'sepa_flow',
                'adyen_abstract',
                $this->_order->getStoreId()
            ));
1371
            $_paymentCode = $this->_paymentMethodCode();
1372
            $captureModeOpenInvoice = $this->_getConfigData(
1373 1374 1375
                'auto_capture_openinvoice',
                'adyen_abstract',
                $this->_order->getStoreId()
1376
            );
1377
            $manualCapturePayPal = trim($this->_getConfigData(
1378 1379 1380 1381
                'paypal_capture_mode',
                'adyen_abstract',
                $this->_order->getStoreId()
            ));
1382 1383 1384 1385 1386

            /*
             * if you are using authcap the payment method is manual.
             * There will be a capture send to indicate if payment is successful
             */
1387
            if ($this->_paymentMethod == "sepadirectdebit" && $sepaFlow == "authcap") {
1388 1389 1390
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'Manual Capture is applied for sepa because it is in authcap flow'
                );
1391 1392
                return false;
            }
1393

1394
            // payment method ideal, cash adyen_boleto has direct capture
1395
            if ($this->_paymentMethod == "sepadirectdebit" && $sepaFlow != "authcap") {
1396 1397
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'This payment method does not allow manual capture.(2) paymentCode:' .
1398
                    $_paymentCode . ' paymentMethod:' . $this->_paymentMethod . ' sepaFLow:' . $sepaFlow
1399
                );
1400 1401
                return true;
            }
1402

1403
            if ($_paymentCode == "adyen_pos_cloud") {
1404 1405
                $captureModePos = $this->_adyenHelper->getAdyenPosCloudConfigData('capture_mode_pos',
                    $this->_order->getStoreId());
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
                if (strcmp($captureModePos, 'auto') === 0) {
                    $this->_adyenLogger->addAdyenNotificationCronjob(
                        'This payment method is POS Cloud and configured to be working as auto capture '
                    );
                    return true;
                } elseif (strcmp($captureModePos, 'manual') === 0) {
                    $this->_adyenLogger->addAdyenNotificationCronjob(
                        'This payment method is POS Cloud and configured to be working as manual capture '
                    );
                    return false;
                }
            }

1419
            // if auto capture mode for openinvoice is turned on then use auto capture
1420
            if ($captureModeOpenInvoice == true &&
1421 1422
                $this->_adyenHelper->isPaymentMethodOpenInvoiceMethod($this->_paymentMethod)
            ) {
1423 1424 1425
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'This payment method is configured to be working as auto capture '
                );
1426
                return true;
1427
            }
1428

1429
            // if PayPal capture modues is different from the default use this one
1430 1431
            if (strcmp($this->_paymentMethod, 'paypal') === 0) {
                if ($manualCapturePayPal) {
1432 1433 1434
                    $this->_adyenLogger->addAdyenNotificationCronjob(
                        'This payment method is paypal and configured to work as manual capture'
                    );
1435
                    return false;
1436 1437 1438 1439 1440
                } else {
                    $this->_adyenLogger->addAdyenNotificationCronjob(
                        'This payment method is paypal and configured to work as auto capture'
                    );
                    return true;
1441 1442 1443
                }
            }
            if (strcmp($captureMode, 'manual') === 0) {
1444
                $this->_adyenLogger->addAdyenNotificationCronjob('Capture mode for this payment is set to manual');
1445 1446
                return false;
            }
1447 1448 1449 1450 1451

            /*
             * online capture after delivery, use Magento backend to online invoice
             * (if the option auto capture mode for openinvoice is not set)
             */
1452
            if ($this->_adyenHelper->isPaymentMethodOpenInvoiceMethod($this->_paymentMethod)) {
1453
                $this->_adyenLogger->addAdyenNotificationCronjob('Capture mode for klarna is by default set to manual');
1454 1455
                return false;
            }
1456 1457

            $this->_adyenLogger->addAdyenNotificationCronjob('Capture mode is set to auto capture');
1458 1459 1460
            return true;
        } else {
            // does not allow manual capture so is always immediate capture
1461
            $this->_adyenLogger->addAdyenNotificationCronjob('This payment method does not allow manual capture');
1462
            return true;
1463
        }
1464 1465 1466 1467 1468
    }

    /**
     * Validate if this payment methods allows manual capture
     * This is a default can be forced differently to overrule on acquirer level
1469 1470
     *
     * @return bool|null
1471 1472 1473 1474 1475 1476
     */
    protected function _manualCaptureAllowed()
    {
        $manualCaptureAllowed = null;
        $paymentMethod = $this->_paymentMethod;

Rik ter Beek's avatar
Rik ter Beek committed
1477 1478 1479 1480 1481
        // For all openinvoice methods manual capture is the default
        if ($this->_adyenHelper->isPaymentMethodOpenInvoiceMethod($paymentMethod)) {
            return true;
        }

1482
        switch ($paymentMethod) {
1483 1484 1485
            case 'cup':
            case 'cartebancaire':
            case 'visa':
1486
            case 'visadankort':
1487 1488 1489 1490
            case 'mc':
            case 'uatp':
            case 'amex':
            case 'maestro':
rikterbeek's avatar
rikterbeek committed
1491
            case 'maestrouk':
1492 1493 1494 1495 1496 1497
            case 'diners':
            case 'discover':
            case 'jcb':
            case 'laser':
            case 'paypal':
            case 'sepadirectdebit':
1498 1499 1500
            case 'dankort':
            case 'elo':
            case 'hipercard':
1501 1502 1503 1504
                $manualCaptureAllowed = true;
                break;
            default:
                $manualCaptureAllowed = false;
1505
        }
1506 1507

        return $manualCaptureAllowed;
1508 1509 1510 1511 1512
    }

    /**
     * @return bool
     */
1513 1514
    protected function _isBankTransfer()
    {
1515
        if (strlen($this->_paymentMethod) >= 12 && substr($this->_paymentMethod, 0, 12) == "bankTransfer") {
1516 1517 1518 1519 1520 1521 1522
            $isBankTransfer = true;
        } else {
            $isBankTransfer = false;
        }
        return $isBankTransfer;
    }

1523 1524 1525
    /**
     * @return mixed
     */
1526 1527
    protected function _getFraudManualReviewStatus()
    {
1528
        return $this->_getConfigData(
1529 1530 1531
            'fraud_manual_review_status',
            'adyen_abstract',
            $this->_order->getStoreId()
1532
        );
1533 1534
    }

1535 1536 1537
    /**
     * @return mixed
     */
1538 1539
    protected function _getFraudManualReviewAcceptStatus()
    {
1540
        return $this->_getConfigData(
1541 1542 1543
            'fraud_manual_review_accept_status',
            'adyen_abstract',
            $this->_order->getStoreId()
1544
        );
1545 1546
    }

1547
    /**
1548 1549
     * @param int $paymentId
     * @param string $orderCurrencyCode
1550 1551
     * @return bool
     */
1552
    protected function _isTotalAmount($paymentId, $orderCurrencyCode)
1553 1554 1555 1556
    {
        $this->_adyenLogger->addAdyenNotificationCronjob(
            'Validate if AUTHORISATION notification has the total amount of the order'
        );
1557

1558
        // get total amount of the order
1559
        $grandTotal = (int)$this->_adyenHelper->formatAmount($this->_order->getGrandTotal(), $orderCurrencyCode);
1560 1561 1562 1563 1564

        // check if total amount of the order is authorised
        $res = $this->_adyenOrderPaymentCollectionFactory
            ->create()
            ->getTotalAmount($paymentId);
1565

1566
        if ($res && isset($res[0]) && is_array($res[0])) {
1567 1568
            $amount = $res[0]['total_amount'];
            $orderAmount = $this->_adyenHelper->formatAmount($amount, $orderCurrencyCode);
1569
            $this->_adyenLogger->addAdyenNotificationCronjob(
1570 1571
                sprintf(
                    'The grandtotal amount is %s and the total order amount that is authorised is: %s',
1572 1573 1574 1575
                    $grandTotal,
                    $orderAmount
                )
            );
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585

            if ($grandTotal == $orderAmount) {
                $this->_adyenLogger->addAdyenNotificationCronjob('AUTHORISATION has the full amount');
                return true;
            } else {
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'This is a partial AUTHORISATION, the amount is ' . $this->_value
                );
                return false;
            }
1586
        }
1587
        return false;
1588 1589
    }

1590 1591 1592
    /**
     * @throws Exception
     * @throws \Magento\Framework\Exception\LocalizedException
1593
     * @return void
1594
     */
1595 1596
    protected function _createInvoice()
    {
1597
        $this->_adyenLogger->addAdyenNotificationCronjob('Creating invoice for order');
1598 1599

        if ($this->_order->canInvoice()) {
1600 1601
            /* We do not use this inside a transaction because order->save()
             * is always done on the end of the notification
1602 1603 1604 1605 1606 1607 1608
             * and it could result in a deadlock see https://github.com/Adyen/magento/issues/334
             */
            try {
                $invoice = $this->_order->prepareInvoice();
                $invoice->getOrder()->setIsInProcess(true);

                // set transaction id so you can do a online refund from credit memo
1609
                $invoice->setTransactionId($this->_pspReference);
1610

1611

1612
                $autoCapture = $this->_isAutoCapture();
1613
                $createPendingInvoice = (bool)$this->_getConfigData(
1614 1615 1616
                    'create_pending_invoice',
                    'adyen_abstract',
                    $this->_order->getStoreId()
1617
                );
1618

1619
                if ((!$autoCapture) && ($createPendingInvoice)) {
1620 1621
                    // if amount is zero create a offline invoice
                    $value = (int)$this->_value;
1622
                    if ($value == 0) {
rikterbeek's avatar
rikterbeek committed
1623
                        $invoice->setRequestedCaptureCase(\Magento\Sales\Model\Order\Invoice::CAPTURE_OFFLINE);
1624
                    } else {
rikterbeek's avatar
rikterbeek committed
1625
                        $invoice->setRequestedCaptureCase(\Magento\Sales\Model\Order\Invoice::NOT_CAPTURE);
1626 1627 1628 1629 1630 1631 1632 1633
                    }

                    $invoice->register();
                } else {
                    $invoice->register()->pay();
                }

                $invoice->save();
1634
                $this->_adyenLogger->addAdyenNotificationCronjob('Created invoice');
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646

                /*
                 * Add invoice in the adyen_invoice table
                 */
                $this->_adyenInvoiceFactory->create()
                    ->setInvoiceId($invoice->getEntityId())
                    ->setPspreference($this->_pspReference)
                    ->setOriginalReference($this->_pspReference)
                    ->setAcquirerReference($this->_acquirerReference)
                    ->save();

                $this->_adyenLogger->addAdyenNotificationCronjob('Created invoice entry in the Adyen table');
1647
            } catch (Exception $e) {
1648 1649 1650
                $this->_adyenLogger->addAdyenNotificationCronjob(
                    'Error saving invoice. The error message is: ' . $e->getMessage()
                );
1651 1652 1653 1654 1655
                throw new Exception(sprintf('Error saving invoice. The error message is:', $e->getMessage()));
            }

            $this->_setPaymentAuthorized();

1656 1657 1658 1659
            $invoiceAutoMail = (bool)$this->_scopeConfig->isSetFlag(
                \Magento\Sales\Model\Order\Email\Container\InvoiceIdentity::XML_PATH_EMAIL_ENABLED,
                \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
                $this->_order->getStoreId()
1660 1661
            );

1662
            if ($invoiceAutoMail) {
1663
                $this->_invoiceSender->send($invoice);
1664 1665
            }
        } else {
1666
            $this->_adyenLogger->addAdyenNotificationCronjob('It is not possible to create invoice for this order');
1667 1668 1669 1670
        }
    }

    /**
1671 1672 1673
     * @param bool $manualReviewComment
     * @param bool $createInvoice
     * @throws Exception
1674 1675 1676
     */
    protected function _setPaymentAuthorized($manualReviewComment = true, $createInvoice = false)
    {
1677
        $this->_adyenLogger->addAdyenNotificationCronjob('Set order to authorised');
1678 1679 1680 1681

        // if full amount is captured create invoice
        $currency = $this->_order->getOrderCurrencyCode();
        $amount = $this->_value;
1682
        $orderAmount = (int)$this->_adyenHelper->formatAmount($this->_order->getGrandTotal(), $currency);
1683 1684

        // create invoice for the capture notification if you are on manual capture
1685 1686
        if ($createInvoice == true && $amount == $orderAmount) {
            $this->_adyenLogger->addAdyenNotificationCronjob(
1687
                'amount notification:' . $amount . ' amount order:' . $orderAmount
1688
            );
rikterbeek's avatar
rikterbeek committed
1689
            $this->_createInvoice();
1690
        }
1691

1692
        $status = $this->_getConfigData(
1693 1694 1695
            'payment_authorized',
            'adyen_abstract',
            $this->_order->getStoreId()
1696
        );
1697 1698

        // virtual order can have different status
1699
        if ($this->_order->getIsVirtual()) {
1700
            $this->_adyenLogger->addAdyenNotificationCronjob('Product is a virtual product');
1701
            $virtualStatus = $this->_getConfigData(
1702 1703 1704
                'payment_authorized_virtual',
                'adyen_abstract',
                $this->_order->getStoreId()
1705
            );
1706 1707
            if ($virtualStatus != "") {
                $status = $virtualStatus;
1708 1709 1710 1711
            }
        }

        // check for boleto if payment is totally paid
1712
        if ($this->_paymentMethodCode() == "adyen_boleto") {
1713 1714 1715 1716
            // check if paid amount is the same as orginal amount
            $orginalAmount = $this->_boletoOriginalAmount;
            $paidAmount = $this->_boletoPaidAmount;

1717
            if ($orginalAmount != $paidAmount) {
1718 1719
                // not the full amount is paid. Check if it is underpaid or overpaid
                // strip the  BRL of the string
1720
                $orginalAmount = str_replace("BRL", "", $orginalAmount);
1721 1722
                $orginalAmount = floatval(trim($orginalAmount));

1723
                $paidAmount = str_replace("BRL", "", $paidAmount);
1724 1725
                $paidAmount = floatval(trim($paidAmount));

1726
                if ($paidAmount > $orginalAmount) {
1727
                    $overpaidStatus = $this->_getConfigData(
1728 1729 1730
                        'order_overpaid_status',
                        'adyen_boleto',
                        $this->_order->getStoreId()
1731
                    );
1732 1733 1734
                    // check if there is selected a status if not fall back to the default
                    $status = (!empty($overpaidStatus)) ? $overpaidStatus : $status;
                } else {
1735
                    $underpaidStatus = $this->_getConfigData(
1736 1737 1738
                        'order_underpaid_status',
                        'adyen_boleto',
                        $this->_order->getStoreId()
1739
                    );
1740 1741 1742 1743 1744 1745 1746 1747 1748
                    // check if there is selected a status if not fall back to the default
                    $status = (!empty($underpaidStatus)) ? $underpaidStatus : $status;
                }
            }
        }

        $comment = "Adyen Payment Successfully completed";

        // if manual review is true use the manual review status if this is set
1749
        if ($manualReviewComment == true && $this->_fraudManualReview) {
1750 1751
            // check if different status is selected
            $fraudManualReviewStatus = $this->_getFraudManualReviewStatus();
1752
            if ($fraudManualReviewStatus != "") {
1753 1754 1755 1756 1757 1758
                $status = $fraudManualReviewStatus;
                $comment = "Adyen Payment is in Manual Review check the Adyen platform";
            }
        }
        $status = (!empty($status)) ? $status : $this->_order->getStatus();
        $this->_order->addStatusHistoryComment(__($comment), $status);
Bas Maassen's avatar
Bas Maassen committed
1759 1760
        $this->_setState($status);

1761 1762 1763
        $this->_adyenLogger->addAdyenNotificationCronjob(
            'Order status is changed to authorised status, status is ' . $status
        );
1764 1765
    }

Bas Maassen's avatar
Bas Maassen committed
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
    /**
     * Set State from Status
     */

    protected function _setState($status)
    {
        $statusObject = $this->_orderStatusCollection->create()
            ->addFieldToFilter('main_table.status', $status)
            ->addFieldToFilter('state_table.is_default', true)
            ->joinStates()
            ->getFirstItem();

        $this->_order->setState($statusObject->getState());
        $this->_adyenLogger->addAdyenNotificationCronjob('State is changed to  ' . $statusObject->getState());
    }
1781

rikterbeek's avatar
rikterbeek committed
1782
    /**
1783
     * Create shipment
rikterbeek's avatar
rikterbeek committed
1784
     *
1785
     * @throws bool
rikterbeek's avatar
rikterbeek committed
1786
     */
1787 1788
    protected function _createShipment()
    {
1789
        $this->_adyenLogger->addAdyenNotificationCronjob('Creating shipment for order');
rikterbeek's avatar
rikterbeek committed
1790 1791
        // create shipment for cash payment
        $payment = $this->_order->getPayment()->getMethodInstance();
1792 1793
        if ($this->_order->canShip()) {
            $itemQty = [];
rikterbeek's avatar
rikterbeek committed
1794
            $shipment = $this->_order->prepareShipment($itemQty);
1795
            if ($shipment) {
rikterbeek's avatar
rikterbeek committed
1796 1797 1798 1799
                $shipment->register();
                $shipment->getOrder()->setIsInProcess(true);
                $comment = __('Shipment created by Adyen');
                $shipment->addComment($comment);
rikterbeek's avatar
rikterbeek committed
1800 1801 1802 1803

                /** @var \Magento\Framework\DB\Transaction $transaction */
                $transaction = $this->_transactionFactory->create();
                $transaction->addObject($shipment)
rikterbeek's avatar
rikterbeek committed
1804 1805
                    ->addObject($shipment->getOrder())
                    ->save();
rikterbeek's avatar
rikterbeek committed
1806

1807
                $this->_adyenLogger->addAdyenNotificationCronjob('Order is shipped');
rikterbeek's avatar
rikterbeek committed
1808 1809
            }
        } else {
1810
            $this->_adyenLogger->addAdyenNotificationCronjob('Order can\'t be shipped');
rikterbeek's avatar
rikterbeek committed
1811 1812 1813
        }
    }

1814 1815 1816
    /**
     * Retrieve information from payment configuration
     *
1817 1818 1819
     * @param $field
     * @param string $paymentMethodCode
     * @param $storeId
1820 1821 1822 1823 1824 1825 1826
     * @return mixed
     */
    protected function _getConfigData($field, $paymentMethodCode = 'adyen_cc', $storeId)
    {
        $path = 'payment/' . $paymentMethodCode . '/' . $field;
        return $this->_scopeConfig->getValue($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
    }
1827
}