-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathwp_robokassa.php
More file actions
1645 lines (1360 loc) · 46.3 KB
/
wp_robokassa.php
File metadata and controls
1645 lines (1360 loc) · 46.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Plugin Name: Robokassa WooCommerce
* Description: Данный плагин добавляет на Ваш сайт метод оплаты Робокасса для WooCommerce
* Plugin URI: /wp-admin/admin.php?page=main_settings_rb.php
* Author: Robokassa
* Author URI: https://robokassa.com
* Version: 1.8.5
*/
require_once('payment-widget.php');
require_once('StatusReporter.php');
use Robokassa\Payment\RoboDataBase;
use Robokassa\Payment\RobokassaPayAPI;
use Robokassa\Payment\RobokassaSms;
use Robokassa\Payment\Util;
use Robokassa\Payment\AgentManager;
use Robokassa\Payment\PaymentObjectManager;
use Robokassa\Payment\TaxManager;
use Automattic\WooCommerce\Utilities\OrderUtil;
use Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry;
define('ROBOKASSA_PAYMENT_DEBUG_STATUS', false);
spl_autoload_register(
function ($className) {
$file = __DIR__ . '/classes/' . str_replace('\\', '/', $className) . '.php';
if (file_exists($file))
require_once $file;
}
);
add_action('woocommerce_cart_calculate_fees', 'robokassa_chosen_payment_method');
add_action('wp_enqueue_scripts', 'robokassa_enqueue_frontend_assets');
if (!function_exists('robokassa_chosen_payment_method')) {
/**
* Добавляет наценку для выбранных методов Robokassa.
*
* @param WC_Cart $cart
* @return void
*/
function robokassa_chosen_payment_method(WC_Cart $cart)
{
if (
(double)get_option('robokassa_patyment_markup') > 0
&& in_array(
WC()->session->get('chosen_payment_method'),
array_map(
function ($class) {
$method = new $class;
return $method->id;
},
robokassa_payment_add_WC_WP_robokassa_class()
)
)
) {
$cart->add_fee(
'Наценка',
$cart->get_cart_contents_total() / 100 * (double)get_option('robokassa_patyment_markup'),
false
);
}
}
}
add_action('woocommerce_review_order_before_payment', 'refresh_payment_methods');
add_action('woocommerce_product_options_general_product_data', 'robokassa_payment_render_product_tax_field');
add_action('woocommerce_product_options_general_product_data', 'robokassa_payment_render_product_payment_object_field');
add_action('woocommerce_product_options_general_product_data', 'robokassa_payment_render_product_agent_fields');
add_action('woocommerce_admin_process_product_object', 'robokassa_payment_save_product_tax_field');
add_action('woocommerce_admin_process_product_object', 'robokassa_payment_save_product_payment_object_field');
add_action('woocommerce_admin_process_product_object', 'robokassa_payment_save_product_agent_fields');
function refresh_payment_methods()
{
// jQuery code
?>
<script type="text/javascript">
(function ($) {
$('form.checkout').on('change', 'input[name^="payment_method"]', function () {
$('body').trigger('update_checkout');
});
})(jQuery);
</script>
<?php
}
function robokassa_enqueue_frontend_assets()
{
if (!function_exists('is_checkout') || !is_checkout()) {
return;
}
$stylePath = plugin_dir_path(__FILE__) . 'assets/css/robokassa-redirect.css';
$scriptPath = plugin_dir_path(__FILE__) . 'assets/js/robokassa-redirect.js';
if (file_exists($stylePath)) {
wp_enqueue_style(
'robokassa-redirect',
plugins_url('assets/css/robokassa-redirect.css', __FILE__),
array(),
filemtime($stylePath)
);
}
if (!file_exists($scriptPath)) {
return;
}
wp_enqueue_script(
'robokassa-redirect',
plugins_url('assets/js/robokassa-redirect.js', __FILE__),
array(),
filemtime($scriptPath),
true
);
$config = robokassa_prepare_redirect_config();
if ($config !== null) {
wp_localize_script('robokassa-redirect', 'robokassaRedirectConfig', $config);
}
}
/**
* Готовит конфигурацию для проверки статуса заказа при iframe-оплате.
*
* @return array|null
*/
function robokassa_prepare_redirect_config()
{
if (!function_exists('is_checkout_pay_page') || !is_checkout_pay_page()) {
return null;
}
$order_id = absint(get_query_var('order-pay'));
$order_key = isset($_GET['key']) ? sanitize_text_field(wp_unslash($_GET['key'])) : '';
if ($order_id <= 0 || $order_key === '') {
return null;
}
$order = wc_get_order($order_id);
if (!$order instanceof \WC_Order || $order->get_order_key() !== $order_key) {
return null;
}
if (!robokassa_should_track_payment_redirect($order)) {
return null;
}
return array(
'ajaxUrl' => admin_url('admin-ajax.php'),
'orderId' => $order_id,
'orderKey' => $order_key,
'successUrl' => $order->get_checkout_order_received_url(),
'checkInterval' => 5000,
'maxAttempts' => 120,
);
}
/**
* Определяет необходимость отслеживания оплаты и автоперехода на страницу успеха.
*
* @param \WC_Order $order
*
* @return bool
*/
function robokassa_should_track_payment_redirect(\WC_Order $order)
{
if ((int)get_option('robokassa_iframe') === 1) {
return true;
}
if ($order->get_payment_method() === 'robokassa_sbp') {
return true;
}
if (!function_exists('WC')) {
return false;
}
$session = WC()->session;
if (!is_object($session)) {
return false;
}
return $session->get('chosen_payment_method') === 'robokassa_sbp';
}
/**
* Возвращает статус заказа для перенаправления после iframe-оплаты.
*
* @return void
*/
function robokassa_check_order_status()
{
$order_id = isset($_POST['orderId']) ? absint($_POST['orderId']) : 0;
$order_key = isset($_POST['orderKey']) ? sanitize_text_field(wp_unslash($_POST['orderKey'])) : '';
if ($order_id <= 0 || $order_key === '') {
wp_send_json_error(array('message' => 'invalid_request'));
}
$order = wc_get_order($order_id);
if (!$order instanceof \WC_Order || $order->get_order_key() !== $order_key) {
wp_send_json_error(array('message' => 'invalid_order'));
}
wp_send_json_success(array(
'paid' => $order->is_paid(),
'status' => $order->get_status(),
));
}
add_action('admin_menu', 'robokassa_payment_initMenu'); // Хук для добавления страниц плагина в админку
add_action('plugins_loaded', 'robokassa_payment_initWC'); // Хук инициализации плагина робокассы
add_action('parse_request', 'robokassa_payment_wp_robokassa_checkPayment'); // Хук парсера запросов
add_action('woocommerce_order_status_completed', 'robokassa_payment_smsWhenCompleted'); // Хук статуса заказа = "Выполнен"
add_action('woocommerce_order_status_changed', 'robokassa_2check_send', 10, 3);
add_action('woocommerce_order_status_changed', 'robokassa_hold_confirm', 10, 4);
add_action('woocommerce_order_status_changed', 'robokassa_hold_cancel', 10, 4);
add_action('robokassa_cancel_payment_event', 'robokassa_hold_cancel_after5', 10, 1);
add_action('wp_ajax_robokassa_check_order_status', 'robokassa_check_order_status');
add_action('wp_ajax_nopriv_robokassa_check_order_status', 'robokassa_check_order_status');
register_activation_hook(__FILE__, 'robokassa_payment_wp_robokassa_activate'); //Хук при активации плагина. Дефолтовые настройки и таблица в БД для СМС.
add_filter('woocommerce_get_privacy_policy_text', 'robokassa_get_privacy_policy_text', 10, 2);
function robokassa_get_privacy_policy_text($text, $type)
{
if (function_exists('wcs_order_contains_subscription')) {
$textAlt = sprintf(
get_option('robokassa_agreement_text'),
get_option('robokassa_agreement_pd_link'),
get_option('robokassa_agreement_oferta_link')
);
$text = $textAlt ?: $text;
}
return $text;
}
/**
* @param string $str
*/
function robokassa_payment_DEBUG($str)
{
/** @var string $file */
$file = __DIR__ . '/data/robokassa_DEBUG.txt';
$time = time();
$DEBUGFile = fopen($file, 'a+');
fwrite($DEBUGFile, date('d.m.Y H:i:s', $time + 10800) . " ($time) : $str\r\n");
fclose($DEBUGFile);
}
/**
* Возвращает сервис управления налоговыми ставками.
*
* @return TaxManager
*/
function robokassa_payment_get_tax_manager()
{
global $robokassa_payment_tax_manager;
if (!$robokassa_payment_tax_manager instanceof TaxManager) {
$robokassa_payment_tax_manager = new TaxManager();
}
return $robokassa_payment_tax_manager;
}
/**
* Возвращает сервис управления источником предмета расчёта.
*
* @return PaymentObjectManager
*/
function robokassa_payment_get_payment_object_manager()
{
global $robokassa_payment_payment_object_manager;
if (!$robokassa_payment_payment_object_manager instanceof PaymentObjectManager) {
$robokassa_payment_payment_object_manager = new PaymentObjectManager();
}
return $robokassa_payment_payment_object_manager;
}
/**
* Возвращает сервис управления агенскими полями товаров.
*
* @return AgentManager
*/
function robokassa_payment_get_agent_manager()
{
global $robokassa_payment_agent_manager;
if (!$robokassa_payment_agent_manager instanceof AgentManager) {
$robokassa_payment_agent_manager = new AgentManager();
}
return $robokassa_payment_agent_manager;
}
/**
* Вычисляет сумму налога для передачи в Робокассу.
*
* @param string $tax
* @param float|int $amount
*
* @return float
*/
function calculate_tax_sum($tax, $amount)
{
return robokassa_payment_get_tax_manager()->calculateTaxSum($tax, $amount);
}
/**
* Возвращает налоговую ставку по умолчанию.
*
* @return string
*/
function robokassa_payment_get_default_tax()
{
return robokassa_payment_get_tax_manager()->getDefaultTax();
}
/**
* Определяет налоговую ставку для позиции заказа.
*
* @param \WC_Order_Item $item
*
* @return string
*/
function robokassa_payment_get_item_tax($item)
{
return robokassa_payment_get_tax_manager()->getItemTax($item);
}
/**
* Определяет предмет расчёта для позиции заказа.
*
* @param \WC_Order_Item $item
*
* @return string
*/
function robokassa_payment_get_item_payment_object($item)
{
return robokassa_payment_get_payment_object_manager()->getItemPaymentObject($item);
}
/**
* Отрисовывает поле выбора налоговой ставки в карточке товара.
*
* @return void
*/
function robokassa_payment_render_product_tax_field()
{
robokassa_payment_get_tax_manager()->renderProductTaxField();
}
/**
* Отрисовывает поле выбора предмета расчёта в карточке товара.
*
* @return void
*/
function robokassa_payment_render_product_payment_object_field()
{
robokassa_payment_get_payment_object_manager()->renderProductPaymentObjectField();
}
/**
* Отрисовывает поля агента в карточке товара.
*
* @return void
*/
function robokassa_payment_render_product_agent_fields()
{
robokassa_payment_get_agent_manager()->renderProductAgentFields();
}
/**
* Сохраняет выбранную налоговую ставку товара.
*
* @param \WC_Product $product
*
* @return void
*/
function robokassa_payment_save_product_tax_field($product)
{
robokassa_payment_get_tax_manager()->saveProductTaxField($product);
}
/**
* Сохраняет выбранный предмет расчёта товара.
*
* @param \WC_Product $product
*
* @return void
*/
function robokassa_payment_save_product_payment_object_field($product)
{
robokassa_payment_get_payment_object_manager()->saveProductPaymentObjectField($product);
}
/**
* Сохраняет поля агента в карточке товара.
*
* @param \WC_Product $product
*
* @return void
*/
function robokassa_payment_save_product_agent_fields($product)
{
robokassa_payment_get_agent_manager()->saveProductAgentFields($product);
}
/**
* @param mixed $order_id
* @param string $debug
*
* @return void
*/
function robokassa_payment_smsWhenCompleted($order_id, $debug = '')
{
//Отправка СМС-2 если необходимо
$mrhLogin = get_option('robokassa_payment_MerchantLogin');
if (get_option('robokassa_payment_test_onoff') == 'true') {
$pass1 = get_option('robokassa_payment_testshoppass1');
$pass2 = get_option('robokassa_payment_testshoppass2');
} else {
$pass1 = get_option('robokassa_payment_shoppass1');
$pass2 = get_option('robokassa_payment_shoppass2');
}
$debug .= "pass1 = $pass1 \r\n";
$debug .= "pass2 = $pass2 \r\n";
if (get_option('robokassa_payment_sms2_enabled') == 'on') {
$debug .= "Условие СМС-2 верно! \r\n";
$order = wc_get_order($order_id);
$phone = $order->billing_phone;
$debug .= "phone = $phone \r\n";
$message = get_option('robokassa_payment_sms2_text');
$debug .= "message = $message \r\n";
$translit = (get_option('robokassa_payment_sms_translit') == 'on');
$debug .= "translit = $translit \r\n";
$debug .= "order_id = $order_id \r\n";
global $wpdb;
$roboDataBase = new RoboDataBase($wpdb);
$robokassa = new RobokassaPayAPI($mrhLogin, get_option('robokassa_payment_shoppass1'), get_option('robokassa_payment_shoppass2'));
$sms = new RobokassaSms($roboDataBase, $robokassa, $phone, $message, $translit, $order_id, 2);
$sms->send();
}
}
/**
* @param string $debug
*
* @return void
*/
function robokassa_payment_wp_robokassa_activate($debug)
{
add_option('robokassa_payment_wc_robokassa_enabled', 'no');
add_option('robokassa_payment_test_onoff', 'false');
add_option('robokassa_payment_type_commission', 'true');
add_option('robokassa_payment_tax', 'none');
add_option('robokassa_payment_tax_source', 'global');
add_option('robokassa_payment_payment_object_source', 'global');
add_option('robokassa_payment_sno', 'fckoff');
add_option('robokassa_payment_who_commission', 'shop');
add_option('robokassa_payment_paytype', 'false');
add_option('robokassa_payment_SuccessURL', 'wc_success');
add_option('robokassa_payment_FailURL', 'wc_checkout');
}
/**
* @return void
*/
function robokassa_payment_initMenu()
{
add_submenu_page('woocommerce', 'Настройки Робокассы', 'Настройки Робокассы', 'edit_pages', 'robokassa_payment_main_settings_rb', 'robokassa_payment_main_settings');
add_submenu_page('main_settings_rb.php', 'Основные настройки', 'Основные настройки', 'edit_pages', 'robokassa_payment_main_rb', 'robokassa_payment_main_settings');
add_submenu_page('main_settings_rb.php', 'Настройки СМС', 'Настройки СМС', 'edit_pages', 'robokassa_payment_sms_rb', 'robokassa_payment_sms_settings');
add_submenu_page('main_settings_rb.php', 'Генерировать YML', 'Генерировать YML', 'edit_pages', 'robokassa_payment_YMLGenerator', 'robokassa_payment_yml_generator');
add_submenu_page('main_settings_rb.php', 'Регистрация', 'Регистрация', 'edit_pages', 'robokassa_payment_registration', 'robokassa_payment_reg');
add_submenu_page('main_settings_rb.php', 'Виджет и бейдж Robokassa', 'Виджет и бейдж Robokassa', 'edit_pages', 'robokassa_payment_credit', 'robokassa_payment_credit');
}
/**
* @param string $name
* @param mixed $order_id
*
* @return string
*/
function robokassa_payment_get_success_fail_url($name, $order_id)
{
$order = new WC_Order($order_id);
switch ($name) {
case 'wc_success':
return $order->get_checkout_order_received_url();
case 'wc_checkout':
return $order->get_view_order_url();
case 'wc_payment':
return $order->get_checkout_payment_url();
default:
return get_page_link(get_option($name));
}
}
/**
* @return void
*/
function robokassa_payment_wp_robokassa_checkPayment()
{
if (isset($_REQUEST['robokassa'])) {
/** @var string $returner */
$returner = '';
$order_status = get_option('robokassa_payment_order_status_after_payment');
if (empty($order_status)) {
$order_status = 'wc-processing';
}
if ($_REQUEST['robokassa'] === 'result') {
/** @var string $crc_confirm */
$crc_confirm = strtoupper(
md5(
implode(
':',
[
$_REQUEST['OutSum'],
$_REQUEST['InvId'],
(
(get_option('robokassa_payment_test_onoff') == 'true')
? get_option('robokassa_payment_testshoppass2')
: get_option('robokassa_payment_shoppass2')
),
'shp_label=official_wordpress',
'Shp_merchant_id=' . get_option('robokassa_payment_MerchantLogin'),
'Shp_order_id=' . $_REQUEST['InvId'],
'Shp_result_url=' . (Util::siteUrl('/?robokassa=result'))
]
)
)
);
if ($crc_confirm == $_REQUEST['SignatureValue']) {
$order = new WC_Order($_REQUEST['InvId']);
$order->add_order_note('Заказ успешно оплачен!');
$order->update_status(str_replace('wc-', '', $order_status));
global $woocommerce;
$woocommerce->cart->empty_cart();
if (function_exists('wcs_order_contains_subscription')) {
$subscriptions = wcs_get_subscriptions_for_order($_REQUEST['InvId']) ?: wcs_get_subscriptions_for_renewal_order($_REQUEST['InvId']);
if ($subscriptions == true) {
foreach ($subscriptions as $subscription) {
$subscription->update_status('active');
}
}
}
$returner = 'OK' . $_REQUEST['InvId'];
if (get_option('robokassa_payment_sms1_enabled') == 'on') {
try {
global $wpdb;
(new RobokassaSms(
(new RoboDataBase($wpdb)),
(new RobokassaPayAPI(
get_option('robokassa_payment_MerchantLogin'),
get_option('robokassa_payment_shoppass1'),
get_option('robokassa_payment_shoppass2')
)
),
$order->billing_phone,
get_option('robokassa_payment_sms1_text'),
(get_option('robokassa_payment_sms_translit') == 'on'),
$_REQUEST['InvId'],
1
))->send();
} catch (Exception $e) {
}
}
} elseif ((int)get_option('robokassa_payment_hold_onoff') === 1 &&
strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false) {
$input_data = file_get_contents('php://input');
$token_parts = explode('.', $input_data);
if (count($token_parts) === 3) {
$json_data = json_decode(base64_decode($token_parts[1]), true);
// Проверяем наличие ключевого поля "state" со значением "HOLD"
if (isset($json_data['data']['state']) && $json_data['data']['state'] === 'HOLD') {
$order = new WC_Order($json_data['data']['invId']);
$date_in_five_days = date('Y-m-d H:i:s', strtotime('+5 days'));
$order->add_order_note("Robokassa: Платеж успешно подтвержден. Он ожидает подтверждения до {$date_in_five_days}, после чего автоматически отменится");
$order->update_status('on-hold');
wp_schedule_single_event(strtotime('+5 days'), 'robokassa_cancel_payment_event', array($order->get_id()));
}
if (isset($json_data['data']['state']) && $json_data['data']['state'] === 'OK') {
$order = new WC_Order($json_data['data']['invId']);
$order->add_order_note("Robokassa: Платеж успешно подтвержден");
$order->update_status('processing');
}
http_response_code(200);
} else {
http_response_code(400);
}
} else {
$returner = 'BAD SIGN';
try {
$order = new WC_Order($_REQUEST['InvId']);
error_log('REQUEST: ' . print_r($_REQUEST, true));
$order->add_order_note('Bad CRC '. $crc_confirm .' . '. $_REQUEST['SignatureValue']);
$order->update_status('failed');
} catch (Exception $e) {}
}
}
if ($_REQUEST['robokassa'] == 'success') {
header('Location:' . robokassa_payment_get_success_fail_url(get_option('robokassa_payment_SuccessURL'), $_REQUEST['InvId']));
die;
}
if ($_REQUEST['robokassa'] == 'fail') {
header('Location:' . robokassa_payment_get_success_fail_url(get_option('robokassa_payment_FailURL'), $_REQUEST['InvId']));
die;
}
echo $returner;
die;
}
}
// Подготовка строки перед кодированием в base64
function formatSignReplace($string)
{
return strtr(
$string,
[
'+' => '-',
'/' => '_',
]
);
}
// Подготовка строки после кодирования в base64
function formatSignFinish($string)
{
return preg_replace('/^(.*?)(=*)$/', '$1', $string);
}
/**
*
* Проверка режимы работы
*
* @return array
*/
function getRobokassaPasses()
{
if (get_option('robokassa_payment_test_onoff') == 'true') {
return [
'pass1' => get_option('robokassa_payment_testshoppass1'),
'pass2' => get_option('robokassa_payment_testshoppass2'),
];
}
return [
'pass1' => get_option('robokassa_payment_shoppass1'),
'pass2' => get_option('robokassa_payment_shoppass2'),
];
}
/**
* Подготовка товарной номенклатуры для формирования чека
*
* @param mixed $order_id
*
* @return array
*/
function createRobokassaReceipt($order_id)
{
global $woocommerce;
$order = new WC_Order($order_id);
$sno = get_option('robokassa_payment_sno');
$default_tax = robokassa_payment_get_default_tax();
$country = get_option('robokassa_country_code');
$receipt = array(
'sno' => $sno,
);
$total_order = $order->get_total();
$total_receipt = 0;
/**
* @var \WC_Order_Item_Product $item
*/
foreach ($order->get_items() as $item) {
$product = $item->get_product();
$current = array();
$current['name'] = $product->get_title();
$current['quantity'] = $item->get_quantity();
$current['sum'] = wc_format_decimal($item->get_total(), get_option('woocommerce_price_num_decimals'));
$current['cost'] = wc_format_decimal($item->get_total(), get_option('woocommerce_price_num_decimals')) / $item->get_quantity();
$total_receipt += $current['sum'];
$item_tax = robokassa_payment_get_item_tax($item);
if ($country == 'RU') {
$current['payment_object'] = robokassa_payment_get_item_payment_object($item);
$current['payment_method'] = get_option('robokassa_payment_paymentMethod');
}
if (($sno == 'osn') || $country == 'RU') {
$current['tax'] = $item_tax;
} else {
$current['tax'] = 'none';
}
$agentData = robokassa_payment_get_agent_manager()->getItemAgentData($item);
if (!empty($agentData)) {
if (isset($agentData['agent_info'])) {
$current['agent_info'] = $agentData['agent_info'];
}
if (isset($agentData['supplier_info'])) {
$current['supplier_info'] = $agentData['supplier_info'];
}
}
$receipt['items'][] = $current;
}
foreach ($order->get_items('fee') as $fee_item) {
$additional_item_name = $fee_item->get_name();
$additional_item_total = (float)$fee_item->get_total();
$additional_item_data = array(
'name' => $additional_item_name,
'quantity' => $fee_item->get_quantity(),
'sum' => wc_format_decimal($additional_item_total, get_option('woocommerce_price_num_decimals')),
'cost' => wc_format_decimal($additional_item_total, get_option('woocommerce_price_num_decimals')) / $fee_item->get_quantity(),
'payment_object' => get_option('robokassa_payment_paymentObject'),
'payment_method' => get_option('robokassa_payment_paymentMethod'),
);
if (($sno == 'osn') || $country == 'RU') {
$additional_item_data['tax'] = $default_tax;
} else {
$additional_item_data['tax'] = 'none';
}
$receipt['items'][] = $additional_item_data;
$total_receipt += $additional_item_total;
}
if ((double)$order->get_shipping_total() > 0) {
$current = array();
$current['name'] = 'Доставка';
$current['quantity'] = 1;
$current['cost'] = (double)sprintf('%01.2f', $order->get_shipping_total());
$current['sum'] = (double)sprintf('%01.2f', $order->get_shipping_total());
if ($country == 'RU') {
$current['payment_object'] = get_option('robokassa_payment_paymentObject_shipping') ?: get_option('robokassa_payment_paymentObject');
$current['payment_method'] = get_option('robokassa_payment_paymentMethod');
}
if (($sno == 'osn') || ($country != 'KZ')) {
$current['tax'] = $default_tax;
} else {
$current['tax'] = 'none';
}
$receipt['items'][] = $current;
$total_receipt += $current['cost'];
}
if ($total_receipt != $total_order) {
robokassa_payment_DEBUG('Robokassa: общая сумма чека (' . $total_receipt . ') НЕ совпадает с общей суммой заказа (' . $total_order . ')');
}
return apply_filters('wc_robokassa_receipt', $receipt);
}
/**
* Формирование формы, перенаправляющей пользователя на сайт робокассы
*
* Включает в себя подготовку данных и рендеринг самой формы
*
* @param mixed $order_id
* @param $label
*
* @return void
*/
function processRobokassaPayment($order_id, $label)
{
$mrhLogin = get_option('robokassa_payment_MerchantLogin');
$passes = getRobokassaPasses();
$order = wc_get_order($order_id);
$receipt = createRobokassaReceipt($order_id);
$rb = new RobokassaPayAPI($mrhLogin, $passes['pass1'], $passes['pass2']);
$order_total = $order->get_total();
$sum = number_format($order_total, 2, '.', '');
$invDesc = "Заказ номер $order_id";
$recurring = false;
if (function_exists('wcs_order_contains_subscription')) {
$order_subscription = wcs_order_contains_subscription($order_id);
if ($order_subscription) {
$recurring = true;
}
}
echo $rb->createForm(
$sum,
$order_id,
$invDesc,
get_option('robokassa_payment_test_onoff'),
$label,
$receipt,
$order->get_billing_email(),
$recurring
);
}
function robokassa_payment_createFormWC($order_id, $label)
{
static $rendered = array();
if ($order_id instanceof \WC_Order) {
$order_key = (string) $order_id->get_id();
} else {
$order_key = (string) $order_id;
}
$unique_key = $label . '|' . $order_key;
if (isset($rendered[$unique_key])) {
return;
}
$rendered[$unique_key] = true;
processRobokassaPayment($order_id, $label);
}
function robokassa_payment_initWC()
{
if (!defined('ABSPATH')) {
exit;
}
if (!class_exists(Robokassa\Payment\WC_WP_robokassa::class))
return;
require 'labelsClasses.php';
add_filter('woocommerce_payment_gateways', 'robokassa_payment_add_WC_WP_robokassa_class');
}
/**
* @return void
*/
function robokassa_payment_main_settings()
{
$_GET['li'] = 'main';
include 'menu_rb.php';
include 'main_settings_rb.php';
}
/**
* @return void
*/
function robokassa_payment_sms_settings()
{
$_GET['li'] = 'sms';
include 'menu_rb.php';
include 'sms_settings_rb.php';
}
/**
* @return void
*/
function robokassa_payment_reg()
{
$_GET['li'] = 'registration';
include 'menu_rb.php';
include 'main_settings_registration.php';
}
/**
* @return void
*/
function robokassa_payment_credit()
{
if (get_option('robokassa_country_code', 'RU') === 'KZ') {
wp_safe_redirect(admin_url('admin.php?page=robokassa_payment_main_rb'));
exit;
}
$_GET['li'] = 'credit';
include 'menu_rb.php';
include 'main_settings_credit.php';
}
/**
* @return void
*/
function robokassa_payment_oferta()
{
$_GET['li'] = 'offer';
include 'menu_rb.php';
include 'main_settings_offer.php';
}
/**
* Возвращает префикс таблиц в базе данных
*
* @return string
*
* @throws Exception
*/
function robokassa_payment_getDbPrefix()
{
global $wpdb;
if ($wpdb instanceof wpdb) {
return $wpdb->prefix;
}
throw new Exception('Объект типа "wpdb" не найден в глобальном пространстве имен по имени "$wpdb"');
}
if (!function_exists('getallheaders')) {
/**
* Возвращает заголовки http-запроса
*
* Не во всех окружениях эта функция есть, а для работы модуля она необходима
*
* @return array
*/
function getallheaders()
{
static $headers = null;
if (null === $headers) {
$headers = array();
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($name, 5)))))] = $value;
}
}
}
return $headers;