WcPagantis4xGateway::generateUrl()   A
last analyzed

Complexity

Conditions 5
Paths 7

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 12
c 1
b 0
f 0
nc 7
nop 1
dl 0
loc 16
rs 9.5555
1
<?php
2
3
//namespace empty
4
use Pagantis\ModuleUtils\Exception\OrderNotFoundException;
5
use Pagantis\OrdersApiClient\Model\Order\User\Address;
6
use Pagantis\OrdersApiClient\Model\Order\User;
7
use Pagantis\OrdersApiClient\Model\Order\User\OrderHistory;
8
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details;
9
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart;
10
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product;
11
use Pagantis\OrdersApiClient\Model\Order\Metadata;
12
use Pagantis\OrdersApiClient\Model\Order\Configuration\Urls;
13
use Pagantis\OrdersApiClient\Model\Order\Configuration\Channel;
14
use Pagantis\OrdersApiClient\Model\Order\Configuration;
15
use Pagantis\OrdersApiClient\Client;
16
use Pagantis\OrdersApiClient\Model\Order;
17
18
if (!defined('ABSPATH')) {
19
    exit;
20
}
21
22
if (!defined('__ROOT__')) {
23
    define('__ROOT__', dirname(dirname(__FILE__)));
24
}
25
26
class WcPagantis4xGateway extends WC_Payment_Gateway
0 ignored issues
show
Bug introduced by
The type WC_Payment_Gateway 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...
27
{
28
    const METHOD_ID = "pagantis4x";
29
30
31
32
    const NOT_CONFIRMED = 'No se ha podido confirmar el pago';
33
34
35
    /** @var array $extraConfig */
36
    public $extraConfig;
37
38
    /** @var string $language */
39
    public $language;
40
41
    /**
42
     * @var string $template_path
43
     */
44
45
    private $template_path;
46
    /**
47
     * @var array $allowed_currencies
48
     */
49
    private $allowed_currencies;
50
51
    /**
52
     * @var string
53
     */
54
    private $urlToken4x;
55
56
57
    /**
58
     * WcPagantis4xGateway constructor.
59
     */
60
    public function __construct()
61
    {
62
        //Mandatory vars for plugin
63
        $this->id = WcPagantis4xGateway::METHOD_ID;
0 ignored issues
show
Bug Best Practice introduced by
The property id does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
64
        $this->has_fields = true;
0 ignored issues
show
Bug Best Practice introduced by
The property has_fields does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
65
        $this->method_title = ucfirst($this->id);
0 ignored issues
show
Bug Best Practice introduced by
The property method_title does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
66
        $this->urlToken4x = strtoupper(md5(uniqid(rand(), true)));
67
68
        //Useful vars
69
        $this->template_path = plugin_dir_path(__FILE__) . '../templates/';
0 ignored issues
show
Bug introduced by
The function plugin_dir_path 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

69
        $this->template_path = /** @scrutinizer ignore-call */ plugin_dir_path(__FILE__) . '../templates/';
Loading history...
70
        $this->allowed_currencies = getAllowedCurrencies();
71
        $this->language = strstr(get_locale(), '_', true);
0 ignored issues
show
Bug introduced by
The function get_locale 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

71
        $this->language = strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true);
Loading history...
72
        if ($this->language=='') {
73
            $this->language = 'ES';
74
        }
75
        $this->icon = 'https://cdn.digitalorigin.com/assets/master/logos/pg-130x30.svg';
0 ignored issues
show
Bug Best Practice introduced by
The property icon does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
76
77
        //Panel form fields
78
        $this->form_fields = include(plugin_dir_path(__FILE__).'../includes/settings-pagantis.php');//Panel options
0 ignored issues
show
Bug Best Practice introduced by
The property form_fields does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
79
        $this->init_settings();
80
81
        $this->extraConfig = getExtraConfig();
82
        $this->title = __($this->extraConfig['PAGANTIS_TITLE_4x'], 'pagantis');
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

82
        $this->title = /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE_4x'], 'pagantis');
Loading history...
Bug Best Practice introduced by
The property title does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
83
        $this->method_description = "Financial Payment Gateway. Enable the possibility for your customers to pay their order in confortable installments with Pagantis.";
0 ignored issues
show
Bug Best Practice introduced by
The property method_description does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
84
85
        $this->settings['ok_url'] = ($this->extraConfig['PAGANTIS_URL_OK']!='')?$this->extraConfig['PAGANTIS_URL_OK']:$this->generateOkUrl();
0 ignored issues
show
Bug Best Practice introduced by
The property settings does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
86
        $this->settings['ko_url'] = ($this->extraConfig['PAGANTIS_URL_KO']!='')?$this->extraConfig['PAGANTIS_URL_KO']:$this->generateKoUrl();
87
        foreach ($this->settings as $setting_key => $setting_value) {
88
            $this->$setting_key = $setting_value;
89
        }
90
91
        //Hooks
92
        add_action('woocommerce_update_options_payment_gateways_'.$this->id, array($this,'process_admin_options')); //Save plugin options
0 ignored issues
show
Bug introduced by
The function add_action 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

92
        /** @scrutinizer ignore-call */ 
93
        add_action('woocommerce_update_options_payment_gateways_'.$this->id, array($this,'process_admin_options')); //Save plugin options
Loading history...
93
        add_action('woocommerce_receipt_'.$this->id, array($this, 'pagantisReceiptPage'));          //Pagantis form
94
        add_action('woocommerce_api_wcpagantisgateway', array($this, 'pagantisNotification'));      //Json Notification
95
        add_filter('woocommerce_payment_complete_order_status', array($this,'pagantisCompleteStatus'), 10, 3);
0 ignored issues
show
Bug introduced by
The function add_filter 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

95
        /** @scrutinizer ignore-call */ 
96
        add_filter('woocommerce_payment_complete_order_status', array($this,'pagantisCompleteStatus'), 10, 3);
Loading history...
96
        add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
97
    }
98
99
    /**
100
     * @param $mofile
101
     * @param $domain
102
     *
103
     * @return string
104
     */
105
    public function loadPagantisTranslation($mofile, $domain)
106
    {
107
        if ('pagantis' === $domain) {
108
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . get_locale() . '.mo';
0 ignored issues
show
Bug introduced by
The constant WP_LANG_DIR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The function get_locale 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

108
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . /** @scrutinizer ignore-call */ get_locale() . '.mo';
Loading history...
109
        }
110
        return $mofile;
111
    }
112
113
    /***********
114
     *
115
     * HOOKS
116
     *
117
     ***********/
118
119
    /**
120
     * PANEL - Display admin panel
121
     * @hooked woocommerce_update_options_payment_gateways_pagantis
122
     */
123
    public function admin_options()
124
    {
125
        $template_fields = array(
126
            'panel_description' => $this->method_description,
127
            'button1_label' => __('Login to your panel', 'pagantis'),
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

127
            'button1_label' => /** @scrutinizer ignore-call */ __('Login to your panel', 'pagantis'),
Loading history...
128
            'button2_label' => __('Documentation', 'pagantis'),
129
            'logo' => $this->icon,
130
            'settings' => $this->generate_settings_html($this->form_fields, false)
131
        );
132
        wc_get_template('admin_header.php', $template_fields, '', $this->template_path);
0 ignored issues
show
Bug introduced by
The function wc_get_template 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

132
        /** @scrutinizer ignore-call */ 
133
        wc_get_template('admin_header.php', $template_fields, '', $this->template_path);
Loading history...
133
    }
134
135
    /**
136
     * CHECKOUT - Generate the pagantis form. "Return" iframe or redirect.
137
     * @param $order_id
138
     *
139
     * @throws Exception
140
     * @hooked woocommerce_receipt_pagantis
141
     */
142
    public function pagantisReceiptPage($order_id)
143
    {
144
        try {
145
            require_once(__ROOT__.'/vendor/autoload.php');
146
            global $woocommerce;
147
            $order = new WC_Order($order_id);
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...
148
            $order->set_payment_method(ucfirst($this->id));
149
            $order->save();
150
151
            if (!isset($order)) {
152
                throw new Exception(_("Order not found"));
153
            }
154
155
            $shippingAddress = $order->get_address('shipping');
156
            $billingAddress = $order->get_address('billing');
157
            if ($shippingAddress['address_1'] == '') {
158
                $shippingAddress = $billingAddress;
159
            }
160
161
            $customer_id = $order->get_customer_id();
162
            $national_id = maybeGetIDNumber($order , $customer_id);
163
            $tax_id = maybeGetTaxIDNumber($order , $customer_id);
164
            $phoneNumber = maybeGetPhoneNumber($order , $customer_id);
165
166
167
            $userAddress = new Address();
168
            $userAddress
169
                ->setZipCode($shippingAddress['postcode'])
170
                ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name'])
171
                ->setCountryCode($shippingAddress['country']!='' ? strtoupper($shippingAddress['country']) : strtoupper($this->language))
172
                ->setCity($shippingAddress['city'])
173
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
174
                ->setDni($national_id)
175
176
            ;
177
            $orderShippingAddress = new Address();
178
            $orderShippingAddress
179
                ->setZipCode($shippingAddress['postcode'])
180
                ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name'])
181
                ->setCountryCode($shippingAddress['country']!='' ? strtoupper($shippingAddress['country']) : strtoupper($this->language))
182
                ->setCity($shippingAddress['city'])
183
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
184
                ->setFixPhone($phoneNumber)
185
                ->setMobilePhone($phoneNumber)
186
                ->setNationalId($national_id)
187
                ->setDni($national_id)
188
                ->setTaxId($tax_id)
189
            ;
190
            $orderBillingAddress =  new Address();
191
            $orderBillingAddress
192
                ->setZipCode($billingAddress['postcode'])
193
                ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name'])
194
                ->setCountryCode($billingAddress['country']!='' ? strtoupper($billingAddress['country']) : strtoupper($this->language))
195
                ->setCity($billingAddress['city'])
196
                ->setAddress($billingAddress['address_1']." ".$billingAddress['address_2'])
197
                ->setFixPhone($phoneNumber)
198
                ->setMobilePhone($phoneNumber)
199
                ->setNationalId($national_id)
200
                ->setTaxId($tax_id)
201
            ;
202
            $orderUser = new User();
203
            $orderUser
204
                ->setAddress($userAddress)
205
                ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name'])
206
                ->setBillingAddress($orderBillingAddress)
207
                ->setEmail($billingAddress['email'])
208
                ->setFixPhone($phoneNumber)
209
                ->setMobilePhone($phoneNumber)
210
                ->setShippingAddress($orderShippingAddress)
211
                ->setNationalId($national_id)
212
                ->setTaxId($tax_id)
213
            ;
214
215
            if (!empty(maybeGetDateOfBirth($customer_id))) {
216
                $orderUser->setDateOfBirth($birthday);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $birthday seems to be never defined.
Loading history...
217
            }
218
219
            $previousOrders = getOrders($order->get_user(), $billingAddress['email']);
220
            foreach ($previousOrders as $previousOrder) {
221
                $orderHistory = new OrderHistory();
222
                $orderElement = wc_get_order($previousOrder);
0 ignored issues
show
Bug introduced by
The function wc_get_order 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

222
                $orderElement = /** @scrutinizer ignore-call */ wc_get_order($previousOrder);
Loading history...
223
                $orderCreated = $orderElement->get_date_created();
224
                $orderHistory
225
                    ->setAmount(intval(100 * $orderElement->get_total()))
226
                    ->setDate(new \DateTime($orderCreated->date('Y-m-d H:i:s')))
0 ignored issues
show
Bug introduced by
new DateTime($orderCreated->date('Y-m-d H:i:s')) of type DateTime is incompatible with the type string expected by parameter $date of Pagantis\OrdersApiClient...OrderHistory::setDate(). ( Ignorable by Annotation )

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

226
                    ->setDate(/** @scrutinizer ignore-type */ new \DateTime($orderCreated->date('Y-m-d H:i:s')))
Loading history...
227
                ;
228
                $orderUser->addOrderHistory($orderHistory);
229
            }
230
231
            $metadataOrder = new Metadata();
232
            $metadata = array(
233
                'pg_module' => 'woocommerce',
234
                'pg_version' => getModuleVersion(),
235
                'ec_module' => 'woocommerce',
236
                'ec_version' => WC()->version
0 ignored issues
show
Bug introduced by
The function WC 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

236
                'ec_version' => /** @scrutinizer ignore-call */ WC()->version
Loading history...
237
            );
238
239
            foreach ($metadata as $key => $metadatum) {
240
                $metadataOrder->addMetadata($key, $metadatum);
241
            }
242
243
            $details = new Details();
244
            $shippingCost = $order->shipping_total;
245
            $details->setShippingCost(intval(strval(100 * $shippingCost)));
246
            $items = $order->get_items();
247
            $promotedAmount = 0;
248
            foreach ($items as $key => $item) {
249
                $wcProduct = $item->get_product();
250
                $product = new Product();
251
                $productDescription = sprintf(
252
                    '%s %s %s',
253
                    $wcProduct->get_name(),
254
                    $wcProduct->get_description(),
255
                    $wcProduct->get_short_description()
256
                );
257
                $productDescription = substr($productDescription, 0, 9999);
258
259
                $product
260
                    ->setAmount(intval(100 * ($item->get_total() + $item->get_total_tax())))
261
                    ->setQuantity($item->get_quantity())
262
                    ->setDescription($productDescription)
263
                ;
264
                $details->addProduct($product);
265
266
                $promotedProduct = isProductPromoted($item->get_product_id());
267
                if ($promotedProduct == 'true') {
268
                    $promotedAmount+=$product->getAmount();
269
                    $promotedMessage = 'Promoted Item: ' . $wcProduct->get_name() .
270
                                       ' - Price: ' . $item->get_total() .
271
                                       ' - Qty: ' . $product->getQuantity() .
272
                                       ' - Item ID: ' . $item['id_product'];
273
                    $promotedMessage = substr($promotedMessage, 0, 999);
274
                    $metadataOrder->addMetadata('promotedProduct', $promotedMessage);
275
                }
276
            }
277
278
            $orderShoppingCart = new ShoppingCart();
279
            $orderShoppingCart
280
                ->setDetails($details)
281
                ->setOrderReference($order->get_id())
282
                ->setPromotedAmount($promotedAmount)
283
                ->setTotalAmount(intval(strval(100 * $order->total)))
284
            ;
285
            $orderConfigurationUrls = new Urls();
286
            $cancelUrl = $this->getKoUrl($order);
287
            $callback_arg = array('wc-api'=>'wcpagantisgateway',
288
                                  'key'=>$order->get_order_key(),
289
                                  'order-received'=>$order->get_id(),
290
                                  'origin' => '',
291
                                  'token' => $this->urlToken4x
292
293
            );
294
295
            $callback_arg_user = $callback_arg;
296
            $callback_arg_user['origin'] = 'redirect';
297
            $callback_arg_user['product'] = Ucfirst(WcPagantis4xGateway::METHOD_ID);
298
            $callback_url_user = add_query_arg($callback_arg_user, home_url('/'));
0 ignored issues
show
Bug introduced by
The function add_query_arg 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

298
            $callback_url_user = /** @scrutinizer ignore-call */ add_query_arg($callback_arg_user, home_url('/'));
Loading history...
Bug introduced by
The function home_url 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

298
            $callback_url_user = add_query_arg($callback_arg_user, /** @scrutinizer ignore-call */ home_url('/'));
Loading history...
299
300
            $callback_arg_notif = $callback_arg;
301
            $callback_arg_notif['origin'] = 'notification';
302
            $callback_arg_notif['product'] = Ucfirst(WcPagantis4xGateway::METHOD_ID);
303
            $callback_url_notif = add_query_arg($callback_arg_notif, home_url('/'));
304
305
            $orderConfigurationUrls
306
                ->setCancel($cancelUrl)
307
                ->setKo($callback_url_user)
308
                ->setAuthorizedNotificationCallback($callback_url_notif)
309
                ->setRejectedNotificationCallback(null)
310
                ->setOk($callback_url_user)
311
            ;
312
            $orderChannel = new Channel();
313
            $orderChannel
314
                ->setAssistedSale(false)
315
                ->setType(Channel::ONLINE)
316
            ;
317
318
            $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
319
            $purchaseCountry =
320
                in_array(strtolower($this->language), $allowedCountries) ? $this->language :
321
                    in_array(strtolower($shippingAddress['country']), $allowedCountries) ? $shippingAddress['country'] :
322
                        in_array(strtolower($billingAddress['country']), $allowedCountries) ? $billingAddress['country'] : null;
323
324
            $orderConfiguration = new Configuration();
325
            $orderConfiguration
326
                ->setChannel($orderChannel)
327
                ->setUrls($orderConfigurationUrls)
328
                ->setPurchaseCountry($purchaseCountry)
329
            ;
330
331
            $orderApiClient = new Order();
332
            $orderApiClient
333
                ->setConfiguration($orderConfiguration)
334
                ->setMetadata($metadataOrder)
335
                ->setShoppingCart($orderShoppingCart)
336
                ->setUser($orderUser)
337
            ;
338
339
            $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

339
            $cfg = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
340
            if ($cfg['pagantis_public_key_4x']=='' || $cfg['pagantis_private_key_4x']=='') {
341
                throw new \Exception('Public and Secret Key not found');
342
            }
343
            $orderClient = new Client($cfg['pagantis_public_key_4x'], $cfg['pagantis_private_key_4x']);
344
            $pagantisOrder = $orderClient->createOrder($orderApiClient);
345
            if ($pagantisOrder instanceof \Pagantis\OrdersApiClient\Model\Order) {
0 ignored issues
show
introduced by
$pagantisOrder is always a sub-type of Pagantis\OrdersApiClient\Model\Order.
Loading history...
346
                $url = $pagantisOrder->getActionUrls()->getForm();
347
                addOrderToProcessingQueue($pagantisOrder->getId(), $order->get_id(), $this->urlToken4x,self::METHOD_ID);
348
            } else {
349
                throw new OrderNotFoundException();
350
            }
351
352
            if ($url=="") {
353
                throw new Exception(_("No ha sido posible obtener una respuesta de Pagantis"));
354
            } elseif ($this->extraConfig['PAGANTIS_FORM_DISPLAY_TYPE']=='0') {
355
                wp_redirect($url);
0 ignored issues
show
Bug introduced by
The function wp_redirect 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

355
                /** @scrutinizer ignore-call */ 
356
                wp_redirect($url);
Loading history...
356
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
357
            } else {
358
                // @todo TM refactor with wp_localize_script - maybe put in other function
359
                $template_fields = array(
360
                    'url' => $url,
361
                    'checkoutUrl'   => $cancelUrl
362
                );
363
                wc_get_template('iframe.php', $template_fields, '', $this->template_path);
0 ignored issues
show
Bug introduced by
The function wc_get_template 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

363
                /** @scrutinizer ignore-call */ 
364
                wc_get_template('iframe.php', $template_fields, '', $this->template_path);
Loading history...
364
            }
365
        } catch (\Exception $exception) {
366
            wc_add_notice(__('Payment error ', 'pagantis') . $exception->getMessage(), 'error');
0 ignored issues
show
Bug introduced by
The function wc_add_notice 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

366
            /** @scrutinizer ignore-call */ 
367
            wc_add_notice(__('Payment error ', 'pagantis') . $exception->getMessage(), 'error');
Loading history...
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

366
            wc_add_notice(/** @scrutinizer ignore-call */ __('Payment error ', 'pagantis') . $exception->getMessage(), 'error');
Loading history...
367
            insertLogEntry($exception);
368
            $checkout_url = get_permalink(wc_get_page_id('checkout'));
0 ignored issues
show
Bug introduced by
The function wc_get_page_id 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

368
            $checkout_url = get_permalink(/** @scrutinizer ignore-call */ wc_get_page_id('checkout'));
Loading history...
Bug introduced by
The function get_permalink 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

368
            $checkout_url = /** @scrutinizer ignore-call */ get_permalink(wc_get_page_id('checkout'));
Loading history...
369
            wp_redirect($checkout_url);
370
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
371
        }
372
    }
373
374
    /**
375
     * NOTIFICATION - Endpoint for Json notification
376
     *
377
     * @hooked woocommerce_api_wcpagantisgateway
378
     */
379
    public function pagantisNotification()
380
    {
381
        try {
382
            $origin = ($_SERVER['REQUEST_METHOD'] == 'POST') ? 'Notify' : 'Order';
383
384
            include_once('notifyController.php');
385
            $notify = new WcPagantisNotify();
386
            $notify->setOrigin($origin);
387
            /** @var \Pagantis\ModuleUtils\Model\Response\AbstractJsonResponse $result */
388
            $result = $notify->processInformation();
389
        } catch (Exception $exception) {
390
            $result['notification_message'] = $exception->getMessage();
391
            $result['notification_error'] = true;
392
        }
393
394
        $paymentOrder = new WC_Order($result->getMerchantOrderId());
395
        if ($paymentOrder instanceof WC_Order) {
396
            $orderStatus = strtolower($paymentOrder->get_status());
397
        } else {
398
            $orderStatus = 'cancelled';
399
        }
400
        $acceptedStatus = array('processing', 'completed');
401
        if (in_array($orderStatus, $acceptedStatus)) {
402
            $returnUrl = $this->getOkUrl($paymentOrder);
403
        } else {
404
            $returnUrl = $this->getKoUrl($paymentOrder);
405
        }
406
407
        wp_redirect($returnUrl);
0 ignored issues
show
Bug introduced by
The function wp_redirect 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

407
        /** @scrutinizer ignore-call */ 
408
        wp_redirect($returnUrl);
Loading history...
408
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
409
    }
410
411
    /**
412
     * After failed status, set to processing not complete -> Hook: woocommerce_payment_complete_order_status
413
     * @param $status
414
     * @param $order_id
415
     * @param $order
416
     *
417
     * @return string
418
     */
419
    public function pagantisCompleteStatus($status, $order_id, $order)
420
    {
421
        if ($order->get_payment_method() == WcPagantis4xGateway::METHOD_ID) {
422
            if ($order->get_status() == 'failed') {
423
                $status = 'processing';
424
            } elseif ($order->get_status() == 'pending' && $status=='completed') {
425
                $status = 'processing';
426
            }
427
        }
428
429
        return $status;
430
    }
431
432
    /***********
433
     *
434
     * REDEFINED FUNCTIONS
435
     *
436
     ***********/
437
438
439
    /**
440
     * CHECKOUT - Check if payment method is available
441
     *
442
     * @return bool
443
     * @see WC_Payment_Gateway::is_available()
444
     */
445
    public function is_available()
446
    {
447
        $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

447
        $cfg = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
448
        $locale = strtolower(strstr(get_locale(), '_', true));
0 ignored issues
show
Bug introduced by
The function get_locale 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

448
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
449
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
450
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
451
        $minAmount = $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT_4x'];
452
        $maxAmount = $this->extraConfig['PAGANTIS_DISPLAY_MAX_AMOUNT_4x'];
453
        $totalPrice = (int)$this->get_order_total();
454
        $validAmount = ($totalPrice>=$minAmount && ($totalPrice<=$maxAmount || $maxAmount=='0'));
455
        if ($cfg['enabled_4x']==='yes' && $cfg['pagantis_public_key_4x']!='' && $cfg['pagantis_private_key_4x']!='' &&
456
            $validAmount && $allowedCountry) {
457
            return true;
458
        }
459
460
        return false;
461
    }
462
463
    /**
464
     * CHECKOUT - Checkout + admin panel title(method_title - get_title)
465
     *
466
     * @return string
467
     * @see WC_Payment_Gateway::get_title()
468
     */
469
    public function get_title()
470
    {
471
        return __($this->extraConfig['PAGANTIS_TITLE_4x'], 'pagantis');
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

471
        return /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE_4x'], 'pagantis');
Loading history...
472
    }
473
474
    /**
475
     * CHECKOUT - Called after push pagantis button on checkout
476
     *
477
     * @param $order_id
478
     *
479
     * @return array
480
     * @see WC_Payment_Gateway::process_payment()
481
     */
482
    public function process_payment($order_id)
483
    {
484
        try {
485
            $order = new WC_Order($order_id);
486
487
            $redirectUrl = $order->get_checkout_payment_url(true); //pagantisReceiptPage function
488
            if (strpos($redirectUrl, 'order-pay=')===false) {
489
                $redirectUrl.="&order-pay=".$order_id;
490
            }
491
492
            return array(
493
                'result'   => 'success',
494
                'redirect' => $redirectUrl
495
            );
496
        } catch (Exception $e) {
497
            wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
0 ignored issues
show
Bug introduced by
The function wc_add_notice 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

497
            /** @scrutinizer ignore-call */ 
498
            wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
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

497
            wc_add_notice(/** @scrutinizer ignore-call */ __('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
498
            return array();
499
        }
500
    }
501
502
    /**
503
     * CHECKOUT - simulator
504
     *
505
     * @see WC_Payment_Gateway::payment_fields()
506
     */
507
    public function payment_fields()
508
    {
509
        $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

509
        $cfg = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
510
        $locale = strtolower(strstr(get_locale(), '_', true));
0 ignored issues
show
Bug introduced by
The function get_locale 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

510
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
511
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
512
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
513
        $promotedAmount = getPromotedAmount();
514
515
        $template_fields = array(
516
            'public_key' => $cfg['pagantis_public_key_4x'],
517
            'total' => WC()->session->cart_totals['total'],
0 ignored issues
show
Bug introduced by
The function WC 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

517
            'total' => /** @scrutinizer ignore-call */ WC()->session->cart_totals['total'],
Loading history...
518
            'enabled' =>  $cfg['enabled_4x'],
519
            'min_installments' => $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT_4x'],
520
            'max_installments' => $this->extraConfig['PAGANTIS_DISPLAY_MAX_AMOUNT_4x'],
521
            'simulator_enabled' => "yes",
522
            'locale' => $locale,
523
            'country' => $locale,
524
            'allowed_country' => $allowedCountry,
525
            'simulator_type' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE_CHECKOUT'],
526
            'promoted_amount' => $promotedAmount,
527
            'thousandSeparator' => $this->extraConfig['PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'],
528
            'decimalSeparator' => $this->extraConfig['PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR'],
529
            'pagantisSimulatorSkin' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_SKIN'],
530
            'product' => '4x'
531
        );
532
533
        wc_get_template('checkout_description4x.php', $template_fields, '', $this->template_path);
0 ignored issues
show
Bug introduced by
The function wc_get_template 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

533
        /** @scrutinizer ignore-call */ 
534
        wc_get_template('checkout_description4x.php', $template_fields, '', $this->template_path);
Loading history...
534
    }
535
536
    /***********
537
     *
538
     * UTILS FUNCTIONS
539
     *
540
     ***********/
541
542
    /**
543
     * PANEL KO_URL FIELD
544
     * CHECKOUT PAGE => ?page_id=91 // ORDER-CONFIRMATION PAGE => ?page_id=91&order-pay=<order_id>&key=<order_key>
545
     */
546
    private function generateOkUrl()
547
    {
548
        return $this->generateUrl($this->get_return_url());
549
    }
550
551
    /**
552
     * PANEL OK_URL FIELD
553
     */
554
    private function generateKoUrl()
555
    {
556
        return $this->generateUrl(get_permalink(wc_get_page_id('checkout')));
0 ignored issues
show
Bug introduced by
The function get_permalink 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

556
        return $this->generateUrl(/** @scrutinizer ignore-call */ get_permalink(wc_get_page_id('checkout')));
Loading history...
Bug introduced by
The function wc_get_page_id 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

556
        return $this->generateUrl(get_permalink(/** @scrutinizer ignore-call */ wc_get_page_id('checkout')));
Loading history...
557
    }
558
559
    /**
560
     * Replace empty space by {{var}}
561
     * @param $url
562
     *
563
     * @return string
564
     */
565
    private function generateUrl($url)
566
    {
567
        $parsed_url = parse_url($url);
568
        if ($parsed_url !== false) {
569
            $parsed_url['query'] = !isset($parsed_url['query']) ? '' : $parsed_url['query'];
570
            parse_str($parsed_url['query'], $arrayParams);
571
            foreach ($arrayParams as $keyParam => $valueParam) {
572
                if ($valueParam=='') {
573
                    $arrayParams[$keyParam] = '{{'.$keyParam.'}}';
574
                }
575
            }
576
            $parsed_url['query'] = http_build_query($arrayParams);
577
            $return_url = $this->unparseUrl($parsed_url);
578
            return urldecode($return_url);
579
        } else {
580
            return $url;
581
        }
582
    }
583
584
    /**
585
     * Replace {{}} by vars values inside ok_url
586
     * @param $order
587
     *
588
     * @return string
589
     */
590
    private function getOkUrl($order)
591
    {
592
        return $this->getKeysUrl($order, $this->ok_url);
593
    }
594
595
    /**
596
     * Replace {{}} by vars values inside ko_url
597
     * @param $order
598
     *
599
     * @return string
600
     */
601
    private function getKoUrl($order)
602
    {
603
        return $this->getKeysUrl($order, $this->ko_url);
604
    }
605
606
    /**
607
     * Replace {{}} by vars values
608
     * @param $order
609
     * @param $url
610
     *
611
     * @return string
612
     */
613
    private function getKeysUrl($order, $url)
614
    {
615
        $defaultFields = (get_class($order)=='WC_Order') ?
616
            array('order-received'=>$order->get_id(), 'key'=>$order->get_order_key()) :
617
            array();
618
619
        $parsedUrl = parse_url($url);
620
        if ($parsedUrl !== false) {
621
            //Replace parameters from url
622
            $parsedUrl['query'] = $this->getKeysParametersUrl($parsedUrl['query'], $defaultFields);
623
624
            //Replace path from url
625
            $parsedUrl['path'] = $this->getKeysPathUrl($parsedUrl['path'], $defaultFields);
626
627
            $returnUrl = $this->unparseUrl($parsedUrl);
628
            return $returnUrl;
629
        }
630
        return $url;
631
    }
632
633
    /**
634
     * Replace {{}} by vars values inside parameters
635
     * @param $queryString
636
     * @param $defaultFields
637
     *
638
     * @return string
639
     */
640
    private function getKeysParametersUrl($queryString, $defaultFields)
641
    {
642
        parse_str(html_entity_decode($queryString), $arrayParams);
643
        $commonKeys = array_intersect_key($arrayParams, $defaultFields);
644
        if (count($commonKeys)) {
645
            $arrayResult = array_merge($arrayParams, $defaultFields);
646
        } else {
647
            $arrayResult = $arrayParams;
648
        }
649
        return urldecode(http_build_query($arrayResult));
650
    }
651
652
    /**
653
     * Replace {{}} by vars values inside path
654
     * @param $pathString
655
     * @param $defaultFields
656
     *
657
     * @return string
658
     */
659
    private function getKeysPathUrl($pathString, $defaultFields)
660
    {
661
        $arrayParams = explode("/", $pathString);
662
        foreach ($arrayParams as $keyParam => $valueParam) {
663
            preg_match('#\{{.*?}\}#', $valueParam, $match);
664
            if (count($match)) {
665
                $key = str_replace(array('{{','}}'), array('',''), $match[0]);
666
                $arrayParams[$keyParam] = $defaultFields[$key];
667
            }
668
        }
669
        return implode('/', $arrayParams);
670
    }
671
672
    /**
673
     * Replace {{var}} by empty space
674
     * @param $parsed_url
675
     *
676
     * @return string
677
     */
678
    private function unparseUrl($parsed_url)
679
    {
680
        $scheme   = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
681
        $host     = isset($parsed_url['host']) ? $parsed_url['host'] : '';
682
        $port     = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
683
        $query    = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
684
        $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
685
        $path     = $parsed_url['path'];
686
        return $scheme . $host . $port . $path . $query . $fragment;
687
    }
688
}
689