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

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