PluginProbe
PayPlug for WooCommerce (Official) / 2.10.0
PayPlug for WooCommerce (Official) v2.10.0
3.0.0 2.18.0 1.0.17 1.0.18 1.0.19 1.0.20 1.0.21 1.0.22 1.0.3 1.0.4 1.0.5 1.0.6 1.0.7 1.0.8 1.1.0 1.10.0 1.10.1 1.2.1 1.2.10 1.2.11 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 All 101 releases
payplug / src / Gateway / PayplugGateway.php

PayplugGateway.php in PayPlug for WooCommerce (Official) 2.10.0, at src/Gateway/PayplugGateway.php

1,867 lines 64.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace Payplug\PayplugWoocommerce\Gateway;
4
5 // Exit if accessed directly
6 if (!defined('ABSPATH')) {
7 exit;
8 }
9
10 use Payplug\Authentication;
11 use Payplug\Exception\ConfigurationException;
12 use Payplug\Exception\HttpException;
13 use Payplug\Payplug;
14 use Payplug\PayplugWoocommerce\Controller\IntegratedPayment;
15 use Payplug\PayplugWoocommerce\Helper\Lock;
16 use Payplug\PayplugWoocommerce\PayplugWoocommerceHelper;
17 use Payplug\Resource\Payment as PaymentResource;
18 use Payplug\Resource\Refund as RefundResource;
19 use WC_Blocks_Utils;
20 use WC_Payment_Gateway_CC;
21 use WC_Payment_Tokens;
22
23 /**
24 * PayPlug WooCommerce Gateway.
25 *
26 * @package Payplug\PayplugWoocommerce\Gateway
27 */
28 class PayplugGateway extends WC_Payment_Gateway_CC
29 {
30 const OPTION_NAME = "payplug_config";
31
32 /**
33 * @var PayplugGatewayRequirements
34 */
35 private $requirements;
36
37 /**
38 * @var PayplugPermissions
39 */
40 private $permissions;
41
42 /**
43 * @var PayplugResponse
44 */
45 public $response;
46
47 /**
48 * @var PayplugApi
49 */
50 public $api;
51
52 /**
53 * @var \WC_Logger
54 */
55 protected static $log;
56
57 /**
58 * @var bool
59 */
60 protected static $log_enabled;
61
62 /**
63 * @var float
64 */
65 const MIN_AMOUNT = 0.99;
66
67 /**
68 * @var float
69 */
70 const MAX_AMOUNT = 20000;
71
72 /**
73 * @var string
74 */
75 private $payplug_merchant_country = 'FR';
76
77 protected $oney_response;
78 public $min_oney_price, $oney_thresholds_min;
79 public $max_oney_price, $oney_thresholds_max;
80
81 const ENABLE_ON_TEST_MODE = true;
82
83
84 /**
85 * Logging method.
86 *
87 * @param string $message Log message.
88 * @param string $level Optional. Default 'info'.
89 * emergency|alert|critical|error|warning|notice|info|debug
90 */
91 public static function log($message, $level = 'info')
92 {
93 if (!self::$log_enabled) {
94 return;
95 }
96
97 if (empty(self::$log)) {
98 self::$log = PayplugWoocommerceHelper::is_pre_30() ? new \WC_Logger() : wc_get_logger();
99 }
100
101 PayplugWoocommerceHelper::is_pre_30()
102 ? self::$log->add('payplug_gateway', $message)
103 : self::$log->log($level, $message, array('source' => 'payplug_gateway'));
104 }
105
106 /**
107 * Construct method
108 *
109 * @return void
110 */
111 public function __construct()
112 {
113 $payplug_gateways = array('payplug', 'american_express', 'apple_pay', 'bancontact', 'oney_x3_with_fees', 'oney_x3_without_fees', 'oney_x4_with_fees', 'oney_x4_without_fees', 'satispay', 'sofort', 'ideal', 'mybank');
114
115 if ((!empty($_GET['section'])) && (in_array($_GET['section'], $payplug_gateways))) {
116 $GLOBALS['hide_save_button'] = true;
117 }
118
119 //TODO: this should be properties of the class and implemented an interface on all classes (set values)
120 $this->id = 'payplug';
121 $this->icon = '';
122 $this->has_fields = false;
123 $this->method_title = _x('PayPlug', 'Gateway method title', 'payplug');
124 $this->method_description = __('Enable PayPlug for your customers.', 'payplug');
125 $this->supports = array(
126 'products',
127 'refunds',
128 'tokenization',
129 );
130 $this->new_method_label = __('Pay with another credit card', 'payplug');
131
132 $this->init_settings();
133 $this->requirements = new PayplugGatewayRequirements($this);
134 if ($this->user_logged_in()) {
135 $this->init_payplug();
136 }else{
137 delete_option('woocommerce_payplug_settings');
138 set_transient( PayplugWoocommerceHelper::get_transient_key(get_option('woocommerce_payplug_settings', [])), null );
139 }
140
141 $this->title = $this->get_option('title');
142 $this->description = $this->get_option('description');
143 $this->mode = 'yes' === $this->get_option('mode', 'no') ? 'live' : 'test';
144 $this->debug = 'yes' === $this->get_option('debug', 'no');
145 $this->email = $this->get_option('email');
146 $this->payment_method = $this->get_option('payment_method');
147 $this->oneclick = (('yes' === $this->get_option('oneclick', 'no')) && (is_user_logged_in()));
148 $this->oney_type = $this->get_option('oney_type', 'with_fees');
149 $oney_range = PayplugWoocommerceHelper::get_min_max_oney();
150
151 //TODO:: remove this properties from here and add them on Oney classes
152 $this->min_oney_price = (isset($oney_range['min'])) ? intval($oney_range['min']) : 100;
153 $this->max_oney_price = (isset($oney_range['max'])) ? intval($oney_range['max']) : 3000;
154 $this->oney_thresholds_min = $this->get_option('oney_thresholds_min', $this->min_oney_price );
155 $this->oney_thresholds_max = $this->get_option('oney_thresholds_max', $this->max_oney_price );
156 $this->init_form_fields();
157 $this->payplug_merchant_country = PayplugWoocommerceHelper::get_payplug_merchant_country();
158 $this->oney_product_animation = $this->get_option('oney_product_animation');
159
160 add_filter('woocommerce_get_customer_payment_tokens', [$this, 'filter_tokens'], 10, 3);
161
162 self::$log_enabled = $this->debug;
163
164
165 // Ensure the description is not empty to correctly display users's save cards
166 if (empty($this->description) && 0 !== count($this->get_tokens()) && $this->oneclick_available()) {
167 $this->description = ' ';
168 }
169
170
171 if ('test' === $this->mode) {
172 $this->description .= " \n";
173 $this->description .= __('You are in TEST MODE. In test mode you can use the card 4242424242424242 with any valid expiration date and CVC.', 'payplug');
174 $this->description = trim($this->description);
175 }
176
177 //add fields of IP to the description
178 if($this->payment_method === 'integrated'){
179 $this->has_fields = true;
180 }
181
182 add_filter('woocommerce_get_order_item_totals', [$this, 'customize_gateway_title'], 10, 2);
183 add_action('wp_enqueue_scripts', [$this, 'scripts']);
184 add_action('the_post', [$this, 'validate_payment']);
185 add_action('woocommerce_available_payment_gateways', [$this, 'check_gateway']);
186 }
187
188 /**
189 * @param $option
190 * @param $value
191 * @return bool|void
192 */
193 public function update_option($option, $value = ''){
194 if ( $this->needs_setup() ) {
195 wp_send_json_error( 'needs_setup' );
196 wp_die();
197 }
198
199 parent::update_option($option, $value);
200 }
201
202 /**
203 * this payment gateway cannot be updated on the wooco payment settings
204 * @return bool
205 */
206 public function needs_setup()
207 {
208 return true;
209 }
210
211 /**
212 * Customize gateway title in emails.
213 *
214 * @param array $total_rows
215 * @param \WC_Order $order
216 *
217 * @return array
218 *
219 * @author Clément Boirie
220 */
221 public function customize_gateway_title($total_rows, $order)
222 {
223
224 $get_payment_method = $this->id;
225 if( method_exists($order, "get_payment_method") ) {
226 $get_payment_method = $order->get_payment_method();
227 }
228
229 $payment_method = PayplugWoocommerceHelper::is_pre_30() ? $order->payment_method : $get_payment_method;
230 if (
231 $this->id !== $payment_method
232 || !isset($total_rows['payment_method'])
233 ) {
234 return $total_rows;
235 }
236
237 $total_rows['payment_method']['value'] = __('Credit card', 'payplug');
238
239 return $total_rows;
240 }
241
242 /**
243 * Validate order payment when the user is redirected to the success confirmation page.
244 *
245 * @throws \WC_Data_Exception
246 */
247 public function validate_payment($id = null, $save_request = true, $ipn = false)
248 {
249 if(!$ipn){
250 if (!is_wc_endpoint_url('order-received') || (empty($_GET['key']) && empty($id)) ) {
251 return;
252 }
253 }
254
255 if (!empty($_GET['order-received'])) {
256 $order_id = (int) ($_GET['order-received']);
257
258 } elseif (!empty($id) && !is_object($id)) {
259 $order_id = (int) $id;
260 }
261
262 if (empty($order_id)) {
263 $order_id = wc_get_order_id_by_order_key(wc_clean( (!empty($_GET['key']) ? $_GET['key'] : $id) ) );
264 if (empty($order_id)) {
265 return;
266 }
267 }
268
269 $order = wc_get_order($order_id);
270 if (!$order instanceof \WC_Order) {
271 return;
272 }
273
274 $payment_method = PayplugWoocommerceHelper::is_pre_30() ? $order->payment_method : $order->get_payment_method();
275 if (!in_array($payment_method, ['payplug', 'oney_x3_with_fees', 'oney_x4_with_fees', 'oney_x3_without_fees', 'oney_x4_without_fees','bancontact', 'apple_pay', 'american_express', "satispay","sofort","mybank","ideal" ])) {
276 return;
277 }
278
279
280 $transaction_id = PayplugWoocommerceHelper::is_pre_30() ? get_post_meta($order_id, '_transaction_id', true) : $order->get_transaction_id();
281 if (empty($transaction_id)) {
282 PayplugGateway::log(sprintf('Order #%s : Missing transaction id.', $order_id), 'error');
283 return;
284 }
285
286 if($payment_method === $this->id) {
287
288 $lock_id = Lock::handle_insert($save_request, $transaction_id);
289 if(!$lock_id){
290 return;
291 }
292
293 try {
294 $payment = $this->api->payment_retrieve($transaction_id);
295
296 } catch (\Exception $e) {
297 PayplugGateway::log(
298 sprintf(
299 'Order #%s : An error occurred while retrieving the payment data with the message : %s',
300 $order_id,
301 $e->getMessage()
302 )
303 );
304
305 return;
306 }
307
308 $this->response->process_payment($payment);
309
310 \Payplug\PayplugWoocommerce\Model\Lock::delete_lock($lock_id);
311 $waiting_requests = \Payplug\PayplugWoocommerce\Model\Lock::get_lock_by_payment_id($transaction_id);
312
313 if($waiting_requests){
314 \Payplug\PayplugWoocommerce\Model\Lock::delete_lock_by_payment_id($transaction_id);
315 $this->validate_payment($order_id, false);
316 };
317 }
318 }
319
320 /**
321 * Get payment icons.
322 *
323 * @return string
324 */
325 public function get_icon()
326 {
327
328 $src = ('it_IT' === get_locale())
329 ? PAYPLUG_GATEWAY_PLUGIN_URL . '/assets/images/checkout/logos_scheme_PostePay.svg'
330 : PAYPLUG_GATEWAY_PLUGIN_URL . '/assets/images/checkout/logos_scheme_CB.svg';
331
332 $icons = apply_filters('payplug_payment_icons', [
333 'payplug' => sprintf('<img src="%s" alt="Visa & Mastercard" class="payplug-payment-icon" />', esc_url($src)),
334 ]);
335
336 $icons_str = '';
337 foreach ($icons as $icon) {
338 $icons_str .= $icon;
339 }
340
341 return $icons_str;
342 }
343
344 /**
345 * Check if this gateway is enabled
346 */
347 public function is_available()
348 {
349 if ('yes' === $this->enabled) {
350 return $this->requirements->satisfy_requirements() && !empty($this->get_api_key($this->get_current_mode()));
351 }
352
353 return parent::is_available();
354 }
355
356 /**
357 * Load gateway settings.
358 */
359 public function init_settings()
360 {
361 parent::init_settings();
362 $this->enabled = !empty($this->settings['enabled']) && 'yes' === $this->settings['enabled'] ? 'yes' : 'no';
363 }
364
365 /**
366 * Register gateway settings.
367 */
368 public function init_form_fields()
369 {
370
371 $anchor = esc_html_x( __("More informations", 'payplug'), 'modal', 'payplug' );
372 $domain = __( 'support.payplug.com/hc/fr/articles/4408142346002', 'payplug' );
373 $link = sprintf( ' <a href="https://%s" target="_blank">%s</a>', $domain, $anchor );
374
375
376 $anchor_bancontact = esc_html_x( __("payplug_bancontact_activation_request", 'payplug'), 'modal', 'payplug' );
377 $domain_bancontact = __( 'payplug_bancontact_activation_url', 'payplug' );
378 $bancontact_call_to_action = sprintf( ' <a id="bancontact_call_to_action" href="https://%s" target="_blank">%s</a>', $domain_bancontact, $anchor_bancontact );
379
380 $fields = [
381 'enabled' => [
382 'title' => __('Enable/Disable', 'payplug'),
383 'type' => 'checkbox',
384 'label' => __('Enable PayPlug', 'payplug'),
385 'description' => __('Only Euro payments can be processed with PayPlug.', 'payplug'),
386 'default' => 'no',
387 ],
388 'title' => [
389 'title' => __('Title', 'payplug'),
390 'type' => 'text',
391 'description' => __('The payment solution title displayed to your customers during checkout', 'payplug'),
392 'default' => _x('Credit card checkout', 'Default gateway title', 'payplug'),
393 'desc_tip' => false,
394 ],
395 'description' => [
396 'title' => __('Description', 'payplug'),
397 'type' => 'text',
398 'description' => __('The payment solution description displayed to your customers during checkout', 'payplug'),
399 'default' => '',
400 'desc_tip' => false,
401 ],
402 'title_connexion' => [
403 'title' => __('Connection', 'payplug'),
404 'type' => 'title',
405 ],
406 'email' => [
407 'type' => 'hidden',
408 'default' => '',
409 ],
410 'login' => [
411 'type' => 'login',
412 'default' => '',
413 ],
414 'payplug_test_key' => [
415 'type' => 'hidden',
416 'default' => '',
417 ],
418 'payplug_live_key' => [
419 'type' => 'hidden',
420 'default' => '',
421 ],
422 'payplug_merchant_id' => [
423 'type' => 'hidden',
424 'default' => '',
425 ],
426 'title_testmode' => [
427 'title' => __('Mode', 'payplug'),
428 'type' => 'title',
429 ],
430 'mode' => [
431 'title' => '',
432 'label' => '',
433 'type' => 'yes_no',
434 'yes' => 'Live',
435 'no' => 'Test',
436 'description' => __('In TEST mode, all payments will be simulations and will not generate real transactions.', 'payplug'),
437 'default' => 'no',
438 'hide_label' => true,
439 ],
440 'title_settings' => [
441 'title' => __('Settings', 'payplug'),
442 'type' => 'title',
443 ],
444 'payment_method' => [
445 'title' => __('Payment page', 'payplug'),
446 'type' => 'radio',
447 'options' => array(
448 'redirect' => __('Redirect', 'payplug'),
449 'embedded' => __('Integrated', 'payplug'),
450 ),
451 'description' => __('Customers will be redirected to a PayPlug payment page to finalize the transaction, or payments will be performed in an embeddable payment form on your website.', 'payplug'),
452 'default' => 'redirect',
453 'desc_tip' => false
454 ],
455 'debug' => [
456 'title' => __('Debug', 'payplug'),
457 'type' => 'checkbox',
458 'description' => __('Debug mode saves additional information on your server for each operation done via the PayPlug plugin (Developer setting).', 'payplug'),
459 'label' => __('Activate debug mode', 'payplug'),
460 'default' => 'yes',
461 'desc_tip' => false
462 ],
463 'title_advanced_settings' => [
464 'title' => __('payplug_advanced_settings', 'payplug'),
465 'description' => __(
466 'Your current offer does not allow this option. Try it on TEST mode. More information <a href="https://www.payplug.com/pricing" target="_blank">here.</a>',
467 'payplug'
468 ),
469 'type' => 'title',
470 ],
471 'oneclick' => [
472 'title' => __('One Click Payment', 'payplug'),
473 'type' => 'checkbox',
474 'label' => __('Activate', 'payplug'),
475 'description' => __('Allow your customers to save their credit card information for later purchases.', 'payplug'),
476 'default' => 'no',
477 'desc_tip' => false
478 ],
479 'bancontact' => [
480 'title' => __('payplug_bancontact_activate_title', 'payplug'),
481 'type' => 'checkbox',
482 'label' => __('Activate', 'payplug'),
483 'description' => '<p class="description" id="bancontact_test_mode_description"> '. __('payplug_bancontact_testmode_description', 'payplug') .' </p>' .
484 '<p class="description" id="bancontact_live_mode_description_disabled"> '. __('payplug_bancontact_livemode_description_disabled', 'payplug') .' </p>' .
485 $bancontact_call_to_action,
486 'default' => 'no',
487 ],
488 'apple_pay' => [
489 'title' => __('payplug_apple_pay_activate_title', 'payplug'),
490 'type' => 'checkbox',
491 'label' => __('Activate', 'payplug'),
492 'description' => '<p class="description" id="apple_pay_test_mode_description"> '. __('payplug_apple_pay_testmode_description', 'payplug') .' </p>' .
493 '<p class="description" id="apple_pay_live_mode_description"> '. __('payplug_apple_pay_livemode_description', 'payplug') .' </p>' ,
494 'default' => 'no',
495 ],
496 'american_express' => [
497 'title' => __('payplug_amex_title', 'payplug'),
498 'type' => 'checkbox',
499 'label' => __('payplug_amex_activate', 'payplug'),
500 'description' => '<p class="description" id="amex_test_mode_description"> '. __('payplug_amex_testmode_description', 'payplug') .' </p>' .
501 '<p class="description" id="amex_live_mode_description"> '. __('payplug_amex_livemode_description', 'payplug') .' </p>' ,
502 'default' => 'no',
503 ],
504 'oney' => [
505 'title' => __('3x 4x Oney payments', 'payplug'),
506 'type' => 'checkbox',
507 'label' => __('Activate', 'payplug'),
508 // TRAD
509 'description' => sprintf(__('Allow your customers to split payments into 3 or 4 installments, for orders between %s€ and %s€', 'payplug'), $this->min_oney_price, $this->max_oney_price) . $link,
510 'default' => 'no',
511 'desc_tip' => false
512 ],
513 'oney_type' => [
514 'title' => '',
515 'type' => 'oney_type',
516 'options' => array(
517 'with_fees' => __('Oney with fees', 'payplug'),
518 'without_fees' => __('Oney without fees', 'payplug'),
519 ),
520 'descriptions' => array(
521 'with_fees' => __('The fees are split between you and your customers', 'payplug'),
522 'without_fees' => __('You pay the fees', 'payplug'),
523 ),
524 'description' => '',
525 'default' => 'with_fees',
526 'desc_tip' => false
527 ],
528 'oney_thresholds' => [
529 'title' => '',
530 'type' => 'oney_thresholds',
531 'description' => sprintf(__('I would like to offer guaranteed payment in installments for amounts between %s€ and %s€.', 'payplug'),
532 '<b class="min">' . $this->oney_thresholds_min . '</b>', '<b class="max">' . $this->oney_thresholds_max . '</b>'),
533 'desc_tip' => false
534 ],
535 'oney_thresholds_min' => [
536 'title' => '',
537 'type' => 'hidden',
538 'label' => '',
539 'description' => '',
540 'default' => 'no',
541 ],
542 'oney_thresholds_max' => [
543 'title' => '',
544 'type' => 'hidden',
545 'label' => '',
546 'description' => '',
547 'default' => 'no',
548 ],
549 'oney_product_animation' => [
550 'title' => __('oney_installments_pop_up', 'payplug'),
551 'description' => __('display_the_oney_installments_pop_up_on_the_product_page', 'payplug'),
552 'label' => __('Activate', 'payplug'),
553 'default' => 'no',
554 'desc_tip' => false,
555 'type' => 'oney_product_animation'
556 ],
557 ];
558
559 if ($this->user_logged_in()) {
560 if ($this->permissions->has_permissions(PayplugPermissions::SAVE_CARD)) {
561 unset($fields['title_advanced_settings']);
562 } else if ('live' === $this->get_current_mode()){
563 $fields['oneclick']['disabled'] = true;
564 }
565 }
566
567 /**
568 * Filter PayPlug gateway settings.
569 *
570 * @param array $fields
571 */
572 $fields = apply_filters('payplug_gateway_settings', $fields);
573 $this->form_fields = $fields;
574 }
575
576 /**
577 * Set global configuration for PayPlug instance.
578 */
579 public function init_payplug()
580 {
581 $this->api = new PayplugApi($this);
582 $this->api->init();
583
584 $this->permissions = new PayplugPermissions($this);
585 $this->response = new PayplugResponse($this);
586
587 // Register IPN handler
588 new PayplugIpnResponse($this);
589
590 }
591
592 public function integrated_payments_scripts(){
593
594 $translations = array(
595 "cardholder" => __('payplug_integrated_payment_cardholder', 'payplug'),
596 "your_card" => __('payplug_integrated_payment_your_card', 'payplug'),
597 "card_number" => __('payplug_integrated_payment_card_number', 'payplug'),
598 "expiration_date" => __('payplug_integrated_payment_expiration_date', 'payplug'),
599 "cvv" => __('payplug_integrated_payment_cvv', 'payplug'),
600 "one_click" => __('payplug_integrated_payment_oneClick', 'payplug'),
601 'ajax_url' => \WC_AJAX::get_endpoint('payplug_create_order'),
602 'order_review_url' => \WC_AJAX::get_endpoint('payplug_order_review_url'),
603 'nonce' => wp_create_nonce('woocommerce-process_checkout'),
604 'mode' => PayplugWoocommerceHelper::check_mode(), // true for TEST, false for LIVE
605 'check_payment_url' => \WC_AJAX::get_endpoint('payplug_check_payment')
606 );
607
608 //TODO:: if integrated payment is active please active form and comment the one above
609 /**x
610 * Integrated payments scripts
611 */
612 wp_enqueue_style('payplugIP', PAYPLUG_GATEWAY_PLUGIN_URL . 'assets/css/payplug-integrated-payments.css', [], PAYPLUG_GATEWAY_VERSION);
613
614 wp_register_script('payplug-domain', PAYPLUG_GATEWAY_PLUGIN_URL . 'assets/js/payplug-domain.js', [], 'v1.0');
615 wp_enqueue_script('payplug-domain');
616
617 wp_register_script('payplug-integrated-payments-api', 'https://cdn.payplug.com/js/integrated-payment/v1@1/index.js', [], 'v1.1', true);
618 wp_enqueue_script('payplug-integrated-payments-api');
619
620 wp_register_script( 'jquery-bind-first', PAYPLUG_GATEWAY_PLUGIN_URL . 'assets/js/jquery.bind-first-0.2.3.min.js', array( 'jquery' ), '1.0.0', true );
621 wp_enqueue_script('jquery-bind-first');
622
623 wp_register_script('payplug-integrated-payments', PAYPLUG_GATEWAY_PLUGIN_URL . 'assets/js/payplug-integrated-payments.js', ['jquery', 'jquery-bind-first', 'payplug-integrated-payments-api'], 'v1.1', true);
624 wp_enqueue_script('payplug-integrated-payments');
625
626 wp_localize_script( 'payplug-integrated-payments', 'payplug_integrated_payment_params', $translations);
627 }
628
629 /**
630 * Embedded payment form scripts.
631 *
632 * Register scripts and additionnal data needed for the
633 * embedded payment form.
634 */
635 public function scripts()
636 {
637 if (!is_cart() && !is_checkout() && !isset($_GET['pay_for_order']) && !is_add_payment_method_page() && !isset($_GET['change_payment_method'])) {
638 return;
639 }
640
641 // If PayPlug is not enabled bail.
642 if ('no' === $this->enabled) {
643 return;
644 }
645
646 // If keys are not set bail.
647 if (empty($this->get_api_key($this->mode))) {
648 PayplugGateway::log('Keys are not set correctly.');
649
650 return;
651 }
652
653 // Register checkout styles.
654 wp_register_style('payplug-checkout', PAYPLUG_GATEWAY_PLUGIN_URL . 'assets/css/payplug-checkout.css', [], PAYPLUG_GATEWAY_VERSION);
655 wp_enqueue_style('payplug-checkout');
656
657 if (
658 ( $this->payment_method == "integrated" && !$this->is_checkout_block() ) ||
659 ($this->payment_method == "integrated" && is_wc_endpoint_url('order-pay') )
660 ) {
661 $this->integrated_payments_scripts();
662 }
663
664 if (($this->payment_method == "popup" ) && ($this->id === "payplug") && !$this->is_checkout_block() ) {
665
666 //load popup features
667 //TODO:: if integrated payment is not active please active this and comment the one bellow
668 wp_register_script('payplug', 'https://api.payplug.com/js/1/form.latest.js', [], null, true);
669 wp_register_script('payplug-checkout', PAYPLUG_GATEWAY_PLUGIN_URL . 'assets/js/payplug-checkout.js', [
670 'jquery',
671 'payplug'
672 ], PAYPLUG_GATEWAY_VERSION, true);
673 wp_localize_script('payplug-checkout', 'payplug_checkout_params', [
674 'ajax_url' => \WC_AJAX::get_endpoint('payplug_create_order'),
675 'order_review_url' => \WC_AJAX::get_endpoint('payplug_order_review_url'),
676 'nonce' => [
677 'checkout' => wp_create_nonce('woocommerce-process_checkout'),
678 ],
679 'is_embedded' => 'redirect' !== $this->payment_method
680 ]);
681
682 wp_enqueue_script('payplug-checkout');
683 }
684
685 }
686
687 /**
688 * Filter saved tokens for the gateway.
689 *
690 * A token will be removed if :
691 * - it doesn't match the current merchant logged in,
692 * - or it doesn't match the current gateway mode,
693 * - or it is expired.
694 *
695 * @param array $tokens
696 * @param int $user_id
697 * @param string $gateway_id
698 *
699 * @return array
700 */
701 public function filter_tokens($tokens, $user_id, $gateway_id)
702 {
703
704 if (!is_user_logged_in() || !class_exists('WC_Payment_Gateway_CC')) {
705 return $tokens;
706 }
707
708 if($this->oneclick === false){
709 foreach($tokens as $token_id => $token){
710 if($token->get_gateway_id() === "payplug"){
711 unset($tokens[$token_id]);
712 }
713 }
714 return $tokens;
715 }
716
717 /* @var \WC_Payment_Token_CC $token */
718 foreach ($tokens as $k => $token) {
719
720 if ($this->id !== $token->get_gateway_id()) {
721 continue;
722 }
723
724 // check if token is associated with a merchant id and if it match the current one
725 $token_merchant_id = $token->get_meta('payplug_account', true);
726 if (empty($token_merchant_id) || $this->get_merchant_id() !== $token_merchant_id) {
727 unset($tokens[$k]);
728 continue;
729 }
730
731 // check if token is available for the current gateway mode
732 if ($this->mode !== $token->get_meta('mode', true)) {
733 unset($tokens[$k]);
734 continue;
735 }
736
737 // check if token is not expired
738 $current_month = \absint(date('n'));
739 $current_year = \absint(date('Y'));
740 if ($current_year > (int) $token->get_expiry_year()) {
741 unset($tokens[$k]);
742 continue;
743 }
744
745 if ($current_year === (int) $token->get_expiry_year() && $current_month > (int) $token->get_expiry_month()) {
746 unset($tokens[$k]);
747 continue;
748 }
749 }
750
751 return $tokens;
752 }
753
754 public function payment_fields()
755 {
756 $description = $this->get_description();
757
758 if (!empty($description)) {
759 echo wpautop(wptexturize($description));
760 }
761
762 if(($this->payment_method === 'integrated') && ($this->id == 'payplug')){
763 echo IntegratedPayment::template_form($this->oneclick);
764 }
765
766 if ($this->oneclick_available()) {
767 $this->tokenization_script();
768 $this->saved_payment_methods();
769 }
770 }
771
772 /**
773 * Handle admin display.
774 */
775 public function admin_options()
776 {
777 /************ VUE Code *************/
778 wp_enqueue_script('chunk-vendors.js', PAYPLUG_GATEWAY_PLUGIN_URL . 'assets/dist/js/chunk-vendors-1.7.2.js', [], PAYPLUG_GATEWAY_VERSION);
779 wp_enqueue_script('app.js', PAYPLUG_GATEWAY_PLUGIN_URL . 'assets/dist/js/app-1.7.2.js', [], PAYPLUG_GATEWAY_VERSION);
780 wp_enqueue_style('app.css', PAYPLUG_GATEWAY_PLUGIN_URL . 'assets/dist/css/app.css', [], PAYPLUG_GATEWAY_VERSION);
781 wp_localize_script('app.js', 'payplug_admin_config',
782 array(
783 "img_path" => esc_url(PAYPLUG_GATEWAY_PLUGIN_URL . 'assets/dist/'),
784 'ajax_url' => get_home_url()
785 ));
786
787 ?>
788 <script>window.get_data_url = "<?php echo rest_url('payplug/data'); ?>"</script>
789 <script>window.set_data_url = "<?php echo rest_url('payplug/save_data'); ?>"</script>
790 <div id="payplug_admin"></div>
791
792 <?php
793
794 /*********** End VUE Code ***********/
795
796 }
797
798 /**
799 * Process payment.
800 *
801 * @param int $order_id
802 *
803 * @return array
804 * @throws \Exception
805 */
806 public function process_payment($order_id)
807 {
808
809 PayplugGateway::log(sprintf('Processing payment for order #%s', $order_id));
810
811 $order = wc_get_order($order_id);
812 $customer_id = PayplugWoocommerceHelper::is_pre_30() ? $order->customer_user : $order->get_customer_id();
813 $amount = (int) PayplugWoocommerceHelper::get_payplug_amount($order->get_total());
814 $amount = $this->validate_order_amount($amount);
815
816 if (is_wp_error($amount)) {
817 PayplugGateway::log(sprintf('Invalid amount %s for the order.', $order->get_total()), 'error');
818 throw new \Exception($amount->get_error_message());
819 }
820
821 $payment_token_id = (isset($_POST['wc-' . $this->id . '-payment-token']) && 'new' !== $_POST['wc-' . $this->id . '-payment-token'])
822 ? wc_clean($_POST['wc-' . $this->id . '-payment-token'])
823 : false;
824
825 if ($payment_token_id && (int) $customer_id > 0) {
826 PayplugGateway::log(sprintf('Payment token found.', $amount));
827
828 return $this->process_payment_with_token($order, $amount, $customer_id, $payment_token_id);
829 }
830
831 return $this->process_standard_payment($order, $amount, $customer_id);
832 }
833
834 /**
835 * if payment was generated by an intend, we shouldn't generate another one and try to pay it, this would generate duplications
836 * @param $order
837 * @return array|null
838 * @throws \Exception
839 */
840 private function process_standard_intent_payment($order){
841
842 //no order-pay page, no ajax_on_order_review_page
843 if ( !is_wc_endpoint_url('order-pay') &&
844 $this->is_checkout_block() &&
845 (
846 ( $this->id === "payplug" && ($this->payment_method === 'integrated'|| $this->payment_method === 'popup') ) ||
847 ( $this->id === "american_express" && $this->payment_method === 'popup')
848 ) &&
849 $_GET["wc-ajax"] !== "payplug_order_review_url"
850 ) {
851
852 $order_id = PayplugWoocommerceHelper::is_pre_30() ? $order->id : $order->get_id();
853
854 try {
855 $payment = $this->api->payment_retrieve($order->get_transaction_id());
856 if (ob_get_length() > 0) {
857 ob_clean();
858 }
859
860 // Save transaction id for the order
861 PayplugWoocommerceHelper::is_pre_30()
862 ? update_post_meta($order_id, '_transaction_id', $payment->id)
863 : $order->set_transaction_id($payment->id);
864
865 if($payment->is_paid){
866 $finished_status = wc_get_is_paid_statuses();
867 $order->set_status($finished_status[0]);
868 }
869
870 if (is_callable([$order, 'save'])) {
871 $order->save();
872 }
873
874 /**
875 * Fires once a payment has been created.
876 *
877 * @param int $order_id Order ID
878 * @param PaymentResource $payment Payment resource
879 */
880 \do_action('payplug_gateway_payment_created', $order_id, $payment);
881
882 $metadata = PayplugWoocommerceHelper::extract_transaction_metadata($payment);
883 PayplugWoocommerceHelper::save_transaction_metadata($order, $metadata);
884
885 PayplugGateway::log(sprintf('Payment intent created for order #%s', $order_id));
886
887 $return_url = esc_url_raw($order->get_checkout_order_received_url());
888
889 wp_send_json_success(array(
890 'payment_id' => $payment->id,
891 'result' => 'success',
892 'redirect' => !empty($payment->hosted_payment->payment_url) ? $payment->hosted_payment->payment_url : $return_url,
893 'cancel' => !empty($payment->hosted_payment->cancel_url) ? $payment->hosted_payment->cancel_url : null
894 ));
895
896 return array("stt" => "OK");
897
898 } catch (HttpException $e) {
899 PayplugGateway::log(sprintf('Error while processing order #%s : %s', $order_id, wc_print_r($e->getErrorObject(), true)), 'error');
900 throw new \Exception(__('Payment processing failed. Please retry.', 'payplug'));
901 } catch (\Exception $e) {
902 PayplugGateway::log(sprintf('Error while processing order #%s : %s', $order_id, $e->getMessage()), 'error');
903 throw new \Exception(__('Payment processing failed. Please retry.', 'payplug'));
904 }
905 }
906
907 return null;
908 }
909
910 /**
911 * @param \WC_Order $order
912 * @param int $amount
913 * @param int $customer_id
914 *
915 * @return array
916 * @throws \Exception
917 */
918 public function process_standard_payment($order, $amount, $customer_id)
919 {
920
921 $order_id = PayplugWoocommerceHelper::is_pre_30() ? $order->id : $order->get_id();
922
923 $intent = $this->process_standard_intent_payment($order);
924 if( !empty($intent) ){
925 return $intent;
926 }
927
928 try {
929 $address_data = PayplugAddressData::from_order($order);
930
931 $return_url = esc_url_raw($order->get_checkout_order_received_url());
932
933 if (!(substr( $return_url, 0, 4 ) === "http")) {
934 $return_url = get_site_url().$return_url;
935 }
936
937 $payment_data = [
938 'amount' => $amount,
939 'currency' => get_woocommerce_currency(),
940 'allow_save_card' => $this->oneclick_available() && (int) $customer_id > 0,
941 'billing' => $address_data->get_billing(),
942 'shipping' => $address_data->get_shipping(),
943 'hosted_payment' => [
944 'return_url' => $return_url,
945 'cancel_url' => esc_url_raw($order->get_cancel_order_url_raw()),
946 ],
947 'notification_url' => esc_url_raw(WC()->api_request_url('PayplugGateway')),
948 'metadata' => [
949 'order_id' => $order_id,
950 'customer_id' => ((int) $customer_id > 0) ? $customer_id : 'guest',
951 'domain' => $this->limit_length(esc_url_raw(home_url()), 500),
952 ],
953 ];
954
955 if($this->payment_method === 'integrated'){
956 $payment_data['initiator'] = 'PAYER';
957 $payment_data['integration'] = 'INTEGRATED_PAYMENT';
958 unset($payment_data['hosted_payment']['cancel_url']);
959 }
960
961 /**
962 * Filter the payment data before it's used
963 *
964 * @param array $payment_data
965 * @param int $order_id
966 * @param array $customer_details
967 * @param PayplugAddressData $address_data
968 */
969 $payment_data = apply_filters('payplug_gateway_payment_data', $payment_data, $order_id, [], $address_data);
970 $payment = $this->api->payment_create($payment_data);
971
972 // Save transaction id for the order
973 PayplugWoocommerceHelper::is_pre_30()
974 ? update_post_meta($order_id, '_transaction_id', $payment->id)
975 : $order->set_transaction_id($payment->id);
976
977 $order->set_payment_method( $this->id );
978
979 if (is_callable([$order, 'save'])) {
980 $order->save();
981 }
982
983 /**
984 * Fires once a payment has been created.
985 *
986 * @param int $order_id Order ID
987 * @param PaymentResource $payment Payment resource
988 */
989 \do_action('payplug_gateway_payment_created', $order_id, $payment);
990
991 $metadata = PayplugWoocommerceHelper::extract_transaction_metadata($payment);
992 PayplugWoocommerceHelper::save_transaction_metadata($order, $metadata);
993
994 PayplugGateway::log(sprintf('Payment creation complete for order #%s', $order_id));
995
996 if(ob_get_length() > 0){
997 ob_clean();
998 }
999
1000 return array(
1001 'payment_id' => $payment->id,
1002 'result' => 'success',
1003 'redirect' => !empty($payment->hosted_payment->payment_url) ? $payment->hosted_payment->payment_url : $return_url,
1004 'cancel' => !empty($payment->hosted_payment->cancel_url) ? $payment->hosted_payment->cancel_url : null
1005 );
1006
1007 } catch (HttpException $e) {
1008 PayplugGateway::log(sprintf('Error while processing order #%s : %s', $order_id, wc_print_r($e->getErrorObject(), true)), 'error');
1009 throw new \Exception(__('Payment processing failed. Please retry.', 'payplug'));
1010 } catch (\Exception $e) {
1011 PayplugGateway::log(sprintf('Error while processing order #%s : %s', $order_id, $e->getMessage()), 'error');
1012 throw new \Exception(__('Payment processing failed. Please retry.', 'payplug'));
1013 }
1014 }
1015
1016 /**
1017 * @param \WC_Order $order
1018 * @param int $amount
1019 * @param int $customer_id
1020 * @param string $token_id
1021 *
1022 * @return array
1023 * @throws \Exception
1024 */
1025 public function process_payment_with_token($order, $amount, $customer_id, $token_id)
1026 {
1027
1028 $order_id = PayplugWoocommerceHelper::is_pre_30() ? $order->id : $order->get_id();
1029 $payment_token = WC_Payment_Tokens::get($token_id);
1030 if (!$payment_token || (int) $customer_id !== (int) $payment_token->get_user_id()) {
1031 PayplugGateway::log('Could not find the payment token or the payment doesn\'t belong to the current user.', 'error');
1032 throw new \Exception(__('Invalid payment method.', 'payplug'));
1033 }
1034
1035 try {
1036 $address_data = PayplugAddressData::from_order($order);
1037
1038 $return_url = esc_url_raw($order->get_checkout_order_received_url());
1039
1040 if (!(substr( $return_url, 0, 4 ) === "http")) {
1041 $return_url = get_site_url().$return_url;
1042 }
1043
1044 $payment_data = [
1045 'amount' => $amount,
1046 'currency' => get_woocommerce_currency(),
1047 'payment_method' => $payment_token->get_token(),
1048 'allow_save_card' => false,
1049 'billing' => $address_data->get_billing(),
1050 'shipping' => $address_data->get_shipping(),
1051 'initiator' => 'PAYER',
1052 'hosted_payment' => [
1053 'return_url' => $return_url,
1054 'cancel_url' => esc_url_raw($order->get_cancel_order_url_raw()),
1055 ],
1056 'notification_url' => esc_url_raw(WC()->api_request_url('PayplugGateway')),
1057 'metadata' => [
1058 'order_id' => $order_id,
1059 'customer_id' => ((int) $customer_id > 0) ? $customer_id : 'guest',
1060 'domain' => $this->limit_length(esc_url_raw(home_url()), 500),
1061 ],
1062 ];
1063
1064 /** This filter is documented in src/Gateway/PayplugGateway */
1065 $payment_data = apply_filters('payplug_gateway_payment_data', $payment_data, $order_id, [], $address_data);
1066 $payment = $this->api->payment_create($payment_data);
1067
1068 // Save transaction id for the order
1069 PayplugWoocommerceHelper::is_pre_30()
1070 ? update_post_meta($order_id, '_transaction_id', $payment->id)
1071 : $order->set_transaction_id($payment->id);
1072
1073 if (is_callable([$order, 'save'])) {
1074 $order->save();
1075 }
1076
1077 /** This action is documented in src/Gateway/PayplugGateway */
1078 \do_action('payplug_gateway_payment_created', $order_id, $payment);
1079
1080
1081 $metadata = PayplugWoocommerceHelper::extract_transaction_metadata($payment);
1082 PayplugWoocommerceHelper::save_transaction_metadata($order, $metadata);
1083
1084 $this->response->process_payment($payment, true);
1085
1086 PayplugGateway::log(sprintf('Payment process complete for order #%s', $order_id));
1087
1088 if(($payment->__get('is_paid'))){
1089 $redirect = $order->get_checkout_order_received_url();
1090 }else if(isset($payment->__get('hosted_payment')->payment_url)){
1091 $redirect = $payment->__get('hosted_payment')->payment_url;
1092 }else{
1093 $redirect = $return_url;
1094 }
1095
1096 return [
1097 'payment_id' => $payment->id,
1098 'result' => 'success',
1099 'is_paid' => $payment->__get('is_paid'), // Use for path redirect before DSP2
1100 'redirect' => $redirect
1101 ];
1102 } catch (HttpException $e) {
1103 PayplugGateway::log(sprintf('Error while processing order #%s : %s', $order_id, wc_print_r($e->getErrorObject(), true)), 'error');
1104 throw new \Exception(__('Payment processing failed. Please retry.', 'payplug'));
1105 } catch (\Exception $e) {
1106 PayplugGateway::log(sprintf('Error while processing order #%s : %s', $order_id, $e->getMessage()), 'error');
1107 throw new \Exception(__('Payment processing failed. Please retry.', 'payplug'));
1108 }
1109 }
1110
1111 /**
1112 * Process refund for an order paid with PayPlug gateway.
1113 *
1114 * @param int $order_id
1115 * @param null $amount
1116 * @param string $reason
1117 *
1118 * @return bool|\WP_Error
1119 */
1120 public function process_refund($order_id, $amount = null, $reason = '')
1121 {
1122 PayplugGateway::log(sprintf('Processing refund for order #%s', $order_id));
1123
1124 if( !$this->user_logged_in()){
1125 PayplugGateway::log(__('You must be logged in with your PayPlug account.', 'payplug'), 'error');
1126 return new \WP_Error('process_refund_error', __('You must be logged in with your PayPlug account.', 'payplug'));
1127 }
1128
1129 $order = wc_get_order($order_id);
1130 if (!$order instanceof \WC_Order) {
1131 PayplugGateway::log(sprintf('The order #%s does not exist.', $order_id), 'error');
1132
1133 return new \WP_Error('process_refund_error', sprintf(__('The order %s does not exist.', 'payplug'), $order_id));
1134 }
1135
1136 if ($order->get_status() === "cancelled") {
1137 PayplugGateway::log(sprintf('The order #%s cannot be refund.', $order_id), 'error');
1138
1139 return new \WP_Error('process_refund_error', sprintf(__('The order %s cannot be refund.', 'payplug'), $order_id));
1140 }
1141
1142 $transaction_id = PayplugWoocommerceHelper::is_pre_30() ? get_post_meta($order_id, '_transaction_id', true) : $order->get_transaction_id();
1143 if (empty($transaction_id)) {
1144 PayplugGateway::log(sprintf('The order #%s does not have PayPlug transaction ID associated with it.', $order_id), 'error');
1145
1146 return new \WP_Error('process_refund_error', __('No PayPlug transaction was found for this order. The refund could not be processed.', 'payplug'));
1147 }
1148
1149 $customer_id = PayplugWoocommerceHelper::is_pre_30() ? $order->customer_user : $order->get_customer_id();
1150
1151 $data = [
1152 'metadata' => [
1153 'order_id' => $order_id,
1154 'customer_id' => ((int) $customer_id > 0) ? $customer_id : 'guest',
1155 'refund_from' => 'woocommerce',
1156 ]
1157 ];
1158
1159 if (!is_null($amount)) {
1160 $data['amount'] = PayplugWoocommerceHelper::get_payplug_amount($amount);
1161 }
1162
1163 if (!empty($reason)) {
1164 $data['metadata']['reason'] = $reason;
1165 }
1166
1167 /**
1168 * Filter the refund data before it's used.
1169 *
1170 * @param array $data
1171 * @param int $order_id
1172 * @param string $transaction_id
1173 */
1174 $data = apply_filters('payplug_gateway_refund_data', $data, $order_id, $transaction_id);
1175
1176 try {
1177 $refund = $this->api->refund_create($transaction_id, $data);
1178
1179 /**
1180 * Fires once a refund has been created.
1181 *
1182 * @param int $order_id Order ID
1183 * @param RefundResource $refund Refund resource
1184 * @param string $transaction_id Transaction id
1185 */
1186 \do_action('payplug_gateway_refund_created', $order_id, $refund, $transaction_id);
1187
1188 $refund_meta_key = sprintf('_pr_%s', wc_clean($refund->id));
1189 if (PayplugWoocommerceHelper::is_pre_30()) {
1190 update_post_meta($order_id, $refund_meta_key, $refund->id);
1191 } else {
1192 $order->add_meta_data($refund_meta_key, $refund->id, true);
1193 $order->save();
1194 }
1195
1196 $note = sprintf(__('Refund %s : Refunded %s', 'payplug'), wc_clean($refund->id), wc_price(((int) $refund->amount) / 100));
1197 if (!empty($refund->metadata['reason'])) {
1198 $note .= sprintf(' (%s)', esc_html($refund->metadata['reason']));
1199 }
1200 $order->add_order_note($note);
1201
1202 try {
1203 $payment = $this->api->payment_retrieve($transaction_id);
1204 $metadata = PayplugWoocommerceHelper::extract_transaction_metadata($payment);
1205 PayplugWoocommerceHelper::save_transaction_metadata($order, $metadata);
1206 } catch (\Exception $e) {
1207 }
1208
1209 PayplugGateway::log('Refund process complete for the order.');
1210
1211 return true;
1212 } catch (HttpException $e) {
1213 PayplugGateway::log(sprintf('Refund request error for the order %s from PayPlug API : %s', $order_id, wc_print_r($e->getErrorObject(), true)), 'error');
1214
1215 return new \WP_Error('process_refund_error', __('The transaction could not be refunded. Please try again.', 'payplug'));
1216 } catch (\Exception $e) {
1217 PayplugGateway::log(sprintf('Refund request error for the order %s : %s', $order_id, wc_clean($e->getMessage())), 'error');
1218
1219 return new \WP_Error('process_refund_error', __('The transaction could not be refunded. Please try again.', 'payplug'));
1220 }
1221 }
1222
1223 /**
1224 * Check the order amount to ensure it's on the allowed range.
1225 *
1226 * @param int $amount
1227 *
1228 * @return int|\WP_Error
1229 */
1230 public function validate_order_amount($amount)
1231 {
1232 if (
1233 $amount < PayplugWoocommerceHelper::get_minimum_amount()
1234 || $amount > PayplugWoocommerceHelper::get_maximum_amount()
1235 ) {
1236 return new \WP_Error(
1237 'invalid order amount',
1238 sprintf(__('Payments for this amount (%s) are not authorised with this payment gateway.', 'payplug'), \wc_price($amount / 100))
1239 );
1240 }
1241
1242 return $amount;
1243 }
1244
1245 /**
1246 * Limit string length.
1247 *
1248 * @param string $value
1249 * @param int $maxlength
1250 *
1251 * @return string
1252 */
1253 public function limit_length($value, $maxlength = 100)
1254 {
1255 return (strlen($value) > $maxlength) ? substr($value, 0, $maxlength) : $value;
1256 }
1257
1258 /**
1259 * Get user's keys.
1260 *
1261 * @param string $email
1262 * @param string $password
1263 *
1264 * @return array|\WP_Error
1265 */
1266 public function retrieve_user_api_keys($email, $password)
1267 {
1268 if (empty($email) || empty($password)) {
1269 return new \WP_Error('missing_login_data', __('Please fill all login fields', 'payplug'));
1270 }
1271
1272 try {
1273 $response = Authentication::getKeysByLogin($email, $password);
1274 if (empty($response) || !isset($response['httpResponse']) && "payplug" === $this->id) {
1275 return new \WP_Error('invalid_credentials', __('Invalid credentials.', 'payplug'));
1276 }
1277
1278 return $response['httpResponse']['secret_keys'];
1279 } catch (HttpException $e) {
1280 if("payplug" === $this->id) {
1281 return new \WP_Error('invalid_credentials', __('Invalid credentials.', 'payplug'));
1282 }
1283 }
1284 }
1285
1286 /**
1287 * Get user merchant id.
1288 *
1289 * This method might be called during the login process before the global PayPlug
1290 * configuration is set. In that case you can pass a valid token to make the request.
1291 *
1292 * @param string|null $key
1293 *
1294 * @return string
1295 */
1296 public function retrieve_merchant_id($key = null)
1297 {
1298 try {
1299 $response = !is_null($key) && !empty($key) ? Authentication::getAccount(new Payplug($key)) : Authentication::getAccount();
1300 PayplugWoocommerceHelper::set_transient_data($response);
1301 $merchant_id = isset($response['httpResponse']['id']) ? $response['httpResponse']['id'] : '';
1302 } catch (ConfigurationException $e) {
1303 PayplugGateway::log(sprintf('Missing API key for PayPlug client : %s', wc_print_r($e->getMessage(), true)), 'error');
1304
1305 $merchant_id = '';
1306 } catch (HttpException $e) {
1307 PayplugGateway::log(sprintf('Account request error from PayPlug API : %s', wc_print_r($e->getErrorObject(), true)), 'error');
1308
1309 $merchant_id = '';
1310 } catch (\Exception $e) {
1311 PayplugGateway::log(sprintf('Account request error : %s', wc_clean($e->getMessage())), 'error');
1312
1313 $merchant_id = '';
1314 }
1315
1316 return $merchant_id;
1317 }
1318
1319 /**
1320 * Generate Hidden HTML.
1321 *
1322 * @param string $key
1323 * @param array $data
1324 *
1325 * @return string
1326 */
1327 public function generate_hidden_html($key, $data)
1328 {
1329 $field_key = $this->get_field_key($key);
1330 $defaults = array(
1331 'title' => '',
1332 'disabled' => false,
1333 'class' => '',
1334 'css' => '',
1335 'placeholder' => '',
1336 'type' => 'text',
1337 'desc_tip' => false,
1338 'description' => '',
1339 'custom_attributes' => array(),
1340 );
1341
1342 $data = wp_parse_args($data, $defaults);
1343
1344 ob_start();
1345 ?>
1346 <input type="<?php echo esc_attr($data['type']); ?>" name="<?php echo esc_attr($field_key); ?>" id="<?php echo esc_attr($field_key); ?>" value="<?php echo esc_attr($this->get_option($key)); ?>" />
1347 <?php
1348
1349 return ob_get_clean();
1350 }
1351
1352 /**
1353 * Generate Yes/No Input HTML.
1354 *
1355 * @param string $key
1356 * @param array $data
1357 *
1358 * @return string
1359 */
1360 public function generate_yes_no_html($key, $data)
1361 {
1362 $field_key = $this->get_field_key($key);
1363 $defaults = array(
1364 'title' => '',
1365 'no' => 'No',
1366 'yes' => 'Yes',
1367 'disabled' => false,
1368 'class' => '',
1369 'css' => '',
1370 'placeholder' => '',
1371 'type' => 'text',
1372 'desc_tip' => false,
1373 'description' => '',
1374 'custom_attributes' => [],
1375 'hide_label' => false,
1376 );
1377
1378 $data = wp_parse_args($data, $defaults);
1379 $checked = 'yes' === $this->get_option($key) ? '1' : '0';
1380
1381 ob_start();
1382 ?>
1383 <tr valign="top">
1384 <?php if (!$data['hide_label']) : ?>
1385 <th scope="row" class="titledesc">
1386 <label for="<?php echo esc_attr($field_key); ?>">
1387 <?php echo wp_kses_post($data['title']); ?>
1388 <?php echo $this->get_tooltip_html($data); ?>
1389 </label>
1390 </th>
1391 <?php endif; ?>
1392 <td class="forminp">
1393 <fieldset>
1394 <legend class="screen-reader-text"><span><?php echo wp_kses_post($data['title']); ?></span>
1395 </legend>
1396 <div class="radio--custom">
1397 <input class="radio radio-yes <?php echo esc_attr($data['class']); ?>" type="radio" name="<?php echo esc_attr($field_key); ?>" id="<?php echo esc_attr($field_key); ?>-yes" value="1" <?php checked('1', $checked); ?> <?php disabled($data['disabled'], true); ?> <?php echo $this->get_custom_attribute_html($data); ?>>
1398 <label for="<?php echo esc_attr($field_key); ?>-yes"><?php echo esc_html($data['yes']); ?></label>
1399 </div>
1400 <div class="radio--custom">
1401 <input class="radio radio-no <?php echo esc_attr($data['class']); ?>" type="radio" name="<?php echo esc_attr($field_key); ?>" id="<?php echo esc_attr($field_key); ?>-no" value="0" <?php checked('0', $checked); ?> <?php disabled($data['disabled'], true); ?> <?php echo $this->get_custom_attribute_html($data); ?>>
1402 <label for="<?php echo esc_attr($field_key); ?>-no"><?php echo esc_html($data['no']); ?></label>
1403 </div>
1404 <div id="live-mode-test-p"><?php echo $this->get_description_html($data); ?></div>
1405 </fieldset>
1406 </td>
1407 </tr>
1408 <?php
1409
1410 return ob_get_clean();
1411 }
1412
1413 /**
1414 * Generate Radio Input HTML.
1415 *
1416 * @param string $key
1417 * @param array $data
1418 *
1419 * @return string
1420 */
1421 public function generate_radio_html($key, $data)
1422 {
1423 $field_key = $this->get_field_key($key);
1424 $defaults = array(
1425 'title' => '',
1426 'disabled' => false,
1427 'class' => '',
1428 'css' => '',
1429 'placeholder' => '',
1430 'type' => 'text',
1431 'desc_tip' => false,
1432 'description' => '',
1433 'custom_attributes' => [],
1434 'options' => [],
1435 );
1436
1437 $data = wp_parse_args($data, $defaults);
1438
1439 ob_start();
1440 ?>
1441 <tr valign="top">
1442 <th scope="row" class="titledesc">
1443 <label for="<?php echo esc_attr($field_key); ?>">
1444 <?php echo wp_kses_post($data['title']); ?>
1445 <?php echo $this->get_tooltip_html($data); ?>
1446 </label>
1447 </th>
1448 <td class="forminp">
1449 <fieldset>
1450 <legend class="screen-reader-text"><span><?php echo wp_kses_post($data['title']); ?></span>
1451 </legend>
1452 <?php foreach ($data['options'] as $option_key => $option_value) : ?>
1453 <input class="radio <?php echo esc_attr($data['class']); ?>" type="radio" name="<?php echo esc_attr($field_key); ?>" id="<?php echo esc_attr($field_key); ?>-<?php echo esc_attr($option_key); ?>" value="<?php echo esc_attr($option_key); ?>" <?php checked($option_key, $this->get_option($key)); ?> <?php disabled($data['disabled'], true); ?> <?php echo $this->get_custom_attribute_html($data); ?>>
1454 <label for="<?php echo esc_attr($field_key); ?>-<?php echo esc_attr($option_key); ?>"><?php echo esc_html($option_value); ?></label>
1455 <?php endforeach; ?>
1456 <?php echo $this->get_description_html($data); ?>
1457 </fieldset>
1458 </td>
1459 </tr>
1460 <?php
1461
1462 return ob_get_clean();
1463 }
1464
1465 /**
1466 * Generate Login HTML.
1467 *
1468 * @param string $key
1469 * @param array $data
1470 *
1471 * @return string
1472 */
1473 public function generate_login_html($key, $data)
1474 {
1475 $field_key = $this->get_field_key($key);
1476 $defaults = [];
1477
1478 $data = wp_parse_args($data, $defaults);
1479
1480 ob_start();
1481 ?>
1482 <tr valign="top">
1483 <td class="forminp">
1484 <p><?php echo $this->get_option('email'); ?></p>
1485 <p>
1486 <input id="payplug-logout" type="submit" name="submit_logout" value="<?php _e('Logout', 'payplug'); ?>">
1487 <input type="hidden" name="save" value="logout">
1488 <?php wp_nonce_field('payplug_user_logout', '_logoutaction'); ?>
1489 |
1490 <a href="https://portal.payplug.com" target="_blank"><?php _e('Go to your PayPlug Portal', 'payplug'); ?></a>
1491 </p>
1492 </td>
1493 </tr>
1494 <?php
1495
1496 return ob_get_clean();
1497 }
1498
1499
1500 /**
1501 * Generate Oney popup option HTML.
1502 *
1503 * @param string $key
1504 * @param array $data
1505 *
1506 * @return string
1507 */
1508 public function generate_oney_product_animation_html($key, $data)
1509 {
1510 $field_key = $this->get_field_key($key);
1511
1512 $defaults = array(
1513 'title' => '',
1514 'disabled' => false,
1515 'class' => '',
1516 'css' => '',
1517 'placeholder' => '',
1518 'type' => 'checkbox',
1519 'desc_tip' => false,
1520 'description' => '',
1521 'custom_attributes' => [],
1522 'options' => [],
1523 );
1524
1525 $data = wp_parse_args($data, $defaults);
1526
1527 ob_start();
1528 ?>
1529 <tr valign="top" id="oney_installments_pop_up">
1530 <th scope="row" class="titledesc">
1531 <label for="<?php echo esc_attr($field_key); ?>">
1532 <?php echo wp_kses_post($data['title']); ?>
1533 <?php echo $this->get_tooltip_html($data); ?>
1534 </label>
1535 </th>
1536 <td class="forminp">
1537 <fieldset>
1538 <legend class="screen-reader-text"><span><?php echo wp_kses_post($data['title']); ?></span></legend>
1539 <label for="woocommerce_payplug_oney_product_animation">
1540 <input class="" type="checkbox" name="woocommerce_payplug_oney_product_animation" id="woocommerce_payplug_oney_product_animation" style="" <?php echo (($this->oney_product_animation == 'yes') ? "checked" : ''); ?>> <?php echo wp_kses_post($data['label']); ?></label><br>
1541 <p class="description"> <?php echo wp_kses_post($data['description']); ?></p>
1542 </fieldset>
1543 </td>
1544 </tr>
1545 <?php
1546
1547 return ob_get_clean();
1548 }
1549
1550 /**
1551 * Generate Oney Type Input HTML.
1552 *
1553 * @param string $key
1554 * @param array $data
1555 *
1556 * @return string
1557 */
1558 public function generate_oney_type_html($key, $data)
1559 {
1560 $field_key = $this->get_field_key($key);
1561 $defaults = array(
1562 'title' => '',
1563 'disabled' => false,
1564 'class' => '',
1565 'css' => '',
1566 'placeholder' => '',
1567 'type' => 'text',
1568 'desc_tip' => false,
1569 'description' => '',
1570 'custom_attributes' => [],
1571 'options' => [],
1572 );
1573
1574 $data = wp_parse_args($data, $defaults);
1575
1576 ob_start();
1577 ?>
1578 <tr valign="top" id="woocommerce_payplug_oney_type">
1579 <th scope="row" class="titledesc" style="padding-top: 0px;">
1580 <label for="<?php echo esc_attr($field_key); ?>">
1581 <?php echo wp_kses_post($data['title']); ?>
1582 <?php echo $this->get_tooltip_html($data); ?>
1583 </label>
1584 </th>
1585 <td class="forminp" style="padding-top: 0px;">
1586 <fieldset>
1587 <legend class="screen-reader-text"><span><?php echo wp_kses_post($data['title']); ?></span>
1588 </legend>
1589 <?php foreach ($data['options'] as $option_key => $option_value) : ?>
1590 <input class="radio <?php echo esc_attr($data['class']); ?>" type="radio" name="<?php echo esc_attr($field_key); ?>" id="<?php echo esc_attr($field_key); ?>-<?php echo esc_attr($option_key); ?>" value="<?php echo esc_attr($option_key); ?>" <?php checked($option_key, $this->get_option($key)); ?> <?php disabled($data['disabled'], true); ?> <?php echo $this->get_custom_attribute_html($data); ?>>
1591 <label for="<?php echo esc_attr($field_key); ?>-<?php echo esc_attr($option_key); ?>" style="margin-right: 20px !important;">
1592 <span style="font-weight: 500;"><?php echo esc_html($option_value); ?></span>
1593 <span style="color:#646970;"> : <?php echo $data['descriptions'][$option_key] ;?></span>
1594 </label>
1595 <?php endforeach; ?>
1596 <?php echo $this->get_description_html($data); ?>
1597 </fieldset>
1598 </td>
1599 </tr>
1600 <?php
1601
1602 return ob_get_clean();
1603 }
1604
1605 /**
1606 * Generate Oney Thresholds Input HTML.
1607 *
1608 * @param string $key
1609 * @param array $data
1610 *
1611 * @return string
1612 */
1613 public function generate_oney_thresholds_html($key, $data)
1614 {
1615 $field_key = $this->get_field_key($key);
1616 $defaults = array(
1617 'title' => '',
1618 'disabled' => false,
1619 'class' => '',
1620 'css' => '',
1621 'placeholder' => '',
1622 'type' => 'text',
1623 'desc_tip' => false,
1624 'description' => '',
1625 'custom_attributes' => [],
1626 'options' => [],
1627 );
1628
1629 $data = wp_parse_args($data, $defaults);
1630
1631 ob_start();
1632 ?>
1633 <tr valign="top" id="woocommerce_payplug_oney_thresholds">
1634 <th scope="row" class="titledesc" style="padding-top: 0px;">
1635 <label for="<?php echo esc_attr($field_key); ?>">
1636 <?php echo wp_kses_post($data['title']); ?>
1637 <?php echo $this->get_tooltip_html($data); ?>
1638 </label>
1639 </th>
1640 <td class="forminp" style="padding-top: 0px;">
1641 <fieldset>
1642 <div id="oney_thresholds_description"><?php echo $this->get_description_html($data); ?></div>
1643 <input type="number" id="payplug_oney_thresholds_min" min="<?php echo $this->min_oney_price;?>" max="<?php echo $this->max_oney_price;?>" class="payplug-admin-oney-threshold-input">
1644 <b class="d-inline-block">€</b>
1645 <div class="d-inline-block" id="slider-range"></div>
1646 <input type="number" id="payplug_oney_thresholds_max" min="<?php echo $this->min_oney_price;?>" max="<?php echo $this->max_oney_price;?>" class="payplug-admin-oney-threshold-input">
1647 <b class="d-inline-block">€</b>
1648 </fieldset>
1649 </td>
1650 </tr>
1651 <?php
1652
1653 return ob_get_clean();
1654 }
1655
1656 /**
1657 * Validate Radio Field.
1658 *
1659 * Make sure the data is escaped correctly, etc.
1660 *
1661 * @param string $key
1662 * @param string|null $value Posted Value
1663 *
1664 * @return string
1665 */
1666 public function validate_radio_field($key, $value)
1667 {
1668 $value = is_null($value) ? '' : $value;
1669
1670 return wc_clean(stripslashes($value));
1671 }
1672
1673 /**
1674 * Validate Yes/No Field.
1675 *
1676 * @param string $key
1677 * @param string $value Posted Value
1678 *
1679 * @return string
1680 */
1681 public function validate_yes_no_field($key, $value)
1682 {
1683 return ('1' === (string) $value) ? 'yes' : 'no';
1684 }
1685
1686 /**
1687 * Validate Yes/No Field.
1688 *
1689 * @param string $key
1690 * @param string $value Posted Value
1691 *
1692 * @return string
1693 */
1694 public function validate_oney_product_animation_field($key, $value)
1695 {
1696 return ('on' === (string) $value) ? 'yes' : 'no';
1697 }
1698
1699 /**
1700 * Validate Oney Type Field.
1701 *
1702 * Make sure the data is escaped correctly, etc.
1703 *
1704 * @param string $key
1705 * @param string|null $value Posted Value
1706 *
1707 * @return string
1708 */
1709 public function validate_oney_type_field($key, $value)
1710 {
1711 $value = is_null($value) ? 'with_fees' : $value;
1712
1713 return wc_clean(stripslashes($value));
1714 }
1715
1716 /**
1717 * Validate Oney Thresholds Field.
1718 *
1719 * Make sure the data is escaped correctly, etc.
1720 *
1721 * @param string $key
1722 * @param string|null $value Posted Value
1723 *
1724 * @return string
1725 */
1726 public function validate_oney_thresholds_field($key, $value)
1727 {
1728 $value = is_null($value) ? [100, 3000] : $value;
1729
1730 return wc_clean($value);
1731 }
1732
1733 /**
1734 * Get PayPlug gateway mode.
1735 *
1736 * @return string
1737 */
1738 public function get_current_mode()
1739 {
1740 return ('yes' === $this->get_option('mode')) ? 'live' : 'test';
1741 }
1742
1743 /**
1744 * Get user API key.
1745 *
1746 * @param string $mode
1747 *
1748 * @return string
1749 */
1750 public function get_api_key($mode = 'test')
1751 {
1752
1753 switch ($mode) {
1754 case 'test':
1755 $key = $this->get_option('payplug_test_key');
1756 break;
1757 case 'live':
1758 $key = $this->get_option('payplug_live_key');
1759 break;
1760 default:
1761 $key = '';
1762 break;
1763 }
1764
1765 return $key;
1766 }
1767
1768 /**
1769 * Check if an api key exist for a mode.
1770 *
1771 * @param string $mode
1772 *
1773 * @return bool
1774 */
1775 public function has_api_key($mode = 'test')
1776 {
1777 $key = $this->get_api_key($mode);
1778 $key = trim($key);
1779
1780 return !empty($key);
1781 }
1782
1783 /**
1784 * Get current merchant id.
1785 *
1786 * @return string
1787 */
1788 public function get_merchant_id()
1789 {
1790 return $this->get_option('payplug_merchant_id', '');
1791 }
1792
1793 /**
1794 * Check if user is logged in and we have an API key for TEST mode.
1795 *
1796 * @return bool
1797 */
1798 public function user_logged_in()
1799 {
1800 return !empty($this->get_option('payplug_test_key'));
1801 }
1802
1803 /**
1804 * Check if oneclick payment is activated and merchant can use it.
1805 *
1806 * @return bool
1807 */
1808 public function oneclick_available()
1809 {
1810 return $this->user_logged_in()
1811 && $this->oneclick
1812 && $this->permissions->has_permissions(PayplugPermissions::SAVE_CARD);
1813 }
1814
1815 /**
1816 * Check if the gatteway is allowed for the order amount
1817 *
1818 * @param array
1819 * @return array
1820 */
1821 public function check_gateway($gateways)
1822 {
1823 if ( !empty( WC()->cart ) && isset($gateways[$this->id]) && $gateways[$this->id]->id == $this->id) {
1824 $order_amount = $this->get_order_total();
1825 if ($order_amount < self::MIN_AMOUNT || $order_amount > self::MAX_AMOUNT) {
1826 unset($gateways[$this->id]);
1827 }
1828 }
1829
1830 if($this->oney_type == 'with_fees'){
1831 unset($gateways['oney_x3_without_fees']);
1832 unset($gateways['oney_x4_without_fees']);
1833 } else{
1834 unset($gateways['oney_x3_with_fees']);
1835 unset($gateways['oney_x4_with_fees']);
1836 }
1837
1838 return $gateways;
1839 }
1840
1841 /**
1842 * Can the order be refunded via this gateway?
1843 *
1844 *
1845 * @param WC_Order $order Order object.
1846 * @return bool If false, the automatic refund button is hidden in the UI.
1847 */
1848 public function can_refund_order($order)
1849 {
1850 $status = $order->get_status();
1851 return $order && $this->supports('refunds') && $status !== "cancelled" && $status !== "failed";
1852 }
1853
1854 public function getPayplugMerchantCountry(){
1855 return $this->payplug_merchant_country;
1856 }
1857
1858 public function setPayplugMerchantCountry($country){
1859 $this->payplug_merchant_country = $country;
1860 }
1861
1862 function is_checkout_block() {
1863 return WC_Blocks_Utils::has_block_in_page( wc_get_page_id('checkout'), 'woocommerce/checkout' );
1864 }
1865
1866 }
1867