Completed
Push — master ( 685db1...fb59b4 )
by pablo
20s queued 14s
created

Controller/Payment/Index.php (2 issues)

Labels
Severity
1
<?php
2
3
namespace Pagantis\Pagantis\Controller\Payment;
4
5
use Magento\Framework\App\Action\Action;
6
use Magento\Framework\App\Action\Context;
7
use Magento\Quote\Model\QuoteRepository;
8
use Magento\Sales\Model\ResourceModel\Order\Collection as OrderCollection;
9
use Magento\Checkout\Model\Session;
10
use Pagantis\OrdersApiClient\Model\Order;
11
use Pagantis\Pagantis\Helper\Config;
12
use Pagantis\Pagantis\Helper\ExtraConfig;
13
use Magento\Framework\App\ResourceConnection;
14
use Magento\Framework\App\ProductMetadataInterface;
15
use Magento\Framework\Module\ModuleList;
16
use Magento\Store\Api\Data\StoreInterface;
17
use Pagantis\OrdersApiClient\Model\Order\User\Address;
18
use Magento\Framework\DB\Ddl\Table;
19
use Pagantis\OrdersApiClient\Model\Order\User;
20
use Pagantis\OrdersApiClient\Model\Order\User\OrderHistory;
21
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details;
22
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart;
23
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product;
24
use Pagantis\OrdersApiClient\Model\Order\Metadata;
25
use Pagantis\OrdersApiClient\Model\Order\Configuration\Urls;
26
use Pagantis\OrdersApiClient\Model\Order\Configuration\Channel;
27
use Pagantis\OrdersApiClient\Model\Order\Configuration;
28
use Pagantis\OrdersApiClient\Client;
29
30
/**
31
 * Class Index
32
 * @package Pagantis\Pagantis\Controller\Payment
33
 */
34
class Index extends Action
35
{
36
    /** Orders tablename */
37
    const ORDERS_TABLE = 'cart_process';
38
39
    /** Concurrency tablename */
40
    const LOGS_TABLE = 'Pagantis_logs';
41
42
    /** @var Context $context */
43
    protected $context;
44
45
    /** @var QuoteRepository  $quoteRepository */
46
    protected $quoteRepository;
47
48
    /** @var OrderCollection $orderCollection */
49
    protected $orderCollection;
50
51
    /** @var Session $session */
52
    protected $session;
53
54
    /** @var mixed $config */
55
    protected $config;
56
57
    /** @var ResourceConnection $dbObject */
58
    protected $dbObject;
59
60
    /** @var ProductMetadataInterface $productMetadataInterface */
61
    protected $productMetadataInterface;
62
63
    /** @var ModuleList $moduleList */
64
    protected $moduleList;
65
66
    /** @var ExtraConfig $extraConfig */
67
    protected $extraConfig;
68
    
69
    /** @var StoreInterface $store */
70
    protected $store;
71
72
    /**
73
     * Index constructor.
74
     *
75
     * @param Context                  $context
76
     * @param QuoteRepository          $quoteRepository
77
     * @param OrderCollection          $orderCollection
78
     * @param Session                  $session
79
     * @param Config                   $config
80
     * @param ResourceConnection       $dbObject
81
     * @param ProductMetadataInterface $productMetadataInterface
82
     * @param ModuleList               $moduleList
83
     * @param ExtraConfig              $extraConfig
84
     * @param StoreInterface           $storeInterface
85
     */
86
    public function __construct(
87
        Context $context,
88
        QuoteRepository $quoteRepository,
89
        OrderCollection $orderCollection,
90
        Session $session,
91
        Config $config,
92
        ResourceConnection $dbObject,
93
        ProductMetadataInterface $productMetadataInterface,
94
        ModuleList $moduleList,
95
        ExtraConfig $extraConfig,
96
        StoreInterface $storeInterface
97
    ) {
98
        parent::__construct($context);
99
        $this->session = $session;
100
        $this->context = $context;
101
        $this->config = $config->getConfig();
102
        $this->quoteRepository = $quoteRepository;
103
        $this->orderCollection = $orderCollection;
104
        $this->dbObject = $dbObject;
105
        $this->moduleList = $moduleList;
106
        $this->productMetadataInterface = $productMetadataInterface;
107
        $this->extraConfig = $extraConfig->getExtraConfig();
108
        $this->store = $storeInterface;
109
    }
110
111
    /**
112
     * Main function
113
     *
114
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|void
115
     * @throws \Zend_Db_Exception
116
     */
117
    public function execute()
118
    {
119
        try {
120
            $cancelUrl = $this->_url->getUrl('checkout', ['_fragment' => 'payment']);
121
            $quote = $this->session->getQuote();
122
            /** @var Order $order */
123
            $lastOrder = $this->session->getLastRealOrder();
124
            $params = $this->getRequest()->getParams();
125
            $customer = $quote->getCustomer();
126
            $shippingAddress = $quote->getShippingAddress();
127
128
            if (isset($params['email']) && $params['email']!='') {
129
                $this->session->setEmail($params['email']); //Get guest email after refresh page
130
                $customer->setEmail($params['email']);
131
                $quote->setCheckoutMethod('guest');
132
                $quote->getBillingAddress()->setEmail($params['email']);
133
            } elseif ($customer->getEmail()=='') {
134
                $customer->setEmail($this->session->getEmail());
135
                $quote->setCheckoutMethod('guest');
136
                $quote->getBillingAddress()->setEmail($this->session->getEmail());
137
            }
138
139
            /** @var Quote $currentQuote */
140
            $currentQuote = $this->quoteRepository->get($quote->getId());
141
            $currentQuote->setCustomerEmail($customer->getEmail());
142
            $this->quoteRepository->save($currentQuote);
143
144
            $userAddress =  new Address();
145
            $userAddress
146
                ->setZipCode($shippingAddress->getPostcode())
147
                ->setFullName($shippingAddress->getFirstname()." ".$shippingAddress->getLastname())
148
                ->setCountryCode($shippingAddress->getCountry())
149
                ->setCity($shippingAddress->getCity())
150
                ->setAddress($shippingAddress->getStreetFull())
151
            ;
152
153
            $tax_id = $this->getTaxId($quote->getBillingAddress());
154
            $orderShippingAddress = new Address();
155
            $orderShippingAddress
156
                ->setZipCode($shippingAddress->getPostcode())
157
                ->setFullName($shippingAddress->getFirstname()." ".$shippingAddress->getLastname())
158
                ->setCountryCode($shippingAddress->getCountry())
159
                ->setCity($shippingAddress->getCity())
160
                ->setAddress($shippingAddress->getStreetFull())
161
                ->setFixPhone($shippingAddress->getTelephone())
162
                ->setMobilePhone($shippingAddress->getTelephone())
163
                ->setTaxId($tax_id)
164
            ;
165
166
            $orderBillingAddress =  new Address();
167
            $billingAddress = $quote->getBillingAddress();
168
            $orderBillingAddress
169
                ->setZipCode($billingAddress->getPostcode())
170
                ->setFullName($billingAddress->getFirstname()." ".$shippingAddress->getLastname())
171
                ->setCountryCode($billingAddress->getCountry())
172
                ->setCity($billingAddress->getCity())
173
                ->setAddress($billingAddress->getStreetFull())
174
                ->setFixPhone($billingAddress->getTelephone())
175
                ->setMobilePhone($billingAddress->getTelephone())
176
                ->setTaxId($tax_id)
177
            ;
178
179
            $orderUser = new User();
180
            $billingAddress->setEmail($customer->getEmail());
181
            $orderUser
182
                ->setAddress($userAddress)
183
                ->setFullName($shippingAddress->getFirstname()." ".$shippingAddress->getLastname())
184
                ->setBillingAddress($orderBillingAddress)
185
                ->setEmail($customer->getEmail())
186
                ->setFixPhone($shippingAddress->getTelephone())
187
                ->setMobilePhone($shippingAddress->getTelephone())
188
                ->setShippingAddress($orderShippingAddress)
189
                ->setTaxId($tax_id)
190
            ;
191
192
            if ($customer->getDob()) {
193
                $orderUser->setDateOfBirth($customer->getDob());
194
            }
195
            if ($customer->getTaxvat()!='') {
196
                $orderUser->setDni($customer->getTaxvat());
0 ignored issues
show
The method setDni() does not exist on Pagantis\OrdersApiClient\Model\Order\User. ( Ignorable by Annotation )

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

196
                $orderUser->/** @scrutinizer ignore-call */ 
197
                            setDni($customer->getTaxvat());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
197
                $orderBillingAddress->setDni($customer->getTaxvat());
0 ignored issues
show
The method setDni() does not exist on Pagantis\OrdersApiClient\Model\Order\User\Address. ( Ignorable by Annotation )

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

197
                $orderBillingAddress->/** @scrutinizer ignore-call */ 
198
                                      setDni($customer->getTaxvat());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
198
                $orderShippingAddress->setDni($customer->getTaxvat());
199
                $orderUser->setNationalId($customer->getTaxvat());
200
                $orderBillingAddress->setNationalId($customer->getTaxvat());
201
                $orderShippingAddress->setNationalId($customer->getTaxvat());
202
            }
203
204
            $previousOrders = $this->getOrders($customer->getId());
205
            foreach ($previousOrders as $orderElement) {
206
                $orderHistory = new OrderHistory();
207
                $orderHistory
208
                    ->setAmount(intval(100 * $orderElement['grand_total']))
209
                    ->setDate(new \DateTime($orderElement['created_at']))
210
                ;
211
                $orderUser->addOrderHistory($orderHistory);
212
            }
213
214
            $metadataOrder = new Metadata();
215
            $metadata = $this->getMetadata();
216
            foreach ($metadata as $key => $metadatum) {
217
                $metadataOrder->addMetadata($key, $metadatum);
218
            }
219
220
            $details = new Details();
221
            $shippingCost = $quote->collectTotals()->getTotals()['shipping']->getData('value');
222
            $details->setShippingCost(intval(strval(100 * $shippingCost)));
223
            $items = $quote->getAllVisibleItems();
224
            $promotedAmount = 0;
225
            foreach ($items as $key => $item) {
226
                $product = new Product();
227
                $product
228
                    ->setAmount(intval(100 * $item->getPrice()))
229
                    ->setQuantity($item->getQty())
230
                    ->setDescription($item->getName());
231
                $details->addProduct($product);
232
233
                $promotedProduct = $this->isPromoted($item);
234
                if ($promotedProduct == 'true') {
235
                    $promotedAmount+=$product->getAmount()*$item->getQty();
236
                    $promotedMessage = 'Promoted Item: ' . $item->getName() .
237
                                       ' Price: ' . $item->getPrice() .
238
                                       ' Qty: ' . $item->getQty() .
239
                                       ' Item ID: ' . $item->getItemId();
240
                    $metadataOrder->addMetadata('promotedProduct', $promotedMessage);
241
                }
242
            }
243
244
            $orderShoppingCart = new ShoppingCart();
245
            $orderShoppingCart
246
                ->setDetails($details)
247
                ->setOrderReference($quote->getId())
248
                ->setPromotedAmount(0)
249
                ->setTotalAmount(intval(strval(100 * $quote->getGrandTotal())))
250
            ;
251
252
            $orderConfigurationUrls = new Urls();
253
            $quoteId = $quote->getId();
254
            $okUrl = $this->_url->getUrl(
255
                'pagantis/notify/index',
256
                ['_query' => ['quoteId'=>$quoteId]]
257
            );
258
259
            $okUrlRoute = 'pagantis/notify/index';
260
            if (version_compare($metadata['magento'], '2.3.0') >= 0) {
261
                $okUrlRoute = 'pagantis/notify/indexV2';
262
            }
263
264
            $okUrlUser = $this->_url->getUrl($okUrlRoute, ['_query' => ['quoteId'=>$quoteId,'origin'=>'redirect']]);
265
            $okUrlNot  = $this->_url->getUrl($okUrlRoute, ['_query' => ['quoteId'=>$quoteId,'origin'=>'notification']]);
266
267
            $orderConfigurationUrls
268
                ->setCancel($cancelUrl)
269
                ->setKo($okUrl)
270
                ->setAuthorizedNotificationCallback($okUrlNot)
271
                ->setOk($okUrlUser)
272
            ;
273
274
            $orderChannel = new Channel();
275
            $orderChannel
276
                ->setAssistedSale(false)
277
                ->setType(Channel::ONLINE)
278
            ;
279
280
            $haystack  = ($this->store->getLocale()!=null) ? $this->store->getLocale() : $this->getResolverCountry();
281
            $langCountry = strtolower(strstr($haystack, '_', true));
282
            $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
283
284
            $purchaseCountry =
285
                in_array($langCountry, $allowedCountries) ? $langCountry :
286
                in_array(strtolower($shippingAddress->getCountry()), $allowedCountries)? $shippingAddress->getCountry():
287
                in_array(strtolower($billingAddress->getCountry()), $allowedCountries)? $billingAddress->getCountry() :
288
                null;
289
290
            $orderConfiguration = new Configuration();
291
            $orderConfiguration
292
                ->setChannel($orderChannel)
293
                ->setUrls($orderConfigurationUrls)
294
                ->setPurchaseCountry($purchaseCountry)
295
            ;
296
297
298
            $order = new Order();
299
            $order
300
                ->setConfiguration($orderConfiguration)
301
                ->setMetadata($metadataOrder)
302
                ->setShoppingCart($orderShoppingCart)
303
                ->setUser($orderUser)
304
            ;
305
306
            if ($this->config['pagantis_public_key']=='' || $this->config['pagantis_private_key']=='') {
307
                throw new \Exception('Public and Secret Key not found');
308
            }
309
310
            $orderClient = new Client(
311
                $this->config['pagantis_public_key'],
312
                $this->config['pagantis_private_key']
313
            );
314
315
            $order = $orderClient->createOrder($order);
316
            if ($order instanceof Order) {
317
                $url = $order->getActionUrls()->getForm();
318
                $result = $this->insertRow($quote->getId(), $order->getId());
319
                if (!$result) {
320
                    throw new \Exception('Unable to save pagantis-order-id');
321
                }
322
            } else {
323
                throw new \Exception('Order not created');
324
            }
325
        } catch (\Exception $exception) {
326
            $this->insertLog($exception);
327
            echo $cancelUrl;
328
            exit;
329
        }
330
331
        $displayMode = $this->extraConfig['PAGANTIS_FORM_DISPLAY_TYPE'];
332
        if ($displayMode==='0') {
333
            echo $url;
334
            exit;
335
        } else {
336
            $iframeUrl = $this->_url->getUrl(
337
                "pagantis/Payment/iframe",
338
                ['_query' => ["orderId"=>$order->getId()]]
339
            );
340
            echo $iframeUrl;
341
            exit;
342
        }
343
    }
344
345
    /**
346
     * Get the orders of a customer
347
     * @param $customerId
348
     *
349
     * @return array
350
     */
351
    private function getOrders($customerId)
352
    {
353
        $orderCollection = array();
354
        if ($customerId!='') {
355
            $this->orderCollection->addAttributeToFilter('customer_id', $customerId)
356
                            ->addAttributeToFilter(
357
                                'status',
358
                                ['in' => ['processing','pending','complete']]
359
                            )
360
                            ->load();
361
            $orderCollection = $this->orderCollection->getData();
362
        }
363
        return $orderCollection;
364
    }
365
366
    /**
367
     * @return void|\Zend_Db_Statement_Interface
368
     * @throws \Zend_Db_Exception
369
     */
370
    private function checkDbTable()
371
    {
372
        $dbConnection = $this->dbObject->getConnection();
373
        $tableName = $this->dbObject->getTableName(self::ORDERS_TABLE);
374
        if (!$dbConnection->isTableExists($tableName)) {
375
            $table = $dbConnection
376
                ->newTable($tableName)
377
                ->addColumn('id', Table::TYPE_SMALLINT, null, array('primary'=>true, 'nullable' => false))
378
                ->addColumn('order_id', Table::TYPE_TEXT, 50)
379
                ->addColumn('mg_order_id', Table::TYPE_TEXT, 50);
380
            return $dbConnection->createTable($table);
381
        }
382
383
        return;
384
    }
385
386
    /**
387
     * Create relationship between quote_id & Pagantis_order_id
388
     * @param $quoteId
389
     * @param $pagantisOrderId
390
     *
391
     * @return int
392
     * @throws \Zend_Db_Exception
393
     */
394
    private function insertRow($quoteId, $pagantisOrderId)
395
    {
396
        $this->checkDbTable();
397
        $dbConnection = $this->dbObject->getConnection();
398
        $tableName = $this->dbObject->getTableName(self::ORDERS_TABLE);
399
        return $dbConnection->insertOnDuplicate(
400
            $tableName,
401
            array('id'=>$quoteId,'order_id'=>$pagantisOrderId),
402
            array('order_id')
403
        );
404
    }
405
406
    /**
407
     * @return array
408
     */
409
    private function getMetadata()
410
    {
411
        $curlInfo = curl_version();
412
        $curlVersion = $curlInfo['version'];
413
        $magentoVersion = $this->productMetadataInterface->getVersion();
414
        $moduleInfo = $this->moduleList->getOne('Pagantis_Pagantis');
415
        return array(  'magento' => $magentoVersion,
416
                       'pagantis' => $moduleInfo['setup_version'],
417
                       'php' => phpversion(),
418
                       'curl' => $curlVersion);
419
    }
420
421
    /**
422
     * Check if log table exists, otherwise create it
423
     *
424
     * @return void|\Zend_Db_Statement_Interface
425
     * @throws \Zend_Db_Exception
426
     */
427
    private function checkDbLogTable()
428
    {
429
        /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
430
        $dbConnection = $this->dbObject->getConnection();
431
        $tableName = $this->dbObject->getTableName(self::LOGS_TABLE);
432
        if (!$dbConnection->isTableExists($tableName)) {
433
            $table = $dbConnection
434
                ->newTable($tableName)
435
                ->addColumn('id', Table::TYPE_SMALLINT, null, array('nullable'=>false, 'auto_increment'=>true, 'primary'=>true))
436
                ->addColumn('log', Table::TYPE_TEXT, null, array('nullable'=>false))
437
                ->addColumn('createdAt', Table::TYPE_TIMESTAMP, null, array('nullable'=>false, 'default'=>Table::TIMESTAMP_INIT));
438
            return $dbConnection->createTable($table);
439
        }
440
441
        return;
442
    }
443
444
    /**
445
     * @param $exceptionMessage
446
     *
447
     * @throws \Zend_Db_Exception
448
     */
449
    private function insertLog($exceptionMessage)
450
    {
451
        if ($exceptionMessage instanceof \Exception) {
452
            $this->checkDbLogTable();
453
            $logObject          = new \stdClass();
454
            $logObject->message = $exceptionMessage->getMessage();
455
            $logObject->code    = $exceptionMessage->getCode();
456
            $logObject->line    = $exceptionMessage->getLine();
457
            $logObject->file    = $exceptionMessage->getFile();
458
            $logObject->trace   = $exceptionMessage->getTraceAsString();
459
460
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
461
            $dbConnection = $this->dbObject->getConnection();
462
            $tableName    = $this->dbObject->getTableName(self::LOGS_TABLE);
463
            $dbConnection->insert($tableName, array('log' => json_encode($logObject)));
464
        }
465
    }
466
467
    /**
468
     * @param $billingAdd
469
     *
470
     * @return null
471
     */
472
    private function getTaxId($billingAdd)
473
    {
474
        if (isset($billingAdd['vat_id'])) {
475
            return $billingAdd['vat_id'];
476
        } elseif (isset($billingAdd['cod_fisc'])) {
477
            return $billingAdd['cod_fisc'];
478
        } else {
479
            return null;
480
        }
481
    }
482
483
    /**
484
     * @param $item
485
     *
486
     * @return string
487
     */
488
    private function isPromoted($item)
489
    {
490
        $magentoProductId = $item->getProductId();
491
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
492
        $product = $objectManager->create('Magento\Catalog\Model\Product')->load($magentoProductId);
493
        return ($product->getData('pagantis_promoted') === '1') ? 'true' : 'false';
494
    }
495
496
    /**
497
     * @return mixed
498
     */
499
    private function getResolverCountry()
500
    {
501
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
502
        $store = $objectManager->get('Magento\Framework\Locale\Resolver');
503
504
        if (method_exists($store, 'getLocale')) {
505
            return $store->getLocale();
506
        }
507
508
        return null;
509
    }
510
}
511