-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass.expresspay.php
More file actions
1130 lines (975 loc) · 39.9 KB
/
class.expresspay.php
File metadata and controls
1130 lines (975 loc) · 39.9 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
class ExpressPay
{
/**
*
* Получение вью из файла.
*
* @param string $name Название файла вью
* @param array $args Аргументы для передачи на вью
*
*/
public static function view($name, array $args = array())
{
foreach ($args as $key => $val) {
$$key = $val;
}
$file = EXPRESSPAY__PLUGIN_DIR . 'views/' . $name . '.php';
include($file);
}
/**
*
* Подключение стилей и скирптов в административной части интеграции
*
*/
static function plugin_admin_styles()
{
//CSS
wp_enqueue_style('pluginAdminCssEp', plugins_url('css/styles.css', __FILE__), array(), get_plugin_version());
wp_enqueue_style('pluginAdminCssBst', plugins_url('css/bootstrap.min.css', __FILE__), array(), get_plugin_version());
wp_enqueue_style('pluginAdminCss', plugins_url('css/admin.css', __FILE__), array(), get_plugin_version());
//JS
wp_enqueue_script('pluginAdminJsJsd', plugins_url('js/popper.min.js', __FILE__));
wp_enqueue_script('pluginAdminJsBst', plugins_url('js/bootstrap.min.js', __FILE__));
wp_enqueue_script('pluginAdminJs', plugins_url('js/admin.js', __FILE__), array('jquery'), get_plugin_version());
}
/**
*
* Подключение стилей и скриптов в клиентской части интеграции
*
*/
static function plugin_client_styles()
{
//CSS
wp_enqueue_style('pluginPaymentCss', plugins_url('css/payment.css', __FILE__), array(), get_plugin_version());
//JS
wp_enqueue_script('pluginPaymentJs', plugins_url('js/shortcode.js', __FILE__), array('jquery'), get_plugin_version());
}
/**
*
* Формирование цифровой подписи
*
* @param array $signatureParams Список передаваемых параметров
* @param string $secretWord Секретное слово
* @param string $method Метод формирования цифровой подписи
*
* @return string $hash Сформированная цифровая подпись
*
*/
public static function computeSignature($signatureParams, $secretWord, $method)
{
$normalizedParams = array_change_key_case($signatureParams, CASE_LOWER);
$mapping = array(
"add-invoice" => array(
"token",
"accountno",
"amount",
"currency",
"expiration",
"info",
"surname",
"firstname",
"patronymic",
"city",
"street",
"house",
"building",
"apartment",
"isnameeditable",
"isaddresseditable",
"isamounteditable"
),
"get-details-invoice" => array(
"token",
"id"
),
"cancel-invoice" => array(
"token",
"id"
),
"status-invoice" => array(
"token",
"id"
),
"get-list-invoices" => array(
"token",
"from",
"to",
"accountno",
"status"
),
"get-list-payments" => array(
"token",
"from",
"to",
"accountno"
),
"get-details-payment" => array(
"token",
"id"
),
"add-card-invoice" => array(
"token",
"accountno",
"expiration",
"amount",
"currency",
"info",
"returnurl",
"failurl",
"language",
"pageview",
"sessiontimeoutsecs",
"expirationdate"
),
"card-invoice-form" => array(
"token",
"cardinvoiceno"
),
"status-card-invoice" => array(
"token",
"cardinvoiceno",
"language"
),
"reverse-card-invoice" => array(
"token",
"cardinvoiceno"
),
"get-qr-code" => array(
"token",
"invoiceid",
"viewtype",
"imagewidth",
"imageheight"
),
"add-web-invoice" => array(
"token",
"serviceid",
"accountno",
"amount",
"currency",
"expiration",
"info",
"surname",
"firstname",
"patronymic",
"city",
"street",
"house",
"building",
"apartment",
"isnameeditable",
"isaddresseditable",
"isamounteditable",
"emailnotification",
"smsphone",
"returntype",
"returnurl",
"failurl"
),
"add-webcard-invoice" => array(
"token",
"serviceid",
"accountno",
"expiration",
"amount",
"currency",
"info",
"returnurl",
"failurl",
"language",
"sessiontimeoutsecs",
"expirationdate",
"returntype"
),
"response-web-invoice" => array(
"token",
"expresspayaccountnumber",
"expresspayinvoiceno"
),
"bind-card" => array(
"token",
"serviceid",
"writeoffperiod",
"amount",
"currency",
"info",
"returnurl",
"failurl",
"language",
"returntype"
),
"response-bind-card" => array(
"token",
"expresspayaccountnumber",
"customerid"
),
"unbind-card" => array(
"token",
"serviceid",
"customerid"
),
"approve-unbind-card" => array(
"token",
"customerid",
"serviceid"
),
"notification" => array(
"data"
)
);
$apiMethod = $mapping[$method];
$result = "";
foreach ($apiMethod as $item) {
$result .= $normalizedParams[$item];
}
$hash = strtoupper(hash_hmac('sha1', $result, $secretWord));
return $hash;
}
/**
* Обновление статуса счета с проверкой рекуррентности
*
* @param string $account_no Номер счета
* @param int $status Новый статус счета
* @return bool Успешность выполнения операции
*/
public static function updateInvoiceStatus($account_no, $status)
{
global $wpdb;
$is_recurrent = $wpdb->get_var(
$wpdb->prepare(
"SELECT recurrence FROM " . EXPRESSPAY_TABLE_INVOICES_NAME . "
WHERE account_no = %s",
$account_no
)
);
if ($is_recurrent === null) {
return false;
}
if ($is_recurrent) {
return true;
}
$result = $wpdb->update(
EXPRESSPAY_TABLE_INVOICES_NAME,
['status' => $status],
['account_no' => $account_no],
['%d'],
['%s']
);
return $result !== false;
}
/**
* Создание/обновление рекуррентного счета
*
* @param string $account_no Номер счета от агрегатора
* @param int $customer_id ID привязки карты
* @param int $status Статус
* @return bool Успешность выполнения операции
*/
public static function handleRecurrentInvoice($account_no, $customer_id, $status)
{
global $wpdb;
$exists_by_customer_id = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*) FROM " . EXPRESSPAY_TABLE_INVOICES_NAME . "
WHERE customer_id = %d",
$customer_id
));
if (!$exists_by_customer_id) {
$exists_by_account_no = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*) FROM " . EXPRESSPAY_TABLE_INVOICES_NAME . "
WHERE account_no = %s",
$account_no
));
if (!$exists_by_account_no) {
return false;
} else {
$result = $wpdb->update(
EXPRESSPAY_TABLE_INVOICES_NAME,
[
'status' => $status,
'customer_id' => $customer_id
],
['account_no' => $account_no],
['%d', '%d'],
['%s']
);
}
} else {
$result = $wpdb->update(
EXPRESSPAY_TABLE_INVOICES_NAME,
['status' => $status],
['customer_id' => $customer_id],
['%d'],
['%d']
);
}
return $result !== false;
}
/**
*
* Обновление даты оплаты счета
*
* @param string $account_no Номер счета
* @param string $dateofpayment Дата оплаты счета
* @return bool Успешность выполнения операции
*
*/
public static function updateInvoiceDateOfPayment($account_no, $dateofpayment)
{
global $wpdb;
$is_recurrent = $wpdb->get_var(
$wpdb->prepare(
"SELECT recurrence FROM " . EXPRESSPAY_TABLE_INVOICES_NAME . "
WHERE account_no = %s",
$account_no
)
);
if ($is_recurrent === null) {
return false;
}
if ($is_recurrent) {
return true;
}
return $wpdb->update(
EXPRESSPAY_TABLE_INVOICES_NAME,
['dateofpayment' => $dateofpayment],
['account_no' => $account_no],
['%s'],
['%s']
) !== false;
}
/**
*
* Обновление даты оплаты счета
*
* @param string $account_no Номер счета
* @param string $dateofpayment Дата оплаты счета
* @return bool Успешность выполнения операции
*
*/
public static function updateRecInvoiceDateOfPayment($customer_id, $dateofpayment)
{
global $wpdb;
return $wpdb->update(
EXPRESSPAY_TABLE_INVOICES_NAME,
['dateofpayment' => $dateofpayment],
['customer_id' => $customer_id],
['%s'],
['%d']
) !== false;
}
/**
* Добавление записи о новом успешном платеже.
*
* Проверяет, существует ли уже платеж с таким номером — в случае дубликата возвращает 'duplicate'.
* Если счет рекуррентный — возврат 'recurrent_skip' без вставки.
* В случае ошибки вставки — 'insert_error'.
* При успешной вставке — 'ok'.
*
* @param object $data Объект с данными уведомления
* @return string Статус выполнения: 'duplicate', 'recurrent_skip', 'not_found', 'insert_error', 'ok'
*/
public static function addNewPayment($data)
{
global $wpdb;
$exists = $wpdb->get_var(
$wpdb->prepare(
"SELECT COUNT(*) FROM " . EXPRESSPAY_TABLE_PAYMENTS . "
WHERE payment_no = %d",
$data->PaymentNo
)
);
if ($exists) {
error_log("Платеж с номером {$data->PaymentNo} уже существует");
return 'duplicate';
}
$invoice_data = $wpdb->get_row(
$wpdb->prepare(
"SELECT options, recurrence FROM " . EXPRESSPAY_TABLE_INVOICES_NAME . "
WHERE account_no = %s",
$data->AccountNo
)
);
if (!$invoice_data) {
error_log("Не найден счет для accountNo={$data->AccountNo}");
return 'not_found';
}
$invoice_options = $invoice_data->options ?? null;
$is_recurrent = !empty($invoice_data->recurrence);
if ($is_recurrent) {
return 'recurrent_skip';
}
if ($invoice_options) {
$options = json_decode($invoice_options, true);
$visibility = $options['Visibility'] ?? false;
$emailNotification = $options['EmailNotification'] ?? false;
$surname = $options['Surname'] ?? '';
$firstName = $options['FirstName'] ?? '';
$patronymic = $options['Patronymic'] ?? '';
$payerParts = array_filter([$surname, $firstName, $patronymic]);
} else {
$visibility = false;
$emailNotification = false;
$payerParts = [];
}
$payer = 'Благотворитель';
if (!empty($data->Payer)) {
$payer = sanitize_text_field($data->Payer);
} elseif ($payerParts) {
$payer = implode(' ', $payerParts);
}
if (!empty($emailNotification) && is_email($emailNotification)) {
self::send_success_email($emailNotification, $data->Amount, $payer);
} else {
error_log(sprintf(
"Не удалось отправить email-уведомление: некорректный или отсутствующий email для account_no=%s. Значение: %s",
$data->AccountNo,
var_export($emailNotification, true)
));
}
$inserted = $wpdb->insert(
EXPRESSPAY_TABLE_PAYMENTS,
[
'payment_no' => $data->PaymentNo,
'account_no' => $data->AccountNo,
'amount' => str_replace(',', '.', (string)$data->Amount),
'dateofpayment' => $data->Created,
'payer' => $payer,
'service' => $data->Service,
'visibility' => $visibility
],
['%d', '%s', '%s', '%s', '%s', '%s', '%d']
);
if (!$inserted) {
error_log("Ошибка при вставке платежа: payment_no={$data->PaymentNo}, account_no={$data->AccountNo}");
return 'insert_error';
}
return 'ok';
}
/**
* Добавление записи о новом успешном рекуррентном платеже.
*
* Проверяет, существует ли уже платеж с заданным номером. Если такой платеж найден,
* возвращает 'duplicate'. Если не найден счет по customer_id — возвращает 'not_found'.
* При ошибке вставки записи в базу — 'insert_error'. В случае успешного добавления
* платежа возвращает 'ok'.
*
* Также выполняется попытка извлечь email для уведомления и логируется его отсутствие или некорректность.
*
* @param object $data Объект с данными из уведомления о платеже (ожидаются поля: PaymentNo, AccountNo, CustomerId, Amount, Created, Payer, Service)
* @return string Статус выполнения операции: 'ok', 'duplicate', 'not_found', 'insert_error'
*/
public static function addNewRecPayment($data)
{
global $wpdb;
$exists = $wpdb->get_var(
$wpdb->prepare(
"SELECT COUNT(*) FROM " . EXPRESSPAY_TABLE_PAYMENTS . "
WHERE payment_no = %d",
$data->PaymentNo
)
);
if ($exists) {
error_log("Платеж с номером {$data->PaymentNo} уже существует");
return 'duplicate';
}
$invoice_data_by_customer_id = $wpdb->get_row(
$wpdb->prepare(
"SELECT options, options_id FROM " . EXPRESSPAY_TABLE_INVOICES_NAME . "
WHERE customer_id = %d",
$data->CustomerId
)
);
if (!$invoice_data_by_customer_id) {
$invoice_data_by_account_no = $wpdb->get_row(
$wpdb->prepare(
"SELECT options, options_id FROM " . EXPRESSPAY_TABLE_INVOICES_NAME . "
WHERE account_no = %s",
$data->AccountNo
)
);
if (!$invoice_data_by_account_no) {
error_log("Не найден счет для customer_id={$data->CustomerId}, account_no={$data->AccountNo}");
return 'not_found';
} else {
$invoice_data = $invoice_data_by_account_no;
}
} else {
$invoice_data = $invoice_data_by_customer_id;
}
$invoice_options = $invoice_data->options;
$type_id = (int) $invoice_data->options_id;
if ($invoice_options) {
$options = json_decode($invoice_options, true);
$visibility = $options['Visibility'] ?? false;
$emailNotification = $options['EmailNotification'] ?? false;
$surname = $options['Surname'] ?? '';
$firstName = $options['FirstName'] ?? '';
$patronymic = $options['Patronymic'] ?? '';
$payerParts = array_filter([$surname, $firstName, $patronymic]);
} else {
$visibility = false;
$emailNotification = false;
$payerParts = [];
}
$payer = 'Благотворитель';
if (!empty($data->Payer)) {
$payer = sanitize_text_field($data->Payer);
} elseif ($payerParts) {
$payer = implode(' ', $payerParts);
}
if (!empty($emailNotification) && is_email($emailNotification)) {
$query = $wpdb->prepare( "SELECT options FROM " . EXPRESSPAY_TABLE_PAYMENT_METHOD_NAME . " WHERE id = %d", $type_id);
$response = $wpdb->get_row($query);
$options = json_decode($response->options);
$unbind_url = self::getUnbindLink($options->Token, $options->ServiceId, $data->CustomerId, $type_id, $options->SecretWord);
self::send_subscription_email($emailNotification, $data->Amount, $data->CustomerId, $unbind_url, $payer);
} else {
error_log(sprintf(
"Не удалось отправить email-уведомление: некорректный или отсутствующий email для customer_id=%d. Значение: %s",
$data->CustomerId,
var_export($emailNotification, true)
));
}
$inserted = $wpdb->insert(
EXPRESSPAY_TABLE_PAYMENTS,
[
'payment_no' => $data->PaymentNo,
'account_no' => $data->AccountNo,
'customer_id' => $data->CustomerId,
'amount' => str_replace(',', '.', (string)$data->Amount),
'dateofpayment' => $data->Created,
'payer' => $payer,
'service' => $data->Service,
'visibility' => $visibility
],
['%d', '%s', '%d', '%s', '%s', '%s', '%s', '%d']
);
if (!$inserted) {
error_log("Ошибка при вставке платежа для customer_id={$data->CustomerId}, payment_no={$data->PaymentNo}");
return 'insert_error';
}
return 'ok';
}
/**
* Удаление записи о платеже (отмена платежа)
*
* @param int $payment_no Номер платежа
* @return bool Успешность выполнения операции
*/
public static function deletePayment($payment_no)
{
global $wpdb;
return $wpdb->delete(
EXPRESSPAY_TABLE_PAYMENTS,
['payment_no' => $payment_no],
['%d']
) !== false;
}
/**
* Хук обработки активации плагина
*/
static function plugin_activation() {
global $wpdb;
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
$charset_collate = $wpdb->get_charset_collate();
$options_table_name = $wpdb->prefix . 'expresspay_options';
$sql = "CREATE TABLE $options_table_name (
id MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
name TINYTEXT NOT NULL,
type TINYTEXT NOT NULL,
options TEXT NULL,
isactive TINYINT NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
dbDelta($sql);
$invoices_table_name = $wpdb->prefix . 'expresspay_invoices';
$sql = "CREATE TABLE $invoices_table_name (
id INT NOT NULL AUTO_INCREMENT,
account_no VARCHAR(30) NOT NULL,
recurrence BOOLEAN NOT NULL DEFAULT FALSE,
customer_id INT NULL,
amount DECIMAL(10,2) NOT NULL,
datecreated DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
status TINYINT NOT NULL DEFAULT 0,
dateofpayment DATETIME NULL DEFAULT NULL,
options TEXT NULL,
options_id MEDIUMINT(9) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY (account_no),
FOREIGN KEY (options_id) REFERENCES $options_table_name(id)
) $charset_collate;";
dbDelta($sql);
$payments_table_name = $wpdb->prefix . 'expresspay_payments';
$sql = "CREATE TABLE $payments_table_name (
payment_no INT NOT NULL,
account_no VARCHAR(30) NOT NULL,
customer_id INT NULL,
amount DECIMAL(10,2) NOT NULL,
dateofpayment DATETIME NOT NULL,
payer VARCHAR(255) NULL DEFAULT NULL,
service VARCHAR(255) NULL DEFAULT NULL,
visibility BOOLEAN NOT NULL DEFAULT FALSE,
PRIMARY KEY (payment_no)
) $charset_collate;";
dbDelta($sql);
add_option('expresspay_plugin_ult', '');
add_option('expresspay_db_version', '1.0');
}
/**
* Хук обработки деактивации плагина
*/
static function plugin_deactivation() {
global $wpdb;
$payments_table_name = $wpdb->prefix . 'expresspay_payments';
$invoices_table_name = $wpdb->prefix . 'expresspay_invoices';
$options_table_name = $wpdb->prefix . 'expresspay_options';
$wpdb->query("DROP TABLE IF EXISTS $payments_table_name");
$wpdb->query("DROP TABLE IF EXISTS $invoices_table_name");
// $wpdb->query("DROP TABLE IF EXISTS $options_table_name"); // Оставляем методы оплаты
delete_option('expresspay_plugin_ult');
delete_option('expresspay_db_version');
}
/**
*
* Хук обработки удаления плагина
*
*/
static function plugin_uninstall()
{
global $wpdb;
$payments_table_name = EXPRESSPAY_TABLE_PAYMENTS;
$invoices_table_name = EXPRESSPAY_TABLE_INVOICES_NAME;
$options_table_name = EXPRESSPAY_TABLE_PAYMENT_METHOD_NAME;
$wpdb->query("DROP TABLE IF EXISTS $payments_table_name");
$wpdb->query("DROP TABLE IF EXISTS $invoices_table_name");
$wpdb->query("DROP TABLE IF EXISTS $options_table_name");
delete_option('expresspay_plugin_is_active');
delete_option('expresspay_plugin_ult');
}
static function log_error_exception($name, $message, $e)
{
self::log($name, "ERROR", $message . '; EXCEPTION MESSAGE - ' . $e->getMessage() . '; EXCEPTION TRACE - ' . $e->getTraceAsString());
}
static function log_error($name, $message)
{
self::log($name, "ERROR", $message);
}
static function log_info($name, $message)
{
self::log($name, "INFO", $message);
}
static function log($name, $type, $message)
{
$log_url = wp_upload_dir();
$log_url = $log_url['basedir'] . "/expresspay";
if (!file_exists($log_url)) {
$is_created = mkdir($log_url, 0777);
if (!$is_created)
return;
}
$log_url .= '/express-pay-' . date('Y.m.d') . '.log';
file_put_contents($log_url, $type . " - IP - " . sanitize_text_field($_SERVER['REMOTE_ADDR']) . "; DATETIME - " . date("Y-m-d H:i:s") . "; USER AGENT - " . sanitize_text_field($_SERVER['HTTP_USER_AGENT']) . "; FUNCTION - " . $name . "; MESSAGE - " . $message . ';' . PHP_EOL, FILE_APPEND);
}
/**
*
* Получение Qr-кода
*
* @param string $token Токен
* @param int $invoice_id Номер счета в сервисе Эксрпесс Платежи
* @param string $secretWord Секретное слово
*
* @return base64 QR-код или false в случае ошибки
*/
public static function getQrCode($token, $invoice_id, $secretWord)
{
$request_params = array(
'Token' => $token,
'InvoiceId' => $invoice_id,
'ViewType' => 'base64'
);
$request_params = http_build_query($request_params);
$url = 'https://api.express-pay.by/v1/qrcode/getqrcode/';
$response = wp_remote_get($url . '?' . $request_params);
if (is_wp_error($response)) {
error_log('ExpressPay API Error: ' . $response->get_error_message());
return false;
}
$body = wp_remote_retrieve_body($response);
if (empty($body)) {
error_log('ExpressPay API Error: Empty response body');
return false;
}
$response_data = json_decode($body);
if (json_last_error() !== JSON_ERROR_NONE) {
error_log('ExpressPay API Error: Invalid JSON - ' . json_last_error_msg());
return false;
}
if (!isset($response_data->QrCodeBody)) {
error_log('ExpressPay API Error: QrCodeBody is missing in response');
return false;
}
return $response_data->QrCodeBody;
}
/**
* Получение ссылки для перехода в банкинг
*
* @param string $token Токен
* @param int $invoice_id Номер счета в сервисе Экспресс Платежи
* @param string $secretWord Секретное слово
*
* @return string|false Ссылка на QR-код или false в случае ошибки
*/
public static function getQrCodeLink($token, $invoice_id, $secretWord)
{
$request_params = array(
'Token' => $token,
'InvoiceId' => $invoice_id,
'ViewType' => 'text'
);
$request_params = http_build_query($request_params);
$url = 'https://api.express-pay.by/v1/qrcode/getqrcode/';
$response = wp_remote_get($url . '?' . $request_params);
if (is_wp_error($response)) {
error_log('ExpressPay API Error: ' . $response->get_error_message());
return false;
}
$body = wp_remote_retrieve_body($response);
if (empty($body)) {
error_log('ExpressPay API Error: Empty response body');
return false;
}
$response_data = json_decode($body);
if (json_last_error() !== JSON_ERROR_NONE) {
error_log('ExpressPay API Error: Invalid JSON - ' . json_last_error_msg());
return false;
}
if (!isset($response_data->QrCodeBody)) {
error_log('ExpressPay API Error: QrCodeBody is missing in response');
return false;
}
return $response_data->QrCodeBody;
}
/**
* Получение информационного HTML-сообщения о привязанной карте с кнопкой отвязки
*
* @param string $token Токен мерчанта
* @param string $service_id Номер услуги
* @param int $customer_id ID привязки карты
* @param string $secretWord Секретное слово
*
* @return string HTML-сообщение
*/
public static function getCardInfoMessage($token, $service_id, $customer_id, $secretWord)
{
$signature_params = array(
'token' => $token,
'serviceid' => $service_id,
'customerid' => $customer_id
);
$signature = self::computeSignature($signature_params, $secretWord, 'unbind-card');
$url = "https://api.express-pay.by/v1/recurringpayment/bind/" . urlencode($customer_id);
$url_with_query = add_query_arg([
'ServiceId' => $service_id,
'Signature' => $signature
], $url);
$response = wp_remote_get($url_with_query);
if (is_wp_error($response)) {
error_log('ExpressPay API GetCardInfo Error: ' . $response->get_error_message());
return '<p>Не удалось получить информацию о карте. Попробуйте позже или свяжите с технической поддержкой.</p>';
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (json_last_error() !== JSON_ERROR_NONE) {
error_log('ExpressPay API JSON Error: ' . json_last_error_msg());
return '<p>Ошибка обработки данных. Попробуйте позже или свяжите с технической поддержкой.</p>';
}
if (!isset($data['Status']) || !isset($data['Card'])) {
error_log('ExpressPay API Error: Invalid response structure');
return '<p>Некорректный ответ от сервиса. Попробуйте позже или свяжите с технической поддержкой.</p>';
}
$status = sanitize_text_field($data['Status']);
$card_number = sanitize_text_field($data['Card']);
$exp_date = isset($data['OfferExpDate']) ? sanitize_text_field($data['OfferExpDate']) : null;
$normalized_status = mb_strtolower(trim($status), 'UTF-8');
$html = '<div class="card-info-container">';
$html .= '<h2>Информация о карте</h2>';
$html .= '<p><strong>Номер карты:</strong> ' . esc_html($card_number) . '</p>';
if ($exp_date) {
$html .= '<p><strong>Действует до:</strong> ' . esc_html($exp_date) . '</p>';
}
$html .= '<p><strong>Статус:</strong> ' . esc_html($status) . '</p>';
if ($normalized_status === 'карта привязана' || $normalized_status === 'привязана') {
$html .= '<div class="unbind-section">';
$html .= '<button class="unbind-btn" id="unbind_card_btn">Отвязать карту</button>';
$html .= '</div>';
}
$html .= '</div>';
return $html;
}
/**
* Отвязка карты
*
* @param string $token Токен
* @param string $service_id Номер услуги
* @param int $customer_id ID привязки карты
* @param string $secretWord Секретное слово
*
* @return bool Успешность выполнения операции
*/
public static function unbindCard($token, $service_id, $customer_id, $secretWord)
{
$signature_params = array(
'token' => $token,
'serviceid' => $service_id,
'customerid' => $customer_id
);
$signature = self::computeSignature($signature_params, $secretWord, 'unbind-card');
$url = "https://api.express-pay.by/v1/recurringpayment/unbind/" . urlencode($customer_id);
$url_with_query = add_query_arg([
'ServiceId' => $service_id,
'Signature' => $signature
], $url);
$response = wp_remote_request($url_with_query, array(
'method' => 'DELETE',
'timeout' => 15
));
if (is_wp_error($response)) {
error_log('ExpressPay API Error: ' . $response->get_error_message());
return false;
}
$body = wp_remote_retrieve_body($response);
if (empty($body)) {
error_log('ExpressPay API Error: Empty response body');
return false;
}
$response_data = json_decode($body);
if (json_last_error() !== JSON_ERROR_NONE) {
error_log('ExpressPay API Error: Invalid JSON - ' . json_last_error_msg());
return false;
}
if (isset($response_data->Rc)) {
if ($response_data->Rc === "0" || $response_data->Rc === 0) {
return true;
} else {
$errorDetails = [
'error' => $response_data->Text ?? 'No error message',
'customerId' => $response_data->CustomerId ?? 'unknown',
'batchTimestamp' => $response_data->BatchTimestamp ?? null,
'rawResponse' => json_encode($response_data)
];
error_log('Ошибка отвязки карты: ' . print_r($errorDetails, true));
return false;
}
} else {
error_log('Некорректный формат ответа при отвязке карты: ' . json_encode($response_data));