Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
restservice.php
1<?php
2
4
15use Bitrix\Crm\Invoice;
16
17if (!Main\Loader::includeModule('rest'))
18{
19 return;
20}
21
26class RestService extends \IRestService
27{
28 const SCOPE = 'pay_system';
29
30 const ERROR_CHECK_FAILURE = 'ERROR_CHECK_FAILURE';
31 const ERROR_HANDLER_ALREADY_EXIST = 'ERROR_HANDLER_ALREADY_EXIST';
32 const ERROR_HANDLER_NOT_FOUND = 'ERROR_HANDLER_NOT_FOUND';
33 const ERROR_PERSON_TYPE_NOT_FOUND = 'ERROR_PERSON_TYPE_NOT_FOUND';
34 const ERROR_PAY_SYSTEM_NOT_FOUND = 'ERROR_PAY_SYSTEM_NOT_FOUND';
35
36 private const ERROR_HANDLER_ADD = 'ERROR_HANDLER_ADD';
37 private const ERROR_HANDLER_UPDATE = 'ERROR_HANDLER_UPDATE';
38 private const ERROR_HANDLER_DELETE = 'ERROR_HANDLER_DELETE';
39
40 const ERROR_PAY_SYSTEM_ADD = 'ERROR_PAY_SYSTEM_ADD';
41 const ERROR_PAY_SYSTEM_UPDATE = 'ERROR_PAY_SYSTEM_UPDATE';
42 const ERROR_PAY_SYSTEM_DELETE = 'ERROR_PAY_SYSTEM_DELETE';
43
44 const ERROR_INTERNAL_INVOICE_NOT_FOUND = 'ERROR_INTERNAL_INVOICE_NOT_FOUND';
45 const ERROR_INTERNAL_ORDER_NOT_FOUND = 'ERROR_INTERNAL_ORDER_NOT_FOUND';
46 const ERROR_PROCESS_REQUEST_RESULT = 'ERROR_PROCESS_REQUEST_RESULT';
47 const ERROR_PAY_INVOICE_NOT_SUPPORTED = 'ERROR_INVOICE_NO_SUPPORTED';
48
49 private const ALLOWED_PAYSYSTEM_FIELDS = [
50 'ID', 'PERSON_TYPE_ID', 'NAME', 'PSA_NAME', 'SORT', 'DESCRIPTION', 'ACTION_FILE', 'RESULT_FILE',
51 'NEW_WINDOW', 'TARIF', 'PS_MODE', 'HAVE_PAYMENT', 'HAVE_ACTION', 'HAVE_RESULT', 'HAVE_PREPAY',
52 'HAVE_PRICE', 'HAVE_RESULT_RECEIVE', 'ENCODING', 'LOGOTIP', 'ACTIVE', 'ALLOW_EDIT_PAYMENT',
53 'IS_CASH', 'AUTO_CHANGE_1C', 'CAN_PRINT_CHECK', 'ENTITY_REGISTRY_TYPE', 'XML_ID'
54 ];
55
56 public static function onRestAppDelete(array $fields): void
57 {
58 if (!Main\Loader::includeModule('rest'))
59 {
60 return;
61 }
62
63 if (empty($fields['APP_ID']) || empty($fields['CLEAN']) || $fields['CLEAN'] !== true)
64 {
65 return;
66 }
67
68 $app = Rest\AppTable::getByClientId($fields['APP_ID']);
69 if (!$app)
70 {
71 return;
72 }
73
74 $restHandlerResult = Internals\PaySystemRestHandlersTable::getList([
75 'select' => ['ID', 'CODE'],
76 'filter' => [
77 '=APP_ID' => $app['CLIENT_ID'],
78 ],
79 ]);
80 while ($restHandler = $restHandlerResult->fetch())
81 {
82 $paySystemResult = Manager::getList([
83 'select' => ['ID'],
84 'filter' => [
85 '=ACTION_FILE' => $restHandler['CODE'],
86 ],
87 ]);
88 while ($paySystem = $paySystemResult->fetch())
89 {
90 Manager::delete($paySystem['ID']);
91 }
92
93 Internals\PaySystemRestHandlersTable::delete($restHandler['ID']);
94 }
95 }
96
100 public static function onRestServiceBuildDescription()
101 {
102 return [
103 static::SCOPE => [
104 'sale.paysystem.handler.add' => [__CLASS__, 'addHandler'],
105 'sale.paysystem.handler.update' => [__CLASS__, 'updateHandler'],
106 'sale.paysystem.handler.delete' => [__CLASS__, 'deleteHandler'],
107 'sale.paysystem.handler.list' => [__CLASS__, 'getHandlerList'],
108
109 'sale.paysystem.add' => [__CLASS__, 'addPaySystem'],
110 'sale.paysystem.update' => [__CLASS__, 'updatePaySystem'],
111 'sale.paysystem.delete' => [__CLASS__, 'deletePaySystem'],
112 'sale.paysystem.list' => [__CLASS__, 'getPaySystemList'],
113
114 'sale.paysystem.settings.get' => [__CLASS__, 'getSettings'],
115 'sale.paysystem.settings.update' => [__CLASS__, 'updateSettings'],
116
117 'sale.paysystem.settings.invoice.get' => [__CLASS__, 'getSettingsByInvoice'],
118 'sale.paysystem.settings.payment.get' => [__CLASS__, 'getSettingsByPayment'],
119
120 'sale.paysystem.pay.invoice' => [__CLASS__, 'payInvoice'],
121 'sale.paysystem.pay.payment' => [__CLASS__, 'payPayment'],
122 ]
123 ];
124 }
125
133 public static function addPaySystem(array $params, $n, \CRestServer $server)
134 {
135 static::checkPaySystemPermission();
136
137 $params = self::preparePaySystemParams($params, $server);
138
139 if (!isset($params['ENTITY_REGISTRY_TYPE']))
140 {
141 if (IsModuleInstalled('crm'))
142 {
143 $params['ENTITY_REGISTRY_TYPE'] = REGISTRY_TYPE_CRM_INVOICE;
144 }
145 else
146 {
147 $params['ENTITY_REGISTRY_TYPE'] = Registry::REGISTRY_TYPE_ORDER;
148 }
149 }
150
151 static::checkParamsBeforePaySystemAdd($params);
152
153 $fields = [
154 'NAME' => $params['NAME'],
155 'PSA_NAME' => $params['NAME'],
156 'NEW_WINDOW' => $params['NEW_WINDOW'] ?: 'N',
157 'ACTIVE' => $params['ACTIVE'] ?: 'N',
158 'PERSON_TYPE_ID' => $params['PERSON_TYPE_ID'],
159 'ACTION_FILE' => $params['BX_REST_HANDLER'],
160 'HAVE_PREPAY' => 'N',
161 'HAVE_RESULT' => 'N',
162 'HAVE_ACTION' => 'N',
163 'HAVE_PAYMENT' => 'N',
164 'HAVE_RESULT_RECEIVE' => 'Y',
165 'ENTITY_REGISTRY_TYPE' => $params['ENTITY_REGISTRY_TYPE'],
166 'DESCRIPTION' => $params['DESCRIPTION'],
167 'XML_ID' => $params['XML_ID'],
168 ];
169
170 if (isset($params['LOGOTIP']))
171 {
172 $fields['LOGOTIP'] = self::saveFile($params['LOGOTIP']);
173 }
174
175 $result = Manager::add($fields);
176 if ($result->isSuccess())
177 {
178 $id = $result->getId();
179 Manager::update($id, array('PAY_SYSTEM_ID' => $id));
180
181 foreach ($params['SETTINGS'] as $key => $value)
182 {
184 $key,
186 $params['PERSON_TYPE_ID'],
187 [
188 'PROVIDER_KEY' => $value['TYPE'],
189 'PROVIDER_VALUE' => $value['VALUE']
190 ]
191 );
192 }
193
194 if ($fields['PERSON_TYPE_ID'] > 0)
195 {
196 static::savePersonTypeId($id, $params['PERSON_TYPE_ID']);
197 }
198
199 static::logAnalytics(
200 'addPaySystem' . $params['ENTITY_REGISTRY_TYPE'],
201 $params['BX_REST_HANDLER'],
202 $params['PERSON_TYPE_ID'],
203 $server
204 );
205
206 return $id;
207 }
208
209 $error = implode("\n", $result->getErrorMessages());
210 throw new RestException($error, self::ERROR_PAY_SYSTEM_ADD);
211 }
212
218 protected static function checkParamsBeforePaySystemAdd($params)
219 {
220 if (empty($params['BX_REST_HANDLER']))
221 {
222 throw new RestException('Parameter BX_REST_HANDLER is not defined', self::ERROR_CHECK_FAILURE);
223 }
224
225 $handlerData = self::getHandlerData($params['BX_REST_HANDLER']);
226 if (!$handlerData)
227 {
228 throw new RestException('Handler not found', self::ERROR_HANDLER_NOT_FOUND);
229 }
230
231 if ($params['APP_ID'] && !empty($handlerData['APP_ID']) && $handlerData['APP_ID'] !== $params['APP_ID'])
232 {
233 throw new AccessException();
234 }
235
236 $dbRes = Internals\PersonTypeTable::getList([
237 'filter' => [
238 '=ID' => $params['PERSON_TYPE_ID'],
239 '=ENTITY_REGISTRY_TYPE' => $params['ENTITY_REGISTRY_TYPE'],
240 ]
241 ]);
242 if (!$dbRes->fetch())
243 {
244 throw new RestException('Incorrect person type id!', self::ERROR_PERSON_TYPE_NOT_FOUND);
245 }
246 }
247
252 private static function savePersonTypeId($serviceId, $personTypeId)
253 {
254 $params = [
255 'filter' => [
256 "SERVICE_ID" => $serviceId,
257 "SERVICE_TYPE" => Restrictions\Manager::SERVICE_TYPE_PAYMENT,
258 "=CLASS_NAME" => '\\'.Restrictions\PersonType::class
259 ]
260 ];
261
262 $dbRes = Internals\ServiceRestrictionTable::getList($params);
263 if ($data = $dbRes->fetch())
264 {
265 $restrictionId = $data['ID'];
266 }
267 else
268 {
269 $restrictionId = 0;
270 }
271
272 $fields = array(
273 "SERVICE_ID" => $serviceId,
274 "SERVICE_TYPE" => Restrictions\Manager::SERVICE_TYPE_PAYMENT,
275 "SORT" => 100,
276 "PARAMS" => array('PERSON_TYPE_ID' => array($personTypeId))
277 );
278
279 Restrictions\PersonType::save($fields, $restrictionId);
280 }
281
288 public static function updatePaySystem(array $params, $n, \CRestServer $server)
289 {
290 static::checkPaySystemPermission();
291
292 $params = self::preparePaySystemParams($params, $server);
293
294 static::checkParamsBeforePaySystemUpdate($params);
295
296 $fields = array();
297 if (isset($params['FIELDS']['NAME']))
298 {
299 $fields['NAME'] = $params['FIELDS']['NAME'];
300 }
301
302 if (isset($params['FIELDS']['DESCRIPTION']))
303 {
304 $fields['DESCRIPTION'] = $params['FIELDS']['DESCRIPTION'];
305 }
306
307 if (isset($params['FIELDS']['NEW_WINDOW']))
308 {
309 $fields['NEW_WINDOW'] = $params['FIELDS']['NEW_WINDOW'];
310 }
311
312 if (isset($params['FIELDS']['ACTIVE']))
313 {
314 $fields['ACTIVE'] = $params['FIELDS']['ACTIVE'];
315 }
316
317 if (isset($params['FIELDS']['PERSON_TYPE_ID']))
318 {
319 $fields['PERSON_TYPE_ID'] = $params['FIELDS']['PERSON_TYPE_ID'];
320 }
321
322 if (isset($params['FIELDS']['BX_REST_HANDLER']))
323 {
324 $fields['ACTION_FILE'] = $params['FIELDS']['BX_REST_HANDLER'];
325 }
326
327 if (isset($params['FIELDS']['LOGOTIP']))
328 {
329 $fields['LOGOTIP'] = self::saveFile($params['FIELDS']['LOGOTIP']);
330 }
331
332 $result = Manager::update($params['ID'], $fields);
333
334 if ($fields['PERSON_TYPE_ID'] > 0)
335 {
336 static::savePersonTypeId($params['ID'], $fields['PERSON_TYPE_ID']);
337 }
338
339 return $result->isSuccess();
340 }
341
347 protected static function checkParamsBeforePaySystemUpdate($params)
348 {
349 $handlerList = Manager::getHandlerList();
350
351 $handler = $params['FIELDS']['BX_REST_HANDLER'];
352 if (!isset($handlerList['USER'][$handler]) && !isset($handlerList['SYSTEM'][$handler]))
353 {
354 throw new RestException('Handler not found', self::ERROR_HANDLER_NOT_FOUND);
355 }
356
357 $dbRes = Manager::getList([
358 'filter' => [
359 'ID' => $params['ID']
360 ]
361 ]);
362
363 $data = $dbRes->fetch();
364 if (!$data)
365 {
366 throw new RestException('Pay system not found', self::ERROR_PAY_SYSTEM_NOT_FOUND);
367 }
368
369 if (!self::hasAccessToPaySystem($data, $params['APP_ID']))
370 {
371 throw new AccessException();
372 }
373
374 $dbRes = Internals\PersonTypeTable::getList([
375 'filter' => [
376 '=ID' => $params['FIELDS']['PERSON_TYPE_ID'],
377 '=ENTITY_REGISTRY_TYPE' => $data['ENTITY_REGISTRY_TYPE'],
378 ]
379 ]);
380 if (!$dbRes->fetch())
381 {
382 throw new RestException('Incorrect person type id!', self::ERROR_PERSON_TYPE_NOT_FOUND);
383 }
384 }
385
393 public static function updateSettings(array $params, $n, \CRestServer $server)
394 {
395 static::checkPaySystemPermission();
396
397 $params = self::preparePaySystemParams($params, $server);
398
399 static::checkParamsBeforeSettingsUpdate($params);
400
401 foreach ($params['SETTINGS'] as $field => $value)
402 {
404 $field,
405 Service::PAY_SYSTEM_PREFIX.$params['ID'],
406 $params['PERSON_TYPE_ID'],
407 [
408 'PROVIDER_KEY' => $value['TYPE'],
409 'PROVIDER_VALUE' => $value['VALUE']
410 ]
411 );
412
413 if (!$result->isSuccess())
414 {
415 return false;
416 }
417 }
418
419 return true;
420 }
421
426 protected static function checkParamsBeforeSettingsUpdate($params)
427 {
428 if (!isset($params['ID']))
429 {
430 throw new RestException('Parameter ID is not defined', self::ERROR_CHECK_FAILURE);
431 }
432
433 $item = Manager::getById($params['ID']);
434 if (!$item)
435 {
436 throw new RestException('Pay system not found', static::ERROR_CHECK_FAILURE);
437 }
438
439 if (!isset($params['SETTINGS']) || empty($params['SETTINGS']))
440 {
441 throw new RestException('Parameter SETTINGS is not defined or empty', self::ERROR_HANDLER_NOT_FOUND);
442 }
443
444 if (!self::hasAccessToPaySystem($item, $params['APP_ID']))
445 {
446 throw new AccessException();
447 }
448 }
449
456 public static function getSettings(array $params, $n, \CRestServer $server)
457 {
458 static::checkPaySystemPermission();
459
460 $params = self::preparePaySystemParams($params, $server);
461
462 static::checkParamsBeforeSettingsGet($params);
463
464 $result = [];
465
466 $consumers = BusinessValue::getConsumers();
467 $codes = $consumers[Service::PAY_SYSTEM_PREFIX.$params['ID']]['CODES'];
468
469 foreach ($codes as $field => $value)
470 {
471 $mapping = BusinessValue::getMapping(
472 $field,
473 Service::PAY_SYSTEM_PREFIX.$params['ID'],
474 $params['PERSON_TYPE_ID']
475 );
476
477 $result[$field] = [
478 'TYPE' => $mapping['PROVIDER_KEY'],
479 'VALUE' => $mapping['PROVIDER_VALUE']
480 ];
481 }
482
483 return $result;
484 }
485
491 protected static function checkParamsBeforeSettingsGet($params)
492 {
493 if (!isset($params['PERSON_TYPE_ID']))
494 {
495 throw new RestException('Parameter PERSON_TYPE_ID is not defined', self::ERROR_CHECK_FAILURE);
496 }
497
498 if (!isset($params['ID']))
499 {
500 throw new RestException('Parameter ID is not defined', self::ERROR_CHECK_FAILURE);
501 }
502
503 $item = Manager::getById($params['ID']);
504 if (!$item)
505 {
506 throw new RestException('Pay system not found', static::ERROR_CHECK_FAILURE);
507 }
508
509 if (!self::hasAccessToPaySystem($item, $params['APP_ID']))
510 {
511 throw new AccessException();
512 }
513 }
514
519 public static function deletePaySystem(array $params, $n, \CRestServer $server)
520 {
521 static::checkPaySystemPermission();
522
523 $params = self::preparePaySystemParams($params, $server);
524
525 static::checkParamsBeforePaySystemDelete($params);
526
527 $result = Manager::delete($params['ID']);
528
529 return $result->isSuccess();
530 }
531
537 protected static function checkParamsBeforePaySystemDelete($params)
538 {
539 $data = Manager::getById($params['ID']);
540 if (!$data)
541 {
542 throw new RestException('Pay system not found', self::ERROR_PAY_SYSTEM_NOT_FOUND);
543 }
544
545 if (!self::hasAccessToPaySystem($data, $params['APP_ID']))
546 {
547 throw new AccessException();
548 }
549 }
550
558 public static function addHandler(array $params, $n, \CRestServer $server)
559 {
560 static::checkPaySystemPermission();
561
562 $params = self::prepareHandlerParams($params, $server);
563
564 self::checkParamsOnAddHandler($params);
565
566 $data = [
567 'NAME' => $params['NAME'],
568 'CODE' => $params['CODE'],
569 'SORT' => $params['SORT'] ?: 100,
570 'SETTINGS' => $params['SETTINGS'],
571 'APP_ID' => $params['APP_ID'],
572 ];
573
574 $result = Internals\PaySystemRestHandlersTable::add($data);
575 if ($result->isSuccess())
576 {
577 return $result->getId();
578 }
579
580 $error = implode("\n", $result->getErrorMessages());
581 throw new RestException($error, self::ERROR_HANDLER_ADD);
582 }
583
588 private static function checkParamsOnAddHandler(array $params)
589 {
590 if (!isset($params['NAME']))
591 {
592 throw new RestException('Parameter NAME is not defined', self::ERROR_CHECK_FAILURE);
593 }
594
595 if (!isset($params['CODE']))
596 {
597 throw new RestException('Parameter CODE is not defined', self::ERROR_CHECK_FAILURE);
598 }
599
600 if (!isset($params['SETTINGS']))
601 {
602 throw new RestException('Parameter SETTINGS is not defined', self::ERROR_CHECK_FAILURE);
603 }
604
605 if (!isset($params['SETTINGS']['CODES']))
606 {
607 throw new RestException('Parameter SETTINGS[CODES] is not defined', self::ERROR_CHECK_FAILURE);
608 }
609
610 if (
611 empty($params['SETTINGS']['FORM_DATA'])
612 && empty($params['SETTINGS']['CHECKOUT_DATA'])
613 && empty($params['SETTINGS']['IFRAME_DATA'])
614 )
615 {
616 throw new RestException(
617 'Parameter SETTINGS[FORM_DATA] or SETTINGS[CHECKOUT_DATA] or SETTINGS[IFRAME_DATA] is not defined',
618 self::ERROR_CHECK_FAILURE
619 );
620 }
621
622 if (
623 !empty($params['SETTINGS']['FORM_DATA'])
624 && empty($params['SETTINGS']['FORM_DATA']['ACTION_URI'])
625 )
626 {
627 throw new RestException('Parameter SETTINGS[FORM_DATA][ACTION_URI] is not defined', self::ERROR_CHECK_FAILURE);
628 }
629
630 if (
631 !empty($params['SETTINGS']['CHECKOUT_DATA'])
632 && empty($params['SETTINGS']['CHECKOUT_DATA']['ACTION_URI'])
633 )
634 {
635 throw new RestException('Parameter SETTINGS[IFRAME_DATA][ACTION_URI] is not defined', self::ERROR_CHECK_FAILURE);
636 }
637
638 if (
639 !empty($params['SETTINGS']['IFRAME_DATA'])
640 && empty($params['SETTINGS']['IFRAME_DATA']['ACTION_URI'])
641 )
642 {
643 throw new RestException('Parameter SETTINGS[IFRAME_DATA][ACTION_URI] is not defined', self::ERROR_CHECK_FAILURE);
644 }
645
646 if (
647 isset($params['SETTINGS']['CLIENT_TYPE'])
648 && !ClientType::isValid((string)$params['SETTINGS']['CLIENT_TYPE'])
649 )
650 {
651 throw new RestException('Parameter value SETTINGS[CLIENT_TYPE] is invalid', self::ERROR_CHECK_FAILURE);
652 }
653
654 $dbRes = Internals\PaySystemRestHandlersTable::getList([
655 'filter' => [
656 '=CODE' => $params['CODE']
657 ]
658 ]);
659 if ($dbRes->fetch())
660 {
661 throw new RestException('Handler already exists!', self::ERROR_HANDLER_ALREADY_EXIST);
662 }
663 }
664
672 public static function updateHandler(array $params, $n, \CRestServer $server)
673 {
674 static::checkPaySystemPermission();
675
676 $params = self::prepareHandlerParams($params, $server);
677
678 self::checkParamsOnUpdateHandler($params);
679
680 $result = Internals\PaySystemRestHandlersTable::update($params['ID'], $params['FIELDS']);
681 if ($result->isSuccess())
682 {
683 return true;
684 }
685
686 $error = implode("\n", $result->getErrorMessages());
687 throw new RestException($error, self::ERROR_HANDLER_UPDATE);
688 }
689
695 private static function checkParamsOnUpdateHandler(array $params)
696 {
697 if (!isset($params['FIELDS']))
698 {
699 throw new RestException('Parameter FIELDS is not defined', self::ERROR_CHECK_FAILURE);
700 }
701
702 if (
703 isset($params['SETTINGS']['CLIENT_TYPE'])
704 && !ClientType::isValid((string)$params['SETTINGS']['CLIENT_TYPE'])
705 )
706 {
707 throw new RestException('Parameter value SETTINGS[CLIENT_TYPE] is invalid', self::ERROR_CHECK_FAILURE);
708 }
709
710 $paySystemRestHandlers = Internals\PaySystemRestHandlersTable::getList(array(
711 'filter' => array(
712 'ID' => $params['ID']
713 )
714 ))->fetch();
715 if (!$paySystemRestHandlers)
716 {
717 throw new RestException('Handler not found', self::ERROR_HANDLER_NOT_FOUND);
718 }
719
720 if ($params['APP_ID'] && !empty($paySystemRestHandlers['APP_ID']) && $paySystemRestHandlers['APP_ID'] !== $params['APP_ID'])
721 {
722 throw new AccessException();
723 }
724 }
725
733 public static function deleteHandler(array $params, $n, \CRestServer $server)
734 {
735 static::checkPaySystemPermission();
736
737 $params = self::prepareHandlerParams($params, $server);
738
739 self::checkParamsOnDeleteHandler($params);
740
741 $result = Internals\PaySystemRestHandlersTable::delete($params['ID']);
742 if ($result->isSuccess())
743 {
744 return true;
745 }
746
747 $error = implode("\n", $result->getErrorMessages());
748 throw new RestException($error, self::ERROR_HANDLER_DELETE);
749 }
750
755 private static function checkParamsOnDeleteHandler($params): void
756 {
757 $dbRes = Internals\PaySystemRestHandlersTable::getList(array(
758 'filter' => array(
759 'ID' => $params['ID']
760 )
761 ));
762 $data = $dbRes->fetch();
763 if (!$data)
764 {
765 throw new RestException('Handler not found', self::ERROR_HANDLER_NOT_FOUND);
766 }
767
768 if ($params['APP_ID'] && !empty($data['APP_ID']) && $data['APP_ID'] !== $params['APP_ID'])
769 {
770 throw new AccessException();
771 }
772
773 $dbRes = Manager::getList(array('filter' => array('ACTION_FILE' => $data['CODE'])));
774 if ($dbRes->fetch())
775 {
776 throw new RestException('Pay system with handler '.ToUpper($data['CODE']).' exists!', self::ERROR_PAY_SYSTEM_DELETE);
777 }
778 }
779
786 public static function getHandlerList(array $params, $n, \CRestServer $server)
787 {
788 static::checkPaySystemPermission();
789
790 $result = array();
791 $dbRes = Internals\PaySystemRestHandlersTable::getList([
792 'select' => ['ID', 'NAME', 'CODE', 'SORT', 'SETTINGS'],
793 ]);
794 while ($item = $dbRes->fetch())
795 {
796 $result[] = $item;
797 }
798
799 return $result;
800 }
801
808 public static function getPaySystemList(array $params, $n, \CRestServer $server)
809 {
810 static::checkPaySystemPermission();
811 $params = self::prepareIncomingParams($params);
812 self::checkParamsBeforePaySystemListGet($params);
813
814 $select =
815 isset($params['SELECT']) && is_array($params['SELECT'])
816 ? array_flip(self::prepareIncomingParams(array_flip($params['SELECT'])))
817 : self::ALLOWED_PAYSYSTEM_FIELDS
818 ;
819
820 $filter = [];
821 $filterFromParams = isset($params['FILTER']) && is_array($params['FILTER']) ? $params['FILTER'] : [];
822 if ($filterFromParams)
823 {
824 $incomingFieldsMap = self::getIncomingFieldsMap();
825 foreach ($filterFromParams as $rawName => $value)
826 {
827 $filterField = \CSqlUtil::GetFilterOperation($rawName);
828 $fieldName = $incomingFieldsMap[$filterField['FIELD']] ?? $filterField['FIELD'];
829 $filter[$filterField['OPERATION'] . $fieldName] = $value;
830 }
831 }
832
833 $order =
834 isset($params['ORDER']) && is_array($params['ORDER'])
835 ? self::prepareIncomingParams($params['ORDER'])
836 : []
837 ;
838
839 $result = array();
840 $dbRes = Manager::getList([
841 'select' => $select,
842 'filter' => $filter,
843 'order' => $order,
844 ]);
845 while ($item = $dbRes->fetch())
846 {
847 $result[] = self::prepareOutcomingFields($item);
848 }
849
850 return $result;
851 }
852
857 private static function checkParamsBeforePaySystemListGet(array $params)
858 {
859 $select = isset($params['SELECT']) && is_array($params['SELECT']) ? $params['SELECT'] : [];
860 if ($select)
861 {
862 $select = array_flip(self::prepareIncomingParams(array_flip($select)));
863 $diffSelect = array_diff($select, self::ALLOWED_PAYSYSTEM_FIELDS);
864
865 if ($diffSelect)
866 {
867 throw new RestException(implode(', ', $diffSelect) . ' not allowed for select');
868 }
869 }
870
871 $filter = isset($params['FILTER']) && is_array($params['FILTER']) ? $params['FILTER'] : [];
872 if ($filter)
873 {
874 $filterFields = [];
875 foreach ($filter as $rawName => $value)
876 {
877 $filterField = \CSqlUtil::GetFilterOperation($rawName);
878 if (isset($filterField['FIELD']))
879 {
880 $filterFields[] = $filterField['FIELD'];
881 }
882 }
883
884 $filterFields = array_flip(self::prepareIncomingParams(array_flip($filterFields)));
885 $diffFilter = array_diff($filterFields, self::ALLOWED_PAYSYSTEM_FIELDS);
886 if ($diffFilter)
887 {
888 throw new RestException(implode(', ', $diffFilter) . ' not allowed for filter');
889 }
890 }
891
892 $order =
893 isset($params['ORDER']) && is_array($params['ORDER'])
894 ? self::prepareIncomingParams($params['ORDER'])
895 : []
896 ;
897 if ($order)
898 {
899 $diffOrder = array_diff(array_keys($order), self::ALLOWED_PAYSYSTEM_FIELDS);
900 if ($diffOrder)
901 {
902 throw new RestException(implode(', ', $diffOrder) . ' not allowed for order');
903 }
904 }
905 }
906
914 public static function getSettingsByInvoice(array $params, $n, \CRestServer $server)
915 {
916 static::checkOrderPermission();
917
918 $params = self::preparePaySystemParams($params, $server);
919
920 self::checkParamsBeforeSettingsByInvoiceGet($params);
921
922 if (isset($params['PAY_SYSTEM_ID']))
923 {
924 $service = Manager::getObjectById($params['PAY_SYSTEM_ID']);
925 }
926 else
927 {
928 $dbRes = Manager::getList(array('filter' => array('=ACTION_FILE' => $params['BX_REST_HANDLER'])));
929 $item = $dbRes->fetch();
930 if (!$item)
931 {
932 throw new RestException('Pay system with handler '.$params['BX_REST_HANDLER'].' not found', self::ERROR_PAY_SYSTEM_NOT_FOUND);
933 }
934
935 $service = new Service($item);
936 }
937
938 $invoice = Invoice\Invoice::load($params['INVOICE_ID']);
939 if ($invoice)
940 {
941 $paymentCollection = $invoice->getPaymentCollection();
942 if ($paymentCollection)
943 {
945 foreach ($paymentCollection as $payment)
946 {
947 if (!$payment->isInner())
948 {
949 return $service->getParamsBusValue($payment);
950 }
951 }
952 }
953 }
954
955 throw new RestException('Invoice #'.$params['INVOICE_ID'].' not found', self::ERROR_INTERNAL_INVOICE_NOT_FOUND);
956 }
957
965 public static function getSettingsByPayment(array $params, $n, \CRestServer $server)
966 {
967 static::checkOrderPermission();
968
969 $params = self::preparePaySystemParams($params, $server);
970
971 self::checkParamsBeforeSettingsByPaymentGet($params);
972
973 list($orderId, $paymentId) = Manager::getIdsByPayment($params['PAYMENT_ID']);
974
976
978 $orderClassName = $registry->getOrderClassName();
979 $order = $orderClassName::load($orderId);
980 if ($order)
981 {
982 $paymentCollection = $order->getPaymentCollection();
983
985 $payment = $paymentCollection->getItemById($paymentId);
986
987 $service = Manager::getObjectById($params['PAY_SYSTEM_ID']);
988
989 return $service->getParamsBusValue($payment);
990 }
991
992 throw new RestException('Order #'.$orderId.' not found', self::ERROR_INTERNAL_ORDER_NOT_FOUND);
993 }
994
1002 public static function payInvoice(array $params, $n, \CRestServer $server)
1003 {
1004 if (!Main\Loader::includeModule('crm'))
1005 {
1006 throw new RestException('Pay invoice is not supported!', self::ERROR_PAY_INVOICE_NOT_SUPPORTED);
1007 }
1008
1009 static::checkOrderPermission();
1010
1011 $params = self::prepareIncomingParams($params);
1012
1013 self::checkParamsForInvoice($params);
1014
1015 $dbRes = Invoice\Payment::getList(array(
1016 'select' => array('ID'),
1017 'filter' => array(
1018 'ORDER_ID' => $params['INVOICE_ID'],
1019 '!PAY_SYSTEM_ID' => Manager::getInnerPaySystemId(),
1020 )
1021 ));
1022
1023 $payment = $dbRes->fetch();
1024 if (!$payment)
1025 {
1026 throw new RestException('Invoice #'.$params['INVOICE_ID'].' not found', self::ERROR_INTERNAL_INVOICE_NOT_FOUND);
1027 }
1028
1029 $params['PAYMENT_ID'] = $payment['ID'];
1030
1031 $filter = [
1032 '=ENTITY_REGISTRY_TYPE' => REGISTRY_TYPE_CRM_INVOICE
1033 ];
1034
1035 if (isset($params['PAY_SYSTEM_ID']))
1036 {
1037 $filter['=ID'] = $params['PAY_SYSTEM_ID'];
1038 }
1039 else
1040 {
1041 $filter['=ACTION_FILE'] = $params['BX_REST_HANDLER'];
1042 }
1043
1044 $dbRes = Manager::getList([
1045 'select' => ['ID'],
1046 'filter' => $filter
1047 ]);
1048 $item = $dbRes->fetch();
1049 if (!$item)
1050 {
1051 throw new RestException('Pay system not found', static::ERROR_PROCESS_REQUEST_RESULT);
1052 }
1053
1054 $params['PAY_SYSTEM_ID'] = $item['ID'];
1055
1056 return self::payPaymentInternal($params, $server);
1057 }
1058
1065 public static function payPayment(array $params, $n, \CRestServer $server)
1066 {
1067 static::checkOrderPermission();
1068
1069 $params = self::prepareIncomingParams($params);
1070
1071 self::checkParamsForPayment($params);
1072
1073 return self::payPaymentInternal($params, $server);
1074 }
1075
1082 private static function payPaymentInternal(array $params, \CRestServer $restServer)
1083 {
1084 $context = Main\Context::getCurrent();
1085 $server = $context->getServer();
1086
1087 $request = new Main\HttpRequest($server, array(), $params, array(), array());
1088
1089 $service = Manager::getObjectById($params['PAY_SYSTEM_ID']);
1090
1091 $result = $service->processRequest($request);
1092 if (!$result->isSuccess())
1093 {
1094 $error = join("\n", $result->getErrorMessages());
1095 throw new RestException($error, static::ERROR_PROCESS_REQUEST_RESULT);
1096 }
1097
1098 static::logAnalytics(
1099 'payPayment' . $service->getField('ENTITY_REGISTRY_TYPE'),
1100 $service->getField('ACTION_FILE'),
1101 $service->getField('PERSON_TYPE_ID'),
1102 $restServer
1103 );
1104
1105 return true;
1106 }
1107
1113 private static function arrayChangeKeyCaseRecursive(array $data, $case = CASE_UPPER)
1114 {
1115 return array_map(static function ($item) use ($case) {
1116 if (is_array($item))
1117 {
1118 $item = self::arrayChangeKeyCaseRecursive($item, $case);
1119 }
1120 return $item;
1121 }, array_change_key_case($data, $case));
1122 }
1123
1128 private static function prepareIncomingParams(array $data): array
1129 {
1130 return self::replaceIncomingKeys(self::arrayChangeKeyCaseRecursive($data));
1131 }
1132
1138 private static function prepareHandlerParams(array $data, \CRestServer $server): array
1139 {
1140 $data = self::replaceIncomingKeys(array_change_key_case($data, CASE_UPPER));
1141 $data['APP_ID'] = $server->getClientId();
1142
1143 return $data;
1144 }
1145
1146 private static function preparePaySystemParams(array $data, \CRestServer $server): array
1147 {
1148 $data = self::prepareIncomingParams($data);
1149 $data['APP_ID'] = $server->getClientId();
1150
1151 return $data;
1152 }
1153
1158 private static function checkParamsForInvoice(array $params)
1159 {
1160 if (!isset($params['BX_REST_HANDLER']) && !isset($params['PAY_SYSTEM_ID']))
1161 {
1162 throw new RestException('Empty field BX_REST_HANDLER and PAY_SYSTEM_ID', self::ERROR_CHECK_FAILURE);
1163 }
1164
1165 if (isset($params['PAY_SYSTEM_ID']))
1166 {
1167 $data = Manager::getById($params['PAY_SYSTEM_ID']);
1168 if (!$data)
1169 {
1170 throw new RestException('Pay system with ID='.$params['PAY_SYSTEM_ID'].' not found', static::ERROR_CHECK_FAILURE);
1171 }
1172 }
1173
1174 if (isset($params['BX_REST_HANDLER']))
1175 {
1176 $dbRes = Internals\PaySystemRestHandlersTable::getList(array(
1177 'filter' => array(
1178 '=CODE' => $params['BX_REST_HANDLER']
1179 )
1180 ));
1181 if (!$dbRes->fetch())
1182 {
1183 throw new RestException('Incorrect rest handler code', static::ERROR_CHECK_FAILURE);
1184 }
1185 }
1186
1187 if (empty($params['INVOICE_ID']))
1188 {
1189 throw new RestException('Empty field INVOICE_ID!', self::ERROR_CHECK_FAILURE);
1190 }
1191 }
1192
1198 private static function checkParamsBeforeSettingsByInvoiceGet(array $params)
1199 {
1200 if (!isset($params['BX_REST_HANDLER']) && !isset($params['PAY_SYSTEM_ID']))
1201 {
1202 throw new RestException('Empty field BX_REST_HANDLER and PAY_SYSTEM_ID', self::ERROR_CHECK_FAILURE);
1203 }
1204
1205 if (empty($params['INVOICE_ID']))
1206 {
1207 throw new RestException('Empty field INVOICE_ID', self::ERROR_CHECK_FAILURE);
1208 }
1209
1210 if (isset($params['PAY_SYSTEM_ID']))
1211 {
1212 $data = Manager::getById($params['PAY_SYSTEM_ID']);
1213 if (!$data)
1214 {
1215 throw new RestException('Pay system with ID='.$params['PAY_SYSTEM_ID'].' not found', static::ERROR_CHECK_FAILURE);
1216 }
1217
1218 if (!self::hasAccessToPaySystem($data, $params['APP_ID']))
1219 {
1220 throw new AccessException();
1221 }
1222 }
1223
1224 if (isset($params['BX_REST_HANDLER']))
1225 {
1226 $dbRes = Internals\PaySystemRestHandlersTable::getList(array(
1227 'filter' => array(
1228 '=CODE' => $params['BX_REST_HANDLER']
1229 )
1230 ));
1231
1232 $handlerData = $dbRes->fetch();
1233 if (!$handlerData)
1234 {
1235 throw new RestException('Incorrect rest handler code', static::ERROR_CHECK_FAILURE);
1236 }
1237
1238 if ($params['APP_ID'] && !empty($handlerData['APP_ID']) && $handlerData['APP_ID'] !== $params['APP_ID'])
1239 {
1240 throw new AccessException();
1241 }
1242 }
1243 }
1244
1250 private static function checkParamsForPayment(array $params)
1251 {
1252 if (empty($params['PAY_SYSTEM_ID']))
1253 {
1254 throw new RestException('Empty field PAY_SYSTEM_ID!', self::ERROR_CHECK_FAILURE);
1255 }
1256
1257 $item = Manager::getById($params['PAY_SYSTEM_ID']);
1258 if (!$item)
1259 {
1260 throw new RestException('Pay system not found', static::ERROR_CHECK_FAILURE);
1261 }
1262
1263 if (empty($params['PAYMENT_ID']))
1264 {
1265 throw new RestException('Empty field PAYMENT_ID', self::ERROR_CHECK_FAILURE);
1266 }
1267
1269
1271 $paymentClassName = $registry->getPaymentClassName();
1272 $dbRes = $paymentClassName::getList([
1273 'select' => ['ID', 'PAY_SYSTEM_ID'],
1274 'filter' => [
1275 '=ID' => $params['PAYMENT_ID'],
1276 '=PAY_SYSTEM_ID' => $params['PAY_SYSTEM_ID']
1277 ]
1278 ]);
1279
1280 if (!$dbRes->fetch())
1281 {
1282 throw new RestException(
1283 'Payment with ID='
1284 . $params['PAYMENT_ID']
1285 . ' and PAY_SYSTEM_ID='.$params['PAY_SYSTEM_ID']
1286 . ' not found', self::ERROR_CHECK_FAILURE
1287 );
1288 }
1289 }
1290
1296 private static function checkParamsBeforeSettingsByPaymentGet(array $params)
1297 {
1298 if (empty($params['PAY_SYSTEM_ID']))
1299 {
1300 throw new RestException('Empty field PAY_SYSTEM_ID!', self::ERROR_CHECK_FAILURE);
1301 }
1302
1303 if (empty($params['PAYMENT_ID']))
1304 {
1305 throw new RestException('Empty field PAYMENT_ID', self::ERROR_CHECK_FAILURE);
1306 }
1307
1308 $item = Manager::getById($params['PAY_SYSTEM_ID']);
1309 if (!$item)
1310 {
1311 throw new RestException('Pay system not found', static::ERROR_CHECK_FAILURE);
1312 }
1313
1314 if (!self::hasAccessToPaySystem($item, $params['APP_ID']))
1315 {
1316 throw new AccessException();
1317 }
1318
1320
1322 $paymentClassName = $registry->getPaymentClassName();
1323 $dbRes = $paymentClassName::getList([
1324 'select' => ['ID', 'PAY_SYSTEM_ID'],
1325 'filter' => [
1326 '=ID' => $params['PAYMENT_ID'],
1327 '=PAY_SYSTEM_ID' => $params['PAY_SYSTEM_ID']
1328 ]
1329 ]);
1330
1331 if (!$dbRes->fetch())
1332 {
1333 throw new RestException(
1334 'Payment with ID='
1335 . $params['PAYMENT_ID']
1336 . ' and PAY_SYSTEM_ID='.$params['PAY_SYSTEM_ID']
1337 . ' not found', self::ERROR_CHECK_FAILURE
1338 );
1339 }
1340 }
1341
1346 protected static function checkOrderPermission()
1347 {
1348 global $APPLICATION;
1349
1350 if (IsModuleInstalled('intranet') && Main\Loader::includeModule('crm'))
1351 {
1352 $CCrmInvoice = new \CCrmInvoice();
1353 if ($CCrmInvoice->cPerms->HavePerm('INVOICE', BX_CRM_PERM_NONE, 'WRITE')
1354 && $CCrmInvoice->cPerms->HavePerm('INVOICE', BX_CRM_PERM_NONE, 'ADD')
1355 )
1356 {
1357 throw new AccessException();
1358 }
1359 }
1360 else
1361 {
1362 $saleModulePermissions = $APPLICATION->GetGroupRight("sale");
1363
1364 if($saleModulePermissions == "D")
1365 {
1366 throw new AccessException();
1367 }
1368 }
1369 }
1370
1375 protected static function checkPaySystemPermission()
1376 {
1377 \Bitrix\Sale\Helpers\Rest\AccessChecker::checkAccessPermission();
1378 }
1379
1384 private static function saveFile($fileContent)
1385 {
1386 $file = \CRestUtil::saveFile($fileContent);
1387 if ($file)
1388 {
1389 $file['MODULE_ID'] = 'sale';
1390 return \CFile::SaveFile($file, 'sale');
1391 }
1392
1393 return null;
1394 }
1395
1399 private static function getIncomingFieldsMap(): array
1400 {
1401 return [
1402 'LOGOTYPE' => 'LOGOTIP',
1403 'TARIFF' => 'TARIF',
1404 ];
1405 }
1406
1410 private static function getOutcomingFieldsMap(): array
1411 {
1412 return [
1413 'LOGOTIP' => 'LOGOTYPE',
1414 'TARIF' => 'TARIFF',
1415 ];
1416 }
1417
1422 private static function prepareOutcomingFields(array $data): array
1423 {
1424 return self::replaceOutcomingKeys($data);
1425 }
1426
1431 private static function replaceIncomingKeys(array $data): array
1432 {
1433 return self::replaceKeys($data, self::getIncomingFieldsMap());
1434 }
1435
1440 private static function replaceOutcomingKeys(array $data): array
1441 {
1442 return self::replaceKeys($data, self::getOutcomingFieldsMap());
1443 }
1444
1450 private static function replaceKeys(array $data, array $map): array
1451 {
1452 foreach ($map as $key => $newKey)
1453 {
1454 if (array_key_exists($key, $data))
1455 {
1456 $data[$newKey] = $data[$key];
1457 unset($data[$key]);
1458 }
1459
1460 if (isset($data['FIELDS']) && array_key_exists($key, $data['FIELDS']))
1461 {
1462 $data['FIELDS'][$newKey] = $data['FIELDS'][$key];
1463 unset($data['FIELDS'][$key]);
1464 }
1465 }
1466
1467 return $data;
1468 }
1469
1470 private static function logAnalytics($action, $handler, $personType, \CRestServer $restServer) : bool
1471 {
1472 $code = '';
1473 $type = '';
1474 if ($restServer->getAuthType() === \Bitrix\Rest\OAuth\Auth::AUTH_TYPE)
1475 {
1476 $app = \Bitrix\Rest\AppTable::getByClientId($restServer->getClientId());
1477 if ($app['CODE'])
1478 {
1479 $code = $app['CODE'];
1480 $type = 'appCode';
1481 }
1482 }
1483 else
1484 {
1485 $code = $restServer->getPasswordId();
1486 $type = 'webHook';
1487 }
1488
1489 if ($code !== '')
1490 {
1491 $tag = uniqid($code, true);
1492 AddEventToStatFile(
1493 'sale',
1494 $action,
1495 $tag,
1496 $code,
1497 $type
1498 );
1499 AddEventToStatFile(
1500 'sale',
1501 $action,
1502 $tag,
1503 $handler,
1504 'handler'
1505 );
1506 AddEventToStatFile(
1507 'sale',
1508 $action,
1509 $tag,
1510 $personType,
1511 'personType'
1512 );
1513 }
1514
1515 return true;
1516 }
1517
1518 private static function hasAccessToPaySystem(array $paySystemData, string $appId = null): bool
1519 {
1520 $handlerCode = $paySystemData['ACTION_FILE'];
1521 if (Manager::isRestHandler($handlerCode))
1522 {
1523 $handlerData = self::getHandlerData($handlerCode);
1524 if ($appId && !empty($handlerData['APP_ID']) && $handlerData['APP_ID'] !== $appId)
1525 {
1526 return false;
1527 }
1528 }
1529 else
1530 {
1531 return false;
1532 }
1533
1534 return true;
1535 }
1536
1537 private static function getHandlerData(string $code): ?array
1538 {
1539 static $result = [];
1540
1541 if (!empty($result[$code]))
1542 {
1543 return $result[$code];
1544 }
1545
1546 $handlerData = Internals\PaySystemRestHandlersTable::getList([
1547 'filter' => ['CODE' => $code],
1548 'limit' => 1,
1549 ])->fetch();
1550 if (is_array($handlerData))
1551 {
1552 $result[$code] = $handlerData;
1553 }
1554
1555 return $result[$code] ?? null;
1556 }
1557}
static setMapping($codeKey, $consumerKey, $personTypeId, array $mapping, $withCommon=false)
static getMapping($codeKey, $consumerKey=null, $personTypeId=null, array $options=array())
static isValid(string $value)
static getList(array $params=array())
Definition manager.php:84
static delete($primary)
Definition manager.php:811
static add(array $data)
Definition manager.php:158
static isRestHandler($handler)
Definition manager.php:1016
static update($primary, array $data)
Definition manager.php:128
static getPaySystemList(array $params, $n, \CRestServer $server)
static updateSettings(array $params, $n, \CRestServer $server)
static onRestAppDelete(array $fields)
static getSettings(array $params, $n, \CRestServer $server)
static checkParamsBeforeSettingsUpdate($params)
static updateHandler(array $params, $n, \CRestServer $server)
static addPaySystem(array $params, $n, \CRestServer $server)
static payInvoice(array $params, $n, \CRestServer $server)
static checkParamsBeforeSettingsGet($params)
static checkParamsBeforePaySystemDelete($params)
static getHandlerList(array $params, $n, \CRestServer $server)
static deleteHandler(array $params, $n, \CRestServer $server)
static payPayment(array $params, $n, \CRestServer $server)
static updatePaySystem(array $params, $n, \CRestServer $server)
static addHandler(array $params, $n, \CRestServer $server)
static checkParamsBeforePaySystemUpdate($params)
static deletePaySystem(array $params, $n, \CRestServer $server)
static checkParamsBeforePaySystemAdd($params)
static getInstance($type)
Definition registry.php:183