PluginProbe
PayPlug for WooCommerce (Official) / 1.5.0
PayPlug for WooCommerce (Official) v1.5.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) 1.5.0, at src/Gateway/PayplugGateway.php

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