Passed
Pull Request — master (#82)
by
unknown
03:14
created

WcPagantisNotify::confirmPagantisOrder()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 11
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 16
rs 9.9
1
<?php
2
3
use Pagantis\OrdersApiClient\Client;
4
use Pagantis\ModuleUtils\Exception\ConcurrencyException;
5
use Pagantis\ModuleUtils\Exception\AlreadyProcessedException;
6
use Pagantis\ModuleUtils\Exception\AmountMismatchException;
7
use Pagantis\ModuleUtils\Exception\MerchantOrderNotFoundException;
8
use Pagantis\ModuleUtils\Exception\NoIdentificationException;
9
use Pagantis\ModuleUtils\Exception\OrderNotFoundException;
10
use Pagantis\ModuleUtils\Exception\QuoteNotFoundException;
11
use Pagantis\ModuleUtils\Exception\UnknownException;
12
use Pagantis\ModuleUtils\Exception\WrongStatusException;
13
use Pagantis\ModuleUtils\Model\Response\JsonSuccessResponse;
14
use Pagantis\ModuleUtils\Model\Response\JsonExceptionResponse;
15
use Pagantis\ModuleUtils\Model\Log\LogEntry;
16
use Pagantis\OrdersApiClient\Model\Order;
17
18
if (!defined('ABSPATH')) {
19
    exit;
20
}
21
22
class WcPagantisNotify extends WcPagantisGateway
23
{
24
    /** Concurrency tablename  */
25
    const CONCURRENCY_TABLE = 'pagantis_concurrency';
26
27
    /** Seconds to expire a locked request */
28
    const CONCURRENCY_TIMEOUT = 5;
29
30
    /** @var mixed $pagantisOrder */
31
    protected $pagantisOrder;
32
33
    /** @var $string $origin */
0 ignored issues
show
Documentation Bug introduced by
The doc comment $string at position 0 could not be parsed: Unknown type name '$string' at position 0 in $string.
Loading history...
34
    public $origin;
35
36
    /** @var $string */
0 ignored issues
show
Documentation Bug introduced by
The doc comment $string at position 0 could not be parsed: Unknown type name '$string' at position 0 in $string.
Loading history...
37
    public $order;
38
39
    /** @var mixed $woocommerceOrderId */
40
    protected $woocommerceOrderId = '';
41
42
    /** @var mixed $cfg */
43
    protected $cfg;
44
45
    /** @var Client $orderClient */
46
    protected $orderClient;
47
48
    /** @var  WC_Order $woocommerceOrder */
0 ignored issues
show
Bug introduced by
The type WC_Order was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
49
    protected $woocommerceOrder;
50
51
    /** @var mixed $pagantisOrderId */
52
    protected $pagantisOrderId = '';
53
54
    /** @var $string */
0 ignored issues
show
Documentation Bug introduced by
The doc comment $string at position 0 could not be parsed: Unknown type name '$string' at position 0 in $string.
Loading history...
55
    protected $product;
56
57
    /** @var $string */
0 ignored issues
show
Documentation Bug introduced by
The doc comment $string at position 0 could not be parsed: Unknown type name '$string' at position 0 in $string.
Loading history...
58
    protected $token;
59
60
    /**
61
     * Validation vs PagantisClient
62
     *
63
     * @return JsonExceptionResponse|JsonSuccessResponse
64
     * @throws ConcurrencyException
65
     */
66
    public function processInformation()
67
    {
68
        try {
69
            require_once(__ROOT__.'/vendor/autoload.php');
70
            try {
71
                if ($_SERVER['REQUEST_METHOD'] == 'GET' && $_GET['origin'] == 'notification') {
72
                    return $this->buildResponse();
73
                }
74
                $this->checkConcurrency();
75
                $this->getProductType();
76
                $this->getMerchantOrder();
77
                $this->getPagantisOrderId();
78
                $this->getPagantisOrder();
79
                $checkAlreadyProcessed = $this->checkOrderStatus();
80
                if ($checkAlreadyProcessed) {
81
                    return $this->buildResponse();
82
                }
83
                $this->validateAmount();
84
                if ($this->checkMerchantOrderStatus()) {
85
                    $this->processMerchantOrder();
86
                }
87
            } catch (\Exception $exception) {
88
                $this->insertLog($exception);
89
90
                return $this->buildResponse($exception);
91
            }
92
93
            try {
94
                $this->confirmPagantisOrder();
95
96
                return $this->buildResponse();
97
            } catch (\Exception $exception) {
98
                $this->rollbackMerchantOrder();
99
                $this->insertLog($exception);
100
101
                return $this->buildResponse($exception);
102
            }
103
        } catch (\Exception $exception) {
104
            $this->insertLog($exception);
105
            return $this->buildResponse($exception);
106
        }
107
    }
108
109
    /**
110
     * COMMON FUNCTIONS
111
     */
112
113
    /**
114
     * @throws ConcurrencyException
115
     * @throws QuoteNotFoundException
116
     */
117
    private function checkConcurrency()
118
    {
119
        $this->woocommerceOrderId = $_GET['order-received'];
120
        if ($this->woocommerceOrderId == '') {
121
            throw new QuoteNotFoundException();
122
        }
123
124
        $this->unblockConcurrency();
125
        $this->blockConcurrency($this->woocommerceOrderId);
126
    }
127
128
    /**
129
     * getProductType
130
     */
131
    private function getProductType()
132
    {
133
        if ($_GET['product'] == '') {
134
            $this->setProduct(WcPagantisGateway::METHOD_ID);
135
        } else {
136
            $this->setProduct($_GET['product']);
137
        }
138
    }
139
140
    /**
141
     * @throws MerchantOrderNotFoundException
142
     */
143
    private function getMerchantOrder()
144
    {
145
        try {
146
            $this->woocommerceOrder = new WC_Order($this->woocommerceOrderId);
147
            $this->woocommerceOrder->set_payment_method_title($this->getProduct());
148
        } catch (\Exception $e) {
149
            throw new MerchantOrderNotFoundException();
150
        }
151
    }
152
153
    /**
154
     * @throws NoIdentificationException
155
     */
156
    private function getPagantisOrderId()
157
    {
158
        global $wpdb;
159
        $this->checkDbTable();
160
        $tableName = $wpdb->prefix.PG_CART_PROCESS_TABLE;
161
        $queryResult = $wpdb->get_row("SELECT order_id FROM $tableName WHERE token='{$this->token}'");
162
        $this->pagantisOrderId = $queryResult->order_id;
163
164
        if ($this->pagantisOrderId == '') {
165
            throw new NoIdentificationException();
166
        }
167
    }
168
169
    /**
170
     * @throws OrderNotFoundException
171
     */
172
    private function getPagantisOrder()
173
    {
174
        try {
175
            $this->cfg = get_option('woocommerce_pagantis_settings');
0 ignored issues
show
Bug introduced by
The function get_option was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

175
            $this->cfg = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
176
            $this->cfg = get_option('woocommerce_pagantis_settings');
177
            if ($this->isProduct4x()) {
178
                $publicKey = $this->cfg['pagantis_public_key_4x'];
179
                $secretKey = $this->cfg['pagantis_private_key_4x'];
180
            } else {
181
                $publicKey = $this->cfg['pagantis_public_key'];
182
                $secretKey = $this->cfg['pagantis_private_key'];
183
            }
184
185
            $this->orderClient = new Client($publicKey, $secretKey);
186
            $this->pagantisOrder = $this->orderClient->getOrder($this->pagantisOrderId);
187
        } catch (\Exception $e) {
188
            throw new OrderNotFoundException();
189
        }
190
    }
191
192
    /**
193
     * @return bool
194
     * @throws WrongStatusException
195
     */
196
    private function checkOrderStatus()
197
    {
198
        try {
199
            $this->checkPagantisStatus(array('AUTHORIZED'));
200
        } catch (\Exception $e) {
201
            if ($this->pagantisOrder instanceof Order) {
202
                $status = $this->pagantisOrder->getStatus();
203
            } else {
204
                $status = '-';
205
            }
206
207
            if ($status === Order::STATUS_CONFIRMED) {
208
                return true;
209
            }
210
            throw new WrongStatusException($status);
211
        }
212
    }
213
214
    /**
215
     * @return bool
216
     */
217
    private function checkMerchantOrderStatus()
218
    {
219
        //Order status reference => https://docs.woocommerce.com/document/managing-orders/
220
        $validStatus   = array('on-hold', 'pending', 'failed', 'processing', 'completed');
221
        $isValidStatus = apply_filters(
0 ignored issues
show
Bug introduced by
The function apply_filters was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

221
        $isValidStatus = /** @scrutinizer ignore-call */ apply_filters(
Loading history...
222
            'woocommerce_valid_order_statuses_for_payment_complete',
223
            $validStatus,
224
            $this
225
        );
226
227
        if (!$this->woocommerceOrder->has_status($isValidStatus)) { // TO CONFIRM
228
            $logMessage = "WARNING checkMerchantOrderStatus." .
229
                          " Merchant order id:".$this->woocommerceOrder->get_id().
230
                          " Merchant order status:".$this->woocommerceOrder->get_status().
231
                          " Pagantis order id:".$this->pagantisOrder->getStatus().
232
                          " Pagantis order status:".$this->pagantisOrder->getId().
233
                          " Pagantis urlToken: ".$this->token;
234
            
235
            $this->insertLog(null, $logMessage);
236
            $this->woocommerceOrder->add_order_note($logMessage);
237
            $this->woocommerceOrder->save();
238
            return false;
239
        }
240
241
        return true; //TO SAVE
242
    }
243
244
    /**
245
     * @throws AmountMismatchException
246
     */
247
    private function validateAmount()
248
    {
249
        $pagantisAmount = $this->pagantisOrder->getShoppingCart()->getTotalAmount();
250
        $wcAmount = intval(strval(100 * $this->woocommerceOrder->get_total()));
251
        if ($pagantisAmount != $wcAmount) {
252
            throw new AmountMismatchException($pagantisAmount, $wcAmount);
253
        }
254
    }
255
256
    /**
257
     * @throws Exception
258
     */
259
    private function processMerchantOrder()
260
    {
261
        $this->saveOrder();
262
        $this->updateBdInfo();
263
    }
264
265
    /**
266
     * @return false|string
267
     * @throws UnknownException
268
     */
269
    private function confirmPagantisOrder()
270
    {
271
        try {
272
            $this->pagantisOrder = $this->orderClient->confirmOrder($this->pagantisOrderId);
273
        } catch (\Exception $e) {
274
            $this->pagantisOrder = $this->orderClient->getOrder($this->pagantisOrderId);
275
            if ($this->pagantisOrder->getStatus() !== Order::STATUS_CONFIRMED) {
276
                throw new UnknownException($e->getMessage());
277
            } else {
278
                $logMessage = 'Concurrency issue: Order_id '.$this->pagantisOrderId.' was confirmed by other process';
279
                $this->insertLog(null, $logMessage);
280
            }
281
        }
282
283
        $jsonResponse = new JsonSuccessResponse();
284
        return $jsonResponse->toJson();
285
    }
286
287
    /**
288
     * UTILS FUNCTIONS
289
     */
290
    /** STEP 1 CC - Check concurrency */
291
292
    /**
293
     * Check if cart processing table exists
294
     */
295
    private function checkDbTable()
296
    {
297
        if (isPgTableCreated(PG_CART_PROCESS_TABLE)){
298
            alterCartProcessingTable();
299
        } else{
300
            createCartProcessingTable();
301
        }
302
    }
303
304
    /**
305
     * Check if logs table exists
306
     */
307
    private function checkDbLogTable()
308
    {
309
        global $wpdb;
310
        $tableName = $wpdb->prefix.PG_LOGS_TABLE_NAME;
311
312
        if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName) {
313
            $charset_collate = $wpdb->get_charset_collate();
314
            $sql = "CREATE TABLE $tableName ( id int NOT NULL AUTO_INCREMENT, log text NOT NULL, 
315
                    createdAt timestamp DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY id (id)) $charset_collate";
316
317
            require_once(ABSPATH.'wp-admin/includes/upgrade.php');
0 ignored issues
show
Bug introduced by
The constant ABSPATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
318
            dbDelta($sql);
0 ignored issues
show
Bug introduced by
The function dbDelta was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

318
            /** @scrutinizer ignore-call */ 
319
            dbDelta($sql);
Loading history...
319
        }
320
        return;
321
    }
322
323
    /** STEP 2 GMO - Get Merchant Order */
324
    /** STEP 3 GPOI - Get Pagantis OrderId */
325
    /** STEP 4 GPO - Get Pagantis Order */
326
    /** STEP 5 COS - Check Order Status */
327
328
    /**
329
     * @param $statusArray
330
     *
331
     * @throws \Exception
332
     */
333
    private function checkPagantisStatus($statusArray)
334
    {
335
        $pagantisStatus = array();
336
        foreach ($statusArray as $status) {
337
            $pagantisStatus[] = constant("\Pagantis\OrdersApiClient\Model\Order::STATUS_$status");
338
        }
339
340
        if ($this->pagantisOrder instanceof Order) {
341
            $payed = in_array($this->pagantisOrder->getStatus(), $pagantisStatus);
342
            if (!$payed) {
343
                if ($this->pagantisOrder instanceof Order) {
0 ignored issues
show
introduced by
$this->pagantisOrder is always a sub-type of Pagantis\OrdersApiClient\Model\Order.
Loading history...
344
                    $status = $this->pagantisOrder->getStatus();
345
                } else {
346
                    $status = '-';
347
                }
348
                throw new WrongStatusException($status);
349
            }
350
        } else {
351
            throw new OrderNotFoundException();
352
        }
353
    }
354
355
    /** STEP 6 CMOS - Check Merchant Order Status */
356
    /** STEP 7 VA - Validate Amount */
357
    /** STEP 8 PMO - Process Merchant Order */
358
    /**
359
     * @throws \Exception
360
     */
361
    private function saveOrder()
362
    {
363
        global $woocommerce;
364
        $paymentResult = $this->woocommerceOrder->payment_complete();
365
        if ($paymentResult) {
366
            $metadataOrder = $this->pagantisOrder->getMetadata();
367
            $metadataInfo = null;
368
            foreach ($metadataOrder as $metadataKey => $metadataValue) {
369
                if ($metadataKey == 'promotedProduct') {
370
                    $metadataInfo.= "/Producto promocionado = $metadataValue";
371
                }
372
            }
373
374
            if ($metadataInfo != null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $metadataInfo of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
375
                $this->woocommerceOrder->add_order_note($metadataInfo);
376
            }
377
378
            $this->woocommerceOrder->add_order_note("Notification received via $this->origin");
379
            $this->woocommerceOrder->reduce_order_stock();
380
            $this->woocommerceOrder->save();
381
382
            $woocommerce->cart->empty_cart();
383
            sleep(3);
384
        } else {
385
            throw new UnknownException('Order can not be saved');
386
        }
387
    }
388
389
    /**
390
     * Save the merchant order_id with the related identification
391
     */
392
    private function updateBdInfo()
393
    {
394
        global $wpdb;
395
396
        $this->checkDbTable();
397
        $tableName = $wpdb->prefix.PG_CART_PROCESS_TABLE;
398
399
        $wpdb->update(
400
            $tableName,
401
            array('wc_order_id'=>$this->woocommerceOrderId),
402
            array('token' => $this->token),
403
            array('%s,%s'),
404
            array('%s,%s')
405
        );
406
    }
407
408
    /** STEP 9 CPO - Confirmation Pagantis Order */
409
    private function rollbackMerchantOrder()
410
    {
411
        $this->woocommerceOrder->update_status('pending', __('Pending payment', 'woocommerce'));
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

411
        $this->woocommerceOrder->update_status('pending', /** @scrutinizer ignore-call */ __('Pending payment', 'woocommerce'));
Loading history...
412
    }
413
414
    /**
415
     * @param null $exception
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $exception is correct as it would always require null to be passed?
Loading history...
416
     * @param null $message
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $message is correct as it would always require null to be passed?
Loading history...
417
     */
418
    private function insertLog($exception = null, $message = null)
419
    {
420
        global $wpdb;
421
422
        $this->checkDbLogTable();
423
        $logEntry     = new LogEntry();
424
        if ($exception instanceof \Exception) {
425
            $logEntry = $logEntry->error($exception);
426
        } else {
427
            $logEntry = $logEntry->info($message);
428
        }
429
430
        $tableName = $wpdb->prefix.PG_LOGS_TABLE_NAME;
431
        $wpdb->insert($tableName, array('log' => $logEntry->toJson()));
432
    }
433
434
    /**
435
     * @param null $orderId
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $orderId is correct as it would always require null to be passed?
Loading history...
436
     *
437
     * @throws ConcurrencyException
438
     */
439
    private function unblockConcurrency($orderId = null)
440
    {
441
        global $wpdb;
442
        $tableName = $wpdb->prefix.PG_CONCURRENCY_TABLE_NAME;
443
        if ($orderId == null) {
0 ignored issues
show
introduced by
The condition $orderId == null is always true.
Loading history...
444
            $query = "DELETE FROM $tableName WHERE createdAt<(NOW()- INTERVAL ".self::CONCURRENCY_TIMEOUT." SECOND)";
445
        } else {
446
            $query = "DELETE FROM $tableName WHERE order_id = $orderId";
447
        }
448
        $resultDelete = $wpdb->query($query);
449
        if ($resultDelete === false) {
450
            throw new ConcurrencyException();
451
        }
452
    }
453
454
    /**
455
     * @param $orderId
456
     *
457
     * @throws ConcurrencyException
458
     */
459
    private function blockConcurrency($orderId)
460
    {
461
        global $wpdb;
462
        $tableName = $wpdb->prefix.PG_CONCURRENCY_TABLE_NAME;
463
        $insertResult = $wpdb->insert($tableName, array('order_id' => $orderId));
464
        if ($insertResult === false) {
465
            if ($this->getOrigin() == 'Notify') {
466
                throw new ConcurrencyException();
467
            } else {
468
                $query = sprintf(
469
                    "SELECT TIMESTAMPDIFF(SECOND,NOW()-INTERVAL %s SECOND, createdAt) as rest FROM %s WHERE %s",
470
                    self::CONCURRENCY_TIMEOUT,
471
                    $tableName,
472
                    "order_id=$orderId"
473
                );
474
                $resultSeconds = $wpdb->get_row($query);
475
                $restSeconds = isset($resultSeconds) ? ($resultSeconds->rest) : 0;
476
                $secondsToExpire = ($restSeconds>self::CONCURRENCY_TIMEOUT) ? self::CONCURRENCY_TIMEOUT : $restSeconds;
477
                sleep($secondsToExpire+1);
478
479
                $logMessage = sprintf(
480
                    "User waiting %s seconds, default seconds %s, bd time to expire %s seconds",
481
                    $secondsToExpire,
482
                    self::CONCURRENCY_TIMEOUT,
483
                    $restSeconds
484
                );
485
                $this->insertLog(null, $logMessage);
486
            }
487
        }
488
    }
489
490
    /**
491
     * @param null $exception
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $exception is correct as it would always require null to be passed?
Loading history...
492
     *
493
     *
494
     * @return JsonExceptionResponse|JsonSuccessResponse
495
     * @throws ConcurrencyException
496
     */
497
    private function buildResponse($exception = null)
498
    {
499
        $this->unblockConcurrency($this->woocommerceOrderId);
500
        $this->setToken($_GET['token']);
501
        pagantisLogger::log( " token " . $_GET['token'] .  "on " . __LINE__ . " in " . __FILE__);
502
        pagantisLogger::log( " token " . $this->token .  "on " . __LINE__ . " in " . __FILE__);
503
504
        if ($exception == null) {
0 ignored issues
show
introduced by
The condition $exception == null is always true.
Loading history...
505
            $jsonResponse = new JsonSuccessResponse();
506
        } else {
507
            $jsonResponse = new JsonExceptionResponse();
508
            $jsonResponse->setException($exception);
509
        }
510
        $jsonResponse->setMerchantOrderId($this->woocommerceOrderId);
511
        $jsonResponse->setPagantisOrderId($this->pagantisOrderId);
512
513
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
514
            $jsonResponse->printResponse();
515
        } else {
516
            return $jsonResponse;
517
        }
518
    }
519
520
    /**
521
     * GETTERS & SETTERS
522
     */
523
524
    /**
525
     * @return mixed
526
     */
527
    public function getOrigin()
528
    {
529
        return $this->origin;
530
    }
531
532
    /**
533
     * @param mixed $origin
534
     */
535
    public function setOrigin($origin)
536
    {
537
        $this->origin = $origin;
538
    }
539
540
    /**
541
     * @return bool
542
     */
543
    private function isProduct4x()
544
    {
545
        return ($this->product === Ucfirst(WcPagantis4xGateway::METHOD_ID));
546
    }
547
548
    /**
549
     * @return mixed
550
     */
551
    public function getProduct()
552
    {
553
        return $this->product;
554
    }
555
556
    /**
557
     * @param mixed $product
558
     */
559
    public function setProduct($product)
560
    {
561
        $this->product = Ucfirst($product);
562
    }
563
564
    /**
565
     * @param $token
566
     */
567
    public function setToken($token)
568
    {
569
        $this->token = $token;
570
    }
571
572
    /**
573
     * @return mixed
574
     */
575
    public function getToken()
576
    {
577
        return $this->token;
578
    }
579
580
}
581