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

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