Total Complexity | 117 |
Total Lines | 879 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
Complex classes like WcPagantisGateway often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use WcPagantisGateway, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
26 | class WcPagantisGateway extends WC_Payment_Gateway |
||
|
|||
27 | { |
||
28 | const METHOD_ID = "pagantis"; |
||
29 | |||
30 | /** @var array $extraConfig */ |
||
31 | public $extraConfig; |
||
32 | |||
33 | /** @var string $language */ |
||
34 | public $language; |
||
35 | |||
36 | |||
37 | /** |
||
38 | * WcPagantisGateway constructor. |
||
39 | */ |
||
40 | public function __construct() |
||
41 | { |
||
42 | //Mandatory vars for plugin |
||
43 | $this->id = self::METHOD_ID; |
||
44 | $this->has_fields = true; |
||
45 | $this->method_title = ucfirst($this->id); |
||
46 | include_once dirname(__FILE__).'/../includes/class-wc-pagantis-extraconfig.php'; |
||
47 | include_once dirname(__FILE__).'/../includes/class-wc-pagantis-logger.php'; |
||
48 | $value = WcPagantisExtraConfig::getExtraConfigValue('PAGANTIS_TITLE'); |
||
49 | WCPagantisLogger::writeLog($value); |
||
50 | //Useful vars |
||
51 | $this->template_path = plugin_dir_path(__FILE__) . '../templates/'; |
||
52 | $this->allowed_currencies = array("EUR"); |
||
53 | $this->language = strstr(get_locale(), '_', true); |
||
54 | if ($this->language=='') { |
||
55 | $this->language = 'ES'; |
||
56 | } |
||
57 | $this->icon = 'https://cdn.digitalorigin.com/assets/master/logos/pg-130x30.svg'; |
||
58 | |||
59 | //Panel form fields |
||
60 | $this->form_fields = include(plugin_dir_path(__FILE__).'../includes/settings-pagantis.php');//Panel options |
||
61 | $this->init_settings(); |
||
62 | |||
63 | $this->extraConfig = $this->getExtraConfig(); |
||
64 | $this->title = __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis'); |
||
65 | $this->method_description = "Financial Payment Gateway. Enable the possibility for your customers to pay their order in confortable installments with Pagantis."; |
||
66 | |||
67 | $this->settings['ok_url'] = ($this->extraConfig['PAGANTIS_URL_OK']!='')?$this->extraConfig['PAGANTIS_URL_OK']:$this->generateOkUrl(); |
||
68 | $this->settings['ko_url'] = ($this->extraConfig['PAGANTIS_URL_KO']!='')?$this->extraConfig['PAGANTIS_URL_KO']:$this->generateKoUrl(); |
||
69 | foreach ($this->settings as $setting_key => $setting_value) { |
||
70 | $this->$setting_key = $setting_value; |
||
71 | } |
||
72 | |||
73 | //Hooks |
||
74 | add_action('woocommerce_update_options_payment_gateways_'.$this->id, array($this,'process_admin_options')); //Save plugin options |
||
75 | add_action('admin_notices', array($this, 'pagantisCheckFields')); //Check config fields |
||
76 | add_action('woocommerce_receipt_'.$this->id, array($this, 'pagantisReceiptPage')); //Pagantis form |
||
77 | add_action('woocommerce_api_wcpagantisgateway', array($this, 'pagantisNotification')); //Json Notification |
||
78 | add_filter('woocommerce_payment_complete_order_status', array($this,'pagantisCompleteStatus'), 10, 3); |
||
79 | add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2); |
||
80 | } |
||
81 | |||
82 | public function enqueue_scripts() |
||
83 | { |
||
84 | if ($this->enabled !== 'yes' || ! is_checkout() || is_order_received_page() || is_wc_endpoint_url('order-pay')) { |
||
85 | return; |
||
86 | } |
||
87 | |||
88 | wp_register_script( |
||
89 | 'pagantis-checkout', |
||
90 | plugins_url('../assets/js/pagantis-checkout.js', __FILE__), |
||
91 | array('jquery', 'woocommerce', 'wc-checkout', 'wc-country-select', 'wc-address-i18n'), |
||
92 | PAGANTIS_VERSION, |
||
93 | true |
||
94 | ); |
||
95 | wp_enqueue_script('pagantis-checkout'); |
||
96 | |||
97 | $checkout_localize_params = array(); |
||
98 | $checkout_localize_params['place_order_url'] = WC_AJAX::get_endpoint('pagantis_checkout'); |
||
99 | $checkout_localize_params['place_order_nonce'] = wp_create_nonce('pagantis_checkout'); |
||
100 | $checkout_localize_params['wc_ajax_url'] = WC_AJAX::get_endpoint('%%endpoint%%'); |
||
101 | $checkout_localize_params['i18n_checkout_error'] = esc_attr__('Error processing pagantis checkout. Please try again.', 'woocommerce'); |
||
102 | |||
103 | wp_localize_script('pagantis-checkout', 'pagantis_params', $checkout_localize_params); |
||
104 | |||
105 | wp_enqueue_script('pagantis_params'); |
||
106 | } |
||
107 | /** |
||
108 | * @param $mofile |
||
109 | * @param $domain |
||
110 | * |
||
111 | * @return string |
||
112 | */ |
||
113 | public function loadPagantisTranslation($mofile, $domain) |
||
114 | { |
||
115 | if ('pagantis' === $domain) { |
||
116 | $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . get_locale() . '.mo'; |
||
117 | } |
||
118 | return $mofile; |
||
119 | } |
||
120 | |||
121 | /*********** |
||
122 | * |
||
123 | * HOOKS |
||
124 | * |
||
125 | ***********/ |
||
126 | |||
127 | /** |
||
128 | * PANEL - Display admin panel -> Hook: woocommerce_update_options_payment_gateways_pagantis |
||
129 | */ |
||
130 | public function admin_options() |
||
131 | { |
||
132 | $template_fields = array( |
||
133 | 'panel_description' => $this->method_description, |
||
134 | 'button1_label' => __('Login to your panel', 'pagantis'), |
||
135 | 'button2_label' => __('Documentation', 'pagantis'), |
||
136 | 'logo' => $this->icon, |
||
137 | 'settings' => $this->generate_settings_html($this->form_fields, false) |
||
138 | ); |
||
139 | wc_get_template('admin_header.php', $template_fields, '', $this->template_path); |
||
140 | } |
||
141 | |||
142 | /** |
||
143 | * PANEL - Check admin panel fields -> Hook: admin_notices |
||
144 | */ |
||
145 | public function pagantisCheckFields() |
||
146 | { |
||
147 | $error_string = ''; |
||
148 | if ($this->settings['enabled'] !== 'yes') { |
||
149 | return; |
||
150 | } elseif (!version_compare(phpversion(), '5.3.0', '>=')) { |
||
151 | $error_string = __(' is not compatible with your php and/or curl version', 'pagantis'); |
||
152 | $this->settings['enabled'] = 'no'; |
||
153 | } elseif ($this->settings['pagantis_public_key']=="" || $this->settings['pagantis_private_key']=="") { |
||
154 | $error_string = __(' is not configured correctly, the fields Public Key and Secret Key are mandatory for use this plugin', 'pagantis'); |
||
155 | $this->settings['enabled'] = 'no'; |
||
156 | } elseif (!in_array(get_woocommerce_currency(), $this->allowed_currencies)) { |
||
157 | $error_string = __(' only can be used in Euros', 'pagantis'); |
||
158 | $this->settings['enabled'] = 'no'; |
||
159 | } elseif ($this->extraConfig['PAGANTIS_SIMULATOR_MAX_INSTALLMENTS']<'2' |
||
160 | || $this->extraConfig['PAGANTIS_SIMULATOR_MAX_INSTALLMENTS']>'12') { |
||
161 | $error_string = __(' only can be payed from 2 to 12 installments', 'pagantis'); |
||
162 | } elseif ($this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS']<'2' |
||
163 | || $this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS']>'12') { |
||
164 | $error_string = __(' only can be payed from 2 to 12 installments', 'pagantis'); |
||
165 | } elseif ($this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT']<0) { |
||
166 | $error_string = __(' can not have a minimum amount less than 0', 'pagantis'); |
||
167 | } |
||
168 | |||
169 | if ($error_string!='') { |
||
170 | $template_fields = array( |
||
171 | 'error_msg' => ucfirst(self::METHOD_ID).' '.$error_string, |
||
172 | ); |
||
173 | wc_get_template('error_msg.php', $template_fields, '', $this->template_path); |
||
174 | } |
||
175 | } |
||
176 | |||
177 | |||
178 | /** |
||
179 | * CHECKOUT - Generate the pagantis form. "Return" iframe or redirect. - Hook: woocommerce_receipt_pagantis |
||
180 | * @param $order_id |
||
181 | * |
||
182 | * @throws Exception |
||
183 | */ |
||
184 | public function pagantisReceiptPage($order_id) |
||
185 | { |
||
186 | try { |
||
187 | require_once(__ROOT__.'/vendor/autoload.php'); |
||
188 | global $woocommerce; |
||
189 | $order = new WC_Order($order_id); |
||
190 | $order->set_payment_method(ucfirst($this->id)); |
||
191 | $order->save(); |
||
192 | |||
193 | if (!isset($order)) { |
||
194 | throw new Exception(_("Order not found")); |
||
195 | } |
||
196 | |||
197 | $shippingAddress = $order->get_address('shipping'); |
||
198 | $billingAddress = $order->get_address('billing'); |
||
199 | if ($shippingAddress['address_1'] == '') { |
||
200 | $shippingAddress = $billingAddress; |
||
201 | } |
||
202 | |||
203 | $national_id = $this->getNationalId($order); |
||
204 | $tax_id = $this->getTaxId($order); |
||
205 | |||
206 | $userAddress = new Address(); |
||
207 | $userAddress |
||
208 | ->setZipCode($shippingAddress['postcode']) |
||
209 | ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name']) |
||
210 | ->setCountryCode($shippingAddress['country']!='' ? strtoupper($shippingAddress['country']) : strtoupper($this->language)) |
||
211 | ->setCity($shippingAddress['city']) |
||
212 | ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2']) |
||
213 | ; |
||
214 | $orderShippingAddress = new Address(); |
||
215 | $orderShippingAddress |
||
216 | ->setZipCode($shippingAddress['postcode']) |
||
217 | ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name']) |
||
218 | ->setCountryCode($shippingAddress['country']!='' ? strtoupper($shippingAddress['country']) : strtoupper($this->language)) |
||
219 | ->setCity($shippingAddress['city']) |
||
220 | ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2']) |
||
221 | ->setFixPhone($shippingAddress['phone']) |
||
222 | ->setMobilePhone($shippingAddress['phone']) |
||
223 | ->setNationalId($national_id) |
||
224 | ->setTaxId($tax_id) |
||
225 | ; |
||
226 | $orderBillingAddress = new Address(); |
||
227 | $orderBillingAddress |
||
228 | ->setZipCode($billingAddress['postcode']) |
||
229 | ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name']) |
||
230 | ->setCountryCode($billingAddress['country']!='' ? strtoupper($billingAddress['country']) : strtoupper($this->language)) |
||
231 | ->setCity($billingAddress['city']) |
||
232 | ->setAddress($billingAddress['address_1']." ".$billingAddress['address_2']) |
||
233 | ->setFixPhone($billingAddress['phone']) |
||
234 | ->setMobilePhone($billingAddress['phone']) |
||
235 | ->setNationalId($national_id) |
||
236 | ->setTaxId($tax_id) |
||
237 | ; |
||
238 | $orderUser = new User(); |
||
239 | $orderUser |
||
240 | ->setAddress($userAddress) |
||
241 | ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name']) |
||
242 | ->setBillingAddress($orderBillingAddress) |
||
243 | ->setEmail($billingAddress['email']) |
||
244 | ->setFixPhone($billingAddress['phone']) |
||
245 | ->setMobilePhone($billingAddress['phone']) |
||
246 | ->setShippingAddress($orderShippingAddress) |
||
247 | ->setNationalId($national_id) |
||
248 | ->setTaxId($tax_id) |
||
249 | ; |
||
250 | |||
251 | $previousOrders = $this->getOrders($order->get_user(), $billingAddress['email']); |
||
252 | foreach ($previousOrders as $previousOrder) { |
||
253 | $orderHistory = new OrderHistory(); |
||
254 | $orderElement = wc_get_order($previousOrder); |
||
255 | $orderCreated = $orderElement->get_date_created(); |
||
256 | $orderHistory |
||
257 | ->setAmount(intval(100 * $orderElement->get_total())) |
||
258 | ->setDate(new \DateTime($orderCreated->date('Y-m-d H:i:s'))) |
||
259 | ; |
||
260 | $orderUser->addOrderHistory($orderHistory); |
||
261 | } |
||
262 | |||
263 | $metadataOrder = new Metadata(); |
||
264 | $metadata = array( |
||
265 | 'pg_module' => 'woocommerce', |
||
266 | 'pg_version' => PAGANTIS_VERSION, |
||
267 | 'ec_module' => 'woocommerce', |
||
268 | 'ec_version' => WC()->version |
||
269 | ); |
||
270 | |||
271 | foreach ($metadata as $key => $metadatum) { |
||
272 | $metadataOrder->addMetadata($key, $metadatum); |
||
273 | } |
||
274 | |||
275 | $details = new Details(); |
||
276 | $shippingCost = $order->shipping_total; |
||
277 | $details->setShippingCost(intval(strval(100 * $shippingCost))); |
||
278 | $items = $order->get_items(); |
||
279 | $promotedAmount = 0; |
||
280 | foreach ($items as $key => $item) { |
||
281 | $wcProduct = $item->get_product(); |
||
282 | $product = new Product(); |
||
283 | $productDescription = sprintf( |
||
284 | '%s %s %s', |
||
285 | $wcProduct->get_name(), |
||
286 | $wcProduct->get_description(), |
||
287 | $wcProduct->get_short_description() |
||
288 | ); |
||
289 | $productDescription = substr($productDescription, 0, 9999); |
||
290 | |||
291 | $product |
||
292 | ->setAmount(intval(100 * ($item->get_total() + $item->get_total_tax()))) |
||
293 | ->setQuantity($item->get_quantity()) |
||
294 | ->setDescription($productDescription) |
||
295 | ; |
||
296 | $details->addProduct($product); |
||
297 | |||
298 | $promotedProduct = $this->isPromoted($item->get_product_id()); |
||
299 | if ($promotedProduct == 'true') { |
||
300 | $promotedAmount+=$product->getAmount(); |
||
301 | $promotedMessage = 'Promoted Item: ' . $wcProduct->get_name() . |
||
302 | ' - Price: ' . $item->get_total() . |
||
303 | ' - Qty: ' . $product->getQuantity() . |
||
304 | ' - Item ID: ' . $item['id_product']; |
||
305 | $promotedMessage = substr($promotedMessage, 0, 999); |
||
306 | $metadataOrder->addMetadata('promotedProduct', $promotedMessage); |
||
307 | } |
||
308 | } |
||
309 | |||
310 | $orderShoppingCart = new ShoppingCart(); |
||
311 | $orderShoppingCart |
||
312 | ->setDetails($details) |
||
313 | ->setOrderReference($order->get_id()) |
||
314 | ->setPromotedAmount($promotedAmount) |
||
315 | ->setTotalAmount(intval(strval(100 * $order->total))) |
||
316 | ; |
||
317 | $orderConfigurationUrls = new Urls(); |
||
318 | $cancelUrl = $this->getKoUrl($order); |
||
319 | $callback_arg = array('wc-api'=>'wcpagantisgateway', |
||
320 | 'key'=>$order->get_order_key(), |
||
321 | 'order-received'=>$order->get_id(), |
||
322 | 'origin' => '' |
||
323 | ); |
||
324 | |||
325 | $callback_arg_user = $callback_arg; |
||
326 | $callback_arg_user['origin'] = 'redirect'; |
||
327 | $callback_url_user = add_query_arg($callback_arg_user, home_url('/')); |
||
328 | |||
329 | $callback_arg_notif = $callback_arg; |
||
330 | $callback_arg_notif['origin'] = 'notification'; |
||
331 | $callback_url_notif = add_query_arg($callback_arg_notif, home_url('/')); |
||
332 | |||
333 | $orderConfigurationUrls |
||
334 | ->setCancel($cancelUrl) |
||
335 | ->setKo($callback_url_user) |
||
336 | ->setAuthorizedNotificationCallback($callback_url_notif) |
||
337 | ->setRejectedNotificationCallback(null) |
||
338 | ->setOk($callback_url_user) |
||
339 | ; |
||
340 | $orderChannel = new Channel(); |
||
341 | $orderChannel |
||
342 | ->setAssistedSale(false) |
||
343 | ->setType(Channel::ONLINE) |
||
344 | ; |
||
345 | |||
346 | $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']); |
||
347 | $purchaseCountry = |
||
348 | in_array(strtolower($this->language), $allowedCountries) ? $this->language : |
||
349 | in_array(strtolower($shippingAddress['country']), $allowedCountries) ? $shippingAddress['country'] : |
||
350 | in_array(strtolower($billingAddress['country']), $allowedCountries) ? $billingAddress['country'] : null; |
||
351 | |||
352 | $orderConfiguration = new Configuration(); |
||
353 | $orderConfiguration |
||
354 | ->setChannel($orderChannel) |
||
355 | ->setUrls($orderConfigurationUrls) |
||
356 | ->setPurchaseCountry($purchaseCountry) |
||
357 | ; |
||
358 | |||
359 | $orderApiClient = new Order(); |
||
360 | $orderApiClient |
||
361 | ->setConfiguration($orderConfiguration) |
||
362 | ->setMetadata($metadataOrder) |
||
363 | ->setShoppingCart($orderShoppingCart) |
||
364 | ->setUser($orderUser) |
||
365 | ; |
||
366 | |||
367 | if ($this->pagantis_public_key=='' || $this->pagantis_private_key=='') { |
||
368 | throw new \Exception('Public and Secret Key not found'); |
||
369 | } |
||
370 | $orderClient = new Client($this->pagantis_public_key, $this->pagantis_private_key); |
||
371 | $pagantisOrder = $orderClient->createOrder($orderApiClient); |
||
372 | if ($pagantisOrder instanceof \Pagantis\OrdersApiClient\Model\Order) { |
||
373 | $url = $pagantisOrder->getActionUrls()->getForm(); |
||
374 | $this->insertRow($order->get_id(), $pagantisOrder->getId()); |
||
375 | } else { |
||
376 | throw new OrderNotFoundException(); |
||
377 | } |
||
378 | |||
379 | if ($url=="") { |
||
380 | throw new Exception(_("No ha sido posible obtener una respuesta de Pagantis")); |
||
381 | } elseif ($this->extraConfig['PAGANTIS_FORM_DISPLAY_TYPE']=='0') { |
||
382 | wp_redirect($url); |
||
383 | exit; |
||
384 | } else { |
||
385 | $template_fields = array( |
||
386 | 'url' => $url, |
||
387 | 'checkoutUrl' => $cancelUrl |
||
388 | ); |
||
389 | wc_get_template('iframe.php', $template_fields, '', $this->template_path); |
||
390 | } |
||
391 | } catch (\Exception $exception) { |
||
392 | wc_add_notice(__('Payment error ', 'pagantis') . $exception->getMessage(), 'error'); |
||
393 | $this->insertLog($exception); |
||
394 | $checkout_url = get_permalink(wc_get_page_id('checkout')); |
||
395 | wp_redirect($checkout_url); |
||
396 | exit; |
||
397 | } |
||
398 | } |
||
399 | |||
400 | /** |
||
401 | * NOTIFICATION - Endpoint for Json notification - Hook: woocommerce_api_wcpagantisgateway |
||
402 | */ |
||
403 | public function pagantisNotification() |
||
404 | { |
||
405 | try { |
||
406 | $origin = ($_SERVER['REQUEST_METHOD'] == 'POST') ? 'Notify' : 'Order'; |
||
407 | |||
408 | include_once('notifyController.php'); |
||
409 | $notify = new WcPagantisNotify(); |
||
410 | $notify->setOrigin($origin); |
||
411 | /** @var \Pagantis\ModuleUtils\Model\Response\AbstractJsonResponse $result */ |
||
412 | $result = $notify->processInformation(); |
||
413 | } catch (Exception $exception) { |
||
414 | $result['notification_message'] = $exception->getMessage(); |
||
415 | $result['notification_error'] = true; |
||
416 | } |
||
417 | |||
418 | $paymentOrder = new WC_Order($result->getMerchantOrderId()); |
||
419 | if ($paymentOrder instanceof WC_Order) { |
||
420 | $orderStatus = strtolower($paymentOrder->get_status()); |
||
421 | } else { |
||
422 | $orderStatus = 'cancelled'; |
||
423 | } |
||
424 | $acceptedStatus = array('processing', 'completed'); |
||
425 | if (in_array($orderStatus, $acceptedStatus)) { |
||
426 | $returnUrl = $this->getOkUrl($paymentOrder); |
||
427 | } else { |
||
428 | $returnUrl = $this->getKoUrl($paymentOrder); |
||
429 | } |
||
430 | |||
431 | wp_redirect($returnUrl); |
||
432 | exit; |
||
433 | } |
||
434 | |||
435 | /** |
||
436 | * After failed status, set to processing not complete -> Hook: woocommerce_payment_complete_order_status |
||
437 | * @param $status |
||
438 | * @param $order_id |
||
439 | * @param $order |
||
440 | * |
||
441 | * @return string |
||
442 | */ |
||
443 | public function pagantisCompleteStatus($status, $order_id, $order) |
||
444 | { |
||
445 | if ($order->get_payment_method() == self::METHOD_ID) { |
||
446 | if ($order->get_status() == 'failed') { |
||
447 | $status = 'processing'; |
||
448 | } elseif ($order->get_status() == 'pending' && $status=='completed') { |
||
449 | $status = 'processing'; |
||
450 | } |
||
451 | } |
||
452 | |||
453 | return $status; |
||
454 | } |
||
455 | |||
456 | /*********** |
||
457 | * |
||
458 | * REDEFINED FUNCTIONS |
||
459 | * |
||
460 | ***********/ |
||
461 | |||
462 | /** |
||
463 | * CHECKOUT - Check if payment method is available (called by woocommerce, can't apply cammel caps) |
||
464 | * @return bool |
||
465 | */ |
||
466 | public function is_available() |
||
467 | { |
||
468 | $locale = strtolower(strstr(get_locale(), '_', true)); |
||
469 | $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']); |
||
470 | $allowedCountry = (in_array(strtolower($locale), $allowedCountries)); |
||
471 | $minAmount = $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT']; |
||
472 | $maxAmount = $this->extraConfig['PAGANTIS_DISPLAY_MAX_AMOUNT']; |
||
473 | $totalPrice = (int)$this->get_order_total(); |
||
474 | $validAmount = ($totalPrice>=$minAmount && ($totalPrice<=$maxAmount || $maxAmount=='0')); |
||
475 | if ($this->enabled==='yes' && $this->pagantis_public_key!='' && $this->pagantis_private_key!='' && |
||
476 | $validAmount && $allowedCountry) { |
||
477 | return true; |
||
478 | } |
||
479 | |||
480 | return false; |
||
481 | } |
||
482 | |||
483 | /** |
||
484 | * CHECKOUT - Checkout + admin panel title(method_title - get_title) (called by woocommerce,can't apply cammel caps) |
||
485 | * @return string |
||
486 | */ |
||
487 | public function get_title() |
||
488 | { |
||
489 | return __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis'); |
||
490 | } |
||
491 | |||
492 | /** |
||
493 | * CHECKOUT - Called after push pagantis button on checkout(called by woocommerce, can't apply cammel caps |
||
494 | * @param $order_id |
||
495 | * @return array |
||
496 | */ |
||
497 | public function process_payment($order_id) |
||
498 | { |
||
499 | try { |
||
500 | $order = new WC_Order($order_id); |
||
501 | |||
502 | $redirectUrl = $order->get_checkout_payment_url(true); //pagantisReceiptPage function |
||
503 | if (strpos($redirectUrl, 'order-pay=')===false) { |
||
504 | $redirectUrl.="&order-pay=".$order_id; |
||
505 | } |
||
506 | |||
507 | return array( |
||
508 | 'result' => 'success', |
||
509 | 'redirect' => $redirectUrl |
||
510 | ); |
||
511 | } catch (Exception $e) { |
||
512 | wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error'); |
||
513 | return array(); |
||
514 | } |
||
515 | } |
||
516 | |||
517 | /** |
||
518 | * CHECKOUT - simulator (called by woocommerce, can't apply cammel caps) |
||
519 | */ |
||
520 | public function payment_fields() |
||
521 | { |
||
522 | $locale = strtolower(strstr(get_locale(), '_', true)); |
||
523 | $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']); |
||
524 | $allowedCountry = (in_array(strtolower($locale), $allowedCountries)); |
||
525 | $promotedAmount = $this->getPromotedAmount(); |
||
526 | |||
527 | $template_fields = array( |
||
528 | 'public_key' => $this->pagantis_public_key, |
||
529 | 'total' => WC()->session->cart_totals['total'], |
||
530 | 'enabled' => $this->settings['enabled'], |
||
531 | 'min_installments' => $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'], |
||
532 | 'max_installments' => $this->extraConfig['PAGANTIS_DISPLAY_MAX_AMOUNT'], |
||
533 | 'simulator_enabled' => $this->settings['simulator'], |
||
534 | 'locale' => $locale, |
||
535 | 'country' => $locale, |
||
536 | 'allowed_country' => $allowedCountry, |
||
537 | 'simulator_type' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE_CHECKOUT'], |
||
538 | 'promoted_amount' => $promotedAmount, |
||
539 | 'thousandSeparator' => $this->extraConfig['PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'], |
||
540 | 'decimalSeparator' => $this->extraConfig['PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR'], |
||
541 | 'pagantisSimulatorSkin' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_SKIN'] |
||
542 | ); |
||
543 | wc_get_template('checkout_description.php', $template_fields, '', $this->template_path); |
||
544 | } |
||
545 | |||
546 | /*********** |
||
547 | * |
||
548 | * UTILS FUNCTIONS |
||
549 | * |
||
550 | ***********/ |
||
551 | |||
552 | /** |
||
553 | * PANEL KO_URL FIELD |
||
554 | * CHECKOUT PAGE => ?page_id=91 // ORDER-CONFIRMATION PAGE => ?page_id=91&order-pay=<order_id>&key=<order_key> |
||
555 | */ |
||
556 | private function generateOkUrl() |
||
557 | { |
||
558 | return $this->generateUrl($this->get_return_url()); |
||
559 | } |
||
560 | |||
561 | /** |
||
562 | * PANEL OK_URL FIELD |
||
563 | */ |
||
564 | private function generateKoUrl() |
||
565 | { |
||
566 | return $this->generateUrl(get_permalink(wc_get_page_id('checkout'))); |
||
567 | } |
||
568 | |||
569 | /** |
||
570 | * Replace empty space by {{var}} |
||
571 | * @param $url |
||
572 | * |
||
573 | * @return string |
||
574 | */ |
||
575 | private function generateUrl($url) |
||
576 | { |
||
577 | $parsed_url = parse_url($url); |
||
578 | if ($parsed_url !== false) { |
||
579 | $parsed_url['query'] = !isset($parsed_url['query']) ? '' : $parsed_url['query']; |
||
580 | parse_str($parsed_url['query'], $arrayParams); |
||
581 | foreach ($arrayParams as $keyParam => $valueParam) { |
||
582 | if ($valueParam=='') { |
||
583 | $arrayParams[$keyParam] = '{{'.$keyParam.'}}'; |
||
584 | } |
||
585 | } |
||
586 | $parsed_url['query'] = http_build_query($arrayParams); |
||
587 | $return_url = $this->unparseUrl($parsed_url); |
||
588 | return urldecode($return_url); |
||
589 | } else { |
||
590 | return $url; |
||
591 | } |
||
592 | } |
||
593 | |||
594 | /** |
||
595 | * Replace {{}} by vars values inside ok_url |
||
596 | * @param $order |
||
597 | * |
||
598 | * @return string |
||
599 | */ |
||
600 | private function getOkUrl($order) |
||
601 | { |
||
602 | return $this->getKeysUrl($order, $this->ok_url); |
||
603 | } |
||
604 | |||
605 | /** |
||
606 | * Replace {{}} by vars values inside ko_url |
||
607 | * @param $order |
||
608 | * |
||
609 | * @return string |
||
610 | */ |
||
611 | private function getKoUrl($order) |
||
612 | { |
||
613 | return $this->getKeysUrl($order, $this->ko_url); |
||
614 | } |
||
615 | |||
616 | /** |
||
617 | * Replace {{}} by vars values |
||
618 | * @param $order |
||
619 | * @param $url |
||
620 | * |
||
621 | * @return string |
||
622 | */ |
||
623 | private function getKeysUrl($order, $url) |
||
624 | { |
||
625 | $defaultFields = (get_class($order)=='WC_Order') ? |
||
626 | array('order-received'=>$order->get_id(), 'key'=>$order->get_order_key()) : |
||
627 | array(); |
||
628 | |||
629 | $parsedUrl = parse_url($url); |
||
630 | if ($parsedUrl !== false) { |
||
631 | //Replace parameters from url |
||
632 | $parsedUrl['query'] = $this->getKeysParametersUrl($parsedUrl['query'], $defaultFields); |
||
633 | |||
634 | //Replace path from url |
||
635 | $parsedUrl['path'] = $this->getKeysPathUrl($parsedUrl['path'], $defaultFields); |
||
636 | |||
637 | $returnUrl = $this->unparseUrl($parsedUrl); |
||
638 | return $returnUrl; |
||
639 | } |
||
640 | return $url; |
||
641 | } |
||
642 | |||
643 | /** |
||
644 | * Replace {{}} by vars values inside parameters |
||
645 | * @param $queryString |
||
646 | * @param $defaultFields |
||
647 | * |
||
648 | * @return string |
||
649 | */ |
||
650 | private function getKeysParametersUrl($queryString, $defaultFields) |
||
651 | { |
||
652 | parse_str(html_entity_decode($queryString), $arrayParams); |
||
653 | $commonKeys = array_intersect_key($arrayParams, $defaultFields); |
||
654 | if (count($commonKeys)) { |
||
655 | $arrayResult = array_merge($arrayParams, $defaultFields); |
||
656 | } else { |
||
657 | $arrayResult = $arrayParams; |
||
658 | } |
||
659 | return urldecode(http_build_query($arrayResult)); |
||
660 | } |
||
661 | |||
662 | /** |
||
663 | * Replace {{}} by vars values inside path |
||
664 | * @param $pathString |
||
665 | * @param $defaultFields |
||
666 | * |
||
667 | * @return string |
||
668 | */ |
||
669 | private function getKeysPathUrl($pathString, $defaultFields) |
||
670 | { |
||
671 | $arrayParams = explode("/", $pathString); |
||
672 | foreach ($arrayParams as $keyParam => $valueParam) { |
||
673 | preg_match('#\{{.*?}\}#', $valueParam, $match); |
||
674 | if (count($match)) { |
||
675 | $key = str_replace(array('{{','}}'), array('',''), $match[0]); |
||
676 | $arrayParams[$keyParam] = $defaultFields[$key]; |
||
677 | } |
||
678 | } |
||
679 | return implode('/', $arrayParams); |
||
680 | } |
||
681 | |||
682 | /** |
||
683 | * Replace {{var}} by empty space |
||
684 | * @param $parsed_url |
||
685 | * |
||
686 | * @return string |
||
687 | */ |
||
688 | private function unparseUrl($parsed_url) |
||
689 | { |
||
690 | $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : ''; |
||
691 | $host = isset($parsed_url['host']) ? $parsed_url['host'] : ''; |
||
692 | $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : ''; |
||
693 | $query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : ''; |
||
694 | $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : ''; |
||
695 | $path = $parsed_url['path']; |
||
696 | return $scheme . $host . $port . $path . $query . $fragment; |
||
697 | } |
||
698 | |||
699 | /** |
||
700 | * Get the orders of a customer |
||
701 | * @param $current_user |
||
702 | * @param $billingEmail |
||
703 | * |
||
704 | * @return mixed |
||
705 | */ |
||
706 | private function getOrders($current_user, $billingEmail) |
||
707 | { |
||
708 | $sign_up = ''; |
||
709 | $total_orders = 0; |
||
710 | $total_amt = 0; |
||
711 | $refund_amt = 0; |
||
712 | $total_refunds = 0; |
||
713 | $partial_refunds = 0; |
||
714 | if ($current_user->user_login) { |
||
715 | $is_guest = "false"; |
||
716 | $sign_up = substr($current_user->user_registered, 0, 10); |
||
717 | $customer_orders = get_posts(array( |
||
718 | 'numberposts' => - 1, |
||
719 | 'meta_key' => '_customer_user', |
||
720 | 'meta_value' => $current_user->ID, |
||
721 | 'post_type' => array( 'shop_order' ), |
||
722 | 'post_status' => array( 'wc-completed', 'wc-processing', 'wc-refunded' ), |
||
723 | )); |
||
724 | } else { |
||
725 | $is_guest = "true"; |
||
726 | $customer_orders = get_posts(array( |
||
727 | 'numberposts' => - 1, |
||
728 | 'meta_key' => '_billing_email', |
||
729 | 'meta_value' => $billingEmail, |
||
730 | 'post_type' => array( 'shop_order' ), |
||
731 | 'post_status' => array( 'wc-completed', 'wc-processing', 'wc-refunded'), |
||
732 | )); |
||
733 | foreach ($customer_orders as $customer_order) { |
||
734 | if (trim($sign_up)=='' || |
||
735 | strtotime(substr($customer_order->post_date, 0, 10)) <= strtotime($sign_up)) { |
||
736 | $sign_up = substr($customer_order->post_date, 0, 10); |
||
737 | } |
||
738 | } |
||
739 | } |
||
740 | |||
741 | return $customer_orders; |
||
742 | } |
||
743 | |||
744 | |||
745 | /** |
||
746 | * @param $orderId |
||
747 | * @param $pagantisOrderId |
||
748 | * |
||
749 | * @throws Exception |
||
750 | */ |
||
751 | private function insertRow($orderId, $pagantisOrderId) |
||
752 | { |
||
753 | global $wpdb; |
||
754 | $this->checkDbTable(); |
||
755 | $tableName = $wpdb->prefix.PAGANTIS_WC_ORDERS_TABLE; |
||
756 | |||
757 | //Check if id exists |
||
758 | $resultsSelect = $wpdb->get_results("select * from $tableName where id='$orderId'"); |
||
759 | $countResults = count($resultsSelect); |
||
760 | if ($countResults == 0) { |
||
761 | $wpdb->insert( |
||
762 | $tableName, |
||
763 | array('id' => $orderId, 'order_id' => $pagantisOrderId), |
||
764 | array('%d', '%s') |
||
765 | ); |
||
766 | } else { |
||
767 | $wpdb->update( |
||
768 | $tableName, |
||
769 | array('order_id' => $pagantisOrderId), |
||
770 | array('id' => $orderId), |
||
771 | array('%s'), |
||
772 | array('%d') |
||
773 | ); |
||
774 | } |
||
775 | } |
||
776 | |||
777 | /** |
||
778 | * Check if orders table exists |
||
779 | */ |
||
780 | private function checkDbTable() |
||
781 | { |
||
782 | global $wpdb; |
||
783 | $tableName = $wpdb->prefix.PAGANTIS_WC_ORDERS_TABLE; |
||
784 | |||
785 | if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName) { |
||
786 | $charset_collate = $wpdb->get_charset_collate(); |
||
787 | $sql = "CREATE TABLE $tableName ( id int, order_id varchar(50), wc_order_id varchar(50), |
||
788 | UNIQUE KEY id (id)) $charset_collate"; |
||
789 | |||
790 | require_once(ABSPATH.'wp-admin/includes/upgrade.php'); |
||
791 | dbDelta($sql); |
||
792 | } |
||
793 | } |
||
794 | |||
795 | /** |
||
796 | * @return array |
||
797 | */ |
||
798 | private function getExtraConfig() |
||
799 | { |
||
800 | global $wpdb; |
||
801 | $tableName = $wpdb->prefix.PAGANTIS_CONFIG_TABLE; |
||
802 | $response = array(); |
||
803 | $dbResult = $wpdb->get_results("select config, value from $tableName", ARRAY_A); |
||
804 | foreach ($dbResult as $value) { |
||
805 | $response[$value['config']] = $value['value']; |
||
806 | } |
||
807 | |||
808 | return $response; |
||
809 | } |
||
810 | |||
811 | /** |
||
812 | * @param $order |
||
813 | * |
||
814 | * @return null |
||
815 | */ |
||
816 | private function getNationalId($order) |
||
817 | { |
||
818 | foreach ((array)$order->get_meta_data() as $mdObject) { |
||
819 | $data = $mdObject->get_data(); |
||
820 | if ($data['key'] == 'vat_number') { |
||
821 | return $data['value']; |
||
822 | } |
||
823 | } |
||
824 | |||
825 | return null; |
||
826 | } |
||
827 | |||
828 | /** |
||
829 | * @param $order |
||
830 | * |
||
831 | * @return mixed |
||
832 | */ |
||
833 | private function getTaxId($order) |
||
834 | { |
||
835 | foreach ((array)$order->get_meta_data() as $mdObject) { |
||
836 | $data = $mdObject->get_data(); |
||
837 | if ($data['key'] == 'billing_cfpiva') { |
||
838 | return $data['value']; |
||
839 | } |
||
840 | } |
||
841 | } |
||
842 | |||
843 | /** |
||
844 | * @param null $exception |
||
845 | * @param null $message |
||
846 | */ |
||
847 | private function insertLog($exception = null, $message = null) |
||
848 | { |
||
849 | global $wpdb; |
||
850 | $this->checkDbLogTable(); |
||
851 | $logEntry = new LogEntry(); |
||
852 | if ($exception instanceof \Exception) { |
||
853 | $logEntry = $logEntry->error($exception); |
||
854 | } else { |
||
855 | $logEntry = $logEntry->info($message); |
||
856 | } |
||
857 | $tableName = $wpdb->prefix.PAGANTIS_LOGS_TABLE; |
||
858 | $wpdb->insert($tableName, array('log' => $logEntry->toJson())); |
||
859 | } |
||
860 | /** |
||
861 | * Check if logs table exists |
||
862 | */ |
||
863 | private function checkDbLogTable() |
||
864 | { |
||
865 | global $wpdb; |
||
866 | $tableName = $wpdb->prefix.PAGANTIS_LOGS_TABLE; |
||
867 | if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName) { |
||
868 | $charset_collate = $wpdb->get_charset_collate(); |
||
869 | $sql = "CREATE TABLE $tableName ( id int NOT NULL AUTO_INCREMENT, log text NOT NULL, |
||
870 | createdAt timestamp DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY id (id)) $charset_collate"; |
||
871 | require_once(ABSPATH.'wp-admin/includes/upgrade.php'); |
||
872 | dbDelta($sql); |
||
873 | } |
||
874 | return; |
||
875 | } |
||
876 | |||
877 | /** |
||
878 | * @param $product_id |
||
879 | * |
||
880 | * @return string |
||
881 | */ |
||
882 | private function isPromoted($product_id) |
||
887 | } |
||
888 | |||
889 | /** |
||
890 | * @return int |
||
891 | */ |
||
892 | private function getPromotedAmount() |
||
893 | { |
||
894 | global $woocommerce; |
||
895 | $items = $woocommerce->cart->get_cart(); |
||
896 | $promotedAmount = 0; |
||
897 | foreach ($items as $key => $item) { |
||
898 | $promotedProduct = $this->isPromoted($item['product_id']); |
||
899 | if ($promotedProduct == 'true') { |
||
900 | $promotedAmount+=$item['line_total'] + $item['line_tax']; |
||
901 | } |
||
902 | } |
||
903 | |||
904 | return $promotedAmount; |
||
905 | } |
||
906 | } |
||
907 |
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:For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths