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

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

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