Completed
Push — master ( e76a9e...dfb6ec )
by
unknown
24s queued 12s
created

Index::checkMerchantOrderStatus()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Pagantis\Pagantis\Controller\Notify;
4
5
use Magento\Quote\Model\QuoteManagement;
6
use Magento\Quote\Api\Data\PaymentInterface;
7
use Magento\Sales\Api\Data\OrderInterface;
8
use Magento\Sales\Api\OrderRepositoryInterface;
9
use Magento\Quote\Model\Quote;
10
use Magento\Quote\Model\QuoteRepository;
11
use Magento\Framework\App\Action\Context;
12
use Magento\Framework\App\Action\Action;
13
use Pagantis\ModuleUtils\Exception\MerchantOrderNotFoundException;
14
use Pagantis\OrdersApiClient\Client;
15
use Pagantis\Pagantis\Helper\Config;
16
use Pagantis\Pagantis\Helper\ExtraConfig;
17
use Magento\Framework\App\ResourceConnection;
18
use Magento\Checkout\Model\Session;
19
use Magento\Framework\DB\Ddl\Table;
20
use Pagantis\ModuleUtils\Exception\AmountMismatchException;
21
use Pagantis\ModuleUtils\Exception\ConcurrencyException;
22
use Pagantis\ModuleUtils\Exception\NoIdentificationException;
23
use Pagantis\ModuleUtils\Exception\OrderNotFoundException;
24
use Pagantis\ModuleUtils\Exception\QuoteNotFoundException;
25
use Pagantis\ModuleUtils\Exception\UnknownException;
26
use Pagantis\ModuleUtils\Exception\WrongStatusException;
27
use Pagantis\ModuleUtils\Model\Response\JsonSuccessResponse;
28
use Pagantis\ModuleUtils\Model\Response\JsonExceptionResponse;
29
use Pagantis\ModuleUtils\Exception\AlreadyProcessedException;
30
use Pagantis\ModuleUtils\Model\Log\LogEntry;
31
32
/**
33
 * Class Index
34
 * @package Pagantis\Pagantis\Controller\Notify
35
 */
36
class Index extends Action
37
{
38
    /** Orders tablename */
39
    const ORDERS_TABLE = 'cart_process';
40
41
    /** Concurrency tablename */
42
    const CONCURRENCY_TABLE = 'Pagantis_orders';
43
44
    /** Concurrency tablename */
45
    const LOGS_TABLE = 'Pagantis_logs';
46
47
    /** Payment code */
48
    const PAYMENT_METHOD = 'pagantis';
49
50
    /** Seconds to expire a locked request */
51
    const CONCURRENCY_TIMEOUT = 10;
52
53
    /**
54
     * EXCEPTION RESPONSES
55
     */
56
    const CPO_ERR_MSG = 'Order not confirmed';
57
    const CPO_OK_MSG = 'Order confirmed';
58
59
    /** @var QuoteManagement */
60
    protected $quoteManagement;
61
62
    /** @var PaymentInterface $paymentInterface */
63
    protected $paymentInterface;
64
65
    /** @var OrderRepositoryInterface $orderRepositoryInterface */
66
    protected $orderRepositoryInterface;
67
68
    /** @var Quote $quote */
69
    protected $quote;
70
71
    /** @var QuoteRepository $quoteRepository */
72
    protected $quoteRepository;
73
74
    /** @var mixed $config */
75
    protected $config;
76
77
    /** @var mixed $quoteId */
78
    protected $quoteId;
79
80
    /** @var array $notifyResult */
81
    protected $notifyResult;
82
83
    /** @var mixed $magentoOrderId */
84
    protected $magentoOrderId;
85
86
    /** @var mixed $pagantisOrder */
87
    protected $pagantisOrder;
88
89
    /** @var ResourceConnection $dbObject */
90
    protected $dbObject;
91
92
    /** @var Session $checkoutSession */
93
    protected $checkoutSession;
94
95
    /** @var Client $orderClient */
96
    protected $orderClient;
97
98
    /** @var mixed $pagantisOrderId */
99
    protected $pagantisOrderId;
100
101
    /** @var  OrderInterface $magentoOrder */
102
    protected $magentoOrder;
103
104
    /** @var ExtraConfig $extraConfig */
105
    protected $extraConfig;
106
107
    /** @var mixed $origin */
108
    protected $origin;
109
110
    /**
111
     * Index constructor.
112
     *
113
     * @param Context                  $context
114
     * @param Quote                    $quote
115
     * @param QuoteManagement          $quoteManagement
116
     * @param PaymentInterface         $paymentInterface
117
     * @param Config                   $config
118
     * @param QuoteRepository          $quoteRepository
119
     * @param OrderRepositoryInterface $orderRepositoryInterface
120
     * @param ResourceConnection       $dbObject
121
     * @param Session                  $checkoutSession
122
     * @param ExtraConfig              $extraConfig
123
     */
124
    public function __construct(
125
        Context $context,
126
        Quote $quote,
127
        QuoteManagement $quoteManagement,
128
        PaymentInterface $paymentInterface,
129
        Config $config,
130
        QuoteRepository $quoteRepository,
131
        OrderRepositoryInterface $orderRepositoryInterface,
132
        ResourceConnection $dbObject,
133
        Session $checkoutSession,
134
        ExtraConfig $extraConfig
135
    ) {
136
        parent::__construct($context);
137
        $this->quote = $quote;
138
        $this->quoteManagement = $quoteManagement;
139
        $this->paymentInterface = $paymentInterface;
140
        $this->extraConfig = $extraConfig->getExtraConfig();
0 ignored issues
show
Documentation Bug introduced by
It seems like $extraConfig->getExtraConfig() of type array or array is incompatible with the declared type Pagantis\Pagantis\Helper\ExtraConfig of property $extraConfig.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
141
        $this->config = $config->getConfig();
142
        $this->quoteRepository = $quoteRepository;
143
        $this->orderRepositoryInterface = $orderRepositoryInterface;
144
        $this->dbObject = $dbObject;
145
        $this->checkoutSession = $checkoutSession;
146
        $this->origin = ($_SERVER['REQUEST_METHOD'] == 'POST') ? 'Notification' : 'Order';
147
    }
148
149
    /**
150
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|void
151
     * @throws UnknownException
152
     */
153
    public function execute()
154
    {
155
        try {
156
            $this->checkConcurrency();
157
            $this->getMerchantOrder();
158
            $this->getPagantisOrderId();
159
            $this->getPagantisOrder();
160
            $this->checkOrderStatus();
161
            $this->checkMerchantOrderStatus();
162
            $this->validateAmount();
163
            $this->processMerchantOrder();
164
        } catch (\Exception $exception) {
165
            $jsonResponse = new JsonExceptionResponse();
166
            $jsonResponse->setMerchantOrderId($this->magentoOrderId);
167
            $jsonResponse->setpagantisOrderId($this->pagantisOrderId);
168
            $jsonResponse->setException($exception);
169
            $response = $jsonResponse->toJson();
170
            $this->insertLog($exception);
171
        }
172
173
        try {
174
            if (!isset($response)) {
175
                $this->confirmpagantisOrder();
176
                $jsonResponse = new JsonSuccessResponse();
177
                $jsonResponse->setMerchantOrderId($this->magentoOrderId);
178
                $jsonResponse->setpagantisOrderId($this->pagantisOrderId);
179
            }
180
        } catch (\Exception $exception) {
181
            $this->rollbackMerchantOrder();
182
            $jsonResponse = new JsonExceptionResponse();
183
            $jsonResponse->setMerchantOrderId($this->magentoOrderId);
184
            $jsonResponse->setpagantisOrderId($this->pagantisOrderId);
185
            $jsonResponse->setException($exception);
186
            $jsonResponse->toJson();
187
            $this->insertLog($exception);
188
        }
189
190
        $this->unblockConcurrency(true);
191
192
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
193
            $jsonResponse->printResponse();
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $jsonResponse does not seem to be defined for all execution paths leading up to this point.
Loading history...
194
        } else {
195
            $returnUrl = $this->getRedirectUrl();
196
            $this->_redirect($returnUrl);
197
        }
198
    }
199
200
    /**
201
     * COMMON FUNCTIONS
202
     */
203
204
    /**
205
     * @throws ConcurrencyException
206
     * @throws QuoteNotFoundException
207
     * @throws UnknownException
208
     */
209
    private function checkConcurrency()
210
    {
211
        $this->getQuoteId();
212
        $this->checkDbTable();
213
        $this->unblockConcurrency();
214
        $this->blockConcurrency();
215
    }
216
217
    /**
218
     * @throws MerchantOrderNotFoundException
219
     */
220
    private function getMerchantOrder()
221
    {
222
        try {
223
            /** @var Quote quote */
224
            $this->quote = $this->quoteRepository->get($this->quoteId);
225
        } catch (\Exception $e) {
226
            throw new MerchantOrderNotFoundException();
227
        }
228
    }
229
230
    /**
231
     * @throws UnknownException
232
     */
233
    private function getPagantisOrderId()
234
    {
235
        try {
236
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
237
            $dbConnection     = $this->dbObject->getConnection();
238
            $tableName        = $this->dbObject->getTableName(self::ORDERS_TABLE);
239
            $query            = "select order_id from $tableName where id='$this->quoteId'";
240
            $queryResult      = $dbConnection->fetchRow($query);
241
            $this->pagantisOrderId = $queryResult['order_id'];
242
            if ($this->pagantisOrderId == '') {
243
                throw new NoIdentificationException();
244
            }
245
        } catch (\Exception $e) {
246
            throw new UnknownException($e->getMessage());
247
        }
248
    }
249
250
    /**
251
     * @throws OrderNotFoundException
252
     */
253
    private function getPagantisOrder()
254
    {
255
        try {
256
            $this->orderClient = new Client(
257
                $this->config['pagantis_public_key'],
258
                $this->config['pagantis_private_key']
259
            );
260
            $this->pagantisOrder = $this->orderClient->getOrder($this->pagantisOrderId);
261
        } catch (\Exception $e) {
262
            throw new OrderNotFoundException();
263
        }
264
    }
265
266
    /**
267
     * @throws AlreadyProcessedException
268
     * @throws WrongStatusException
269
     */
270
    private function checkOrderStatus()
271
    {
272
        try {
273
            $this->checkPagantisStatus(array('AUTHORIZED'));
274
        } catch (\Exception $e) {
275
            $this->getMagentoOrderId();
276
            if ($this->magentoOrderId!='') {
277
                throw new AlreadyProcessedException();
278
            } else {
279
                throw new WrongStatusException($this->pagantisOrder->getStatus());
280
            }
281
        }
282
    }
283
284
    /**
285
     * @throws AlreadyProcessedException
286
     */
287
    private function checkMerchantOrderStatus()
288
    {
289
        if ($this->quote->getIsActive()=='0') {
290
            $this->getMagentoOrderId();
291
            throw new AlreadyProcessedException();
292
        }
293
    }
294
295
    /**
296
     * @throws AmountMismatchException
297
     */
298
    private function validateAmount()
299
    {
300
        $pagantisAmount = $this->pagantisOrder->getShoppingCart()->getTotalAmount();
301
        $merchantAmount = intval(strval(100 * $this->quote->getGrandTotal()));
302
        if ($pagantisAmount != $merchantAmount) {
303
            throw new AmountMismatchException($pagantisAmount, $merchantAmount);
304
        }
305
    }
306
307
    /**
308
     * @throws UnknownException
309
     */
310
    private function processMerchantOrder()
311
    {
312
        try {
313
            $this->saveOrder();
314
            $this->updateBdInfo();
315
        } catch (\Exception $e) {
316
            throw new UnknownException($e->getMessage());
317
        }
318
    }
319
320
    /**
321
     * @return false|string
322
     * @throws UnknownException
323
     */
324
    private function confirmpagantisOrder()
325
    {
326
        try {
327
            $this->pagantisOrder = $this->orderClient->confirmOrder($this->pagantisOrderId);
328
        } catch (\Exception $e) {
329
            throw new UnknownException($e->getMessage());
330
        }
331
332
        $jsonResponse = new JsonSuccessResponse();
333
        $jsonResponse->setStatusCode(200);
334
        $jsonResponse->setMerchantOrderId($this->magentoOrderId);
335
        $jsonResponse->setpagantisOrderId($this->pagantisOrderId);
336
        $jsonResponse->setResult(self::CPO_OK_MSG);
337
        return $jsonResponse->toJson();
338
    }
339
340
    /**
341
     * UTILS FUNCTIONS
342
     */
343
344
    /** STEP 1 CC - Check concurrency
345
     * @throws QuoteNotFoundException
346
     */
347
    private function getQuoteId()
348
    {
349
        $this->quoteId = $this->getRequest()->getParam('quoteId');
350
        if ($this->quoteId == '') {
351
            throw new QuoteNotFoundException();
352
        }
353
    }
354
355
    /**
356
     * @return \Zend_Db_Statement_Interface
357
     * @throws UnknownException
358
     */
359
    private function checkDbTable()
360
    {
361
        try {
362
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
363
            $dbConnection = $this->dbObject->getConnection();
364
            $tableName    = $this->dbObject->getTableName(self::CONCURRENCY_TABLE);
365
            $query        = "CREATE TABLE IF NOT EXISTS $tableName(`id` int not null,`timestamp` int not null,PRIMARY KEY (`id`))";
366
367
            return $dbConnection->query($query);
368
        } catch (\Exception $e) {
369
            throw new UnknownException($e->getMessage());
370
        }
371
    }
372
373
    /**
374
     * @return void|\Zend_Db_Statement_Interface
375
     * @throws UnknownException
376
     */
377
    private function checkDbLogTable()
378
    {
379
        try {
380
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
381
            $dbConnection = $this->dbObject->getConnection();
382
            $tableName = $this->dbObject->getTableName(self::LOGS_TABLE);
383
            if (!$dbConnection->isTableExists($tableName)) {
384
                $table = $dbConnection
385
                    ->newTable($tableName)
386
                    ->addColumn(
387
                        'id',
388
                        Table::TYPE_SMALLINT,
389
                        null,
390
                        array('nullable'=>false, 'auto_increment'=>true, 'primary'=>true)
391
                    )
392
                    ->addColumn('log', Table::TYPE_TEXT, null, array('nullable'=>false))
393
                    ->addColumn(
394
                        'createdAt',
395
                        Table::TYPE_TIMESTAMP,
396
                        null,
397
                        array('nullable'=>false, 'default'=>Table::TIMESTAMP_INIT)
398
                    );
399
                return $dbConnection->createTable($table);
400
            }
401
402
            return;
403
        } catch (\Exception $e) {
404
            throw new UnknownException($e->getMessage());
405
        }
406
    }
407
408
    /**
409
     * @param bool $mode
410
     *
411
     * @throws \Exception
412
     */
413
    private function unblockConcurrency($mode = false)
414
    {
415
        try {
416
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
417
            $dbConnection = $this->dbObject->getConnection();
418
            $tableName    = $this->dbObject->getTableName(self::CONCURRENCY_TABLE);
419
            if ($mode == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
420
                $dbConnection->delete($tableName, "timestamp<".(time() - 5));
421
            } elseif ($this->quoteId!='') {
422
                $dbConnection->delete($tableName, "id=".$this->quoteId);
423
            }
424
        } catch (Exception $exception) {
0 ignored issues
show
Bug introduced by
The type Pagantis\Pagantis\Controller\Notify\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
425
            throw new ConcurrencyException();
426
        }
427
    }
428
429
    /**
430
     * @throws ConcurrencyException
431
     * @throws UnknownException
432
     */
433
    private function blockConcurrency()
434
    {
435
        /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
436
        $dbConnection = $this->dbObject->getConnection();
437
        $tableName    = $this->dbObject->getTableName(self::CONCURRENCY_TABLE);
438
        $query = "SELECT timestamp FROM $tableName where id='$this->quoteId'";
439
        $resultsSelect = $dbConnection->fetchRow($query);
440
        if (isset($resultsSelect['timestamp'])) {
441
            if ($this->getOrigin() == 'Notification') {
442
                throw new ConcurrencyException();
443
            } else {
444
                $query = sprintf(
445
                    "SELECT timestamp - %s as rest FROM %s %s",
446
                    (time() - self::CONCURRENCY_TIMEOUT),
447
                    $tableName,
448
                    "WHERE id='".$this->quoteId."'"
449
                );
450
                $resultsSelect = $dbConnection->fetchRow($query);
451
                $restSeconds   = isset($resultsSelect['rest']) ? ($resultsSelect['rest']) : 0;
452
                $expirationSec = ($restSeconds > self::CONCURRENCY_TIMEOUT) ? self::CONCURRENCY_TIMEOUT : $restSeconds;
453
                if ($expirationSec > 0) {
454
                    sleep($expirationSec + 1);
455
                }
456
457
                $logMessage  = sprintf(
458
                    "User waiting %s seconds, default seconds %s, bd time to expire %s seconds",
459
                    $expirationSec,
460
                    self::CONCURRENCY_TIMEOUT,
461
                    $restSeconds
462
                );
463
                throw new UnknownException($logMessage);
464
            }
465
        } else {
466
            $dbConnection->insert($tableName, array('id'=>$this->quoteId, 'timestamp'=>time()));
467
        }
468
    }
469
470
    /** STEP 2 GMO - Get Merchant Order */
471
    /** STEP 3 GPOI - Get Pagantis OrderId */
472
    /** STEP 4 GPO - Get Pagantis Order */
473
    /** STEP 5 COS - Check Order Status */
474
    /**
475
     * @param $statusArray
476
     *
477
     * @throws \Exception
478
     */
479
    private function checkPagantisStatus($statusArray)
480
    {
481
        $pagantisStatus = array();
482
        foreach ($statusArray as $status) {
483
            $pagantisStatus[] = constant("\Pagantis\OrdersApiClient\Model\Order::STATUS_$status");
484
        }
485
486
        $payed = in_array($this->pagantisOrder->getStatus(), $pagantisStatus);
487
        if (!$payed) {
488
            throw new WrongStatusException($this->pagantisOrder->getStatus());
489
        }
490
    }
491
492
    /** STEP 6 CMOS - Check Merchant Order Status */
493
    /**
494
     * @throws \Exception
495
     */
496
    private function getMagentoOrderId()
497
    {
498
        try {
499
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
500
            $dbConnection = $this->dbObject->getConnection();
501
            $tableName    = $this->dbObject->getTableName(self::ORDERS_TABLE);
502
            $pagantisOrderId   = $this->pagantisOrderId;
503
504
            $query        = "select mg_order_id from $tableName where id='$this->quoteId' and order_id='$pagantisOrderId'";
505
            $queryResult  = $dbConnection->fetchRow($query);
506
            $this->magentoOrderId = $queryResult['mg_order_id'];
507
        } catch (\Exception $e) {
508
            throw new UnknownException($e->getMessage());
509
        }
510
    }
511
512
    /** STEP 7 VA - Validate Amount */
513
    /** STEP 8 PMO - Process Merchant Order */
514
    /**
515
     * @throws UnknownException
516
     */
517
    private function saveOrder()
518
    {
519
        try {
520
            $this->paymentInterface->setMethod(self::PAYMENT_METHOD);
521
            $this->magentoOrderId = $this->quoteManagement->placeOrder($this->quoteId, $this->paymentInterface);
522
523
            /** @var OrderRepositoryInterface magentoOrder */
524
            $this->magentoOrder = $this->orderRepositoryInterface->get($this->magentoOrderId);
525
            $metadataOrder = $this->pagantisOrder->getMetadata();
526
            $metadataInfo = null;
527
            foreach ($metadataOrder as $metadataKey => $metadataValue) {
528
                if ($metadataKey == 'promotedProduct') {
529
                    $metadataInfo.= " Producto promocionado = $metadataValue //";
530
                }
531
            }
532
533
            $this->magentoOrder->addStatusHistoryComment($metadataInfo)
534
                               ->setIsCustomerNotified(false)
535
                               ->setEntityName('order')
536
                               ->save();
537
538
            $comment = 'pagantisOrderId: '.$this->pagantisOrder->getId(). ' ' .
539
                       'pagantisOrderStatus: '.$this->pagantisOrder->getStatus(). ' ' .
540
                       'via: '.$this->origin;
541
            $this->magentoOrder->addStatusHistoryComment($comment)
542
                               ->setIsCustomerNotified(false)
543
                               ->setEntityName('order')
544
                               ->save();
545
546
            if ($this->magentoOrderId == '') {
547
                throw new UnknownException('Order can not be saved');
548
            }
549
        } catch (\Exception $e) {
550
            throw new UnknownException($e->getMessage());
551
        }
552
    }
553
554
    /**
555
     * @throws UnknownException
556
     */
557
    private function updateBdInfo()
558
    {
559
        try {
560
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
561
            $dbConnection = $this->dbObject->getConnection();
562
            $tableName    = $this->dbObject->getTableName(self::ORDERS_TABLE);
563
            $pagantisOrderId   = $this->pagantisOrder->getId();
564
            $dbConnection->update(
565
                $tableName,
566
                array('mg_order_id' => $this->magentoOrderId),
567
                "order_id='$pagantisOrderId' and id='$this->quoteId'"
568
            );
569
        } catch (\Exception $e) {
570
            throw new UnknownException($e->getMessage());
571
        }
572
    }
573
574
    /** STEP 9 CPO - Confirmation Pagantis Order */
575
    /**
576
     * @throws UnknownException
577
     */
578
    private function rollbackMerchantOrder()
579
    {
580
        try {
581
            $this->magentoOrder->setState(\Magento\Sales\Model\Order::STATE_PENDING_PAYMENT, true);
0 ignored issues
show
Unused Code introduced by
The call to Magento\Sales\Api\Data\OrderInterface::setState() has too many arguments starting with true. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

581
            $this->magentoOrder->/** @scrutinizer ignore-call */ 
582
                                 setState(\Magento\Sales\Model\Order::STATE_PENDING_PAYMENT, true);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
582
            $this->magentoOrder->setStatus(\Magento\Sales\Model\Order::STATE_PENDING_PAYMENT);
583
            $this->magentoOrder->save();
584
        } catch (\Exception $e) {
585
            throw new UnknownException($e->getMessage());
586
        }
587
    }
588
589
590
    /**
591
     * @return mixed
592
     */
593
    public function getOrigin()
594
    {
595
        return $this->origin;
596
    }
597
598
    /**
599
     * @param mixed $origin
600
     */
601
    public function setOrigin($origin)
602
    {
603
        $this->origin = $origin;
604
    }
605
606
    /**
607
     * @return string
608
     */
609
    private function getRedirectUrl()
610
    {
611
        //$returnUrl = 'checkout/#payment';
612
        $returnUrl = $this->_url->getUrl('checkout', ['_fragment' => 'payment']);
613
        if ($this->magentoOrderId!='') {
614
            /** @var Order $this->magentoOrder */
615
            $this->magentoOrder = $this->orderRepositoryInterface->get($this->magentoOrderId);
616
            if (!$this->_objectManager->get(\Magento\Checkout\Model\Session\SuccessValidator::class)->isValid()) {
617
                $this->checkoutSession
618
                    ->setLastOrderId($this->magentoOrderId)
619
                    ->setLastRealOrderId($this->magentoOrder->getIncrementId())
620
                    ->setLastQuoteId($this->quoteId)
621
                    ->setLastSuccessQuoteId($this->quoteId)
622
                    ->setLastOrderStatus($this->magentoOrder->getStatus());
623
            }
624
625
            //Magento status flow => https://docs.magento.com/m2/ce/user_guide/sales/order-status-workflow.html
626
            //Order Workflow => https://docs.magento.com/m2/ce/user_guide/sales/order-workflow.html
627
            $orderStatus    = strtolower($this->magentoOrder->getStatus());
628
            $acceptedStatus = array('processing', 'completed');
629
            if (in_array($orderStatus, $acceptedStatus)) {
630
                if (isset($this->extraConfig['PAGANTIS_OK_URL']) &&  $this->extraConfig['PAGANTIS_OK_URL']!= '') {
631
                    $returnUrl = $this->extraConfig['PAGANTIS_OK_URL'];
632
                } else {
633
                    $returnUrl = 'checkout/onepage/success';
634
                }
635
            } else {
636
                if (isset($this->extraConfig['PAGANTIS_KO_URL']) && $this->extraConfig['PAGANTIS_KO_URL'] != '') {
637
                    $returnUrl = $this->extraConfig['PAGANTIS_KO_URL'];
638
                } else {
639
                    //$returnUrl = 'checkout/#payment';
640
                    $returnUrl = $this->_url->getUrl('checkout', ['_fragment' => 'payment']);
641
                }
642
            }
643
        }
644
        return $returnUrl;
645
    }
646
647
    /**
648
     * @param $exceptionMessage
649
     *
650
     * @throws UnknownException
651
     */
652
    private function insertLog($exceptionMessage)
653
    {
654
        try {
655
            if ($exceptionMessage instanceof \Exception) {
656
                $this->checkDbLogTable();
657
                $logEntry = new LogEntry();
658
                $logEntryJson = $logEntry->error($exceptionMessage)->toJson();
659
660
                /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
661
                $dbConnection = $this->dbObject->getConnection();
662
                $tableName    = $this->dbObject->getTableName(self::LOGS_TABLE);
663
                $dbConnection->insert($tableName, array('log' => $logEntryJson));
664
            }
665
        } catch (\Exception $e) {
666
            throw new UnknownException($e->getMessage());
667
        }
668
    }
669
}
670