· 5 years ago · Dec 03, 2020, 09:40 AM
1<?php
2
3/**
4 * Class WC_Gateway_Przelewy24
5 */
6class WC_Gateway_Przelewy24 extends WC_Payment_Gateway
7{
8 const PAYMENT_METHOD = 'przelewy24';
9
10 /**
11 * The active currency.
12 *
13 * @var string
14 */
15 private $active_currency;
16
17 /**
18 * The P24_Core instance
19 *
20 * @var P24_Core
21 */
22 private $plugin_core;
23
24 /**
25 * @var array
26 *
27 * List of common settings that are used by the gateway class.
28 * There could be more keys set by other parts of plugin.
29 */
30 private $common_settings_keys = [
31 'enabled',
32 ];
33
34 /**
35 * P24_Communication_Parser instance.
36 *
37 * @var P24_Communication_Parser
38 */
39 private $communication_parser;
40
41 /**
42 * WC_Gateway_Przelewy24 constructor.
43 */
44 public function __construct()
45 {
46 $this->plugin_core = get_przelewy24_plugin_instance();
47 $this->plugin_core->register_gateway( $this );
48
49 $this->supports = array(
50 'products',
51 'refunds',
52 );
53
54 $this->id = self::PAYMENT_METHOD;
55 $this->icon = PRZELEWY24_URI . 'logo.png';
56 $this->method_title = 'Przelewy24';
57 $this->method_description = __( 'Moduł Przelewy24.pl w tej chwili posiada podstawową funkcjonalność, która sukcesywnie będzie rozszerzana.', 'przelewy24' );
58 $this->has_fields = false;
59
60 $this->generator = new Przelewy24Generator( $this );
61
62 $communication_parser = $this->plugin_core->get_communication_parser();
63 $communication_parser->parse_status_response( $this );
64 /* If we parse some data form Przelewy24, it may change active currency. */
65 $this->plugin_core->try_override_active_currency( $communication_parser );
66 $this->active_currency = null;
67 $this->communication_parser = $communication_parser;
68
69 $this->init_settings();
70
71 $this->title = (isset($this->settings['title']) ? $this->settings['title'] : '');
72 $this->description = (isset($this->settings['description'])) ? $this->settings['description'] : '';
73 $this->instructions = $this->get_option('instructions', $this->description);
74 $this->merchant_id = (isset($this->settings['merchant_id'])) ? $this->settings['merchant_id'] : 0;
75 $this->shop_id = (isset($this->settings['shop_id'])) ? $this->settings['shop_id'] : 0;
76 $this->salt = (isset($this->settings['CRC_key'])) ? $this->settings['CRC_key'] : '';
77 $this->p24_oneclick = (isset($this->settings['p24_oneclick']) ? $this->settings['p24_oneclick'] : 'no');
78 $this->p24_payinshop = (isset($this->settings['p24_oneclick']) ? $this->settings['p24_oneclick'] : 'no');
79 $this->p24_acceptinshop = (isset($this->settings['p24_acceptinshop']) ? $this->settings['p24_acceptinshop'] : 'no');
80 $this->p24_testmod = (isset($this->settings['p24_testmod']) ? $this->settings['p24_testmod'] : 0);
81 $this->p24_api = (isset($this->settings['p24_api']) ? $this->settings['p24_api'] : '');
82 $this->init_form_fields();
83
84 add_action('woocommerce_update_options_payment_gateways_' . $this->id, array(&$this, 'process_admin_options'));
85
86 add_action('woocommerce_receipt_przelewy24', array(&$this, 'receipt_page'));
87 add_action('woocommerce_thankyou_przelewy24', array($this, 'thankyou_page'));
88 add_action('woocommerce_email_before_order_table', array($this, 'email_instructions'), 10, 3);
89 add_action('admin_enqueue_scripts', array($this, 'load_custom_admin_scripts'));
90 add_action('wp_enqueue_scripts', array($this,'load_custom_scripts'));
91
92 add_action('woocommerce_api_wc_gateway_przelewy24', array($this, 'przelewy24_response'));
93 }
94
95 /**
96 * Get active currency.
97 *
98 * @return string
99 */
100 private function get_active_currency() {
101 if ( ! $this->active_currency ) {
102 $this->active_currency = get_woocommerce_currency();
103 if ( is_admin() ) {
104 $this->active_currency = apply_filters( 'przelewy24_multi_currency_admin_currency', $this->active_currency );
105 }
106 }
107 return $this->active_currency;
108 }
109
110 /**
111 * Get kay of option record from database.
112 *
113 * It is different for each currency.
114 *
115 * @param null|string $for_currency
116 *
117 * @return string
118 */
119 public function get_option_key( $for_currency = null ) {
120 if ( !$for_currency ) {
121 $for_currency = $this->get_active_currency();
122 }
123 $code = strtolower( $for_currency );
124 return $this->plugin_id . $this->id . '_' . $code . '_settings';
125 }
126
127 /**
128 * Set other variables based on updated settings.
129 */
130 private function propagate_settings()
131 {
132 $this->enabled = ! empty( $this->settings['enabled'] ) && 'yes' === $this->settings['enabled'] ? 'yes' : 'no';
133 }
134
135 /**
136 * Init settings.
137 *
138 * There is one record for each currency and one common.
139 * For new currency, copy data from default one.
140 */
141 public function init_settings()
142 {
143 $this->settings = $this->load_settings_form_db();
144 $this->settings['alt_nonce'] = wp_create_nonce('p24_action');
145 $common_settings = get_option( P24_Request_Support::OPTION_KEY_COMMON, [] );
146 $this->common_settings_keys = array_unique( array_merge( array_keys( $common_settings ), $this->common_settings_keys ) );
147 $this->settings = $common_settings + $this->settings;
148 $this->propagate_settings();
149 }
150
151 /**
152 * Get config for currency in array.
153 *
154 * @param null|string $for_currency The currency.
155 * @return array
156 */
157 public function load_settings_form_db( $for_currency = null ) {
158 if ( ! $for_currency ) {
159 $for_currency = $this->get_active_currency();
160 }
161 $option_key = $this->get_option_key( $for_currency );
162 $settings = get_option( $option_key, null );
163 if ( ! is_array( $settings ) && $for_currency === $this->plugin_core->get_default_currency() ) {
164 /* Try import legacy config. */
165 $alt_key = parent::get_option_key();
166 $settings = get_option( $alt_key, null );
167 if ( ! isset( $settings['sub_enabled'] ) && isset( $settings['enabled'] ) ) {
168 $settings['sub_enabled'] = $settings['enabled'];
169 }
170 }
171 if ( ! is_array( $settings ) ) {
172 $form_fields = $this->get_form_fields();
173 $settings = array_merge( array_fill_keys( array_keys( $form_fields ), '' ), wp_list_pluck( $form_fields, 'default' ) );
174 }
175 return $settings;
176 }
177
178 /**
179 * Get config for currency in object.
180 *
181 * @param null|string $for_currency
182 * @return P24_Config_Accessor
183 */
184 public function load_settings_from_db_formatted( $for_currency = null ) {
185 if ( ! $for_currency ) {
186 $for_currency = $this->get_active_currency();
187 }
188 $array = $this->load_settings_form_db( $for_currency );
189 $config_holder = $this->map_array_to_config_holder( $array );
190 return new P24_Config_Accessor( $for_currency, $config_holder );
191 }
192
193 /**
194 * Get config for currency from sanitized fields.
195 *
196 * @param null|string $for_currency
197 * @return P24_Config_Accessor
198 */
199 private function get_settings_from_sanitized_formatted( $for_currency = null ) {
200 if ( ! $for_currency ) {
201 $for_currency = $this->get_active_currency();
202 }
203 $config_holder = $this->map_array_to_config_holder( $this->sanitized_fields );
204 return new P24_Config_Accessor( $for_currency, $config_holder );
205 }
206
207 /**
208 * Get config for currency from internal configuration.
209 *
210 * @param null|string $for_currency
211 * @param bool $ignore_api
212 * @return P24_Config_Accessor
213 */
214 public function get_settings_from_internal_formatted($for_currency = null, $ignore_api = false) {
215 if ( ! $for_currency ) {
216 $for_currency = $this->get_active_currency();
217 }
218 $config_holder = new P24_Config_Holder();
219 $config_holder->merchant_id = $this->merchant_id;
220 $config_holder->shop_id = $this->shop_id;
221 $config_holder->salt = $this->salt;
222 $config_holder->p24_operation_mode = $this->p24_testmod;
223 $config_holder->p24_oneclick = $this->p24_oneclick;
224 if (!$ignore_api) {
225 $config_holder->p24_api = $this->p24_api;
226 }
227 return new P24_Config_Accessor( $for_currency, $config_holder );
228 }
229
230 /**
231 * Convert common arrays to config holder.
232 *
233 * @param $array
234 * @return P24_Config_Holder
235 */
236 private function map_array_to_config_holder ( $array) {
237 $config_holder = new P24_Config_Holder();
238 foreach ( $array as $k => $v ) {
239 if ( property_exists( $config_holder, $k ) ) {
240 $config_holder->{$k} = $v;
241 } elseif ( $k === 'CRC_key' ) {
242 $config_holder->salt = $v;
243 } elseif ( $k === 'p24_testmod' ) {
244 $config_holder->p24_operation_mode = $v;
245 } elseif ( $k === 'p24_paymethods' ) {
246 $config_holder->p24_show_paymethods = $v;
247 }
248 }
249 return $config_holder;
250 }
251
252 /**
253 * Update one option in database.
254 *
255 * There are two records in database.
256 * Each record hold an serialized array.
257 * The option may be in one of these arrays.
258 *
259 * The parent method is overwritten.
260 *
261 * @param string $key
262 * @param mixed $value
263 * @return bool
264 */
265 public function update_option($key, $value = '')
266 {
267 if ( empty( $this->settings ) ) {
268 $this->init_settings();
269 }
270 $this->settings[ $key ] = $value;
271 $this->propagate_settings();
272
273 $options = apply_filters( 'woocommerce_settings_api_sanitized_fields_' . $this->id, $this->settings );
274 if ( in_array( $key, $this->common_settings_keys ) ) {
275 $options = array_intersect_key( $options, array_flip( $this->common_settings_keys ) );
276 $options_key = P24_Request_Support::OPTION_KEY_COMMON;
277 } else {
278 $options = array_diff_key( $options, array_flip( $this->common_settings_keys ) );
279 $options_key = $this->get_option_key();
280 }
281 return update_option( $options_key, $options, 'yes' );
282 }
283
284 /**
285 * Return if gateway is available for selected currency.
286 *
287 * @return bool
288 */
289 public function is_available()
290 {
291 if ( empty( $this->settings ) ) {
292 $this->init_settings();
293 }
294 $is_available = parent::is_available();
295 if ( ! array_key_exists( 'sub_enabled', $this->settings ) ) {
296 $is_available = false;
297 } elseif ( $this->settings[ 'sub_enabled' ] !== 'yes' ) {
298 $is_available = false;
299 }
300 return $is_available;
301 }
302
303 /**
304 * Validate text fields.
305 *
306 * This method works for hidden fields too.
307 * We have to propagate hack for checkbox.
308 *
309 * @param string $key Name of fields.
310 * @param string $value Value of field.
311 *
312 * @return string
313 */
314 public function validate_text_field( $key, $value ) {
315 if ( $key === 'sub_enabled' ) {
316 return $value ? 'yes' : 'no';
317 } else {
318 return parent::validate_text_field( $key, $value );
319 }
320 }
321
322 /**
323 * Returns the POSTed data, to be used to save the settings.
324 *
325 * @return array
326 */
327 public function get_post_data()
328 {
329 $post = parent::get_post_data();
330 $key = $this->get_field_key( 'active_currency' );
331 if ( array_key_exists( $key, $post ) ) {
332 $this->active_currency = $post[$key];
333 }
334 return $post;
335 }
336
337 /**
338 * Generate Settings HTML.
339 *
340 * Generate the HTML for the fields on the "settings" screen.
341 *
342 * @param array $form_fields (default: array()) Array of form fields.
343 * @param bool $echo Echo or return.
344 * @return string|null The html for the settings or nothing.
345 */
346 public function generate_settings_html( $form_fields = array(), $echo = true ) {
347 if ( empty( $form_fields ) ) {
348 $form_fields = $this->get_form_fields();
349 }
350 $core = get_przelewy24_plugin_instance();
351 if ( $core->is_multi_currency_active() ) {
352 $this->settings['active_currency'] = $this->get_active_currency();
353 $prefix = array(
354 'active_currency' => array(
355 'title' => __('Aktywna waluta', 'przelewy24'),
356 'type' => 'select',
357 'options' => get_przelewy24_multi_currency_options(),
358 'class' => 'js_currency_admin_selector',
359 'default' => 'PLN'
360 ),
361 'alt_nonce' => array(
362 'type' => 'hidden',
363 'class' => 'js-p24-alt-nonce',
364 )
365 );
366 $form_fields = $prefix + $form_fields;
367 $form_fields['sub_enabled']['type'] = 'checkbox';
368 $form_fields['sub_enabled']['title'] = __('Włącz/Wyłącz', 'przelewy24');
369 }
370 return parent::generate_settings_html( $form_fields, $echo );
371 }
372
373 /**
374 * Load scripts for webpage.
375 */
376 function load_custom_scripts()
377 {
378 if ( empty( $this->settings ) ) {
379 $this->init_settings();
380 }
381 $is_one_click_enabled = ( isset( $this->settings['p24_oneclick'] ) && 'yes' === $this->settings['p24_oneclick'] );
382 wp_enqueue_script('jquery');
383 wp_enqueue_script('jquery-blockui');
384 wp_enqueue_style('p24_plugin_css', $this->getCssUrl());
385 wp_enqueue_style('p24_css', $this->get_bank_dependant_css_url());
386 wp_enqueue_script('p24_payment_script', $this->getJsUrl());
387 wp_localize_script('p24_payment_script', 'p24_payment_php_vars', array(
388 'error_msg4js' => __('Wystąpił błąd. Spróbuj ponownie lub wybierz inną metodę płatności.', 'przelewy24'),
389 'payments_msg4js' => '\f078'.__('więcej metod płatności','przelewy24').' \f078',
390 'forget_card' => self::get_cc_forget(get_current_user_id()),
391 'show_save_card' => (int) ( is_user_logged_in() && $is_one_click_enabled ),
392 )
393 );
394 }
395
396 /**
397 *
398 */
399 function load_custom_admin_scripts($hook)
400 {
401 if (empty($_REQUEST['section']) || 'woocommerce_page_wc-settings' != $hook || strpos($_REQUEST['section'], 'przelewy24') === false) {
402 return;
403 }
404 wp_enqueue_script('jquery');
405 wp_enqueue_script('jquery-blockui');
406 wp_enqueue_style('p24_plugin_css', PRZELEWY24_URI . 'assets/css/paymethods.css');
407 wp_enqueue_style('p24_css', $this->get_bank_dependant_css_url());
408 wp_enqueue_script('p24_payment_script', PRZELEWY24_URI . 'assets/js/admin.js');
409 wp_localize_script('p24_payment_script', 'p24_payment_script_vars', array(
410 'php_msg1' => __('Metody płatności widoczne od razu - upuść tutaj max. 5 metod płatności:','przelewy24'),
411 'php_msg2' => __('Metody płatności widoczne po kliknięciu przycisku (więcej...):','przelewy24'),
412 )
413 );
414 }
415
416 /**
417 * Returns url to css file with styles for bank logos and payment methods previews.
418 *
419 * @return string
420 */
421 private function get_bank_dependant_css_url() {
422 return Przelewy24Class::getHostStatic( false ) . 'skrypty/ecommerce_plugin.css.php';
423 }
424
425 function init_form_fields()
426 {
427 $this->form_fields = array(
428 'enabled' => array(
429 'title' => __('Włącz/Wyłącz', 'przelewy24'),
430 'type' => 'checkbox',
431 'label' => __('Aktywuj moduł płatności Przelewy24.', 'przelewy24'),
432 'default' => 'no'),
433 'sub_enabled' => array(
434 'type' => 'hidden',
435 'label' => __('Aktywuj moduł płatności Przelewy24 dla danej waluty.', 'przelewy24'),
436 'default' => 'yes'),
437 'title' => array(
438 'title' => __('Tytuł:', 'przelewy24'),
439 'type' => 'text',
440 'description' => __('Tekst który zobaczą klienci podczas dokonywania zakupu', 'przelewy24'),
441 'default' => __('Przelewy24', 'przelewy24')),
442 'merchant_id' => array(
443 'title' => __('ID Sprzedawcy', 'przelewy24'),
444 'type' => 'text',
445 'description' => __('Identyfikator sprzedawcy nadany w systemie Przelewy24.', 'przelewy24'),
446 'default' => 0,
447 'required' => true),
448 'shop_id' => array(
449 'title' => __('ID Sklepu', 'przelewy24'),
450 'type' => 'text',
451 'description' => __('Identyfikator sklepu nadany w systemie Przelewy24.', 'przelewy24'),
452 'default' => 0,
453 'required' => true),
454 'CRC_key' => array(
455 'title' => __('Klucz CRC', 'przelewy24'),
456 'type' => 'text',
457 'description' => __('Klucz do CRC nadany w systemie Przelewy24.', 'przelewy24'),
458 'placeholder' => __('(16 znaków)', 'przelewy24'),
459 'required' => true),
460 'p24_testmod' => array(
461 'title' => __('Tryb modułu', 'przelewy24'),
462 'type' => 'select',
463 'options' => $this->get_options(),
464 'description' => __('Tryb przeprowadzania transakcji', 'przelewy24')),
465 'description' => array(
466 'title' => __('Opis', 'przelewy24'),
467 'type' => 'textarea',
468 'description' => __('Tekst który zobaczą klienci przy wyborze metody płatności', 'przelewy24'),
469 'default' => __('Płać z Przelewy24', 'przelewy24')),
470 'p24_api' => array(
471 'title' => __('Klucz API','przelewy24'),
472 'type' => 'text',
473 'description' => __('Klucz API należy pobrać z panelu Przelewy24 z zakładki Moje dane','przelewy24'),
474 'placeholder' => __('(32 znaki)','przelewy24')),
475 'p24_oneclick' => array(
476 'title' => __('Oneclick','przelewy24'),
477 'type' => 'checkbox',
478 'label' => __('Aktywuj płatności oneclick','przelewy24'),
479 'default' => 'no'),
480 'p24_payinshop' => array(
481 'title' => __('Płatność w sklepie','przelewy24'),
482 'type' => 'checkbox',
483 'label' => __('Płatność kartą wewnątrz sklepu','przelewy24'),
484 'default' => 'no'),
485 'p24_acceptinshop' => array(
486 'title' => __('Akceptacja regulaminu Przelewy24.pl','przelewy24'),
487 'type' => 'checkbox',
488 'label' => __('Akceptacja regulaminu Przelewy24.pl','przelewy24'),
489 'default' => 'no'),
490 'p24_paymethods' => array(
491 'type' => 'checkbox',
492 'title' => __('Pokaż metody płatności','przelewy24'),
493 'label' => __('Pokaż dostępne metody płatności w sklepie','przelewy24'),
494 'description' => __('Klient może wybrać metodę płatności na stronie potwierdzenia zamówienia','przelewy24'),
495 'default' => 'no'),
496 'p24_graphics' => array(
497 'type' => 'checkbox',
498 'label' => __('Użyj graficznej listy metod płatności na stronie potwierdzenia zamówienia','przelewy24'),
499 'default' => 'yes'),
500 'p24_paymethods_first' => array(
501 'type' => 'text',
502 'title' => __('Widoczne metody płatności','przelewy24'),
503 'default' => '25,31,112,20,65'
504 ),
505 'p24_paymethods_second' => array(
506 'type' => 'text',
507 'title' => '',
508 'default' => ''),
509 'p24_paymethods_all' => array(
510 'type' => 'select',
511 'options' => $this->get_all_payment_methods(),
512 'default' => 0),
513 'p24_wait_for_result' => array(
514 'type' => 'checkbox',
515 'title' => __('Czekaj na wynik transakcji', 'przelewy24'),
516 'label' => ' ',
517 'default' => 'no'
518 )
519 );
520 }
521
522 /**
523 * @param bool $pay_slow
524 *
525 * @return array
526 */
527 public function get_all_payment_methods($pay_slow = false)
528 {
529 $config_accessor = $this->load_settings_from_db_formatted();
530 $P24 = new Przelewy24Class($config_accessor);
531 $all = $P24->availablePaymentMethodsSimple($pay_slow, $this->get_active_currency());
532 return $all;
533 }
534
535 public function validate_payment_methods_status($key)
536 {
537 $keyVal = "0";
538 if (isset($_POST[$this->plugin_id . $this->id . '_' . $key])) {
539 $keyVal = $_POST[$this->plugin_id . $this->id . '_' . $key];
540 if ($keyVal) {
541 try {
542 $is_test_mode = $this->sanitized_fields['p24_testmod'] === 'sandbox';
543 $address = Przelewy24Class::getHostStatic($is_test_mode) . 'external/' . $this->sanitized_fields['merchant_id'] . '.wsdl';
544 $client = new SoapClient($address, array('trace' => true, 'exceptions' => true));
545 if (!$client->PaymentMethods($this->sanitized_fields['merchant_id'], $this->sanitized_fields['p24_api'], 'PL')) {
546 throw new Exception();
547 }
548 } catch (Exception $ex) {
549 error_log(__METHOD__ . ' ' . $ex->getMessage());
550 $_POST[$this->plugin_id . $this->id . '_' . $key] = "0";
551 $this->add_error(__("Usługa PaymentMethods nie jest włączona dla tego sprzedawcy.",'przelewy24'));
552 return "no";
553 }
554 }
555 }
556 return $keyVal ? "yes" : "no";
557 }
558
559 /**
560 * @param $key
561 * @param $error
562 * @return string
563 */
564 public function validate_id($key, $error)
565 {
566
567 $ret = $this->get_option($key);
568 $valid = false;
569 if (isset($_POST[$this->plugin_id . $this->id . '_' . $key])) {
570 $ret = $_POST[$this->plugin_id . $this->id . '_' . $key];
571 if (is_numeric($ret) && $ret >= 1000) $valid = true;
572 }
573 if (!$valid) $this->errors[$key] = $error;
574 return $ret;
575 }
576
577 /**
578 * @param $key
579 * @return string
580 */
581 public function validate_crc($key)
582 {
583 $ret = $this->get_option($key);
584 $valid = false;
585 if (isset($_POST[$this->plugin_id . $this->id . '_' . $key])) {
586 $ret = $_POST[$this->plugin_id . $this->id . '_' . $key];
587 if (strlen($ret) == 16 && ctype_xdigit($ret)) $valid = true;
588 }
589 if (!$valid) $this->errors[$key] = __('Klucz do CRC powinien mieć 16 znaków.', 'przelewy24');
590 return $ret;
591 }
592
593 /**
594 * @param string $key
595 * @param null $empty_value
596 * @return string
597 */
598 public function get_option($key, $empty_value = null)
599 {
600 if (isset($this->sanitized_fields[$key])) {
601 return $this->sanitized_fields[$key];
602 }
603 return parent::get_option($key, $empty_value);
604 }
605
606 /**
607 * Display errors.
608 */
609 public function display_errors() {
610 foreach ( $this->errors as $v ) {
611 WC_Admin_Settings::add_error(
612 __( 'Błąd', 'przelewy24' ) . ': ' . filter_var( $v, FILTER_SANITIZE_STRING )
613 );
614 }
615 }
616
617 /**
618 * @param string $error
619 */
620 public function add_error($error)
621 {
622 if (!in_array($error, $this->errors)) {
623 parent::add_error($error);
624 }
625 }
626
627 /**
628 * Update options from admin panel.
629 *
630 * The parent method is overwritten.
631 */
632 public function process_admin_options()
633 {
634 $this->init_settings();
635 $post_data = $this->get_post_data();
636 foreach ( $this->get_form_fields() as $key => $field ) {
637 if ( 'title' !== $this->get_field_type( $field ) ) {
638 try {
639 $this->settings[ $key ] = $this->get_field_value( $key, $field, $post_data );
640 } catch ( Exception $e ) {
641 $this->add_error( $e->getMessage() );
642 }
643 }
644 }
645
646 $options = apply_filters( 'woocommerce_settings_api_sanitized_fields_' . $this->id, $this->settings );
647 $common_options = array_intersect_key( $options, array_flip( $this->common_settings_keys ) );
648 $currency_options = array_diff_key( $options, array_flip( $this->common_settings_keys ) );
649 update_option( P24_Request_Support::OPTION_KEY_COMMON, $common_options, 'yes' );
650 update_option( $this->get_option_key(), $currency_options, 'yes' );
651
652 $this->validate_fields( true );
653 if (!empty($this->errors)) {
654 $this->display_errors();
655 }
656 }
657
658 /**
659 * @param bool $processing_admin_options
660 * @throws Exception
661 * @return bool|void
662 */
663 public function validate_fields( $processing_admin_options = false )
664 {
665 if ( $processing_admin_options ) {
666 $this->sanitized_fields['p24_testmod'] = $_POST[ $this->plugin_id . $this->id . '_p24_testmod' ] == 'secure' ? 'secure' : 'sandbox';
667 $this->sanitized_fields['p24_api'] = $_POST[ $this->plugin_id . $this->id . '_p24_api' ];
668 }
669
670 $this->sanitized_fields['merchant_id'] = $this->validate_id('merchant_id', __('Błędny ID Sprzedawcy.', 'przelewy24'));
671 $this->sanitized_fields['shop_id'] = $this->validate_id('shop_id', __('Błędny ID Sklepu.', 'przelewy24'));
672 $this->sanitized_fields['CRC_key'] = $this->validate_crc('CRC_key');
673 $this->sanitized_fields['p24_paymethods'] = $this->validate_payment_methods_status('p24_paymethods');
674
675 $config_accessor = $this->get_settings_from_sanitized_formatted();
676 $P24 = new Przelewy24Class($config_accessor);
677 $ret = $P24->testConnection();
678 if ($ret['error'] != 0)
679 $this->errors['p24_testmod'] = __('Błędny ID Sklepu, Sprzedawcy lub Klucz do CRC dla tego trybu pracy wtyczki.', 'przelewy24');
680
681 if (!empty($this->sanitized_fields['p24_api'])) {
682 $ret = $P24->apiTestAccess();
683 if (!$ret)
684 $this->errors['p24_testmod'] = __('Błędny klucz API dla tego ID Sklepu, Sprzedawcy lub trybu pracy wtyczki.','przelewy24');
685 }
686
687 $_SESSION['P24'] = $this->sanitized_fields;
688 }
689
690 public function admin_options()
691 {
692 echo '<h3>' . __('Bramka płatności Przelewy24','przelewy24') . '</h3>';
693 echo '<table class="form-table">';
694 // Generate the HTML For the settings form.
695 $this->generate_settings_html();
696 echo '</table>';
697
698 $config_holder = $this->map_array_to_config_holder( $this->settings );
699 $config_holder->p24_api = $this->p24_api;
700 $config_accessor = new P24_Config_Accessor($this->get_active_currency(), $config_holder);
701 $P24 = new Przelewy24Class($config_accessor);
702
703 if (!$P24->apiTestAccess()) {
704 echo '<input type="hidden" id="p24_no_api_key_provided">';
705 }
706 }
707
708 /**
709 * Receipt Page
710 **/
711 function receipt_page($order)
712 {
713 global $woocommerce;
714
715 $config = $this->settings;
716
717 $orderObj = new WC_Order($order);
718
719 if (!empty($_POST['p24_cc']) && !empty($_POST['p24_session_id'])) {
720 $result = $this->chargeCard($order, $_POST['p24_cc']);
721
722 if ($result) {
723
724 $orderObj->add_order_note(__('IPN payment completed', 'woocommerce'));
725 $orderObj->payment_complete();
726 $woocommerce->cart->empty_cart();
727
728 if ($this->p24_orderstate_after)
729 $orderObj->update_status($this->p24_orderstate_after);
730
731 wp_redirect($this->get_return_url($orderObj));
732 } else {
733 //Sorry your transaction did not go through successfully, please try again.
734 $this->addNotice(
735 $woocommerce,
736 __('Błąd płatności: ', 'przelewy24') . __('Przepraszamy, ale twoja transakcja nie została przeprowadzona pomyślnie, prosimy spróbować ponownie.', 'przelewy24'),
737 'error'
738 );
739 wp_redirect($orderObj->get_cancel_order_url_raw());
740 error_log(__METHOD__ . ' :(');
741 }
742 }
743
744 if (!empty($this->p24_api) && $config['p24_paymethods'] == 'yes') {
745
746 $paymethod_all = $this->get_all_payment_methods();
747
748 // usunięcie rat gdy koszyk poniżej kwoty
749 if (is_array($paymethod_all) && get_woocommerce_currency() == 'PLN' && $this->get_order_total() < Przelewy24Class::getMinRatyAmount()) {
750 $raty = Przelewy24Class::getChannelsRaty();
751 foreach ($paymethod_all as $key => $item) {
752 if (in_array($key, $raty)) {
753 unset($paymethod_all[$key]);
754 }
755 }
756 }
757
758 if (isset($_POST['act']) && $_POST['act'] == 'cardrm' && isset($_POST['cardrm']) && (int)$_POST['cardrm'] > 0) {
759 self::del_card(get_current_user_id(), (int)$_POST['cardrm']);
760 }
761
762 if (!empty($_POST['p24_cc']) && !empty($_POST['p24_session_id'])) {
763 $result = $this->chargeCard($order, $_POST['p24_cc']);
764
765 if ($result) {
766 $orderObj->add_order_note(__('IPN payment completed', 'woocommerce'));
767 $orderObj->payment_complete();
768 $woocommerce->cart->empty_cart();
769
770 if ($this->p24_orderstate_after)
771 $orderObj->update_status($this->p24_orderstate_after);
772
773 wp_redirect($this->get_return_url($orderObj));
774 } else {
775 //Sorry your transaction did not go through successfully, please try again.
776 $this->addNotice(
777 $woocommerce,
778 __('Błąd płatności: ', 'przelewy24') . __('Przepraszamy, ale twoja transakcja nie została przeprowadzona pomyślnie, prosimy spróbować ponownie.', 'przelewy24'),
779 'error'
780 );
781
782 wp_redirect($orderObj->get_cancel_order_url_raw());
783 error_log(__METHOD__ . ' :(');
784 }
785 }
786
787 $paymethod_first = explode(',', $config['p24_paymethods_first']);
788 $paymethod_second = explode(',', $config['p24_paymethods_second']);
789 $ccards = $this->get_all_custom_data('user_cards', get_current_user_id());
790 $last_method = (int)$this->get_custom_data('user', get_current_user_id(), 'lastmethod');
791
792 $makeUnfold = false;
793
794 $ignore_array = array();
795 echo '<ul>';
796 if ($config['p24_graphics'] == 'yes') {
797 // lista graficzna
798
799 // ostatnia metoda płatności
800 if ($last_method > 0 && !in_array($last_method, Przelewy24Class::getChannelsCard())) {
801 if (isset($paymethod_all[$last_method])) {
802 $makeUnfold = true;
803 $ignore_array[] = $last_method;
804 echo Przelewy24Helpers::getBankHtml($last_method, __('Ostatnio używane', 'przelewy24'));
805 }
806 }
807
808 // recuring
809 if (is_array($ccards) && sizeof($ccards)) {
810 foreach ($ccards as $card) {
811 $makeUnfold = true;
812 echo Przelewy24Helpers::getBankHtml(md5($card->custom_value['type']), $card->custom_value['type'], substr($card->custom_value['mask'], -9), $card->id, 'recurring');
813 }
814 }
815
816 // wyróżnione metody
817 foreach ($paymethod_first as $bank_id) {
818 if (isset($paymethod_all[$bank_id]) && !in_array($bank_id, $ignore_array)) {
819 $makeUnfold = true;
820 $ignore_array[] = $bank_id;
821 $onclick = '';
822 if (in_array($bank_id, Przelewy24Class::getChannelsCard()) && $config['p24_payinshop'] == 'yes') {
823 $onclick = 'showPayJsPopup()';
824 }
825 echo Przelewy24Helpers::getBankHtml($bank_id, $paymethod_all[$bank_id], '', '', '', $onclick);
826 }
827 }
828
829 echo "<div style='clear:both'></div>";
830 echo '<div class="morePayMethods" style="' . ($makeUnfold ? 'display: none' : '') . '">';
831 // pozostałe metody płatności
832 foreach ($paymethod_second as $bank_id) {
833 if (isset($paymethod_all[$bank_id]) && !in_array($bank_id, $ignore_array)) {
834 $ignore_array[] = $bank_id;
835 $onclick = '';
836 if (in_array($bank_id, Przelewy24Class::getChannelsCard()) && $config['p24_payinshop'] == 'yes') {
837 $onclick = 'showPayJsPopup()';
838 }
839 echo Przelewy24Helpers::getBankHtml($bank_id, $paymethod_all[$bank_id], '', '', '', $onclick);
840 }
841 }
842
843 if ( ! isset( $paymethod_all ) || ! is_array( $paymethod_all ) ) {
844 $paymethod_all = array();
845 }
846 // metody nieuwględnione w konfiguracji (np nowe)
847 foreach ($paymethod_all as $bank_id => $bank_name) {
848 if (!in_array($bank_id, $paymethod_first) && !in_array($bank_id, $ignore_array)) {
849 $ignore_array[] = $bank_id;
850 $onclick = '';
851 if (in_array($bank_id, Przelewy24Class::getChannelsCard()) && $config['p24_payinshop'] == 'yes') {
852 $onclick = 'showPayJsPopup()';
853 }
854 echo Przelewy24Helpers::getBankHtml($bank_id, $paymethod_all[$bank_id], '', '', '', $onclick);
855 }
856 }
857 echo "<div style='clear:both'></div>";
858 echo '</div>';
859 } else {
860 // lista tekstowa
861 $checkedCounter = 0;
862
863 // wyróżnione metody
864 foreach ($paymethod_first as $bank_id) {
865 if (isset($paymethod_all[$bank_id]) && !in_array($bank_id, $ignore_array)) {
866 $makeUnfold = true;
867 $ignore_array[] = $bank_id;
868 $onclick = '';
869 if (in_array($bank_id, Przelewy24Class::getChannelsCard()) && $config['p24_payinshop'] == 'yes') {
870 $onclick = 'showPayJsPopup()';
871 }
872 echo Przelewy24Helpers::getBankTxt($checkedCounter, $bank_id, $paymethod_all[$bank_id], '', '', '', $onclick);
873 }
874 }
875 echo "<div style='clear:both'></div>";
876 echo '<div class="morePayMethods" style="' . ($makeUnfold ? 'display: none' : '') . '">';
877 // pozostałe metody płatności
878 foreach ($paymethod_second as $bank_id) {
879 if (isset($paymethod_all[$bank_id]) && !in_array($bank_id, $ignore_array)) {
880 $ignore_array[] = $bank_id;
881 $onclick = '';
882 if (in_array($bank_id, Przelewy24Class::getChannelsCard()) && $config['p24_payinshop'] == 'yes') {
883 $onclick = 'showPayJsPopup()';
884 }
885 echo Przelewy24Helpers::getBankTxt($checkedCounter, $bank_id, $paymethod_all[$bank_id], '', '', '', $onclick);
886 }
887 }
888
889 // metody nieuwględnione w konfiguracji (np nowe)
890 foreach ($paymethod_all as $bank_id => $bank_name) {
891 if (!in_array($bank_id, $paymethod_first) && !in_array($bank_id, $ignore_array)) {
892 $ignore_array[] = $bank_id;
893 $onclick = '';
894 if (in_array($bank_id, Przelewy24Class::getChannelsCard()) && $config['p24_payinshop'] == 'yes') {
895 $onclick = 'showPayJsPopup()';
896 }
897 echo Przelewy24Helpers::getBankTxt($checkedCounter, $bank_id, $paymethod_all[$bank_id], '', '', '', $onclick);
898 }
899 }
900 echo "<div style='clear:both'></div>";
901 echo '</div>';
902 }
903
904 if ($makeUnfold) {
905 echo '<div class="moreStuff" onclick="jQuery(this).fadeOut(100);jQuery(\'.morePayMethods\').slideDown()" title="' . __('Pokaż więcej metod płatności.', 'przelewy24') . '"></div>';
906 $payments_msg4js = '↓ ' . __('więcej metod płatności', 'przelewy24') . ' ↓';
907 }
908 echo '</ul>';
909
910 if ($config['p24_payinshop'] == 'yes') {
911 $p24_ajax_url = add_query_arg(array('wc-api' => 'WC_Gateway_Przelewy24'), home_url('/'));
912 $translate = array(
913 'name' => __('Imię i nazwisko','przelewy24'),
914 'nr' => __('Numer karty','przelewy24'),
915 'cvv' => __('CVV','przelewy24'),
916 'dt' => __('Data ważności','przelewy24'),
917 'pay' => __('Zapłać','przelewy24'),
918 '3ds' => __('Kliknij tutaj aby kontynuować zakupy','przelewy24'),
919 'registerCardLabel' => __('Zapisz kartę','przelewy24'),
920 'description' => __('Zarejestruj i zapłać','przelewy24'),
921 );
922 $myAccountLink = get_permalink(get_option('woocommerce_myaccount_page_id'));
923 echo <<<HTML
924 <span id="p24-link-to-my-account" data-link="{$myAccountLink}"></span>
925 <div id="P24FormAreaHolder" onclick="hidePayJsPopup();" style="display: none"><div onclick="arguments[0].stopPropagation();" id="P24FormArea" class="popup"></div></div>
926 <input type="hidden" id="p24_ajax_url" value="{$p24_ajax_url}">
927 <input type="hidden" id="p24_dictionary" value='{"registerCardLabel":"{$translate['registerCardLabel']}","description":"{$translate['description']}", "cardHolderLabel":"{$translate['name']}", "cardNumberLabel":"{$translate['nr']}", "cvvLabel":"{$translate['cvv']}", "expDateLabel":"{$translate['dt']}", "payButtonCaption":"{$translate['pay']}", "threeDSAuthMessage":"{$translate['3ds']}"}'>
928 <input type="hidden" id="p24_woo_order_id" value='{$order}'>
929 <form method="post" id="cardrm">
930 <input type="hidden" name="act" value="cardrm">
931 <input type="hidden" name="cardrm">
932 </form>
933HTML;
934
935 }
936 echo $this->generator->generate_przelewy24_form($order, false, $config['p24_oneclick'] == 'yes' && is_array($ccards) && sizeof($ccards));
937
938 } else {
939 echo $this->generator->generate_przelewy24_form($order, true);
940 }
941 }
942
943 /**
944 * Transfer money to merchants
945 **/
946 function transfer_money_to_merchant($amount, $merchant_id, $session_id, $order_id )
947 {
948 $merchant_id_api = WC()->payment_gateways->payment_gateways()['przelewy24']->settings['merchant_id'];
949 $P24_api = WC()->payment_gateways->payment_gateways()['przelewy24']->settings['p24_api'];
950 $process = curl_init('url');
951 // Content-Type header required
952 curl_setopt(
953 $process,
954 CURLOPT_HTTPHEADER,
955 array('Content-Type: application/json')
956 );
957 // Constructing parameters
958 $data = [];
959 $data['batchId'] = $merchant_id_api;
960 $data['details'] = array (
961 'details' => array (
962 0 =>
963 array (
964 'orderId' => $order_id,
965 'sessionId' => $session_id,
966 'sellerId' => $merchant_id,
967 'amount' => $amount,
968 ),
969 ),
970 );
971
972 // Passing parameters
973 curl_setopt($process, CURLOPT_POSTFIELDS, json_encode($data));
974 // Basic Auth authentication
975 curl_setopt($process, CURLOPT_USERPWD, $merchant_id_api . ":" . $P24_api);
976 curl_setopt($process, CURLOPT_RETURNTRANSFER, true);
977 $return = json_decode(curl_exec($process));
978 echo json_encode($return, JSON_PRETTY_PRINT) . "\n";
979 curl_close($process);
980 }
981
982 /**
983 * Process the payment and return the result
984 **/
985 function process_payment($order_id)
986 {
987 $order = new WC_Order($order_id);
988 /* This is the default place to reduce stock levels. */
989 /* It is safe to call function below multiple times. */
990 wc_maybe_reduce_stock_levels($order);
991 $order->update_meta_data(P24_Core::CHOSEN_TIMESTAMP_META_KEY, time());
992 $order->save_meta_data();
993 //---------
994
995 return array('result' => 'success', 'redirect' => $order->get_checkout_payment_url($order));
996 }
997
998 /**
999 * @param string $session_id Session id taken from P24 API.
1000 *
1001 * @throws SoapFault Soap fault exception.
1002 *
1003 * @return mixed
1004 */
1005 private function get_transaction_data_from_p24( $session_id ) {
1006 $soap = $this->getSoapClient();
1007
1008 try {
1009 return $soap->GetTransactionBySessionId(
1010 $this->merchant_id,
1011 $this->p24_api,
1012 $session_id
1013 );
1014 } catch ( Exception $e ) {
1015 return false;
1016 }
1017 }
1018
1019 /**
1020 * @param int $order_id WC Order Id.
1021 * @param float|null $amount Order amount.
1022 * @param string $reason Reason of refund.
1023 *
1024 * @throws SoapFault
1025 * @return bool|WP_Error
1026 */
1027 public function process_refund( $order_id, $amount = null, $reason = '' ) {
1028 $order = new WC_Order( $order_id );
1029
1030 if ( ! $this->can_refund_order( $order ) ) {
1031 return new WP_Error( 'error', __( 'Refund failed.', 'woocommerce' ) );
1032 }
1033
1034 $session_id = $order->get_meta(
1035 P24_Core::ORDER_SESSION_ID_KEY,
1036 true
1037 );
1038
1039 $transaction_data = $this->get_transaction_data_from_p24( $session_id );
1040
1041 if ( empty( $transaction_data->result->status ) || 2 !== $transaction_data->result->status || 0 !== $transaction_data->error->errorCode ) {
1042 return new WP_Error( 'error', __( 'Refund failed.', 'woocommerce' ) );
1043 }
1044
1045 $refunds = array(
1046 array(
1047 'sessionId' => $session_id,
1048 'orderId' => $transaction_data->result->orderId,
1049 'amount' => P24_Core::convert_stringified_float_to_cents( $amount ),
1050 ),
1051 );
1052
1053 $soap = $this->getSoapClient();
1054
1055 try {
1056 $p24_response = $soap->RefundTransaction(
1057 $this->merchant_id,
1058 $this->p24_api,
1059 time(),
1060 $refunds
1061 );
1062
1063 if ( ! empty( $p24_response->error->errorCode ) ) {
1064 return new WP_Error( 'error', __( 'Return failed.', 'woocommerce' ) );
1065 }
1066 } catch ( Exception $e ) {
1067 return new WP_Error( 'error', __( 'Refund failed.', 'woocommerce' ) );
1068 }
1069
1070 return true;
1071 }
1072
1073 function get_suborder_ids_by( $parent_order_id ) {
1074 global $wpdb;
1075
1076 $sub_orders = $wpdb->get_results(
1077 $wpdb->prepare(
1078 "SELECT ID FROM {$wpdb->posts}
1079 WHERE post_type = 'shop_order'
1080 AND post_parent = %d", $parent_order_id
1081 )
1082 );
1083
1084 if ( ! $sub_orders ) {
1085 return null;
1086 }
1087
1088 return $sub_orders;
1089}
1090
1091 /**
1092 * /*Check przelewy24 response
1093 **/
1094
1095
1096
1097 function przelewy24_response()
1098 {
1099 global $wpdb;
1100 global $woocommerce;
1101
1102 if (isset($_POST['p24_session_id']) && isset($_POST['action']) && $_POST['action'] === 'trnRegister' && isset($_POST['order_id'])) {
1103 $config_accessor = $this->get_settings_from_internal_formatted(null, true);
1104 $P24C = new Przelewy24Class($config_accessor);
1105 $post_data = $this->generator->generate_fields_array($_POST['order_id'], $_POST['p24_session_id']);
1106 foreach ($post_data as $k => $v) {
1107 $P24C->addValue($k, $v);
1108 }
1109 $token = $P24C->trnRegister();
1110 if (is_array($token)) {
1111 $token = $token['token'];
1112 exit(json_encode(array(
1113 'p24jsURL' => $P24C->getHost() . 'inchtml/card/register_card_and_pay/ajax.js?token=' . $token,
1114 'p24cssURL' => $P24C->getHost() . 'inchtml/card/register_card_and_pay/ajax.css',
1115 'p24_sign' => $post_data['p24_sign'],
1116 'sessionId' => $post_data['p24_session_id'],
1117 'client_id' => get_current_user_id()
1118 )));
1119 }
1120
1121 exit();
1122 }
1123 if (
1124 isset($_POST['action']) &&
1125 isset($_POST['orderId']) &&
1126 isset($_POST['oneclickOrderId']) &&
1127 isset($_POST['sign']) &&
1128 (int)$_POST['orderId'] > 0 &&
1129 (int)$_POST['oneclickOrderId'] > 0 &&
1130 $_POST['action'] == 'rememberOrderId') {
1131
1132 if (strlen((int)$_POST['oneclickOrderId']) != strlen($_POST['oneclickOrderId']) ||
1133 strlen((int)$_POST['orderId']) != strlen($_POST['orderId'])) {
1134 exit('int error');
1135 }
1136
1137 if (!$this->checkSign($_POST['sign'], $_POST['sessionId']) ) {
1138 exit('error');
1139 }
1140
1141 if ($wpdb->query("SELECT * FROM `{$wpdb->prefix}woocommerce_p24_data` where `custom_key` = '".md5($_POST['oneclickOrderId'])."'")) {
1142 exit('oneclickOrderId must be unique');
1143 }
1144
1145 Przelewy24Helpers::setCustomData('oneclick', 1, md5($_POST['oneclickOrderId']),json_encode(array(
1146 'orderId' => $_POST['orderId'],
1147 'oneclickOrderId' => $_POST['oneclickOrderId'],
1148 'sessionId' => $_POST['sessionId']
1149
1150 ))
1151 );
1152
1153
1154 //START
1155
1156//END
1157 exit('ok');
1158 }
1159
1160
1161 if (isset($_POST['p24_session_id'])) {
1162
1163 $p24_session_id = $_POST['p24_session_id'];
1164 $reg_session = "/^[0-9a-zA-Z_\.]+$/D";
1165 if (!preg_match($reg_session, $p24_session_id)) exit;
1166 $session_id = explode('_', $p24_session_id);
1167 $order_id = $session_id[0];
1168 $order = new WC_Order($order_id);
1169 $currency = $order->get_currency();
1170 $validation = array('p24_amount' => number_format($order->get_total() * 100, 0, "", ""));
1171 $config_accessor = $this->get_settings_from_internal_formatted($currency, true);
1172
1173 $p24 = new Przelewy24Class( $config_accessor );
1174 $result = $p24->trnVerifyEx( $validation );
1175
1176 if ( null === $result ) {
1177 exit( "\n" . 'MALFORMED POST' );
1178 } elseif ( $result ) {
1179 $order->add_order_note(__('IPN payment completed!', 'woocommerce'));
1180 $order->payment_complete();
1181 // zapis ostatniej metody płatności
1182 if ((int)$_POST['p24_method']) {
1183 Przelewy24Helpers::setCustomData('user', $order->get_user_id(), 'lastmethod', (int)$_POST['p24_method']);
1184 Przelewy24Helpers::setCustomData('user', $order->get_user_id(), 'accept', 1);
1185
1186 // jeśli karta i ma recuring to zapisz
1187 if (in_array($_POST['p24_method'], Przelewy24Class::getChannelsCard()) && $this->p24_oneclick == 'yes') {
1188 $this->saveCard((int)$order->get_user_id(), (int)$_POST['p24_order_id']);
1189 }
1190
1191
1192 $merchant_id = WC()->payment_gateways->payment_gateways()['przelewy24']->settings['merchant_id'];
1193 $P24_api = WC()->payment_gateways->payment_gateways()['przelewy24']->settings['p24_api'];
1194
1195 $basic = $merchant_id.':'.$P24_api;
1196
1197 $curl = curl_init();
1198curl_setopt_array($curl, array(
1199 CURLOPT_URL => "https://secure.przelewy24.pl/api/v1/transaction/by/sessionId/".$_POST['p24_session_id'],
1200 CURLOPT_RETURNTRANSFER => true,
1201 CURLOPT_ENCODING => "",
1202 CURLOPT_MAXREDIRS => 10,
1203 CURLOPT_TIMEOUT => 30,
1204 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
1205 CURLOPT_CUSTOMREQUEST => "GET",
1206 CURLOPT_HTTPHEADER => array(
1207 "authorization: ".'Basic '.base64_encode($basic),
1208 "cache-control: no-cache",
1209 "content-type: application/x-www-form-urlencoded;",
1210 "postman-token: 429e4e11-bf3b-bdb8-7f68-f45f97d094c7"
1211 ),
1212));
1213
1214$response = curl_exec($curl);
1215$err = curl_error($curl);
1216
1217curl_close($curl);
1218 $response = json_decode( $response );
1219
1220 $batchId = rand( mt_rand( ), mt_rand() );
1221
1222 $orderId = intval( $response->data->orderId );
1223
1224 //wysyłamy
1225 $order_items = $order->get_items();
1226 $details = [ ];
1227 $sub_orders=[];
1228 if ( $order->get_meta( 'has_sub_order') ) {
1229 global $wpdb;
1230
1231 $sub_orders = $wpdb->get_results(
1232 $wpdb->prepare(
1233 "SELECT ID FROM {$wpdb->posts}
1234 WHERE post_type = 'shop_order'
1235 AND post_parent = %d", $order->get_id()
1236 )
1237 );
1238
1239
1240 }
1241 else
1242 array_push($sub_orders,$order);
1243
1244 foreach( $sub_orders as $index=>$order ) {
1245 $user_id = wc_get_order_item_meta($order->get_id(),'_dokan_vendor_id');
1246 if( isset( get_user_meta( $user_id, 'p24_seller_merchant_id' )[ 0 ])) {
1247 $merchant_id_ = intval( get_user_meta( $user_id, 'p24_seller_merchant_id' )[0] );
1248 $details[$index] = [];
1249
1250 $details[$index]["orderId"] = $orderId;
1251 $details[$index]["sessionId"] = $_POST['p24_session_id'];
1252 $details[$index]['sellerId'] = $merchant_id_;
1253 $details[$index]['amount'] = wc_get_order_item_meta($order->get_id(),'_order_total');
1254 }
1255 }
1256
1257 // foreach( $order_items as $index=>$product ) {
1258 // $user_id = get_post($product->get_product_id())->post_author;
1259 // if( isset( get_user_meta( $user_id, 'p24_seller_merchant_id' )[ 0 ])) {
1260 // $merchant_id_ = intval( get_user_meta( $user_id, 'p24_seller_merchant_id' )[0] );
1261 // $details[$index] = [];
1262
1263 // $details[$index]["orderId"] = $orderId;
1264 // $details[$index]["sessionId"] = $_POST['p24_session_id'];
1265 // $details[$index]['sellerId'] = $merchant_id_;
1266 // $details[$index]['amount'] = $product->get_total()*100;
1267 // }
1268 // }
1269 //dzielenie
1270 $curl = curl_init();
1271
1272 $data = [ "batchId" => $batchId, "details" => $details ];
1273
1274curl_setopt_array($curl, array(
1275 CURLOPT_URL => "https://secure.przelewy24.pl/api/v1/multiStore/dispatchTransaction",
1276 CURLOPT_RETURNTRANSFER => true,
1277 CURLOPT_ENCODING => "",
1278 CURLOPT_MAXREDIRS => 10,
1279 CURLOPT_TIMEOUT => 30,
1280 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
1281 CURLOPT_CUSTOMREQUEST => "POST",
1282 CURLOPT_POSTFIELDS => http_build_query( $data ),
1283 CURLOPT_HTTPHEADER => array(
1284 "authorization: ".'Basic '.base64_encode($basic),
1285 "cache-control: no-cache",
1286 "content-type: application/x-www-form-urlencoded;",
1287 "postman-token: 429e4e11-bf3b-bdb8-7f68-f45f97d094c7"
1288 ),
1289));
1290
1291$response = curl_exec($curl);
1292$err = curl_error($curl);
1293
1294curl_close($curl);
1295
1296 $response = json_decode( $response );
1297
1298 //end dzielenie
1299
1300}
1301 // session id save
1302 $order->update_meta_data( P24_Core::ORDER_SESSION_ID_KEY, $p24_session_id );
1303 $order->save_meta_data();
1304 }
1305 if (!isset($_GET['order_id'])) exit;
1306 }
1307
1308 if (isset($_GET['order_id'])) {
1309 $order = new WC_Order($_GET['order_id']);
1310
1311 if ( 'failed' === $order->get_status() ) {
1312 $this->addNotice(
1313 // Sorry your transaction did not go through successfully, please try again.
1314 $woocommerce,
1315 __('Błąd płatności: ', 'przelewy24') . __('Przepraszamy, ale twoja transakcja nie została przeprowadzona pomyślnie, prosimy spróbować ponownie.', 'przelewy24'),
1316 'error'
1317 );
1318
1319 wp_redirect($order->get_cancel_order_url_raw());
1320 } else if ( 'completed' === $order->get_status() || 'processing' === $order->get_status() ) {
1321 $woocommerce->cart->empty_cart();
1322 if ( empty( $_GET['return'] ) || ! ( 'true' === $_GET['return'] && 'true' === $_GET['success'] && is_numeric( $_GET['orderId'] ) && is_numeric( $_GET['order_id'] ) ) ) {
1323 wp_redirect($this->get_return_url($order));
1324 }
1325 } else {
1326 // We did not received information about payment. If you are sure you completed your payment please contact our customer service
1327 if ( empty( $_GET['return'] ) || ! ( 'true' === $_GET['return'] && 'true' === $_GET['success'] && is_numeric( $_GET['orderId'] ) && is_numeric( $_GET['order_id'] ) ) ) {
1328 $this->addNotice(
1329 $woocommerce,
1330 __('Płatność realizowana przez Przelewy24 nie została jeszcze potwierdzona. Jeśli potwierdzenie nadejdzie w czasie późniejszym, płatność zostanie automatycznie przekazana do sklepu', 'przelewy24'),
1331 'notice'
1332 );
1333
1334 wp_redirect($this->get_return_url($order));
1335 }
1336 }
1337 }
1338 }
1339
1340 /**
1341 * @param $woocommerce
1342 * @param $message
1343 * @param $type
1344 */
1345 function addNotice($woocommerce, $message, $type)
1346 {
1347 if ($type == 'error' && method_exists($woocommerce, 'add_error')) {
1348 $woocommerce->add_error($message);
1349 } else if (in_array($type, array('success', 'notice')) && method_exists($woocommerce, 'add_message')) {
1350 $woocommerce->add_message($message);
1351 } else {
1352 wc_add_notice($message, $type);
1353 }
1354 }
1355
1356 /**
1357 * @return array
1358 */
1359 function get_options()
1360 {
1361 $option_list = array();
1362 $option_list['secure'] = __('normalny', 'przelewy24');
1363 $option_list['sandbox'] = __('testowy', 'przelewy24');
1364
1365 return $option_list;
1366 }
1367
1368
1369 /**
1370 * Output for the order received page.
1371 */
1372
1373 function thankyou_page()
1374 {
1375 if ($this->instructions) {
1376 echo wpautop(wptexturize($this->instructions));
1377 }
1378 }
1379
1380 /**
1381 * Add content to the WC emails.
1382 *
1383 * @access public
1384 * @param WC_Order $order
1385 * @param bool $sent_to_admin
1386 * @param bool $plain_text
1387 */
1388
1389 function email_instructions($order, $sent_to_admin, $plain_text = false)
1390 {
1391 if ($this->instructions && !$sent_to_admin && 'przelewy24' === $order->get_payment_method()) {
1392 echo wpautop(wptexturize($this->instructions)) . PHP_EOL;
1393 }
1394 }
1395
1396 public function getCssUrl()
1397 {
1398 return PRZELEWY24_URI . 'assets/css/paymethods.css';
1399 }
1400
1401 public function getJsUrl()
1402 {
1403 return PRZELEWY24_URI . 'assets/js/payment.js';
1404 }
1405 private static function get_custom_data($data_type, $data_id, $key)
1406 {
1407 global $wpdb;
1408 $table_name = $wpdb->prefix . 'woocommerce_p24_data';
1409
1410 $query = $wpdb->prepare("SELECT * FROM {$table_name} WHERE data_type = %s AND data_id = %d AND custom_key = %s",
1411 [
1412 $data_type,
1413 $data_id,
1414 $key
1415 ]
1416 );
1417
1418 $fields = $wpdb->get_results(
1419 $query,
1420 OBJECT
1421 );
1422
1423 foreach ($fields as $field) {
1424 $value = json_decode($field->custom_value, true);
1425 if ($value != null) return $value;
1426 else return $field->custom_value;
1427 }
1428 return null;
1429 }
1430
1431 private static function get_all_custom_data($data_type, $data_id)
1432 {
1433 global $wpdb;
1434 $table_name = $wpdb->prefix . 'woocommerce_p24_data';
1435
1436 $query = $wpdb->prepare("SELECT * FROM {$table_name} WHERE data_type = %s AND data_id = %d",
1437 [
1438 $data_type,
1439 $data_id,
1440 ]
1441 );
1442
1443 $fields = $wpdb->get_results(
1444 $query,
1445 OBJECT
1446 );
1447 foreach ($fields as &$field) {
1448 $value = json_decode($field->custom_value, true);
1449 if ($value != null) $field->custom_value = $value;
1450 }
1451 return $fields;
1452 }
1453
1454 public static function get_all_cards($user_id)
1455 {
1456 $user_id = (int)$user_id;
1457 return self::get_all_custom_data('user_cards', $user_id);
1458 }
1459
1460 public static function del_card($user_id, $card_id)
1461 {
1462 global $wpdb;
1463 $table_name = $wpdb->prefix . 'woocommerce_p24_data';
1464 $card = self::getCard((int)$user_id, (int)$card_id);
1465 if ($card) {
1466 $key = md5($card->custom_value['mask'] . '|' . $card->custom_value['type'] . '|' . $card->custom_value['exp']);
1467
1468 $wpdb->delete($table_name, [
1469 'data_type' => 'user_cards',
1470 'data_id' => $user_id,
1471 'custom_key' => $key
1472 ], ['%s', '%d', '%s' ]);
1473
1474 return true;
1475 }
1476 return false;
1477
1478 }
1479
1480 public static function get_cc_forget($user_id)
1481 {
1482 if ($user_id) {
1483 return (int)self::get_custom_data('user', $user_id, 'cc_forget');
1484 } else {
1485 /* By default forget. */
1486 return 1;
1487 }
1488 }
1489
1490 public static function set_cc_forget($user_id, $value)
1491 {
1492 Przelewy24Helpers::setCustomData('user', $user_id, 'cc_forget', (int)$value == 1);
1493 }
1494
1495 /**
1496 * @throws SoapFault Soap fault exception.
1497 *
1498 * @return SoapClient
1499 */
1500 protected function getSoapClient() {
1501 $host = Przelewy24Class::getHostStatic(
1502 $this->p24_testmod === 'sandbox'
1503 );
1504
1505 $address = sprintf(
1506 '%sexternal/%s.wsdl',
1507 $host,
1508 $this->merchant_id
1509 );
1510
1511 return new SoapClient(
1512 $address,
1513 array(
1514 'trace' => true,
1515 'exceptions' => true,
1516 'cache_wsdl' => WSDL_CACHE_NONE,
1517 )
1518 );
1519 }
1520
1521 private static function getCard($user_id, $card_id)
1522 {
1523 $all = self::get_all_custom_data('user_cards', $user_id);
1524 foreach ($all as $item) {
1525 if ($item->id == $card_id) return $item;
1526 }
1527 return false;
1528 }
1529
1530 private function saveCard($user_id, $order_id)
1531 {
1532 if ($user_id > 0) {
1533 $oneclickOrderId = $this->getOneclickOrderId($order_id);
1534
1535 if (self::get_cc_forget($user_id)) return; // nie zapamiętuj karty - Customer sobie nie życzy
1536
1537 if ($this->p24_payinshop != 'yes' || $this->p24_oneclick != 'yes') return; // wyłączone w konfiguracji
1538
1539 try {
1540 $config_accessor = $this->get_settings_from_internal_formatted();
1541 $P24 = new Przelewy24Class($config_accessor);
1542 $s = new SoapClient($P24->getHost() . $P24->getWsdlCCService(), array('trace' => true, 'exceptions' => true));
1543
1544 $res = $s->GetTransactionReference($this->shop_id, $this->p24_api, $order_id);
1545
1546 $hasRecurency = $s->GetTransactionReference($this->merchant_id, $this->p24_api, $oneclickOrderId);
1547
1548 if ($res->error->errorCode === 0) {
1549
1550 $ref = $res->result->refId;
1551 $exp = substr($res->result->cardExp, 2, 2) . substr($res->result->cardExp, 0, 2);
1552 if (!empty($ref)) {
1553
1554 if ($oneclickOrderId > 0) {
1555 $hasRecurency = $s->GetTransactionReference($this->merchant_id, $this->p24_api, $oneclickOrderId);
1556 } else {
1557 $hasRecurency = $s->CheckCard($this->merchant_id, $this->p24_api, $ref);
1558 }
1559
1560 if ($hasRecurency->error->errorCode === 0 && $hasRecurency->result == true) {
1561 if (date('ym') <= $exp) {
1562 Przelewy24Helpers::setCustomData('user_cards', $user_id, md5($res->result->mask . '|' . $res->result->cardType . '|' . $exp), array(
1563 'ref' => $ref,
1564 'exp' => $exp,
1565 'mask' => $res->result->mask,
1566 'type' => $res->result->cardType,
1567 'time' => date('Y-m-d H:i.s'),
1568 ));
1569 } else {
1570 error_log(__METHOD__ . ' termin ważności ' . var_export($exp, true));
1571 }
1572 } else {
1573 error_log(__METHOD__ . ' nie ma rekurencji ' . var_export($hasRecurency, true));
1574 }
1575 }
1576 }
1577 } catch (Exception $e) {
1578 error_log(__METHOD__ . ' ' . $e->getMessage());
1579 }
1580 }
1581
1582 }
1583
1584 private function chargeCard($order_id, $card_id)
1585 {
1586 $card = $this->getCard(get_current_user_id(), (int)$card_id);
1587 $data = $this->generator->generate_fields_array((int)$order_id);
1588
1589 if ($data && $card) {
1590
1591 if (empty($card->custom_value['ref'])) return false;
1592
1593 $config_accessor = $this->get_settings_from_internal_formatted();
1594 $P24 = new Przelewy24Class($config_accessor);
1595
1596 try {
1597 $s = new SoapClient($P24->getHost() . $P24->getWsdlCCService(), array('trace' => true, 'exceptions' => true));
1598 $res = $s->ChargeCard(
1599 $data['p24_merchant_id'], $this->p24_api, $card->custom_value['ref'], $data['p24_amount'], $data['p24_currency'],
1600 $data['p24_email'], $data['p24_session_id'], $data['p24_client'], $data['p24_description']
1601 );
1602 return $res->error->errorCode === 0;
1603 } catch (Exception $e) {
1604 error_log(__METHOD__ . ' ' . $e->getMessage());
1605 }
1606 }
1607 return false;
1608 }
1609
1610 private function getOneclickOrderId($order_id) {
1611 global $wpdb;
1612 $query_result = $wpdb->get_var("SELECT json_extract(custom_value,'$.oneclickOrderId') FROM `{$wpdb->prefix}woocommerce_p24_data` where json_extract(custom_value,'$.orderId') = '".$order_id."' limit 1");
1613
1614 return (int)$query_result;
1615
1616 }
1617
1618 private function checkSign($sign, $sessionId)
1619 {
1620 list($orderId) = explode('_', $sessionId, 1);
1621
1622 $orderId = (int)$orderId;
1623
1624 $order = new WC_Order($orderId);
1625 $amount = (int)($order->get_total() * 100);
1626 $currency_code = $order->get_currency();
1627
1628 $merchantId = $this->merchant_id;
1629 $salt = $this->salt;
1630 $countedSign = md5($sessionId . '|' . $merchantId . '|' . $amount . '|' . $currency_code . '|' . $salt);
1631
1632 if ($sign === $countedSign) {
1633 return true;
1634 }
1635 return false;
1636 }
1637}
1638