PluginProbe
PayPlug for WooCommerce (Official) / 2.0.1
PayPlug for WooCommerce (Official) v2.0.1
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.0.1, at src/Gateway/PayplugGateway.php

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