├── CHANGELOG.rst ├── LICENSE ├── RELEASE.md ├── autoload.php ├── composer.json ├── docker_env ├── Dockerfile ├── Makefile ├── README.txt └── docker-compose.yml ├── examples ├── v1 │ ├── send_check_example.php │ ├── send_correction_check_example.php │ └── send_order_example.php └── v2 │ ├── send_check_example.php │ ├── send_correction_check_example.php │ └── send_order_example.php └── src ├── Exception ├── ApiValidationException.php ├── ClientException.php └── SdkException.php ├── v1 ├── AdditionalUserProps.php ├── Agent.php ├── AuthorisedPerson.php ├── Buyer.php ├── CalculationMethod.php ├── CalculationSubject.php ├── Cashier.php ├── CashlessPayment.php ├── Check.php ├── Client.php ├── Correction.php ├── CorrectionCheck.php ├── Employee.php ├── EmployeeManager.php ├── EmployeeType.php ├── Nomenclature.php ├── Order.php ├── OrderManager.php ├── OrderPosition.php ├── Payment.php ├── Position.php ├── QueueManager.php ├── TaskManager.php ├── TaxSystem.php └── Vat.php └── v2 ├── AdditionalUserProps.php ├── Agent.php ├── AuthorisedPerson.php ├── Buyer.php ├── Cashier.php ├── CashlessPayment.php ├── Check.php ├── Client.php ├── Company.php ├── CorrectionCheck.php ├── CorrectionInfo.php ├── Employee.php ├── EmployeeManager.php ├── EmployeeType.php ├── MarkCode.php ├── MarkQuantity.php ├── Measure.php ├── OperatingCheckProps.php ├── Order.php ├── OrderBuyer.php ├── OrderCompany.php ├── OrderManager.php ├── OrderPosition.php ├── Payment.php ├── PaymentMethod.php ├── PaymentObject.php ├── PlannedStatus.php ├── Position.php ├── QueueManager.php ├── SectoralCheckProps.php ├── SectoralItemProps.php ├── TaskManager.php ├── TaxSystem.php ├── TimeZone.php └── Vat.php /CHANGELOG.rst: -------------------------------------------------------------------------------- 1 | Changelog 2 | ========= 3 | 4 | Unreleased 5 | ---------- 6 | 7 | 10.2.3 (08.09.2025) 8 | ------------------ 9 | - Изменения по v1: 10 | - В классе `Correction` параметр `document` стал необязательным для `createSelf` 11 | - Изменения по v2: 12 | - В классе `CorrectionInfo` параметр `base_number` стал необязательным для `createSelf` 13 | 14 | 10.2.2 (26.08.2025) 15 | ------------------ 16 | - Изменения по v1: 17 | - В класс `CorrectionCheck` добавлен метод `setUser` - email или телефон пользователя для отправки электронного чека 18 | - В классе `Correction` параметр `description` стал необязательным (устарел и будет удален в будущих версиях) 19 | 20 | 10.2.1 (12.08.2025) 21 | ------------------ 22 | - Изменения по v2: 23 | - В класс `PlannedStatus` добавлен `PLANNED_STATUS_255` - cтатус товара, подлежащего обязательной маркировке, не изменился 24 | 25 | 10.2.0 (05.08.2025) 26 | ------------------- 27 | - Изменения по v1: 28 | - Добавлен класс `CashlessPayment` для передачи сведений об оплате безналичными 29 | - В классы `Check` и `CorrectionCheck` добавлен метод `setInternet` - признак расчета в "Интернет" 30 | - В класс `Check` добавлен метод `addCashlessPayment` - сведения об оплате безналичными 31 | 32 | - Изменения по v2: 33 | - Добавлен класс `CashlessPayment` для передачи сведений об оплате безналичными 34 | - Добавлен класс `TimeZone` для передачи сведений о часовой зоне 35 | - Добавлен класс `PlannedStatus` для передачи сведений о планируемом статусе товара 36 | - В классы `Check` и `CorrectionCheck` добавлен метод `setInternet` - признак расчета в "Интернет" 37 | - В классы `Check` и `CorrectionCheck` добавлен метод `setTimeZone` - часовая зона 38 | - В класс `Check` добавлен метод `addCashlessPayment` - сведения об оплате безналичными 39 | - В класс `Position` добавлен метод `setPlannedStatus` - планируемый статус товара 40 | 41 | 10.1.1 (11.06.2025) 42 | ------------------- 43 | - Возможность установки флага признака использования ОСУ для позиции чека v2 44 | 45 | 10.1.0 (06.11.2024) 46 | ------------------- 47 | - Поддержка НДС 5%, НДС 7%, НДС 5/105 и НДС 7/107 48 | 49 | 10.0.0 (16.09.2024) 50 | ------------------- 51 | - Исправлено "Deprecated function: Creation of dynamic property" в ApiValidationException->__construct() 52 | - Минимальная поддерживаемая версия PHP 7.2 53 | - Прекращена поддержка PHP 5.x 54 | 55 | 9.2.0 (21.02.2024) 56 | ------------------- 57 | - Поддержка place_address 58 | 59 | 9.1.2 (25.07.2023) 60 | ------------------- 61 | - Тесты для подакцизного товара в позиции заказа 62 | 63 | 9.1.1 (30.12.2022) 64 | ------------------- 65 | - Поднял версию php5 cli 66 | - Поддержка типа `gs10` для v2 структуры чеков 67 | 68 | 9.1.0 (03.11.2022) 69 | ------------------- 70 | 71 | - У чека коррекции v2 убран параметр base_name 72 | - Параметр base_number теперь является необязательным для чека коррекции v2 73 | 74 | 9.0.2 (06.05.2022) 75 | ------------------- 76 | 77 | - Добавил метод set_client для чека коррекции в v1 78 | 79 | 9.0.1 (06.04.2022) 80 | ------------------- 81 | 82 | - email является необязательным для Buyer в v2 83 | - Исправлены тесты 84 | 85 | 9.0.0 (31.03.2022) 86 | ------------------- 87 | 88 | - php_sdk_v2 89 | 90 | 8.0.0 (02.03.2021) 91 | ------------------- 92 | 93 | - Параметр `sno` для класса `Order` является обязательным 94 | - Изменен порядок передачи параметра `sno` в классе `Order` 95 | 96 | 7.3.0 (03.02.2021) 97 | ------------------- 98 | 99 | - В класс `Order` добавлено поле `client_coordinate` 100 | - Добавлен признак расчёта `pay` 101 | 102 | 7.2.0 (02.10.2020) 103 | ------------------- 104 | 105 | - В класс `OrderPosition` добавлен метод для добавления маркировки 106 | 107 | 7.1.0 (21.09.2020) 108 | ------------------- 109 | 110 | - Для заказов добавлена поддержка `nomenclature_code`, `is_need_nomenclature_code` 111 | 112 | 7.0.0 (08.09.2020) 113 | ------------------- 114 | 115 | - Добавлены классы `Employee`, `EmployeeType`, `EmployeeManager` для создания, просмотра, редактирования сотрудников 116 | - Класс `CourierManager` заменен на общий `EmployeeManager` 117 | 118 | 6.2.0 (10.06.2020) 119 | ------------------- 120 | 121 | - Добавлен класс `AdditionalUserProps` для передачи дополнительного реквизита пользователя 122 | - В класс `Check` добавлен метод `setAdditionalUserProps` для установки дополнительного реквизита пользователя в чек 123 | - В классe `Check` переименован метод `addAdditionalCheckProps` в `setAdditionalCheckProps` 124 | 125 | 6.1.0 (25.06.2020) 126 | ------------------- 127 | 128 | - В классе `Nomenclature` параметр `code` сделан необязательным 129 | - В класс `Nomenclature` добавлен метод `setCode` для передачи номенклатуры в ASCII виде 130 | - В класс `Nomenclature` добавлены методы `setHexCode` для передачи номенклатуры в HEX виде 131 | 132 | 6.0.0 (22.06.2020) 133 | ------------------- 134 | 135 | - Из Класса кода маркировки Nomenclature убран атрибут type, теперь достаточно передавать только code. 136 | 137 | 5.0.0 (19.06.2020) 138 | ------------------- 139 | 140 | - Параметр `task_id` заменен на параметр `external_id` 141 | 142 | 4.2.0 (04.06.2020) 143 | ------------------- 144 | 145 | - Добавлен класс ApiValidationException для обработки исключений валидации на API 146 | 147 | 4.1.0 (03.06.2020) 148 | ------------------- 149 | 150 | - В класс `Check` добавлен метод `setCallbackUrl` для установки `callback_url` 151 | 152 | 4.0.0 (26.03.2020) 153 | ------------------- 154 | 155 | - В классе `Position` убрана поддержка `discount` 156 | - В класс `Check` добавлен метод `addAdditionalCheckProps` для поддержки дополнительного реквизита чека 157 | 158 | 3.1.0 (02.03.2020) 159 | ------------------- 160 | 161 | - Для заказов добавлена поддержка `exices`, `country_code`, `declaration_number` 162 | 163 | 3.0.0 (20.01.2020) 164 | ------------------- 165 | 166 | - Заменены параметры `gtin` и `serial` класса `Nomenclature` на `code` 167 | 168 | 2.6.0 (16.12.2019) 169 | ------------------ 170 | 171 | - В метод `Order.add_position` добавлен необязательный параметр `agent`. 172 | 173 | 2.5.0 (18.11.2019) 174 | ------------------ 175 | 176 | - Параметр `inn` в классе `Cashier` и `AuthorisedPerson` необязателен для ввода 177 | 178 | 2.4.2 (06.09.2019) 179 | ------------------ 180 | 181 | - Точности округления перед использованием функции `json_encode` выставлена для всех версий php 182 | 183 | 2.4.1 (03.09.2019) 184 | ------------------ 185 | 186 | - Изменена настройка точности округления перед использованием функции `json_encode` 187 | 188 | 2.4.0 (12.08.2019) 189 | ------------------ 190 | 191 | - Добавлен метод `setName` в класс `Buyer` 192 | 193 | 2.3.4 (06.08.2019) 194 | ------------------ 195 | 196 | - Исправлены ошибки при серилиазации полей класса `Position` 197 | 198 | 2.3.3 (18.07.2019) 199 | ------------------ 200 | 201 | - Добавлены празнаки рассчета `PROPERTY_RIGHT`, `NON_OPERATING`, `INSURANCE`, `SALES_TAX`, `RESORT_FEE` у класса `CalculationSubject` 202 | - Добавлен класс `Nomenclature` для создания маркировок 203 | - Добавлены новые методы `Position::setNomenclature`, `Position::setExcise`, `Position::setCountryCode` и `Position::setDeclarationNumber` 204 | 205 | 206 | 2.3.2 (10.07.2019) 207 | ------------------ 208 | 209 | - Исправлена обработка НДС 0% 210 | 211 | 212 | 2.3.1 (08.07.2019) 213 | ------------------ 214 | 215 | - Параметры конструктора `Buyer` сделаны необязательны для ввода 216 | - Добавлен метод `setINN` в класс `Buyer` 217 | 218 | 219 | 2.3.0 (26.06.2019) 220 | ------------------ 221 | 222 | - Добавлена настройка точности округления перед использованием функции `json_encode` 223 | - Добавлена функция `applyDiscount` для заказа доставки для применения общей скидки 224 | 225 | 2.2.0 (19.04.2019) 226 | ------------------ 227 | 228 | - Добавлены классы `Order`, `OrderManager`, `OrderPosition` для работы с заказами 229 | - Добавлен класс `CourierManager` для работы с курьерами 230 | - Добавлено конвертирование типов НДС `Vat::RATE_18` и `Vat::RATE_118` в `Vat::RATE_20` и `Vat::RATE_120`. 231 | 232 | 2.1.0 (05.06.2019) 233 | ------------------ 234 | 235 | - Добавлен класс покупателя `Buyer` 236 | - Добавлена функция `Check::addBuyer` для передачи данных покупателя в чек на фискализацию 237 | 238 | 239 | 2.0.2 (16.04.2019) 240 | ------------------ 241 | 242 | - Исправлена структура передачи данных поставщика в позиции заказа 243 | - Расширенны возможности статических функций `Check::createSell`, `Check::createSellReturn`, 244 | `Check::createBuy` и `Check::createBuyReturn` приемом адреса места расчета `$paymentAddress` 245 | 246 | 247 | 2.0.1 (23.01.2019) 248 | ------------------ 249 | 250 | - Перед использованием констант добавлена проверка на существование класса `Psr\Log\LogLevel` 251 | 252 | 253 | 2.0.0 (18.01.2019) 254 | ------------------ 255 | 256 | - Убраны типы НДС `Vat::RATE_18` и `Vat::RATE_118` 257 | 258 | 259 | 1.3.0 (24.12.2018) 260 | ------------------ 261 | 262 | - Добавлены новые методы `Agent::setSupplierInfo`, `Agent::setPayingAgentInfo`, `Agent::setReceivePaymentsOperatorInfo` и `Agent::setMoneyTransferOperatorInfo` 263 | 264 | - Класс `Check` принимает необязательный параметр места расчета `$paymentAddress` 265 | 266 | 267 | 1.2.0 (10.12.2018) 268 | ------------------ 269 | 270 | - Добалвены новые виды НДС `Vat::RATE_20` и `Vat::RATE_120` 271 | 272 | 273 | 1.1.0 (27.11.2018) 274 | ------------------ 275 | 276 | - Добавлен метод применения скидки к чеку `Check::applyDiscount` 277 | 278 | 279 | 1.0.0 (01.09.2018) 280 | ------------------ 281 | 282 | - Убраны методы `Payment::createCard` и `Payment::createCash` из-за расширения списка возможных видов оплаты 283 | 284 | 285 | 0.9.1 (01.09.2018) 286 | ------------------ 287 | 288 | - Вернул методы `createCard` и `createCash` для подержания совместимости версии 0.X.X 289 | 290 | 291 | 0.9.0 (15.08.2018) 292 | ------------------ 293 | 294 | - Добавлены константы направлений платежа `INTENT_BUY` и `INTENT_BUY_RETURN` в класс `Check` 295 | 296 | 297 | 0.8.0 (09.04.2018) 298 | ------------------ 299 | 300 | - Добавлен класс `AuthorisedPerson` 301 | 302 | 303 | 0.7.0 (22.03.2018) 304 | ------------------ 305 | 306 | - Добавлена поддержка ФФД 1.0.5 (Признак рассчета, способ рассчета, данные по кассиру, 307 | данные по агенту) 308 | 309 | 310 | 0.6.0 (28.11.2017) 311 | ------------------ 312 | 313 | - Добавлен метод `Client::setPartner` 314 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2017 Komtet 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /RELEASE.md: -------------------------------------------------------------------------------- 1 | ## Публикация релизов 2 | 3 | Убедииться, что все тесты прошли успешно. 4 | 5 | Убедиться, что README.md содержит всю необходимую актуальную информацию. 6 | 7 | Обновить лог изменений. При его оформлении следует придерживаться следующего формата: 8 | 9 | ```markdown 10 | ## Changelog 11 | 12 | ### ver_major.ver_minor.patch (dd.mm.yyyy) 13 | 14 | - Список изменений. 15 | - Каждый элемент списка должен начинаться с заглавной буквы и завершаться точкой. 16 | - Между секциями должно быть по одной пустой строке. 17 | 18 | ### ver_major.ver_minor.patch (dd.mm.yyyy) 19 | 20 | - Несмотря на то, что коммиты на английском, в логе изменений всё пишем на русском. 21 | 22 | ``` 23 | 24 | Через интерфейс GitHub [создать](https://github.com/Komtet/komtet-kassa-php-sdk/releases/new) новый релиз. 25 | В "Tag version" и "Release title" пишем номер версии. В описание копируем список изменений из changelog. 26 | Обратите внимание, что копировать нужно исходный код, чтобы сохранить форматирование. 27 | Для примера можно посмотреть, как [оформлены](https://github.com/Komtet/komtet-kassa-php-sdk/releases/edit/0.4.0) предыдущие версии. 28 | 29 | При определении номера версии следует придерживаться [Semantic Versioning 2.0.0](http://semver.org/spec/v2.0.0.html). 30 | 31 | Единственное исключение — для версий 0.y.z действуют свои правила: 32 | - минорная версия изменяется в случае потери обратной совместимости. 33 | - патч версия увеличивается при любых изменениях, которые не нарушают обратную совместимость. 34 | -------------------------------------------------------------------------------- /autoload.php: -------------------------------------------------------------------------------- 1 | registerQueue('queue', 'YOUR_QUEUE_ID'); //int 23 | 24 | // уникальный ID, предоставляемый магазином 25 | $checkID = 'testdf1234'; 26 | // E-Mail клиента, на который будет отправлен E-Mail с чеком. 27 | $clientEmail = 'user@host.com'; 28 | 29 | $check = Check::createSell($checkID, $clientEmail, TaxSystem::COMMON); 30 | 31 | $vat = new Vat(Vat::RATE_20); 32 | 33 | // Позиция в чеке: имя, цена, кол-во, общая стоимость, налог 34 | $position = new Position('name', 100, 1, 100, $vat); 35 | 36 | $check->addPosition($position); 37 | 38 | // Итоговая сумма расчёта 39 | $payment = new Payment(Payment::TYPE_CARD, 100); 40 | $check->addPayment($payment); 41 | 42 | // Добавление кассира (опционально) 43 | $cashier = new Cashier('Иваров И.П.', '1234567890123'); 44 | $check->addCashier($cashier); 45 | 46 | // Добавляем чек в очередь. 47 | try { 48 | $manager->putCheck($check, 'queue'); 49 | } catch (ApiValidationException $e) { 50 | echo $e->getMessage(); 51 | echo $e->getVLDCode(); 52 | echo $e->getDescription(); 53 | } catch (SdkException $e) { 54 | echo $e->getMessage(); 55 | } 56 | -------------------------------------------------------------------------------- /examples/v1/send_correction_check_example.php: -------------------------------------------------------------------------------- 1 | registerQueue('queue', 'YOUR_QUEUE_ID'); //int 27 | 28 | // ЧЕК КОРРЕКЦИИ 29 | 30 | // createSelf для самостоятельной коррекции 31 | // createForced для коррекции по предписанию 32 | $correction = Correction::createSelf( 33 | '2012-12-21', // Дата документа коррекции в формате yyyy-mm-dd 34 | '4815162342', // Номер документа коррекции 35 | 'description' // Описание коррекции 36 | ); 37 | 38 | $correctionCheck = CorrectionCheck::createSellCorrection('12345', TaxSystem::COMMON, $correction); // Чек коррекции прихода 39 | // $correctionCheck = CorrectionCheck::createSellReturnCorrection('123', TaxSystem::COMMON, $correction); // Чек возврата коррекции прихода 40 | // $correctionCheck = CorrectionCheck::createBuyCorrection('123', TaxSystem::COMMON, $correction); // Чек коррекции расхода 41 | // $correctionCheck = CorrectionCheck::createBuyReturnCorrection('123', TaxSystem::COMMON, $correction); // Чек возврата коррекции прихода 42 | 43 | // Печатать ли чек 44 | $correctionCheck->setShouldPrint(false); 45 | 46 | // Данные уполномоченного лица 47 | $authorised_person = new AuthorisedPerson('name', 'inn'); 48 | $correctionCheck->setAuthorisedPerson($authorised_person); 49 | 50 | // Добавление кассира 51 | $cashier = new Cashier('Иванов И.П.', '012345678912'); 52 | $correctionCheck->addCashier($cashier); 53 | 54 | // Дополнительный реквизит чека 55 | $correctionCheck->setAdditionalCheckProps('доп. реквизит'); 56 | 57 | // Адрес для получения отчёта по чеку 58 | $correctionCheck->setCallbackUrl('https://test.ru/callback-url'); 59 | 60 | // Дополнительный реквизит пользователя 61 | $additional_user_props = new AdditionalUserProps('name', 'value'); 62 | $correctionCheck->setAdditionalUserProps($additional_user_props); 63 | 64 | // Информация о покупателе 65 | $buyer = new Buyer('Пупкин П.П.', '123412341234'); 66 | $check->addBuyer($buyer); 67 | 68 | // ПОЗИЦИИ ЧЕКА КОРРЕКЦИИ 69 | 70 | $vat = new Vat(Vat::RATE_20); 71 | 72 | // Позиция в чеке: имя, цена, кол-во, общая стоимость, налог 73 | $position = new Position('name', 100, 1, 100, $vat); 74 | 75 | $correctionCheck->addPosition($position); 76 | 77 | // Опционально можно установить: 78 | // Идентификатор позиции 79 | // $position->setId('123'); 80 | 81 | // Единицу измерения 82 | // $position->setMeasureName('Кг.'); 83 | 84 | // Cпособ рассчета 85 | // $position->setCalculationMethod(CalculationMethod::FULL_PAYMENT); 86 | 87 | // Признак рассчета 88 | // $position->setCalculationSubject(CalculationSubject::PRODUCT); 89 | 90 | // Агента по предмету расчета 91 | // $agent = new Agent(Agent::COMMISSIONAIRE, "+77777777777", "ООО 'Лютик'", "12345678901"); 92 | // $position->setAgent($agent); 93 | 94 | // Код маркировки 95 | // $nomenclature = new Nomenclature('kjgldfjgdfklg234234'); 96 | // $position->setNomenclature($nomenclature); 97 | 98 | // Сумма акциза 99 | // $position->setExcise(25); 100 | 101 | // Цифровой код страны происхождения товара 102 | // $position->setCountryCode('5'); 103 | 104 | // Номер таможенной декларации 105 | // $position->setDeclarationNumber('15'); 106 | 107 | // Итоговая сумма расчёта 108 | $payment = new Payment(Payment::TYPE_CARD, 50); 109 | $correctionCheck->addPayment($payment); 110 | 111 | $payment = new Payment(Payment::TYPE_CASH, 50); 112 | $correctionCheck->addPayment($payment); 113 | 114 | // Добавляем чек в очередь. 115 | try { 116 | $manager->putCheck($correctionCheck, 'queue'); 117 | } catch (ApiValidationException $e) { 118 | echo $e->getMessage(); 119 | echo $e->getVLDCode(); 120 | echo $e->getDescription(); 121 | } catch (SdkException $e) { 122 | echo $e->getMessage(); 123 | } 124 | -------------------------------------------------------------------------------- /examples/v1/send_order_example.php: -------------------------------------------------------------------------------- 1 | setCourierId(5); 26 | 27 | // Адрес для получения отчёта по заказу 28 | $order->setCallbackUrl('https://test.ru/callback-url'); 29 | 30 | // Комментарий к заказу 31 | $order->setDescription('Комментарий к заказу'); 32 | 33 | // Информация о покупателе 34 | $order->setClient('г.Пенза, ул.Суворова д.10 кв.25', 35 | '+87654443322', 36 | 'client@email.com', 37 | 'Сергеев Виктор Сергеевич'); 38 | 39 | // Дата и время доставки 40 | $order->setDeliveryTime('2018-02-28 14:00', 41 | '2018-02-28 15:20'); 42 | 43 | // Позиции заказа 44 | 45 | // Агент по предмету расчета 46 | $agent = new Agent(Agent::COMMISSIONAIRE, "+77777777777", "ООО 'Лютик'", "502906602876"); 47 | 48 | $orderPosition = new OrderPosition(['oid' => '1', 49 | 'name' => 'position name1', 50 | 'price' => 555.0, 51 | 'quantity' => 1, 52 | 'type' => 'product', 53 | 'vat' => Vat::RATE_NO, 54 | 'agent' => $agent, 55 | 'is_need_nomenclature_code' => true, 56 | 'excise' => 4, 57 | 'country_code' => 'country_code', 58 | 'declaration_number' => 'declaration_number' 59 | ]); 60 | 61 | // Код маркировки 62 | $orderPosition->setNomenclatureCode('kjgldfjgdfklg234234'); 63 | 64 | $order->addPosition($orderPosition); 65 | 66 | try { 67 | $orderManager->createOrder($order); 68 | } catch (ApiValidationException $e) { 69 | echo $e->getMessage(); 70 | echo $e->getVLDCode(); 71 | echo $e->getDescription(); 72 | } catch (SdkException $e) { 73 | echo $e->getMessage(); 74 | } 75 | -------------------------------------------------------------------------------- /examples/v2/send_check_example.php: -------------------------------------------------------------------------------- 1 | registerQueue('queue', 'YOUR_QUEUE_ID'); //int 35 | 36 | // ЧЕК 37 | 38 | // уникальный ID, предоставляемый магазином 39 | $checkID = '123456'; 40 | // E-Mail клиента, на который будет отправлен E-Mail с чеком. 41 | $clientEmail = 'test@test.ru'; 42 | 43 | // Место расчетов 44 | $payment_address = 'Офис 3'; 45 | 46 | // Информация о покупателе 47 | $buyer = new Buyer(); 48 | $buyer->setEmail($clientEmail); // Email 49 | $buyer->setName('Иванов А.А.'); // Покупатель 50 | $buyer->setPhone('+79099099999'); // Телефон 51 | $buyer->setBirthdate('20.10.2000'); // Дата рождения покупателя 52 | $buyer->setCitizenship('123'); // Числовой код страны, гражданином которой является покупатель 53 | $buyer->setDocumentCode('12'); // Числовой код вида документа, удостоверяющего личность 54 | $buyer->setDocumentData('Реквизиты документа, удостоверяющего личность'); // Реквизиты документа, удостоверяющего личность 55 | $buyer->setAddress('Город, Улица д.5'); // Адрес покупателя 56 | 57 | // Информация о компании 58 | $company = new Company(TaxSystem::COMMON, $payment_address); 59 | $company->setPlaceAddress('г. Москва'); // Адрес расчетов 60 | $company->setINN('502906602876'); // ИНН организации 61 | 62 | $check = Check::createSell($checkID, $buyer, $company); // Чек прихода 63 | // $check = Check::createSellReturn($checkID, $buyer, $company); // Чек возврата прихода 64 | // $check = Check::createBuy($checkID, $buyer, $company); // Чек Расхода 65 | // $check = Check::createBuyReturn($checkID, $buyer, $company); // Чек возврата расхода 66 | 67 | // Дополнительный реквизит пользователя 68 | $additional_user_props = new AdditionalUserProps('name', 'value'); 69 | $check->setAdditionalUserProps($additional_user_props); 70 | 71 | // Отраслевой реквезит чека 72 | $sectoral_check_props = new SectoralCheckProps('001', '25.10.2020', '1', 'значение отраслевого реквизита'); 73 | $check->setSectoralCheckProps($sectoral_check_props); 74 | 75 | // Возможность добавления нескольких SectoralCheckProps 76 | // $sectoral_check_props2 = new SectoralCheckProps('002', '01.01.2020', '2', 'значение отраслевого реквизита2'); 77 | // $check->setSectoralCheckProps($sectoral_check_props2); 78 | 79 | // Операционный реквизит пользователя 80 | $operating_check_props = new OperatingCheckProps('0', 'данные операции', '12.03.2020 16:55:25'); 81 | $check->setOperatingCheckProps($operating_check_props); 82 | 83 | // Дополнительный реквизит чека 84 | $check->setAdditionalCheckProps('доп. реквизит чека'); 85 | 86 | // Адрес для получения отчёта по чеку 87 | $check->setCallbackUrl('https://test.ru/callback-url'); 88 | 89 | // Говорим, что чек нужно распечатать 90 | $check->setShouldPrint(true); 91 | 92 | // Добавление кассира 93 | $cashier = new Cashier('Иванов И.П.', '012345678912'); 94 | $check->addCashier($cashier); 95 | 96 | 97 | // ПОЗИЦИИ ЧЕКА 98 | 99 | // Ставка налога 100 | $vat = new Vat(Vat::RATE_NO); 101 | // $vat = new Vat(Vat::RATE_0); 102 | // $vat = new Vat(Vat::RATE_10); 103 | // $vat = new Vat(Vat::RATE_20); 104 | // $vat = new Vat(Vat::RATE_110); 105 | // $vat = new Vat(Vat::RATE_120); 106 | 107 | // Еденица измерения 108 | $measure = Measure::PIECE; 109 | // $measure = Measure::GRAMM; 110 | // $measure = Measure::KILOGRAMM; 111 | // $measure = Measure::TON; 112 | // $measure = Measure::CENTIMETER; 113 | // $measure = Measure::DECIMETER; 114 | // $measure = Measure::METER; 115 | // $measure = Measure::SQUARE_CENTIMETER; 116 | // $measure = Measure::SQUARE_DECIMETER; 117 | // $measure = Measure::SQUARE_METER; 118 | // $measure = Measure::MILLILITER; 119 | // $measure = Measure::LITER; 120 | // $measure = Measure::CUBIC_METER; 121 | // $measure = Measure::KILOWATT_HOUR; 122 | // $measure = Measure::GIGA_CALORIE; 123 | // $measure = Measure::DAY; 124 | // $measure = Measure::HOUR; 125 | // $measure = Measure::MINUTE; 126 | // $measure = Measure::SECOND; 127 | // $measure = Measure::KILOBYTE; 128 | // $measure = Measure::MEGABYTE; 129 | // $measure = Measure::GIGABYTE; 130 | // $measure = Measure::TERABYTE; 131 | // $measure = Measure::OTHER_MEASURMENTS; 132 | 133 | // Cпособ расчета 134 | $payment_method = PaymentMethod::FULL_PAYMENT; 135 | // $payment_method = PaymentMethod::PRE_PAYMENT_FULL; 136 | // $payment_method = PaymentMethod::PRE_PAYMENT_PART; 137 | // $payment_method = PaymentMethod::ADVANCE; 138 | // $payment_method = PaymentMethod::CREDIT_PART; 139 | // $payment_method = PaymentMethod::CREDIT_PAY; 140 | // $payment_method = PaymentMethod::CREDIT; 141 | 142 | // Предмет расчета 143 | $payment_object = PaymentObject::PRODUCT; 144 | // $payment_object = PaymentObject::PRODUCT_PRACTICAL; 145 | // $payment_object = PaymentObject::WORK; 146 | // $payment_object = PaymentObject::SERVICE; 147 | // $payment_object = PaymentObject::GAMBLING_BET; 148 | // $payment_object = PaymentObject::GAMBLING_WIN; 149 | // $payment_object = PaymentObject::LOTTERY_BET; 150 | // $payment_object = PaymentObject::LOTTERY_WIN; 151 | // $payment_object = PaymentObject::RID; 152 | // $payment_object = PaymentObject::PAYMENT; 153 | // $payment_object = PaymentObject::COMMISSION; 154 | // $payment_object = PaymentObject::COMPOSITE; 155 | // $payment_object = PaymentObject::PAY; 156 | // $payment_object = PaymentObject::OTHER; 157 | // $payment_object = PaymentObject::PROPERTY_RIGHT; 158 | // $payment_object = PaymentObject::NON_OPERATING; 159 | // $payment_object = PaymentObject::INSURANCE; 160 | // $payment_object = PaymentObject::SALES_TAX; 161 | // $payment_object = PaymentObject::RESORT_FEE; 162 | // $payment_object = PaymentObject::DEPOSIT; 163 | // $payment_object = PaymentObject::CONSUMPTION; 164 | // $payment_object = PaymentObject::SOLE_PROPRIETOR_CPI_CONTRIBUTINS; 165 | // $payment_object = PaymentObject::CPI_CONTRIBUTINS; 166 | // $payment_object = PaymentObject::SOLE_PROPRIETOR_CMI_CONTRIBUTINS; 167 | // $payment_object = PaymentObject::CMI_CONTRIBUTINS; 168 | // $payment_object = PaymentObject::CSI_CONTRIBUTINS; 169 | // $payment_object = PaymentObject::CASINO_PAYMENT; 170 | // $payment_object = PaymentObject::PAYMENT_OF_THE_MONEY; 171 | // $payment_object = PaymentObject::ATNM; 172 | // $payment_object = PaymentObject::ATM; 173 | // $payment_object = PaymentObject::TNM; 174 | // $payment_object = PaymentObject::TM; 175 | 176 | // Позиция в чеке: имя, цена, кол-во, общая стоимость, налог, еденица измерения, способ расчета, предмет расчета 177 | $position = new Position('name', 100, 1, 100, $vat, $measure, $payment_method, $payment_object); 178 | 179 | // Задаём id позиции 180 | $position->setId('123456'); 181 | 182 | // Агент по предмету расчета 183 | $agent = new Agent(Agent::COMMISSIONAIRE, "+77777777777", "ООО 'Лютик'", "502906602876"); 184 | $position->setAgent($agent); 185 | 186 | // Отраслевой реквизит предмета расчета 187 | $sectoral_item_props = new SectoralItemProps('001', '25.10.2020', '1', 'значение отраслевого реквизита'); 188 | $position->setSectoralItemProps($sectoral_item_props); 189 | 190 | // Возможность добавления нескольких SectoralItemProps 191 | // $sectoral_item_props2 = new SectoralItemProps('002', '26.01.1935', '15', 'значение отраслевого реквизита2'); 192 | // $position->setSectoralItemProps($sectoral_item_props2); 193 | 194 | // Дополнительный реквизит предмета расчета 195 | $position->setUserData('Дополнительный реквизит предмета расчета'); 196 | 197 | // Возможность добавления фрага работы по ОСУ(Объемно-сортовому учёту). 198 | // В случае передачи флага в true необходимо указать mark_code с типом ITF14, quantity > 1 и sectoral_item_props 199 | // $position->setWholesale(true); 200 | 201 | // Сумма акциза 202 | $position->setExcise(25); 203 | 204 | // Цифровой код страны происхождения товара 205 | $position->setCountryCode('5'); 206 | 207 | // Номер таможенной декларации 208 | $position->setDeclarationNumber('15'); 209 | 210 | // Дробное количество маркированного товара 211 | $mark_quantity = new MarkQuantity(1, 2); 212 | $position->setMarkQuantity($mark_quantity); 213 | 214 | // Атрибуты кода товара (маркировки) 215 | $mark_code = new MarkCode(MarkCode::GS1M, '0123455g54drgdfsgre54st5ergdfg'); 216 | $position->setMarkCode($mark_code); 217 | 218 | $check->addPosition($position); 219 | 220 | // Применение к позициям единой общей скидки на чек (например скидочного купона) 221 | $check->applyDiscount(50); 222 | 223 | // Итоговая сумма расчёта 224 | $payment = new Payment(Payment::TYPE_CASH, 50); 225 | $check->addPayment($payment); 226 | 227 | // Добавляем чек в очередь. 228 | try { 229 | $manager->putCheck($check, 'queue'); 230 | } catch (ApiValidationException $e) { 231 | echo $e->getMessage(); 232 | echo $e->getVLDCode(); 233 | echo $e->getDescription(); 234 | } catch (SdkException $e) { 235 | echo $e->getMessage(); 236 | } 237 | -------------------------------------------------------------------------------- /examples/v2/send_correction_check_example.php: -------------------------------------------------------------------------------- 1 | registerQueue('queue', 'YOUR_QUEUE_ID'); //int 37 | 38 | // ЧЕК КОРРЕКЦИИ 39 | 40 | // уникальный ID, предоставляемый магазином 41 | $checkID = '12345'; 42 | // E-Mail клиента, на который будет отправлен E-Mail с чеком. 43 | $clientEmail = 'test@test.ru'; 44 | 45 | // Место расчетов 46 | $payment_address = 'Офис 3'; 47 | 48 | // Данные коррекции с опциональным параметром base_number(номером документа коррекции) 49 | $correction_info = new CorrectionInfo(CorrectionInfo::TYPE_SELF, '31.01.2021', '1'); 50 | // Данные коррекции без опционального параметра base_number(номером документа коррекции) 51 | // $correction_info = new CorrectionInfo(CorrectionInfo::TYPE_INSTRUCTION, '31.01.2021'); 52 | 53 | // Информация о компании 54 | $company = new Company(TaxSystem::COMMON, $payment_address); 55 | $company->setPlaceAddress('г. Москва'); // Адрес расчетов 56 | $company->setINN('502906602876'); // ИНН организации 57 | 58 | $correctionCheck = CorrectionCheck::createSellCorrection($checkID, $company, $correction_info); // Чек коррекции прихода 59 | // $correctionCheck = CorrectionCheck::createSellReturnCorrection($checkID, $company, $correction_info); // Чек коррекции возврата прихода 60 | // $correctionCheck = CorrectionCheck::createBuyCorrection($checkID, $company, $correction_info); // Чек коррекции расхода 61 | // $correctionCheck = CorrectionCheck::createBuyReturnCorrection($checkID, $company, $correction_info); // Чек возврата коррекции расхода 62 | 63 | // Данные уполномоченного лица 64 | $authorised_person = new AuthorisedPerson('name', 'inn'); 65 | $correctionCheck->setAuthorisedPerson($authorised_person); 66 | 67 | // Информация о покупателе 68 | $buyer = new Buyer(); 69 | $buyer->setEmail($clientEmail); // Email 70 | // $buyer->setName('Иванов А.А.'); // Покупатель 71 | // $buyer->setPhone('79099099999'); // Телефон 72 | // $buyer->setBirthdate('20.10.2000'); // Дата рождения покупателя 73 | // $buyer->setCitizenship('123'); // Числовой код страны, гражданином которой является покупатель 74 | // $buyer->setDocumentCode('12'); // Числовой код вида документа, удостоверяющего личность 75 | // $buyer->setDocumentData('Реквизиты документа, удостоверяющего личность'); // Реквизиты документа, удостоверяющего личность 76 | // $buyer->setAddress('Город, Улица д.5'); // Адрес покупателя 77 | $correctionCheck->setBuyer($buyer); 78 | 79 | // Дополнительный реквизит пользователя 80 | $additional_user_props = new AdditionalUserProps('name', 'value'); 81 | $correctionCheck->setAdditionalUserProps($additional_user_props); 82 | 83 | // Отраслевой реквезит чека 84 | $sectoral_check_props = new SectoralCheckProps('001', '25.10.2020', '1', 'значение отраслевого реквизита'); 85 | $correctionCheck->setSectoralCheckProps($sectoral_check_props); 86 | 87 | // Возможность добавления нескольких SectoralCheckProps 88 | $sectoral_check_props2 = new SectoralCheckProps('002', '01.01.2020', '2', 'значение отраслевого реквизита2'); 89 | $correctionCheck->setSectoralCheckProps($sectoral_check_props2); 90 | 91 | // Операционный реквизит пользователя 92 | $operating_check_props = new OperatingCheckProps('0', 'данные операции', '12.03.2020 16:55:25'); 93 | $correctionCheck->setOperatingCheckProps($operating_check_props); 94 | 95 | // Дополнительный реквизит чека 96 | $correctionCheck->setAdditionalCheckProps('доп. реквизит чека'); 97 | 98 | // Адрес для получения отчёта по чеку 99 | $correctionCheck->setCallbackUrl('https://test.ru/callback-url'); 100 | 101 | // Добавление кассира 102 | $cashier = new Cashier('Иванов И.П.', '012345678912'); 103 | $correctionCheck->addCashier($cashier); 104 | 105 | 106 | // ПОЗИЦИИ ЧЕКА КОРРЕКЦИИ 107 | 108 | // Ставка налога 109 | $vat = new Vat(Vat::RATE_NO); 110 | // $vat = new Vat(Vat::RATE_0); 111 | // $vat = new Vat(Vat::RATE_10); 112 | // $vat = new Vat(Vat::RATE_20); 113 | // $vat = new Vat(Vat::RATE_110); 114 | // $vat = new Vat(Vat::RATE_120); 115 | 116 | // Еденица измерения 117 | $measure = Measure::PIECE; 118 | // $measure = Measure::GRAMM; 119 | // $measure = Measure::KILOGRAMM; 120 | // $measure = Measure::TON; 121 | // $measure = Measure::CENTIMETER; 122 | // $measure = Measure::DECIMETER; 123 | // $measure = Measure::METER; 124 | // $measure = Measure::SQUARE_CENTIMETER; 125 | // $measure = Measure::SQUARE_DECIMETER; 126 | // $measure = Measure::SQUARE_METER; 127 | // $measure = Measure::MILLILITER; 128 | // $measure = Measure::LITER; 129 | // $measure = Measure::CUBIC_METER; 130 | // $measure = Measure::KILOWATT_HOUR; 131 | // $measure = Measure::GIGA_CALORIE; 132 | // $measure = Measure::DAY; 133 | // $measure = Measure::HOUR; 134 | // $measure = Measure::MINUTE; 135 | // $measure = Measure::SECOND; 136 | // $measure = Measure::KILOBYTE; 137 | // $measure = Measure::MEGABYTE; 138 | // $measure = Measure::GIGABYTE; 139 | // $measure = Measure::TERABYTE; 140 | // $measure = Measure::OTHER_MEASURMENTS; 141 | 142 | // Cпособ расчета 143 | $payment_method = PaymentMethod::FULL_PAYMENT; 144 | // $payment_method = PaymentMethod::PRE_PAYMENT_FULL; 145 | // $payment_method = PaymentMethod::PRE_PAYMENT_PART; 146 | // $payment_method = PaymentMethod::ADVANCE; 147 | // $payment_method = PaymentMethod::CREDIT_PART; 148 | // $payment_method = PaymentMethod::CREDIT_PAY; 149 | // $payment_method = PaymentMethod::CREDIT; 150 | 151 | // Предмет расчета 152 | $payment_object = PaymentObject::PRODUCT; 153 | // $payment_object = PaymentObject::PRODUCT_PRACTICAL; 154 | // $payment_object = PaymentObject::WORK; 155 | // $payment_object = PaymentObject::SERVICE; 156 | // $payment_object = PaymentObject::GAMBLING_BET; 157 | // $payment_object = PaymentObject::GAMBLING_WIN; 158 | // $payment_object = PaymentObject::LOTTERY_BET; 159 | // $payment_object = PaymentObject::LOTTERY_WIN; 160 | // $payment_object = PaymentObject::RID; 161 | // $payment_object = PaymentObject::PAYMENT; 162 | // $payment_object = PaymentObject::COMMISSION; 163 | // $payment_object = PaymentObject::COMPOSITE; 164 | // $payment_object = PaymentObject::PAY; 165 | // $payment_object = PaymentObject::OTHER; 166 | // $payment_object = PaymentObject::PROPERTY_RIGHT; 167 | // $payment_object = PaymentObject::NON_OPERATING; 168 | // $payment_object = PaymentObject::INSURANCE; 169 | // $payment_object = PaymentObject::SALES_TAX; 170 | // $payment_object = PaymentObject::RESORT_FEE; 171 | // $payment_object = PaymentObject::DEPOSIT; 172 | // $payment_object = PaymentObject::CONSUMPTION; 173 | // $payment_object = PaymentObject::SOLE_PROPRIETOR_CPI_CONTRIBUTINS; 174 | // $payment_object = PaymentObject::CPI_CONTRIBUTINS; 175 | // $payment_object = PaymentObject::SOLE_PROPRIETOR_CMI_CONTRIBUTINS; 176 | // $payment_object = PaymentObject::CMI_CONTRIBUTINS; 177 | // $payment_object = PaymentObject::CSI_CONTRIBUTINS; 178 | // $payment_object = PaymentObject::CASINO_PAYMENT; 179 | // $payment_object = PaymentObject::PAYMENT_OF_THE_MONEY; 180 | // $payment_object = PaymentObject::ATNM; 181 | // $payment_object = PaymentObject::ATM; 182 | // $payment_object = PaymentObject::TNM; 183 | // $payment_object = PaymentObject::TM; 184 | 185 | // Позиция в чеке: имя, цена, кол-во, общая стоимость, налог, еденица измерения, способ расчета, предмет расчета 186 | $position = new Position('name', 100, 1, 100, $vat, $measure, $payment_method, $payment_object); 187 | 188 | // Задаём id позиции 189 | $position->setId('123456'); 190 | 191 | // Агент по предмету расчета 192 | $agent = new Agent(Agent::COMMISSIONAIRE, "+77777777777", "ООО 'Лютик'", "502906602876"); 193 | $position->setAgent($agent); 194 | 195 | // Отраслевой реквизит предмета расчета 196 | $sectoral_item_props = new SectoralItemProps('001', '25.10.2020', '1', 'значение отраслевого реквизита'); 197 | $position->setSectoralItemProps($sectoral_item_props); 198 | 199 | // Возможность добавления нескольких SectoralItemProps 200 | $sectoral_item_props2 = new SectoralItemProps('002', '26.01.1935', '15', 'значение отраслевого реквизита2'); 201 | $position->setSectoralItemProps($sectoral_item_props2); 202 | 203 | // Дополнительный реквизит предмета расчета 204 | $position->setUserData('Дополнительный реквизит предмета расчета'); 205 | 206 | // Сумма акциза 207 | $position->setExcise(25); 208 | 209 | // Цифровой код страны происхождения товара 210 | $position->setCountryCode('5'); 211 | 212 | // Номер таможенной декларации 213 | $position->setDeclarationNumber('15'); 214 | 215 | // Дробное количество маркированного товара 216 | $mark_quantity = new MarkQuantity(1, 2); 217 | $position->setMarkQuantity($mark_quantity); 218 | 219 | // Атрибуты кода товара (маркировки) 220 | $mark_code = new MarkCode(MarkCode::GS1M, '0123455g54drgdfsgre54st5ergdfg'); 221 | $position->setMarkCode($mark_code); 222 | 223 | $correctionCheck->addPosition($position); 224 | 225 | // Итоговая сумма расчёта 226 | $payment = new Payment(Payment::TYPE_CARD, 50); 227 | $correctionCheck->addPayment($payment); 228 | 229 | $payment = new Payment(Payment::TYPE_CASH, 50); 230 | $correctionCheck->addPayment($payment); 231 | 232 | // Добавляем чек в очередь. 233 | try { 234 | $manager->putCheck($correctionCheck, 'queue'); 235 | } catch (ApiValidationException $e) { 236 | echo $e->getMessage(); 237 | echo $e->getVLDCode(); 238 | echo $e->getDescription(); 239 | } catch (SdkException $e) { 240 | echo $e->getMessage(); 241 | } 242 | -------------------------------------------------------------------------------- /examples/v2/send_order_example.php: -------------------------------------------------------------------------------- 1 | setPlaceAddress('г. Москва'); // Адрес расчетов 34 | $orderCompany->setINN('502906602876'); // ИНН организации 35 | $order->setCompany($orderCompany); 36 | 37 | // Дата и время доставки 38 | $order->setDeliveryTime('20.02.2022 14:00', 39 | '20.02.2022 15:20'); 40 | 41 | // Информация о покупателе 42 | $orderBuyer = new OrderBuyer('+87654443322', 43 | 'г.Пенза, ул.Суворова д.10 кв.25', 44 | 'Сергеев Виктор Сергеевич', 45 | '502906602876', 46 | 'client@email.com'); 47 | 48 | // Координаты доставки заказа 49 | $orderBuyer->setCoordinate('123', '780'); 50 | 51 | $order->setOrderBuyer($orderBuyer); 52 | 53 | // Идентификатор курьера 54 | $order->setCourierId(5); 55 | 56 | // Адрес для получения отчёта по заказу 57 | $order->setCallbackUrl('https://test.ru/callback-url'); 58 | 59 | // Комментарий к заказу 60 | $order->setDescription('Комментарий к заказу'); 61 | 62 | // Дополнительный реквизит пользователя 63 | $additional_user_props = new AdditionalUserProps('name', 'value'); 64 | $order->setAdditionalUserProps($additional_user_props); 65 | 66 | // Отраслевой реквезит чека 67 | $sectoral_check_props = new SectoralCheckProps('001', '25.10.2020', '1', 'значение отраслевого реквизита'); 68 | $order->setSectoralCheckProps($sectoral_check_props); 69 | 70 | // Возможность добавления нескольких SectoralCheckProps 71 | $sectoral_check_props2 = new SectoralCheckProps('002', '01.01.2020', '2', 'значение отраслевого реквизита2'); 72 | $order->setSectoralCheckProps($sectoral_check_props2); 73 | 74 | // Операционный реквизит пользователя 75 | $operating_check_props = new OperatingCheckProps('0', 'данные операции', '12.03.2020 16:55:25'); 76 | $order->setOperatingCheckProps($operating_check_props); 77 | 78 | // Дополнительный реквизит чека 79 | $order->setAdditionalCheckProps('доп. реквизит чека'); 80 | 81 | // Позиции заказа 82 | $orderPosition = new OrderPosition(['order_item_id' => '1', 83 | 'name' => 'position name1', 84 | 'price' => 555.0, 85 | 'quantity' => 1, 86 | 'total' => 555.0, 87 | 'type' => 'service', 88 | 'vat' => '20', 89 | 'measure' => 0, 90 | 'excise' => 5, 91 | 'country_code' => '6', 92 | 'declaration_number' => '7', 93 | 'user_data' => 'доп. реквизит', 94 | 'is_need_mark_code' => false, 95 | ]); 96 | 97 | // Агент по предмету расчета 98 | $agent = new Agent(Agent::COMMISSIONAIRE, "+77777777777", "ООО 'Лютик'", "502906602876"); 99 | $orderPosition->setAgent($agent); 100 | 101 | // Отраслевой реквизит предмета расчета 102 | $sectoral_item_props = new SectoralItemProps('001', '25.10.2020', '1', 'значение отраслевого реквизита'); 103 | $orderPosition->setSectoralItemProps($sectoral_item_props); 104 | 105 | // Возможность добавления нескольких SectoralItemProps 106 | $sectoral_item_props2 = new SectoralItemProps('002', '26.01.1935', '15', 'значение отраслевого реквизита2'); 107 | $orderPosition->setSectoralItemProps($sectoral_item_props2); 108 | 109 | // Дробное количество маркированного товара 110 | $mark_quantity = new MarkQuantity(1, 2); 111 | $orderPosition->setMarkQuantity($mark_quantity); 112 | 113 | // Атрибуты кода товара (маркировки) 114 | $mark_code = new MarkCode(MarkCode::GS1M, '0123455g54drgdfsgre54st5ergdfg'); 115 | $orderPosition->setMarkCode($mark_code); 116 | 117 | $order->addPosition($orderPosition); 118 | 119 | $order->applyDiscount(100); 120 | 121 | try { 122 | $orderManager->createOrder($order); 123 | } catch (ApiValidationException $e) { 124 | echo $e->getMessage(); 125 | echo $e->getVLDCode(); 126 | echo $e->getDescription(); 127 | } catch (SdkException $e) { 128 | echo $e->getMessage(); 129 | } 130 | -------------------------------------------------------------------------------- /src/Exception/ApiValidationException.php: -------------------------------------------------------------------------------- 1 | title = $title; 20 | $this->vldCode = $vldCode; 21 | $this->description = $description; 22 | 23 | parent::__construct($title, $respCode, $previous); 24 | } 25 | 26 | public function getTitle() { 27 | return $this->title; 28 | } 29 | 30 | public function getVLDCode() { 31 | return $this->vldCode; 32 | } 33 | 34 | public function getDescription() { 35 | return $this->description; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Exception/ClientException.php: -------------------------------------------------------------------------------- 1 | name = $name; 33 | $this->value = $value; 34 | } 35 | 36 | /** 37 | * @return array 38 | */ 39 | public function asArray() 40 | { 41 | $result = [ 42 | 'name' => $this->name, 43 | 'value' => $this->value 44 | ]; 45 | 46 | return $result; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/v1/Agent.php: -------------------------------------------------------------------------------- 1 | agent_info = [ 65 | 'type' => $agent_type 66 | ]; 67 | 68 | if ($name) { 69 | $this->setSupplierInfo($name, [$phone], $inn); 70 | } 71 | } 72 | 73 | /** 74 | * Передача атрибутов поставщика 75 | * 76 | * @param string $name 77 | * @param array $phones 78 | * @param string $inn 79 | * 80 | * @return Agent 81 | */ 82 | public function setSupplierInfo($name, $phones, $inn) { 83 | $this->agent_info['supplier_info'] = [ 84 | 'phones' => $phones, 85 | 'name' => $name, 86 | 'inn' => $inn 87 | ]; 88 | return $this; 89 | } 90 | 91 | /** 92 | * Передача атрибутов платежного агента 93 | * 94 | * @param string $operation 95 | * @param array $phones 96 | * 97 | * @return Agent 98 | */ 99 | public function setPayingAgentInfo($operation, $phones) { 100 | $this->agent_info['paying_agent'] = [ 101 | 'operation' => $operation, 102 | 'phones' => $phones 103 | ]; 104 | return $this; 105 | } 106 | 107 | 108 | /** 109 | * Передача атрибутов оператора по приему платежей 110 | * 111 | * @param array $phones 112 | * 113 | * @return Agent 114 | */ 115 | public function setReceivePaymentsOperatorInfo($phones) { 116 | $this->agent_info['receive_payments_operator'] = [ 117 | 'phones' => $phones 118 | ]; 119 | return $this; 120 | } 121 | 122 | /** 123 | * Передача атрибутов оператора перевода 124 | * 125 | * @param string $name 126 | * @param array $phones 127 | * @param string $address 128 | * @param string $inn 129 | * 130 | * @return Agent 131 | */ 132 | public function setMoneyTransferOperatorInfo($name, $phones, $address, $inn) { 133 | $this->agent_info['money_transfer_operator'] = [ 134 | 'name' => $name, 135 | 'phones' => $phones, 136 | 'address' => $address, 137 | 'inn' => $inn 138 | ]; 139 | return $this; 140 | } 141 | 142 | /** 143 | * @return array 144 | */ 145 | public function asArray() 146 | { 147 | return $this->agent_info; 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/v1/AuthorisedPerson.php: -------------------------------------------------------------------------------- 1 | name = $name; 33 | $this->inn = $inn; 34 | } 35 | 36 | /** 37 | * @return array 38 | */ 39 | public function asArray() 40 | { 41 | $result = ['name' => $this->name]; 42 | 43 | if ($this->inn !== null) { 44 | $result['inn'] = $this->inn; 45 | } 46 | 47 | return $result; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/v1/Buyer.php: -------------------------------------------------------------------------------- 1 | name = $name; 33 | $this->inn = $inn; 34 | } 35 | 36 | /** 37 | * @param string $name 38 | * 39 | * @return Buyer 40 | */ 41 | public function setName($name) 42 | { 43 | $this->name = $name; 44 | return $this; 45 | } 46 | 47 | /** 48 | * @param string $inn 49 | * 50 | * @return Buyer 51 | */ 52 | public function setINN($inn) 53 | { 54 | $this->inn = $inn; 55 | return $this; 56 | } 57 | 58 | /** 59 | * @return array 60 | */ 61 | public function asArray() 62 | { 63 | $data = []; 64 | 65 | if ($this->name) { 66 | $data['name'] = $this->name; 67 | } 68 | 69 | if ($this->inn) { 70 | $data['inn'] = $this->inn; 71 | } 72 | 73 | return $data; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/v1/CalculationMethod.php: -------------------------------------------------------------------------------- 1 | name = $name; 33 | $this->inn = $inn; 34 | } 35 | 36 | /** 37 | * @return array 38 | */ 39 | public function asArray() 40 | { 41 | $result = ['name' => $this->name]; 42 | 43 | if ($this->inn !== null) { 44 | $result['inn'] = $this->inn; 45 | } 46 | 47 | return $result; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/v1/CashlessPayment.php: -------------------------------------------------------------------------------- 1 | sum = $sum; 44 | $this->method = $method; 45 | $this->id = $id; 46 | } 47 | 48 | /** 49 | * @param string $additionalInfo Дополнительные сведения о безналичной оплате 50 | * 51 | * @return CashlessPayment 52 | */ 53 | public function setAdditionalInfo($additionalInfo) 54 | { 55 | $this->additionalInfo = $additionalInfo; 56 | 57 | return $this; 58 | } 59 | 60 | /** 61 | * @return array 62 | */ 63 | public function asArray() 64 | { 65 | $result = [ 66 | 'sum' => $this->sum, 67 | 'method' => $this->method, 68 | 'id' => $this->id 69 | ]; 70 | 71 | if ($this->additionalInfo !== null) { 72 | $result['additionalInfo'] = $this->additionalInfo; 73 | } 74 | 75 | return $result; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/v1/Client.php: -------------------------------------------------------------------------------- 1 | key = $key; 59 | $this->secret = $secret; 60 | $this->logger = $logger; 61 | } 62 | 63 | /** 64 | * @param string $value 65 | * 66 | * @return Client 67 | */ 68 | public function setHost($value) 69 | { 70 | $this->host = $value; 71 | 72 | return $this; 73 | } 74 | 75 | /** 76 | * @param string $value 77 | * 78 | * @return Client 79 | */ 80 | public function setPartner($value) 81 | { 82 | $this->partner = $value; 83 | 84 | return $this; 85 | } 86 | 87 | /** 88 | * @param string $path 89 | * @param mixed $data 90 | * 91 | * @return mixed 92 | */ 93 | public function sendRequest($path, $data = null, $method = null) 94 | { 95 | if (is_array($data)) { 96 | $system_php_serialize_precision = ini_get('serialize_precision'); 97 | $system_php_precision = ini_get('precision'); 98 | 99 | ini_set('precision', 10); 100 | ini_set('serialize_precision', 10); 101 | 102 | $data = json_encode($data); 103 | 104 | if ($system_php_precision != False) { 105 | ini_set('precision', $system_php_precision); 106 | } 107 | 108 | if ($system_php_serialize_precision != False) { 109 | ini_set('serialize_precision', $system_php_serialize_precision); 110 | } 111 | 112 | } elseif ($data) { 113 | throw new InvalidArgumentException('Unexpected type of $data, excepts array or null'); 114 | } 115 | 116 | if (!$method) { 117 | $method = $data !== null ? 'POST' : 'GET'; 118 | } 119 | 120 | if (class_exists('Psr\Log\LogLevel')) { 121 | $log_level_debug = LogLevel::DEBUG; 122 | $log_level_warning = LogLevel::WARNING; 123 | } 124 | else { 125 | $log_level_debug = 'debug'; 126 | $log_level_warning = 'warning'; 127 | } 128 | 129 | $url = sprintf('%s/%s', $this->host, $path); 130 | $signature = hash_hmac('md5', $method . $url . ($data ? $data : ''), $this->secret); 131 | 132 | $headers = [ 133 | 'Accept: application/json', 134 | sprintf('Authorization: %s', $this->key), 135 | sprintf('X-HMAC-Signature: %s', $signature) 136 | ]; 137 | if (!empty($this->partner)) { 138 | $headers[] = sprintf('X-Partner-ID: %s', $this->partner); 139 | } 140 | if (in_array($method, array('POST', 'PUT'))) { 141 | $headers[] = 'Content-Type: application/json'; 142 | } 143 | 144 | $ch = curl_init($url); 145 | curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); 146 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 147 | curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 148 | curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 149 | if (in_array($method, array('POST', 'PUT'))) { 150 | curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 151 | } 152 | $response = curl_exec($ch); 153 | 154 | $this->log($log_level_debug, 'request: url={url} headers={headers} data={data}', [ 155 | 'url' => $url, 156 | 'headers' => $this->maskHeaders($headers), 157 | 'data' => $data 158 | ]); 159 | 160 | 161 | if ($response === false) { 162 | throw new ClientException(curl_error($ch)); 163 | } else { 164 | $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); 165 | if ($status !== 200) { 166 | $this->log($log_level_warning, 'error: {error} {response}', [ 167 | 'error' => $status, 168 | 'response' => $response 169 | ]); 170 | 171 | if (in_array($status, [500, 422, 403])) { 172 | $resp_data = json_decode($response, true); 173 | throw new ApiValidationException($resp_data['title'], 174 | $resp_data['code'], 175 | $resp_data['description'], 176 | $status); 177 | } 178 | 179 | throw new ClientException(sprintf('Unexpected status (%s)', $status), $status); 180 | } 181 | } 182 | 183 | curl_close($ch); 184 | 185 | $this->log($log_level_debug, 'response: {response}', ['response' => $response]); 186 | 187 | return json_decode($response, true); 188 | } 189 | 190 | private function log($level, $message, $context) 191 | { 192 | if ($this->logger !== null) { 193 | $message = sprintf('KOMTET Kassa %s', $message); 194 | $this->logger->log($level, $message, $context); 195 | } 196 | } 197 | 198 | private function maskHeaders($headers) 199 | { 200 | return array_map( 201 | function($header) { 202 | $parts = explode(':', $header); 203 | $key = trim($parts[0]); 204 | $value = trim($parts[1]); 205 | if (in_array($key, $this->maskedHeaders)) { 206 | $value = str_repeat('*', strlen($value) - 2) . substr($value, -2); 207 | } 208 | return [$key, $value]; 209 | }, 210 | $headers 211 | ); 212 | } 213 | } 214 | -------------------------------------------------------------------------------- /src/v1/Correction.php: -------------------------------------------------------------------------------- 1 | type = $type; 49 | $this->date = $date; 50 | 51 | if ($document) { 52 | $this->document = $document; 53 | } 54 | 55 | if ($description) { 56 | $this->description = $description; 57 | } 58 | } 59 | 60 | /** 61 | * @param string $date Document date (yyyy-mm-dd) 62 | * @param string $document Document number 63 | * @param string $description Description (Deprecated, will be removed) 64 | * 65 | * @return Correction 66 | */ 67 | public static function createSelf($date, $document=null, $description=null) 68 | { 69 | return new static(static::TYPE_SELF, $date, $document, $description); 70 | } 71 | 72 | /** 73 | * @param string $date Document date (yyyy-mm-dd) 74 | * @param string $document Document number 75 | * @param string $description Description (Deprecated, will be removed) 76 | * 77 | * @return Correction 78 | */ 79 | public static function createForced($date, $document, $description=null) 80 | { 81 | return new static(static::TYPE_FORCED, $date, $document, $description); 82 | } 83 | 84 | /** 85 | * @return array 86 | */ 87 | public function asArray() 88 | { 89 | $result = [ 90 | 'type' => $this->type, 91 | 'date' => $this->date 92 | ]; 93 | 94 | if ($this->document !== null) { 95 | $result['document'] = $this->document; 96 | } 97 | 98 | if ($this->description !== null) { 99 | $result['description'] = $this->description; 100 | } 101 | 102 | return $result; 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/v1/CorrectionCheck.php: -------------------------------------------------------------------------------- 1 | id = $id; 115 | $this->intent = $intent; 116 | $this->taxSystem = $taxSystem; 117 | $this->correction = $correction; 118 | $this->paymentAddress = $paymentAddress; 119 | $this->placeAddress = $placeAddress; 120 | } 121 | 122 | /** 123 | * @param string $id An unique ID provided by an online store 124 | * @param int $taxSystem One of TaxSystem::* constants 125 | * @param Correction $correction Correction data 126 | * 127 | * @return CorrectionCheck 128 | */ 129 | public static function createSellCorrection($id, $taxSystem, Correction $correction) 130 | { 131 | return new static($id, static::INTENT_SELL_CORRECTION, $taxSystem, $correction); 132 | } 133 | 134 | /** 135 | * @param string $id An unique ID provided by an online store 136 | * @param int $taxSystem One of TaxSystem::* constants 137 | * @param Correction $correction Correction data 138 | * 139 | * @return CorrectionCheck 140 | */ 141 | public static function createSellReturnCorrection($id, $taxSystem, Correction $correction) 142 | { 143 | return new static($id, static::INTENT_SELL_RETURN_CORRECTION, $taxSystem, $correction); 144 | } 145 | 146 | /** 147 | * @param string $id An unique ID provided by an online store 148 | * @param int $taxSystem One of TaxSystem::* constants 149 | * @param Correction $correction Correction data 150 | * 151 | * @return CorrectionCheck 152 | */ 153 | public static function createBuyCorrection($id, $taxSystem, Correction $correction) 154 | { 155 | return new static($id, static::INTENT_BUY_CORRECTION, $taxSystem, $correction); 156 | } 157 | 158 | /** 159 | * @param string $id An unique ID provided by an online store 160 | * @param int $taxSystem One of TaxSystem::* constants 161 | * @param Correction $correction Correction data 162 | * 163 | * @return CorrectionCheck 164 | */ 165 | public static function createBuyReturnCorrection($id, $taxSystem, Correction $correction) 166 | { 167 | return new static($id, static::INTENT_BUY_RETURN_CORRECTION, $taxSystem, $correction); 168 | } 169 | 170 | /** 171 | * @param bool $value 172 | * 173 | * @return CorrectionCheck 174 | */ 175 | public function setShouldPrint($value) 176 | { 177 | $this->shouldPrint = (bool) $value; 178 | 179 | return $this; 180 | } 181 | 182 | /** 183 | * @param Position $position 184 | * 185 | * @return CorrectionCheck 186 | */ 187 | public function addPosition(Position $position) 188 | { 189 | $this->positions[] = $position; 190 | 191 | return $this; 192 | } 193 | 194 | /** 195 | * @param Payment $payment 196 | * 197 | * @return CorrectionCheck 198 | */ 199 | public function addPayment(Payment $payment) 200 | { 201 | $this->payments[] = $payment; 202 | 203 | return $this; 204 | } 205 | 206 | /** 207 | * @param Buyer $buyer 208 | * 209 | * @return CorrectionCheck 210 | */ 211 | public function addBuyer(Buyer $buyer) 212 | { 213 | $this->buyer = $buyer; 214 | 215 | return $this; 216 | } 217 | 218 | /** 219 | * @param Cashier $cashier 220 | * 221 | * @return CorrectionCheck 222 | */ 223 | public function addCashier(Cashier $cashier) 224 | { 225 | $this->cashier = $cashier; 226 | 227 | return $this; 228 | } 229 | 230 | /** 231 | * @param string $value 232 | * 233 | * @return CorrectionCheck 234 | */ 235 | public function setAdditionalCheckProps($value) 236 | { 237 | $this->additionalCheckProps = $value; 238 | 239 | return $this; 240 | } 241 | 242 | /** 243 | * @param AdditionalUserProps $additionalUserProps 244 | * 245 | * @return CorrectionCheck 246 | */ 247 | public function setAdditionalUserProps(AdditionalUserProps $additional_user_props) 248 | { 249 | $this->additionalUserProps = $additional_user_props; 250 | 251 | return $this; 252 | } 253 | 254 | /** 255 | * @param AuthorisedPerson $authorised_person 256 | * 257 | * @return CorrectionCheck 258 | */ 259 | public function setAuthorisedPerson(AuthorisedPerson $authorised_person) 260 | { 261 | $this->authorisedPerson = $authorised_person; 262 | 263 | return $this; 264 | } 265 | 266 | /** 267 | * @param bool $value 268 | * 269 | * @return CorrectionCheck 270 | */ 271 | public function setInternet($value) 272 | { 273 | $this->internet = (bool) $value; 274 | 275 | return $this; 276 | } 277 | 278 | /** 279 | * @param string $user 280 | * 281 | * @return CorrectionCheck 282 | */ 283 | public function setUser($user) 284 | { 285 | $this->user = $user; 286 | 287 | return $this; 288 | } 289 | 290 | /** 291 | * @param string $callback_url callback url for CorrectionCheck 292 | * 293 | */ 294 | public function setCallbackUrl($callback_url) 295 | { 296 | $this->callbackUrl = $callback_url; 297 | } 298 | 299 | /** 300 | * @return array 301 | */ 302 | public function asArray() 303 | { 304 | $result = [ 305 | 'external_id' => $this->id, 306 | 'intent' => $this->intent, 307 | 'sno' => $this->taxSystem, 308 | 'payments' => array_map( 309 | function ($payment) { 310 | return $payment->asArray(); 311 | }, 312 | $this->payments 313 | ), 314 | 'positions' => array_map( 315 | function ($position) { 316 | return $position->asArray(); 317 | }, 318 | $this->positions 319 | ), 320 | 'correction' => $this->correction->asArray() 321 | ]; 322 | 323 | if ($this->buyer !== null) { 324 | $result['client'] = $this->buyer->asArray(); 325 | } 326 | 327 | if ($this->shouldPrint !== null) { 328 | $result['print'] = $this->shouldPrint; 329 | } 330 | 331 | if ($this->authorisedPerson !== null) { 332 | $result['authorised_person'] = $this->authorisedPerson->asArray(); 333 | } 334 | 335 | if ($this->cashier !== null) { 336 | $result['cashier'] = $this->cashier->asArray(); 337 | } 338 | 339 | if ($this->paymentAddress !== null) { 340 | $result['payment_address'] = $this->paymentAddress; 341 | } 342 | 343 | if ($this->placeAddress !== null) { 344 | $result['place_address'] = $this->placeAddress; 345 | } 346 | 347 | if ($this->additionalCheckProps !== null) { 348 | $result['additional_check_props'] = $this->additionalCheckProps; 349 | } 350 | 351 | if ($this->additionalUserProps !== null) { 352 | $result['additional_user_props'] = $this->additionalUserProps->asArray(); 353 | } 354 | 355 | if ($this->internet !== null) { 356 | $result['internet'] = $this->internet; 357 | } 358 | 359 | if ($this->user !== null) { 360 | $result['user'] = $this->user; 361 | } 362 | 363 | if ($this->callbackUrl !== null) { 364 | $result['callback_url'] = $this->callbackUrl; 365 | } 366 | 367 | return $result; 368 | } 369 | } 370 | -------------------------------------------------------------------------------- /src/v1/Employee.php: -------------------------------------------------------------------------------- 1 | type = $type; 89 | $this->name = $name; 90 | 91 | $this->login = $login; 92 | $this->password = $password; 93 | 94 | $this->pos_id = $pos_id; 95 | 96 | if ($inn) { 97 | $this->inn = $inn; 98 | } 99 | 100 | if ($phone) { 101 | $this->phone = $phone; 102 | } 103 | 104 | if ($email) { 105 | $this->email = $email; 106 | } 107 | } 108 | 109 | /** 110 | * @param string $paymentAddress Settlement address 111 | * 112 | */ 113 | public function setPaymentAddress($paymentAddress) 114 | { 115 | $this->paymentAddress = $paymentAddress; 116 | } 117 | 118 | /** 119 | * @param bool $isManager 120 | * @param bool $isCanAssignOrder 121 | * @param bool isAppFastBasket 122 | * 123 | */ 124 | public function setAccessSettings($isManager = null, $isCanAssignOrder = null, $isAppFastBasket = null) 125 | { 126 | if ($isManager) { 127 | $this->isManager = $isManager; 128 | } 129 | 130 | if ($isCanAssignOrder) { 131 | $this->isCanAssignOrder = $isCanAssignOrder; 132 | } 133 | 134 | if ($isAppFastBasket) { 135 | $this->isAppFastBasket = $isAppFastBasket; 136 | } 137 | } 138 | 139 | /** 140 | * @return array 141 | */ 142 | public function asArray() 143 | { 144 | $result = [ 145 | 'type' => $this->type, 146 | 'name' => $this->name, 147 | 'login' => $this->login, 148 | 'password' => $this->password, 149 | 'pos_id' => $this->pos_id 150 | ]; 151 | 152 | if ($this->inn !== null) { 153 | $result['inn'] = $this->inn; 154 | } 155 | 156 | if ($this->phone !== null) { 157 | $result['phone'] = $this->phone; 158 | } 159 | 160 | if ($this->email !== null) { 161 | $result['email'] = $this->email; 162 | } 163 | 164 | if ($this->paymentAddress !== null) { 165 | $result['payment_address'] = $this->paymentAddress; 166 | } 167 | 168 | if ($this->isManager !== null) { 169 | $result['is_manager'] = $this->isManager; 170 | } 171 | 172 | if ($this->isCanAssignOrder !== null) { 173 | $result['is_can_assign_order'] = $this->isCanAssignOrder; 174 | } 175 | 176 | if ($this->isAppFastBasket !== null) { 177 | $result['is_app_fast_basket'] = $this->isAppFastBasket; 178 | } 179 | 180 | return $result; 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /src/v1/EmployeeManager.php: -------------------------------------------------------------------------------- 1 | client = $client; 25 | } 26 | 27 | 28 | /** 29 | * Feed back the information about employees 30 | * 31 | * @param EmployeeType $type type of employees 32 | * @param string $start Launch the employees input from "start" 33 | * @param string $limit Bound the employees input to the "limit" elements 34 | * 35 | * @return mixed 36 | */ 37 | public function getEmployees($start = '0', $limit = '10', $type = null) 38 | { 39 | $path = sprintf('api/shop/v1/employees?start=%s&limit=%s', $start, $limit); 40 | if ($type) { 41 | $path .= sprintf('&type=%s', $type); 42 | } 43 | return $this->client->sendRequest($path); 44 | } 45 | 46 | /** 47 | * Employee creation 48 | * 49 | * @param Employee $employee Employee 50 | * 51 | * @return mixed 52 | */ 53 | public function createEmployee($employee) 54 | { 55 | $path = sprintf('api/shop/v1/employees'); 56 | return $this->client->sendRequest($path, $employee->asArray()); 57 | } 58 | 59 | 60 | /** 61 | * Employee update 62 | * 63 | * @param int $oid Employee ID 64 | * @param Employee $employee Employee 65 | * 66 | * @return mixed 67 | */ 68 | public function updateEmployee($eid, $employee) 69 | { 70 | $path = sprintf('api/shop/v1/employees/%s', $eid); 71 | return $this->client->sendRequest($path, $employee->asArray(), 'PUT'); 72 | } 73 | 74 | 75 | /** 76 | * Viewing employee information 77 | * 78 | * @param int $eid Employee ID 79 | * 80 | * @return mixed 81 | */ 82 | public function getEmployeeInfo($eid) 83 | { 84 | $path = sprintf('api/shop/v1/employees/%s', $eid); 85 | return $this->client->sendRequest($path); 86 | } 87 | 88 | 89 | /** 90 | * Delete employee 91 | * 92 | * @param int $eid Employee ID 93 | * 94 | * @return mixed 95 | */ 96 | public function deleteEmployee($eid) 97 | { 98 | $path = sprintf('api/shop/v1/employees/%s', $eid); 99 | return $this->client->sendRequest($path, null, 'DELETE'); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/v1/EmployeeType.php: -------------------------------------------------------------------------------- 1 | nomenclature_code = []; 26 | 27 | if ($code !== null) { 28 | $this->setCode($code); 29 | } 30 | 31 | if ($hex_code !== null) { 32 | $this->setHexCode($hex_code); 33 | } 34 | } 35 | 36 | /** 37 | * @param string $code 38 | * 39 | */ 40 | public function setCode($code) 41 | { 42 | $this->nomenclature_code['code'] = $code; 43 | } 44 | 45 | /** 46 | * @param string $code 47 | * 48 | */ 49 | public function setHexCode($code) 50 | { 51 | $this->nomenclature_code['hex_code'] = $code; 52 | } 53 | 54 | /** 55 | * @return array 56 | */ 57 | public function asArray() 58 | { 59 | return $this->nomenclature_code; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/v1/Order.php: -------------------------------------------------------------------------------- 1 | order_id = $order_id; 113 | $this->is_paid = $is_paid; 114 | 115 | $this->state = $state; 116 | $this->sno = $sno; 117 | 118 | $this->prepayment = $prepayment; 119 | $this->payment_type = $payment_type; 120 | } 121 | 122 | /** 123 | * @param string $address Address of the recipient 124 | * @param string $phone Phone of the recipient 125 | * @param string $email Email of the recipient 126 | * @param string $name Name of the recipient 127 | * @param array $coordinate Coordinate latitude/longitude 128 | * 129 | */ 130 | public function setClient($address, $phone, $email = null, $name = null, $coordinate=null) 131 | { 132 | $this->client_address = $address; 133 | $this->client_phone = $phone; 134 | 135 | $this->client_email = $email; 136 | $this->client_name = $name; 137 | 138 | $this->client_coordinate = $coordinate; 139 | } 140 | /** 141 | * @param string $date_start Initial order delivery time 142 | * @param string $date_end Final order delivery time 143 | * 144 | */ 145 | public function setDeliveryTime($date_start, $date_end) 146 | { 147 | $this->date_start = $date_start; 148 | $this->date_end = $date_end; 149 | } 150 | 151 | /** 152 | * @param string $description Order comment 153 | * 154 | */ 155 | public function setDescription($description) 156 | { 157 | $this->description = $description; 158 | } 159 | 160 | /** 161 | * @param string $oid Item identifier 162 | * @param string $name Item 163 | * @param int|float $price Item price in the check 164 | * @param int|float $quantity Number of items 165 | * @param int|float $total Item total value 166 | * @param string $vat Tax rate 167 | * @param string $type Order type 168 | * 169 | */ 170 | public function addPosition(OrderPosition $orderPosition) 171 | { 172 | array_push($this->items, $orderPosition); 173 | } 174 | 175 | /** 176 | * @param string $callback_url callback url for Order 177 | * 178 | */ 179 | public function setCallbackUrl($callback_url) 180 | { 181 | $this->callback_url = $callback_url; 182 | } 183 | 184 | /** 185 | * @param int $courier_id ID courier 186 | * 187 | */ 188 | public function setCourierId($courier_id) 189 | { 190 | $this->courier_id = $courier_id; 191 | } 192 | 193 | /** 194 | * @return array 195 | */ 196 | public function getPositions() 197 | { 198 | return $this->items; 199 | } 200 | 201 | /** 202 | * @return int|float 203 | */ 204 | public function getTotalPositionsSum() 205 | { 206 | $positionsTotal = 0; 207 | foreach ($this->items as $item) { 208 | $positionsTotal += $item->getTotal(); 209 | } 210 | 211 | return $positionsTotal; 212 | } 213 | 214 | /** 215 | * 216 | * Применение к позициям единой общей скидки на чек (например скидочного купона) 217 | * 218 | * @param float $checkDiscount 219 | * 220 | * @return Order 221 | */ 222 | public function applyDiscount($checkDiscount) 223 | { 224 | $positionsTotal = $this->getTotalPositionsSum(); 225 | $checkPositions = $this->getPositions(); 226 | 227 | $positionsCount = count($checkPositions); 228 | $accumulatedDiscount = 0; 229 | 230 | foreach ($checkPositions as $index => $position) { 231 | if ($index < $positionsCount - 1) { 232 | $positionPricePercent = $position->getTotal() / $positionsTotal * 100; 233 | $curPositionDiscount = round($checkDiscount * $positionPricePercent / 100, 2); 234 | $accumulatedDiscount += $curPositionDiscount; 235 | } else { 236 | $curPositionDiscount = round($checkDiscount - $accumulatedDiscount, 2); 237 | } 238 | 239 | $position->setTotal($position->getTotal() - $curPositionDiscount); 240 | } 241 | 242 | return $this; 243 | } 244 | 245 | /** 246 | * @return array 247 | */ 248 | public function asArray() 249 | { 250 | $result = [ 251 | 'order_id' => $this->order_id, 252 | 'sno' => $this->sno, 253 | 'client_address' => $this->client_address, 254 | 'client_phone' => $this->client_phone, 255 | 'is_paid' => $this->is_paid, 256 | 'description' => $this->description, 257 | 'date_start' => $this->date_start, 258 | 'date_end' => $this->date_end, 259 | 'items' => array_map( 260 | function ($item) { 261 | return $item->asArray(); 262 | }, 263 | $this->items 264 | ), 265 | ]; 266 | 267 | if ($this->client_email !== null) { 268 | $result['client_email'] = $this->client_email; 269 | } 270 | 271 | if ($this->client_name !== null) { 272 | $result['client_name'] = $this->client_name; 273 | } 274 | 275 | if ($this->state !== null) { 276 | $result['state'] = $this->state; 277 | } 278 | 279 | if ($this->courier_id !== null) { 280 | $result['courier_id'] = $this->courier_id; 281 | } 282 | 283 | if ($this->callback_url !== null) { 284 | $result['callback_url'] = $this->callback_url; 285 | } 286 | 287 | if ($this->payment_type !== null) { 288 | $result['payment_type'] = $this->payment_type; 289 | } 290 | 291 | if ($this->prepayment !== null) { 292 | $result['prepayment'] = $this->prepayment; 293 | } 294 | 295 | if ($this->client_coordinate !== null) { 296 | $result['client_coordinate'] = $this->client_coordinate; 297 | } 298 | 299 | return $result; 300 | } 301 | } 302 | -------------------------------------------------------------------------------- /src/v1/OrderManager.php: -------------------------------------------------------------------------------- 1 | client = $client; 25 | } 26 | 27 | 28 | /** 29 | * Order making for delivery 30 | * 31 | * @param Order $order Order 32 | * 33 | * @return mixed 34 | */ 35 | public function createOrder($order) 36 | { 37 | $path = sprintf('api/shop/v1/orders'); 38 | return $this->client->sendRequest($path, $order->asArray()); 39 | } 40 | 41 | 42 | /** 43 | * Updating order for delivery 44 | * 45 | * @param int $oid Order ID 46 | * @param Order $order Order 47 | * 48 | * @return mixed 49 | */ 50 | public function updateOrder($oid, $order) 51 | { 52 | $path = sprintf('api/shop/v1/orders/%s', $oid); 53 | return $this->client->sendRequest($path, $order->asArray(), 'PUT'); 54 | } 55 | 56 | 57 | /** 58 | * Viewing order information 59 | * 60 | * @param int $oid Order ID 61 | * 62 | * @return mixed 63 | */ 64 | public function getOrderInfo($oid) 65 | { 66 | $path = sprintf('api/shop/v1/orders/%s', $oid); 67 | return $this->client->sendRequest($path); 68 | } 69 | 70 | 71 | /** 72 | * Delete order 73 | * 74 | * @param int $oid Order ID 75 | * 76 | * @return mixed 77 | */ 78 | public function deleteOrder($oid) 79 | { 80 | $path = sprintf('api/shop/v1/orders/%s', $oid); 81 | return $this->client->sendRequest($path, null, 'DELETE'); 82 | } 83 | 84 | /** 85 | * Feed the order information back 86 | * 87 | * @param string $courier_id Courier ID 88 | * @param string $date_start Delivery date and time 89 | * @param string $start Launch the order input from "start" 90 | * @param string $limit Bound the order input to the "limit" elements 91 | * 92 | * @return mixed 93 | */ 94 | public function getOrders($start='0', $limit='10', $courier_id=null, $date_start=null) 95 | { 96 | $path = sprintf('api/shop/v1/orders?start=%s&limit=%s', $start, $limit); 97 | 98 | if ($courier_id !== null) { 99 | $path .= sprintf('&courier_id=%s', $courier_id); 100 | } 101 | 102 | if ($date_start !== null) { 103 | $path .= sprintf('&date_start=%s', $date_start); 104 | } 105 | return $this->client->sendRequest($path); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/v1/OrderPosition.php: -------------------------------------------------------------------------------- 1 | Vat::RATE_NO, 103 | 'total' => null, 104 | 'measure_name' => null, 105 | 'type' => null, 106 | 'quantity' => 1, 107 | 'agent' => null, 108 | 'excise' => null, 109 | 'country_code' => null, 110 | 'declaration_number' => null, 111 | 'nomenclature_code' => null, 112 | 'is_need_nomenclature_code' => false 113 | ]; 114 | $args = array_merge($defaultArgs, $args); 115 | 116 | if ($args['total'] == null) { 117 | $args['total'] = $args['price'] * $args['quantity']; 118 | } 119 | 120 | $this->oid = $args['oid']; 121 | $this->name = $args['name']; 122 | $this->price = $args['price']; 123 | $this->quantity = $args['quantity']; 124 | $this->total = $args['total']; 125 | $this->vat = new Vat($args['vat']); 126 | $this->is_need_nomenclature_code = $args['is_need_nomenclature_code']; 127 | 128 | if ($args['measure_name'] !== null) { 129 | $this->measure_name = $args['measure_name']; 130 | } 131 | 132 | if ($args['type'] !== null) { 133 | $this->type = $args['type']; 134 | } 135 | 136 | if ($args['agent'] !== null) { 137 | $this->agent = $args['agent']; 138 | } 139 | 140 | if ($args['excise'] !== null) { 141 | $this->excise = $args['excise']; 142 | } 143 | 144 | if ($args['country_code'] !== null) { 145 | $this->country_code = $args['country_code']; 146 | } 147 | 148 | if ($args['declaration_number'] !== null) { 149 | $this->declaration_number = $args['declaration_number']; 150 | } 151 | 152 | if ($args['nomenclature_code'] !== null) { 153 | $this->nomenclature_code = $args['nomenclature_code']; 154 | } 155 | } 156 | 157 | /** 158 | * @return int|float 159 | */ 160 | public function getTotal() 161 | { 162 | return $this->total; 163 | } 164 | 165 | /** 166 | * @param float $total 167 | * 168 | * @return OrderPosition 169 | */ 170 | public function setTotal($total) 171 | { 172 | $this->total = $total; 173 | 174 | return $this; 175 | } 176 | 177 | /** 178 | * @param string $nomenclature_code 179 | * 180 | * @return OrderPosition 181 | */ 182 | public function setNomenclatureCode($nomenclature_code) 183 | { 184 | if (is_null($nomenclature_code)) { 185 | $this->is_need_nomenclature_code = true; 186 | } 187 | $this->nomenclature_code = $nomenclature_code; 188 | 189 | return $this; 190 | } 191 | 192 | /** 193 | * @return array 194 | */ 195 | public function asArray() 196 | { 197 | $result = [ 198 | 'order_item_id' => $this->oid, 199 | 'name' => $this->name, 200 | 'price' => $this->price, 201 | 'quantity' => $this->quantity, 202 | 'total' => $this->total, 203 | 'vat' => $this->vat->getRate(), 204 | 'is_need_nomenclature_code' => $this->is_need_nomenclature_code, 205 | ]; 206 | 207 | if ($this->measure_name !== null) { 208 | $result['measure_name'] = $this->measure_name; 209 | } 210 | 211 | if ($this->type !== null) { 212 | $result['type'] = $this->type; 213 | } 214 | 215 | if ($this->agent !== null) { 216 | $result['agent_info'] = $this->agent->asArray(); 217 | if (array_key_exists('supplier_info', $result['agent_info'])) { 218 | $result['supplier_info'] = $result['agent_info']['supplier_info']; 219 | unset($result['agent_info']['supplier_info']); 220 | } 221 | } 222 | 223 | if ($this->excise !== null) { 224 | $result['excise'] = $this->excise; 225 | } 226 | 227 | if ($this->country_code !== null) { 228 | $result['country_code'] = $this->country_code; 229 | } 230 | 231 | if ($this->declaration_number !== null) { 232 | $result['declaration_number'] = $this->declaration_number; 233 | } 234 | 235 | if ($this->nomenclature_code !== null) { 236 | $result['nomenclature_code'] = $this->nomenclature_code; 237 | } 238 | 239 | return $result; 240 | } 241 | } 242 | -------------------------------------------------------------------------------- /src/v1/Payment.php: -------------------------------------------------------------------------------- 1 | type = $type; 58 | $this->sum = $sum; 59 | } 60 | 61 | /** 62 | * @return int|float 63 | */ 64 | public function getSum() 65 | { 66 | return $this->sum; 67 | } 68 | 69 | /** 70 | * @return array 71 | */ 72 | public function asArray() 73 | { 74 | return [ 75 | 'type' => $this->type, 76 | 'sum' => $this->sum 77 | ]; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/v1/Position.php: -------------------------------------------------------------------------------- 1 | name = $name; 96 | $this->price = $price; 97 | $this->quantity = $quantity; 98 | $this->total = $total; 99 | $this->vat = $vat; 100 | } 101 | 102 | /** 103 | * @param string|null $value 104 | * 105 | * @return Position 106 | */ 107 | public function setId($value) 108 | { 109 | $this->id = $value; 110 | 111 | return $this; 112 | } 113 | 114 | /** 115 | * @param string|null $value 116 | * 117 | * @return Position 118 | */ 119 | public function setMeasureName($value) 120 | { 121 | $this->measureName = $value; 122 | 123 | return $this; 124 | } 125 | 126 | /** 127 | * @param string $calc_method 128 | * 129 | * @return Position 130 | */ 131 | public function setCalculationMethod($calc_method) 132 | { 133 | $this->calcMethod = $calc_method; 134 | 135 | return $this; 136 | } 137 | 138 | /** 139 | * @param string $calc_subject 140 | * 141 | * @return Position 142 | */ 143 | public function setCalculationSubject($calc_subject) 144 | { 145 | $this->calcSubject = $calc_subject; 146 | 147 | return $this; 148 | } 149 | 150 | /** 151 | * @param int|float $value 152 | * 153 | * @return Position 154 | */ 155 | public function setExcise($value) 156 | { 157 | $this->excise = $value; 158 | 159 | return $this; 160 | } 161 | 162 | /** 163 | * @param string $value 164 | * 165 | * @return Position 166 | */ 167 | public function setCountryCode($value) 168 | { 169 | $this->countryCode = $value; 170 | 171 | return $this; 172 | } 173 | 174 | /** 175 | * @param string $value 176 | * 177 | * @return Position 178 | */ 179 | public function setDeclarationNumber($value) 180 | { 181 | $this->declarationNumber = $value; 182 | 183 | return $this; 184 | } 185 | 186 | /** 187 | * @param Agent $agent 188 | * 189 | * @return Position 190 | */ 191 | public function setAgent(Agent $agent) 192 | { 193 | $this->agent = $agent; 194 | 195 | return $this; 196 | } 197 | 198 | /** 199 | * @param Nomenclature $nomenclature 200 | * 201 | * @return Position 202 | */ 203 | public function setNomenclature(Nomenclature $nomenclature) 204 | { 205 | $this->nomenclature = $nomenclature; 206 | 207 | return $this; 208 | } 209 | 210 | /** 211 | * @return int|float 212 | */ 213 | public function getTotal() 214 | { 215 | return $this->total; 216 | } 217 | 218 | /** 219 | * @param float $total 220 | * 221 | * @return Position 222 | */ 223 | public function setTotal($total) 224 | { 225 | $this->total = $total; 226 | 227 | return $this; 228 | } 229 | 230 | /** 231 | * @return array 232 | */ 233 | public function asArray() 234 | { 235 | $result = [ 236 | 'name' => $this->name, 237 | 'price' => $this->price, 238 | 'quantity' => $this->quantity, 239 | 'total' => $this->total, 240 | 'vat' => $this->vat->getRate() 241 | ]; 242 | 243 | if ($this->id !== null) { 244 | $result['id'] = $this->id; 245 | } 246 | 247 | if ($this->measureName !== null) { 248 | $result['measure_name'] = $this->measureName; 249 | } 250 | 251 | if ($this->calcMethod !== null) { 252 | $result['calculation_method'] = $this->calcMethod; 253 | } 254 | 255 | if ($this->calcSubject !== null) { 256 | $result['calculation_subject'] = $this->calcSubject; 257 | } 258 | 259 | if ($this->excise !== null) { 260 | $result['excise'] = $this->excise; 261 | } 262 | 263 | if ($this->countryCode !== null) { 264 | $result['country_code'] = $this->countryCode; 265 | } 266 | 267 | if ($this->declarationNumber !== null) { 268 | $result['declaration_number'] = $this->declarationNumber; 269 | } 270 | 271 | if ($this->agent !== null) { 272 | $result['agent_info'] = $this->agent->asArray(); 273 | if (array_key_exists('supplier_info', $result['agent_info'])) { 274 | $result['supplier_info'] = $result['agent_info']['supplier_info']; 275 | unset($result['agent_info']['supplier_info']); 276 | } 277 | } 278 | 279 | if ($this->nomenclature !== null) { 280 | $result['nomenclature_code'] = $this->nomenclature->asArray(); 281 | } 282 | 283 | return $result; 284 | } 285 | } 286 | -------------------------------------------------------------------------------- /src/v1/QueueManager.php: -------------------------------------------------------------------------------- 1 | client = $client; 35 | } 36 | 37 | /** 38 | * Registers an queue 39 | * 40 | * @param string $name Queue name 41 | * @param string $id Queue ID 42 | * 43 | * @return QueueManager 44 | */ 45 | public function registerQueue($name, $id) 46 | { 47 | $this->queues[$name] = $id; 48 | 49 | return $this; 50 | } 51 | 52 | /** 53 | * Sets default queue 54 | * 55 | * @param string $name Queue name 56 | * 57 | * @return QueueManager 58 | */ 59 | public function setDefaultQueue($name) 60 | { 61 | if (!$this->hasQueue($name)) { 62 | throw new \InvalidArgumentException(sprintf('Unknown queue "%s"', $name)); 63 | } 64 | 65 | $this->defaultQueue = $name; 66 | 67 | return $this; 68 | } 69 | 70 | /** 71 | * Whether queue registered 72 | * 73 | * @param string $name Queue name 74 | * 75 | * @return bool 76 | */ 77 | public function hasQueue($name) 78 | { 79 | return array_key_exists($name, $this->queues); 80 | } 81 | 82 | /** 83 | * Sends a check to queue 84 | * 85 | * @param Check|CorrectionCheck $check Check instance 86 | * @param string $queueName Queue name 87 | * 88 | * @return mixed 89 | */ 90 | public function putCheck($check, $queueName = null) 91 | { 92 | if ($queueName === null) { 93 | if ($this->defaultQueue === null) { 94 | throw new \LogicException('Default queue is not set'); 95 | } 96 | $queueName = $this->defaultQueue; 97 | } 98 | 99 | if (!$this->hasQueue($queueName)) { 100 | throw new \InvalidArgumentException(sprintf('Unknown queue "%s"', $queueName)); 101 | } 102 | 103 | $path = sprintf('api/shop/v1/queues/%s/task', $this->queues[$queueName]); 104 | return $this->client->sendRequest($path, $check->asArray()); 105 | } 106 | 107 | /** 108 | * Whether queue active 109 | * 110 | * @param string $name Queue name 111 | * 112 | * @return bool 113 | */ 114 | public function isQueueActive($name) 115 | { 116 | if (!$this->hasQueue($name)) { 117 | throw new \InvalidArgumentException(sprintf('Unknown queue "%s"', $name)); 118 | } 119 | $path = sprintf('api/shop/v1/queues/%s', $this->queues[$name]); 120 | $data = $this->client->sendRequest($path); 121 | return is_array($data) && array_key_exists('state', $data) ? $data['state'] == 'active' : false; 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/v1/TaskManager.php: -------------------------------------------------------------------------------- 1 | client = $client; 25 | } 26 | 27 | /** 28 | * Returns info about the task 29 | * 30 | * @param string $taskId Task ID 31 | * 32 | * @return mixed 33 | */ 34 | public function getTaskInfo($taskId) 35 | { 36 | $path = sprintf('api/shop/v1/tasks/%s', $taskId); 37 | return $this->client->sendRequest($path); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/v1/TaxSystem.php: -------------------------------------------------------------------------------- 1 | static::RATE_105, 90 | '7/107' => static::RATE_107, 91 | '10/110' => static::RATE_110, 92 | '20/120' => static::RATE_120, 93 | // С 1 января 2019 года ставка по налогу 18% увеличилась до 20% и больше не применяется 94 | '18' => static::RATE_20, 95 | '118' => static::RATE_120, 96 | '18/118' => static::RATE_120 97 | ]; 98 | 99 | $rate = $rateMapping[$rate] ?? $rate; 100 | 101 | if (!in_array($rate, [ 102 | static::RATE_NO, 103 | static::RATE_0, 104 | static::RATE_5, 105 | static::RATE_7, 106 | static::RATE_10, 107 | static::RATE_20, 108 | static::RATE_105, 109 | static::RATE_107, 110 | static::RATE_110, 111 | static::RATE_120 112 | ])) { 113 | throw new \InvalidArgumentException(sprintf('Unknown VAT rate: %s', $rate)); 114 | } 115 | 116 | $this->rate = $rate; 117 | } 118 | 119 | /** 120 | * @return string 121 | */ 122 | public function getRate() 123 | { 124 | return $this->rate; 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/v2/AdditionalUserProps.php: -------------------------------------------------------------------------------- 1 | name = $name; 33 | $this->value = $value; 34 | } 35 | 36 | /** 37 | * @return array 38 | */ 39 | public function asArray() 40 | { 41 | $result = [ 42 | 'name' => $this->name, 43 | 'value' => $this->value 44 | ]; 45 | 46 | return $result; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/v2/Agent.php: -------------------------------------------------------------------------------- 1 | agent_info = [ 65 | 'type' => $agent_type 66 | ]; 67 | 68 | if ($name) { 69 | $this->setSupplierInfo($name, [$phone], $inn); 70 | } 71 | } 72 | 73 | /** 74 | * Передача атрибутов поставщика 75 | * 76 | * @param string $name 77 | * @param array $phones 78 | * @param string $inn 79 | * 80 | * @return Agent 81 | */ 82 | public function setSupplierInfo($name, $phones, $inn) { 83 | $this->agent_info['supplier_info'] = [ 84 | 'phones' => $phones, 85 | 'name' => $name, 86 | 'inn' => $inn 87 | ]; 88 | return $this; 89 | } 90 | 91 | /** 92 | * Передача атрибутов платежного агента 93 | * 94 | * @param string $operation 95 | * @param array $phones 96 | * 97 | * @return Agent 98 | */ 99 | public function setPayingAgentInfo($operation, $phones) { 100 | $this->agent_info['paying_agent'] = [ 101 | 'operation' => $operation, 102 | 'phones' => $phones 103 | ]; 104 | return $this; 105 | } 106 | 107 | 108 | /** 109 | * Передача атрибутов оператора по приему платежей 110 | * 111 | * @param array $phones 112 | * 113 | * @return Agent 114 | */ 115 | public function setReceivePaymentsOperatorInfo($phones) { 116 | $this->agent_info['receive_payments_operator'] = [ 117 | 'phones' => $phones 118 | ]; 119 | return $this; 120 | } 121 | 122 | /** 123 | * Передача атрибутов оператора перевода 124 | * 125 | * @param string $name 126 | * @param array $phones 127 | * @param string $address 128 | * @param string $inn 129 | * 130 | * @return Agent 131 | */ 132 | public function setMoneyTransferOperatorInfo($name, $phones, $address, $inn) { 133 | $this->agent_info['money_transfer_operator'] = [ 134 | 'name' => $name, 135 | 'phones' => $phones, 136 | 'address' => $address, 137 | 'inn' => $inn 138 | ]; 139 | return $this; 140 | } 141 | 142 | /** 143 | * @return array 144 | */ 145 | public function asArray() 146 | { 147 | return $this->agent_info; 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/v2/AuthorisedPerson.php: -------------------------------------------------------------------------------- 1 | name = $name; 33 | $this->inn = $inn; 34 | } 35 | 36 | /** 37 | * @return array 38 | */ 39 | public function asArray() 40 | { 41 | $result = ['name' => $this->name]; 42 | 43 | if ($this->inn !== null) { 44 | $result['inn'] = $this->inn; 45 | } 46 | 47 | return $result; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/v2/Buyer.php: -------------------------------------------------------------------------------- 1 | email = $email; 73 | return $this; 74 | } 75 | 76 | /** 77 | * @param string $name 78 | * 79 | * @return Buyer 80 | */ 81 | public function setName($name) 82 | { 83 | $this->name = $name; 84 | return $this; 85 | } 86 | 87 | /** 88 | * @param string $inn 89 | * 90 | * @return Buyer 91 | */ 92 | public function setINN($inn) 93 | { 94 | $this->inn = $inn; 95 | return $this; 96 | } 97 | 98 | /** 99 | * @param string $phone 100 | * 101 | * @return Buyer 102 | */ 103 | public function setPhone($phone) 104 | { 105 | $this->phone = $phone; 106 | return $this; 107 | } 108 | 109 | /** 110 | * @param string $birthdate 111 | * 112 | * @return Buyer 113 | */ 114 | public function setBirthdate($birthdate) 115 | { 116 | $this->birthdate = $birthdate; 117 | return $this; 118 | } 119 | 120 | /** 121 | * @param string $citizenship 122 | * 123 | * @return Buyer 124 | */ 125 | public function setCitizenship($citizenship) 126 | { 127 | $this->citizenship = $citizenship; 128 | return $this; 129 | } 130 | 131 | /** 132 | * @param string $document_code 133 | * 134 | * @return Buyer 135 | */ 136 | public function setDocumentCode($document_code) 137 | { 138 | $this->documentCode = $document_code; 139 | return $this; 140 | } 141 | 142 | /** 143 | * @param string $document_data 144 | * 145 | * @return Buyer 146 | */ 147 | public function setDocumentData($document_data) 148 | { 149 | $this->documentData = $document_data; 150 | return $this; 151 | } 152 | 153 | /** 154 | * @param string $address 155 | * 156 | * @return Buyer 157 | */ 158 | public function setAddress($address) 159 | { 160 | $this->address = $address; 161 | return $this; 162 | } 163 | 164 | /** 165 | * @return array 166 | */ 167 | public function asArray() 168 | { 169 | $buyer = []; 170 | 171 | if ($this->email) { 172 | $buyer['email'] = $this->email; 173 | } 174 | 175 | if ($this->name) { 176 | $buyer['name'] = $this->name; 177 | } 178 | 179 | if ($this->inn) { 180 | $buyer['inn'] = $this->inn; 181 | } 182 | 183 | if ($this->phone) { 184 | $buyer['phone'] = $this->phone; 185 | } 186 | 187 | if ($this->birthdate) { 188 | $buyer['birthdate'] = $this->birthdate; 189 | } 190 | 191 | if ($this->citizenship) { 192 | $buyer['citizenship'] = $this->citizenship; 193 | } 194 | 195 | if ($this->documentCode) { 196 | $buyer['document_code'] = $this->documentCode; 197 | } 198 | 199 | if ($this->documentData) { 200 | $buyer['document_data'] = $this->documentData; 201 | } 202 | 203 | if ($this->address) { 204 | $buyer['address'] = $this->address; 205 | } 206 | 207 | return $buyer; 208 | } 209 | } 210 | -------------------------------------------------------------------------------- /src/v2/Cashier.php: -------------------------------------------------------------------------------- 1 | name = $name; 33 | $this->inn = $inn; 34 | } 35 | 36 | /** 37 | * @return array 38 | */ 39 | public function asArray() 40 | { 41 | $result = ['name' => $this->name]; 42 | 43 | if ($this->inn !== null) { 44 | $result['inn'] = $this->inn; 45 | } 46 | 47 | return $result; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/v2/CashlessPayment.php: -------------------------------------------------------------------------------- 1 | sum = $sum; 44 | $this->method = $method; 45 | $this->id = $id; 46 | } 47 | 48 | /** 49 | * @param string $additionalInfo Дополнительные сведения о безналичной оплате 50 | * 51 | * @return CashlessPayment 52 | */ 53 | public function setAdditionalInfo($additionalInfo) 54 | { 55 | $this->additionalInfo = $additionalInfo; 56 | 57 | return $this; 58 | } 59 | 60 | /** 61 | * @return array 62 | */ 63 | public function asArray() 64 | { 65 | $result = [ 66 | 'sum' => $this->sum, 67 | 'method' => $this->method, 68 | 'id' => $this->id 69 | ]; 70 | 71 | if ($this->additionalInfo !== null) { 72 | $result['additionalInfo'] = $this->additionalInfo; 73 | } 74 | 75 | return $result; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/v2/Client.php: -------------------------------------------------------------------------------- 1 | key = $key; 59 | $this->secret = $secret; 60 | $this->logger = $logger; 61 | } 62 | 63 | /** 64 | * @param string $value 65 | * 66 | * @return Client 67 | */ 68 | public function setHost($value) 69 | { 70 | $this->host = $value; 71 | 72 | return $this; 73 | } 74 | 75 | /** 76 | * @param string $value 77 | * 78 | * @return Client 79 | */ 80 | public function setPartner($value) 81 | { 82 | $this->partner = $value; 83 | 84 | return $this; 85 | } 86 | 87 | /** 88 | * @param string $path 89 | * @param mixed $data 90 | * 91 | * @return mixed 92 | */ 93 | public function sendRequest($path, $data = null, $method = null) 94 | { 95 | if (is_array($data)) { 96 | $system_php_serialize_precision = ini_get('serialize_precision'); 97 | $system_php_precision = ini_get('precision'); 98 | 99 | ini_set('precision', 10); 100 | ini_set('serialize_precision', 10); 101 | 102 | $data = json_encode($data); 103 | 104 | if ($system_php_precision != False) { 105 | ini_set('precision', $system_php_precision); 106 | } 107 | 108 | if ($system_php_serialize_precision != False) { 109 | ini_set('serialize_precision', $system_php_serialize_precision); 110 | } 111 | 112 | } elseif ($data) { 113 | throw new InvalidArgumentException('Unexpected type of $data, excepts array or null'); 114 | } 115 | 116 | if (!$method) { 117 | $method = $data !== null ? 'POST' : 'GET'; 118 | } 119 | 120 | if (class_exists('Psr\Log\LogLevel')) { 121 | $log_level_debug = LogLevel::DEBUG; 122 | $log_level_warning = LogLevel::WARNING; 123 | } 124 | else { 125 | $log_level_debug = 'debug'; 126 | $log_level_warning = 'warning'; 127 | } 128 | 129 | $url = sprintf('%s/%s', $this->host, $path); 130 | $signature = hash_hmac('md5', $method . $url . ($data ? $data : ''), $this->secret); 131 | 132 | $headers = [ 133 | 'Accept: application/json', 134 | sprintf('Authorization: %s', $this->key), 135 | sprintf('X-HMAC-Signature: %s', $signature) 136 | ]; 137 | if (!empty($this->partner)) { 138 | $headers[] = sprintf('X-Partner-ID: %s', $this->partner); 139 | } 140 | if (in_array($method, array('POST', 'PUT'))) { 141 | $headers[] = 'Content-Type: application/json'; 142 | } 143 | 144 | $ch = curl_init($url); 145 | curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); 146 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 147 | curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 148 | curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 149 | if (in_array($method, array('POST', 'PUT'))) { 150 | curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 151 | } 152 | $response = curl_exec($ch); 153 | 154 | $this->log($log_level_debug, 'request: url={url} headers={headers} data={data}', [ 155 | 'url' => $url, 156 | 'headers' => $this->maskHeaders($headers), 157 | 'data' => $data 158 | ]); 159 | 160 | 161 | if ($response === false) { 162 | throw new ClientException(curl_error($ch)); 163 | } else { 164 | $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); 165 | if ($status !== 200) { 166 | $this->log($log_level_warning, 'error: {error} {response}', [ 167 | 'error' => $status, 168 | 'response' => $response 169 | ]); 170 | 171 | if (in_array($status, [500, 422, 403])) { 172 | $resp_data = json_decode($response, true); 173 | throw new ApiValidationException($resp_data['title'], 174 | $resp_data['code'], 175 | $resp_data['description'], 176 | $status); 177 | } 178 | 179 | throw new ClientException(sprintf('Unexpected status (%s)', $status), $status); 180 | } 181 | } 182 | 183 | curl_close($ch); 184 | 185 | $this->log($log_level_debug, 'response: {response}', ['response' => $response]); 186 | 187 | return json_decode($response, true); 188 | } 189 | 190 | private function log($level, $message, $context) 191 | { 192 | if ($this->logger !== null) { 193 | $message = sprintf('KOMTET Kassa %s', $message); 194 | $this->logger->log($level, $message, $context); 195 | } 196 | } 197 | 198 | private function maskHeaders($headers) 199 | { 200 | return array_map( 201 | function($header) { 202 | $parts = explode(':', $header); 203 | $key = trim($parts[0]); 204 | $value = trim($parts[1]); 205 | if (in_array($key, $this->maskedHeaders)) { 206 | $value = str_repeat('*', strlen($value) - 2) . substr($value, -2); 207 | } 208 | return [$key, $value]; 209 | }, 210 | $headers 211 | ); 212 | } 213 | } 214 | -------------------------------------------------------------------------------- /src/v2/Company.php: -------------------------------------------------------------------------------- 1 | sno = $sno; 42 | $this->paymentAddress = $payment_address; 43 | } 44 | 45 | /** 46 | * @param string $place_address 47 | * 48 | * @return Company 49 | */ 50 | public function setPlaceAddress($place_address) 51 | { 52 | $this->placeAddress = $place_address; 53 | return $this; 54 | } 55 | 56 | /** 57 | * @param string $inn 58 | * 59 | * @return Company 60 | */ 61 | public function setINN($inn) 62 | { 63 | $this->inn = $inn; 64 | return $this; 65 | } 66 | 67 | public function asArray() 68 | { 69 | $company = [ 70 | 'sno' => $this->sno, 71 | 'payment_address' => $this->paymentAddress 72 | ]; 73 | 74 | if ($this->placeAddress) { 75 | $company['place_address'] = $this->placeAddress; 76 | } 77 | 78 | if ($this->inn) { 79 | $company['inn'] = $this->inn; 80 | } 81 | 82 | return $company; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/v2/CorrectionInfo.php: -------------------------------------------------------------------------------- 1 | type = $type; 42 | $this->base_date = $base_date; 43 | 44 | if ($base_number) { 45 | $this->base_number = $base_number; 46 | } 47 | } 48 | 49 | /** 50 | * @param string $base_date Document date (dd-mm-yyyy) 51 | * @param string $base_number Document number 52 | * 53 | * @return CorrectionInfo 54 | */ 55 | public static function createSelf($base_date, $base_number = null) 56 | { 57 | return new static(static::TYPE_SELF, $base_date, $base_number); 58 | } 59 | 60 | /** 61 | * @param string $base_date Document date (dd-mm-yyyy) 62 | * @param string $base_number Document number 63 | * 64 | * @return CorrectionInfo 65 | */ 66 | public static function createInstruction($base_date, $base_number) 67 | { 68 | return new static(static::TYPE_INSTRUCTION, $base_date, $base_number); 69 | } 70 | 71 | /** 72 | * @return array 73 | */ 74 | public function asArray() 75 | { 76 | $result = [ 77 | 'type' => $this->type, 78 | 'base_date' => $this->base_date, 79 | ]; 80 | 81 | if ($this->base_number !== null) { 82 | $result['base_number'] = $this->base_number; 83 | } 84 | 85 | return $result; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/v2/Employee.php: -------------------------------------------------------------------------------- 1 | type = $type; 89 | $this->name = $name; 90 | 91 | $this->login = $login; 92 | $this->password = $password; 93 | 94 | $this->pos_id = $pos_id; 95 | 96 | if ($inn) { 97 | $this->inn = $inn; 98 | } 99 | 100 | if ($phone) { 101 | $this->phone = $phone; 102 | } 103 | 104 | if ($email) { 105 | $this->email = $email; 106 | } 107 | } 108 | 109 | /** 110 | * @param string $paymentAddress Settlement address 111 | * 112 | */ 113 | public function setPaymentAddress($paymentAddress) 114 | { 115 | $this->paymentAddress = $paymentAddress; 116 | } 117 | 118 | /** 119 | * @param bool $isManager 120 | * @param bool $isCanAssignOrder 121 | * @param bool isAppFastBasket 122 | * 123 | */ 124 | public function setAccessSettings($isManager = null, $isCanAssignOrder = null, $isAppFastBasket = null) 125 | { 126 | if ($isManager) { 127 | $this->isManager = $isManager; 128 | } 129 | 130 | if ($isCanAssignOrder) { 131 | $this->isCanAssignOrder = $isCanAssignOrder; 132 | } 133 | 134 | if ($isAppFastBasket) { 135 | $this->isAppFastBasket = $isAppFastBasket; 136 | } 137 | } 138 | 139 | /** 140 | * @return array 141 | */ 142 | public function asArray() 143 | { 144 | $result = [ 145 | 'type' => $this->type, 146 | 'name' => $this->name, 147 | 'login' => $this->login, 148 | 'password' => $this->password, 149 | 'pos_id' => $this->pos_id 150 | ]; 151 | 152 | if ($this->inn !== null) { 153 | $result['inn'] = $this->inn; 154 | } 155 | 156 | if ($this->phone !== null) { 157 | $result['phone'] = $this->phone; 158 | } 159 | 160 | if ($this->email !== null) { 161 | $result['email'] = $this->email; 162 | } 163 | 164 | if ($this->paymentAddress !== null) { 165 | $result['payment_address'] = $this->paymentAddress; 166 | } 167 | 168 | if ($this->isManager !== null) { 169 | $result['is_manager'] = $this->isManager; 170 | } 171 | 172 | if ($this->isCanAssignOrder !== null) { 173 | $result['is_can_assign_order'] = $this->isCanAssignOrder; 174 | } 175 | 176 | if ($this->isAppFastBasket !== null) { 177 | $result['is_app_fast_basket'] = $this->isAppFastBasket; 178 | } 179 | 180 | return $result; 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /src/v2/EmployeeManager.php: -------------------------------------------------------------------------------- 1 | client = $client; 25 | } 26 | 27 | 28 | /** 29 | * Feed back the information about employees 30 | * 31 | * @param EmployeeType $type type of employees 32 | * @param string $start Launch the employees input from "start" 33 | * @param string $limit Bound the employees input to the "limit" elements 34 | * 35 | * @return mixed 36 | */ 37 | public function getEmployees($start = '0', $limit = '10', $type = null) 38 | { 39 | $path = sprintf('api/shop/v2/employees?start=%s&limit=%s', $start, $limit); 40 | if ($type) { 41 | $path .= sprintf('&type=%s', $type); 42 | } 43 | return $this->client->sendRequest($path); 44 | } 45 | 46 | /** 47 | * Employee creation 48 | * 49 | * @param Employee $employee Employee 50 | * 51 | * @return mixed 52 | */ 53 | public function createEmployee($employee) 54 | { 55 | $path = sprintf('api/shop/v2/employees'); 56 | return $this->client->sendRequest($path, $employee->asArray()); 57 | } 58 | 59 | 60 | /** 61 | * Employee update 62 | * 63 | * @param int $oid Employee ID 64 | * @param Employee $employee Employee 65 | * 66 | * @return mixed 67 | */ 68 | public function updateEmployee($eid, $employee) 69 | { 70 | $path = sprintf('api/shop/v2/employees/%s', $eid); 71 | return $this->client->sendRequest($path, $employee->asArray(), 'PUT'); 72 | } 73 | 74 | 75 | /** 76 | * Viewing employee information 77 | * 78 | * @param int $eid Employee ID 79 | * 80 | * @return mixed 81 | */ 82 | public function getEmployeeInfo($eid) 83 | { 84 | $path = sprintf('api/shop/v2/employees/%s', $eid); 85 | return $this->client->sendRequest($path); 86 | } 87 | 88 | 89 | /** 90 | * Delete employee 91 | * 92 | * @param int $eid Employee ID 93 | * 94 | * @return mixed 95 | */ 96 | public function deleteEmployee($eid) 97 | { 98 | $path = sprintf('api/shop/v2/employees/%s', $eid); 99 | return $this->client->sendRequest($path, null, 'DELETE'); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/v2/EmployeeType.php: -------------------------------------------------------------------------------- 1 | mark_code = [ 76 | $mark_type => $value 77 | ]; 78 | } 79 | 80 | /** 81 | * @return array 82 | */ 83 | public function asArray() 84 | { 85 | return $this->mark_code; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/v2/MarkQuantity.php: -------------------------------------------------------------------------------- 1 | numerator = $numerator; 34 | $this->denominator = $denominator; 35 | } 36 | 37 | /** 38 | * @return array 39 | */ 40 | public function asArray() 41 | { 42 | return [ 43 | 'numerator' => $this->numerator, 44 | 'denominator' => $this->denominator, 45 | ]; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/v2/Measure.php: -------------------------------------------------------------------------------- 1 | name = $name; 38 | $this->value = $value; 39 | $this->timestamp = $timestamp; 40 | } 41 | 42 | /** 43 | * @return array 44 | */ 45 | public function asArray() 46 | { 47 | $result = [ 48 | 'name' => $this->name, 49 | 'value' => $this->value, 50 | 'timestamp' => $this->timestamp 51 | ]; 52 | 53 | return $result; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/v2/OrderBuyer.php: -------------------------------------------------------------------------------- 1 | orderBuyer = [ 22 | 'phone' => $phone, 23 | 'address' => $address 24 | ]; 25 | 26 | if ($name !== null) { 27 | $this->orderBuyer['name'] = $name; 28 | } 29 | 30 | if ($inn !== null) { 31 | $this->orderBuyer['inn'] = $inn; 32 | } 33 | 34 | if ($email !== null) { 35 | $this->orderBuyer['email'] = $email; 36 | } 37 | 38 | if ($coordinate !== null) { 39 | $this->orderBuyer['coordinate'] = $coordinate; 40 | } 41 | } 42 | 43 | /** 44 | * 45 | * 46 | * @param array 47 | * 48 | * @return OrderBuyer 49 | */ 50 | public function setCoordinate($longitude, $latitude) { 51 | $this->orderBuyer['coordinate'] = [ 52 | 'longitude' => $longitude, 53 | 'latitude' => $latitude 54 | ]; 55 | return $this; 56 | } 57 | 58 | /** 59 | * @return array 60 | */ 61 | public function asArray() 62 | { 63 | return $this->orderBuyer; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/v2/OrderCompany.php: -------------------------------------------------------------------------------- 1 | sno = $sno; 44 | $this->paymentAddress = $payment_address; 45 | $this->placeAddress = $place_address; 46 | $this->inn = $inn; 47 | } 48 | 49 | /** 50 | * @param string $place_address 51 | * 52 | * @return Company 53 | */ 54 | public function setPlaceAddress($place_address) 55 | { 56 | $this->placeAddress = $place_address; 57 | 58 | return $this; 59 | } 60 | 61 | /** 62 | * @param string $inn 63 | * 64 | * @return Company 65 | */ 66 | public function setINN($inn) 67 | { 68 | $this->inn = $inn; 69 | 70 | return $this; 71 | } 72 | 73 | public function asArray() 74 | { 75 | $company = [ 76 | 'sno' => $this->sno, 77 | ]; 78 | 79 | if ($this->paymentAddress) { 80 | $company['payment_address'] = $this->paymentAddress; 81 | } 82 | 83 | if ($this->placeAddress) { 84 | $company['place_address'] = $this->placeAddress; 85 | } 86 | 87 | if ($this->inn) { 88 | $company['inn'] = $this->inn; 89 | } 90 | 91 | return $company; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/v2/OrderManager.php: -------------------------------------------------------------------------------- 1 | client = $client; 25 | } 26 | 27 | 28 | /** 29 | * Order making for delivery 30 | * 31 | * @param Order $order Order 32 | * 33 | * @return mixed 34 | */ 35 | public function createOrder($order) 36 | { 37 | $path = sprintf('api/shop/v2/orders'); 38 | return $this->client->sendRequest($path, $order->asArray()); 39 | } 40 | 41 | 42 | /** 43 | * Updating order for delivery 44 | * 45 | * @param int $oid Order ID 46 | * @param Order $order Order 47 | * 48 | * @return mixed 49 | */ 50 | public function updateOrder($oid, $order) 51 | { 52 | $path = sprintf('api/shop/v2/orders/%s', $oid); 53 | return $this->client->sendRequest($path, $order->asArray(), 'PUT'); 54 | } 55 | 56 | 57 | /** 58 | * Viewing order information 59 | * 60 | * @param int $oid Order ID 61 | * 62 | * @return mixed 63 | */ 64 | public function getOrderInfo($oid) 65 | { 66 | $path = sprintf('api/shop/v2/orders/%s', $oid); 67 | return $this->client->sendRequest($path); 68 | } 69 | 70 | 71 | /** 72 | * Delete order 73 | * 74 | * @param int $oid Order ID 75 | * 76 | * @return mixed 77 | */ 78 | public function deleteOrder($oid) 79 | { 80 | $path = sprintf('api/shop/v2/orders/%s', $oid); 81 | return $this->client->sendRequest($path, null, 'DELETE'); 82 | } 83 | 84 | /** 85 | * Feed the order information back 86 | * 87 | * @param string $courier_id Courier ID 88 | * @param string $date_start Delivery date and time 89 | * @param string $start Launch the order input from "start" 90 | * @param string $limit Bound the order input to the "limit" elements 91 | * 92 | * @return mixed 93 | */ 94 | public function getOrders($start='0', $limit='10', $courier_id=null, $date_start=null) 95 | { 96 | $path = sprintf('api/shop/v2/orders?start=%s&limit=%s', $start, $limit); 97 | 98 | if ($courier_id !== null) { 99 | $path .= sprintf('&courier_id=%s', $courier_id); 100 | } 101 | 102 | if ($date_start !== null) { 103 | $path .= sprintf('&date_start=%s', $date_start); 104 | } 105 | return $this->client->sendRequest($path); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/v2/OrderPosition.php: -------------------------------------------------------------------------------- 1 | 1, 125 | 'total' => null, 126 | 'vat' => Vat::RATE_NO, 127 | 'type' => null, 128 | 'measure' => 0, 129 | 'agent' => null, 130 | 'excise' => null, 131 | 'country_code' => null, 132 | 'declaration_number' => null, 133 | 'user_data' => null, 134 | 'is_need_mark_code' => false, 135 | 'mark_quantity' => null, 136 | 'mark_code' => null, 137 | 'sectoral_item_props' => null, 138 | ]; 139 | $args = array_merge($defaultArgs, $args); 140 | 141 | if ($args['total'] == null) { 142 | $args['total'] = $args['price'] * $args['quantity']; 143 | } 144 | 145 | $this->orderItemId = $args['order_item_id']; 146 | $this->name = $args['name']; 147 | $this->price = $args['price']; 148 | $this->quantity = $args['quantity']; 149 | $this->total = $args['total']; 150 | $this->vat = new Vat($args['vat']); 151 | $this->isNeedMarkCode = $args['is_need_mark_code']; 152 | 153 | if ($args['type'] !== null) { 154 | $this->type = $args['type']; 155 | } 156 | 157 | if ($args['measure'] !== null) { 158 | $this->measure = $args['measure']; 159 | } 160 | 161 | if ($args['agent'] !== null) { 162 | $this->agent = $args['agent']; 163 | } 164 | 165 | if ($args['excise'] !== null) { 166 | $this->excise = $args['excise']; 167 | } 168 | 169 | if ($args['country_code'] !== null) { 170 | $this->countryCode = $args['country_code']; 171 | } 172 | 173 | if ($args['declaration_number'] !== null) { 174 | $this->declarationNumber = $args['declaration_number']; 175 | } 176 | 177 | if ($args['user_data'] !== null) { 178 | $this->userData = $args['user_data']; 179 | } 180 | 181 | if ($args['mark_quantity'] !== null) { 182 | $this->markQuantity = $args['mark_quantity']; 183 | } 184 | 185 | if ($args['mark_code'] !== null) { 186 | $this->markCode = $args['mark_code']; 187 | } 188 | 189 | if ($args['sectoral_item_props'] !== null) { 190 | $this->sectoralItemProps = $args['sectoral_item_props']; 191 | } 192 | } 193 | 194 | /** 195 | * @return int|float 196 | */ 197 | public function getTotal() 198 | { 199 | return $this->total; 200 | } 201 | 202 | /** 203 | * @param float $total 204 | * 205 | * @return OrderPosition 206 | */ 207 | public function setTotal($total) 208 | { 209 | $this->total = $total; 210 | 211 | return $this; 212 | } 213 | 214 | /** 215 | * @param Agent $agent 216 | * 217 | * @return OrderPosition 218 | */ 219 | public function setAgent(Agent $agent) 220 | { 221 | $this->agent = $agent; 222 | 223 | return $this; 224 | } 225 | 226 | /** 227 | * @param SectoralItemProps $sectoral_item_props 228 | * 229 | * @return OrderPosition 230 | */ 231 | public function setSectoralItemProps(SectoralItemProps $sectoral_item_props) 232 | { 233 | $this->sectoralItemProps[] = $sectoral_item_props; 234 | 235 | return $this; 236 | } 237 | 238 | /** 239 | * @param MarkQuantity $mark_quantity 240 | * 241 | * @return OrderPosition 242 | */ 243 | public function setMarkQuantity(MarkQuantity $mark_quantity) 244 | { 245 | $this->markQuantity = $mark_quantity; 246 | 247 | return $this; 248 | } 249 | 250 | /** 251 | * @param MarkCode $mark_code 252 | * 253 | * @return OrderPosition 254 | */ 255 | public function setMarkCode(MarkCode $mark_code) 256 | { 257 | $this->markCode = $mark_code; 258 | 259 | return $this; 260 | } 261 | 262 | /** 263 | * @return array 264 | */ 265 | public function asArray() 266 | { 267 | $result = [ 268 | 'order_item_id' => $this->orderItemId, 269 | 'name' => $this->name, 270 | 'price' => $this->price, 271 | 'quantity' => $this->quantity, 272 | 'total' => $this->total, 273 | 'vat' => $this->vat->getRate(), 274 | 'is_need_mark_code' => $this->isNeedMarkCode, 275 | ]; 276 | 277 | if ($this->type !== null) { 278 | $result['type'] = $this->type; 279 | } 280 | 281 | if ($this->measure !== null) { 282 | $result['measure'] = $this->measure; 283 | } 284 | 285 | if ($this->agent !== null) { 286 | $result['agent_info'] = $this->agent->asArray(); 287 | if (array_key_exists('supplier_info', $result['agent_info'])) { 288 | $result['supplier_info'] = $result['agent_info']['supplier_info']; 289 | unset($result['agent_info']['supplier_info']); 290 | } 291 | } 292 | 293 | if ($this->excise !== null) { 294 | $result['excise'] = $this->excise; 295 | } 296 | 297 | if ($this->countryCode !== null) { 298 | $result['country_code'] = $this->countryCode; 299 | } 300 | 301 | if ($this->declarationNumber !== null) { 302 | $result['declaration_number'] = $this->declarationNumber; 303 | } 304 | 305 | if ($this->userData !== null) { 306 | $result['user_data'] = $this->userData; 307 | } 308 | 309 | if ($this->markQuantity !== null) { 310 | $result['mark_quantity'] = $this->markQuantity->asArray(); 311 | } 312 | 313 | if ($this->markCode !== null) { 314 | $result['mark_code'] = $this->markCode->asArray(); 315 | } 316 | 317 | if ($this->sectoralItemProps !== null) { 318 | $result['sectoral_item_props'] = array_map( 319 | function($sectoral_item_props) { 320 | return $sectoral_item_props->asArray(); 321 | }, 322 | $this->sectoralItemProps 323 | ); 324 | } 325 | 326 | return $result; 327 | } 328 | } 329 | -------------------------------------------------------------------------------- /src/v2/Payment.php: -------------------------------------------------------------------------------- 1 | type = $type; 58 | $this->sum = $sum; 59 | } 60 | 61 | /** 62 | * @return int|float 63 | */ 64 | public function getSum() 65 | { 66 | return $this->sum; 67 | } 68 | 69 | /** 70 | * @return array 71 | */ 72 | public function asArray() 73 | { 74 | return [ 75 | 'type' => $this->type, 76 | 'sum' => $this->sum 77 | ]; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/v2/PaymentMethod.php: -------------------------------------------------------------------------------- 1 | name = $name; 125 | $this->price = $price; 126 | $this->quantity = $quantity; 127 | $this->total = $total; 128 | $this->vat = $vat; 129 | $this->measure = $measure; 130 | $this->paymentMethod = $paymentMethod; 131 | $this->paymentObject = $paymentObject; 132 | } 133 | 134 | /** 135 | * @param string|null $value 136 | * 137 | * @return Position 138 | */ 139 | public function setId($value) 140 | { 141 | $this->id = $value; 142 | 143 | return $this; 144 | } 145 | 146 | /** 147 | * @param int|float $value 148 | * 149 | * @return Position 150 | */ 151 | public function setExcise($value) 152 | { 153 | $this->excise = $value; 154 | 155 | return $this; 156 | } 157 | 158 | /** 159 | * @param string $value 160 | * 161 | * @return Position 162 | */ 163 | public function setCountryCode($value) 164 | { 165 | $this->countryCode = $value; 166 | 167 | return $this; 168 | } 169 | 170 | /** 171 | * @param string $value 172 | * 173 | * @return Position 174 | */ 175 | public function setDeclarationNumber($value) 176 | { 177 | $this->declarationNumber = $value; 178 | 179 | return $this; 180 | } 181 | 182 | /** 183 | * @param float $total 184 | * 185 | * @return Position 186 | */ 187 | public function setTotal($total) 188 | { 189 | $this->total = $total; 190 | 191 | return $this; 192 | } 193 | 194 | /** 195 | * @return int|float 196 | */ 197 | public function getTotal() 198 | { 199 | return $this->total; 200 | } 201 | 202 | /** 203 | * @param string $value 204 | * 205 | * @return Position 206 | */ 207 | public function setUserData($value) 208 | { 209 | $this->userData = $value; 210 | 211 | return $this; 212 | } 213 | 214 | /** 215 | * @param bool $value 216 | * 217 | * @return Position 218 | */ 219 | public function setWholesale($value) 220 | { 221 | $this->wholesale = (bool) $value; 222 | 223 | return $this; 224 | } 225 | 226 | /** 227 | * @param Agent $agent 228 | * 229 | * @return Position 230 | */ 231 | public function setAgent(Agent $agent) 232 | { 233 | $this->agent = $agent; 234 | 235 | return $this; 236 | } 237 | 238 | /** 239 | * @param MarkQuantity $mark_quantity 240 | * 241 | * @return Position 242 | */ 243 | public function setMarkQuantity(MarkQuantity $mark_quantity) 244 | { 245 | $this->markQuantity = $mark_quantity; 246 | 247 | return $this; 248 | } 249 | 250 | /** 251 | * @param MarkCode $mark_code 252 | * 253 | * @return Position 254 | */ 255 | public function setMarkCode(MarkCode $mark_code) 256 | { 257 | $this->markCode = $mark_code; 258 | 259 | return $this; 260 | } 261 | 262 | /** 263 | * @param SectoralItemProps $sectoral_item_props 264 | * 265 | * @return Position 266 | */ 267 | public function setSectoralItemProps(SectoralItemProps $sectoral_item_props) 268 | { 269 | $this->sectoralItemProps[] = $sectoral_item_props; 270 | 271 | return $this; 272 | } 273 | 274 | /** 275 | * @param int $plannedStatus One of PlannedStatus::PLANNED_STATUS_* constants 276 | * 277 | * @return Position 278 | */ 279 | public function setPlannedStatus($plannedStatus) 280 | { 281 | $this->plannedStatus = $plannedStatus; 282 | 283 | return $this; 284 | } 285 | 286 | /** 287 | * @return array 288 | */ 289 | public function asArray() 290 | { 291 | $result = [ 292 | 'name' => $this->name, 293 | 'price' => $this->price, 294 | 'quantity' => $this->quantity, 295 | 'total' => $this->total, 296 | 'vat' => $this->vat->getRate(), 297 | 'measure' => $this->measure, 298 | 'payment_method' => $this->paymentMethod, 299 | 'payment_object' => $this->paymentObject 300 | ]; 301 | 302 | if ($this->id !== null) { 303 | $result['id'] = $this->id; 304 | } 305 | 306 | if ($this->excise !== null) { 307 | $result['excise'] = $this->excise; 308 | } 309 | 310 | if ($this->countryCode !== null) { 311 | $result['country_code'] = $this->countryCode; 312 | } 313 | 314 | if ($this->declarationNumber !== null) { 315 | $result['declaration_number'] = $this->declarationNumber; 316 | } 317 | 318 | if ($this->userData !== null) { 319 | $result['user_data'] = $this->userData; 320 | } 321 | 322 | if ($this->wholesale !== null) { 323 | $result['wholesale'] = $this->wholesale; 324 | } 325 | 326 | if ($this->agent !== null) { 327 | $result['agent_info'] = $this->agent->asArray(); 328 | if (array_key_exists('supplier_info', $result['agent_info'])) { 329 | $result['supplier_info'] = $result['agent_info']['supplier_info']; 330 | unset($result['agent_info']['supplier_info']); 331 | } 332 | } 333 | 334 | if ($this->markQuantity !== null) { 335 | $result['mark_quantity'] = $this->markQuantity->asArray(); 336 | } 337 | 338 | if ($this->markCode !== null) { 339 | $result['mark_code'] = $this->markCode->asArray(); 340 | } 341 | 342 | if ($this->sectoralItemProps !== null) { 343 | $result['sectoral_item_props'] = array_map( 344 | function($sectoral_item_props) { 345 | return $sectoral_item_props->asArray(); 346 | }, 347 | $this->sectoralItemProps 348 | ); 349 | } 350 | 351 | if ($this->plannedStatus !== null) { 352 | $result['planned_status'] = $this->plannedStatus; 353 | } 354 | 355 | return $result; 356 | } 357 | } 358 | -------------------------------------------------------------------------------- /src/v2/QueueManager.php: -------------------------------------------------------------------------------- 1 | client = $client; 35 | } 36 | 37 | /** 38 | * Registers an queue 39 | * 40 | * @param string $name Queue name 41 | * @param int $id Queue ID 42 | * 43 | * @return QueueManager 44 | */ 45 | public function registerQueue($name, $id) 46 | { 47 | $this->queues[$name] = $id; 48 | 49 | return $this; 50 | } 51 | 52 | /** 53 | * Sets default queue 54 | * 55 | * @param string $name Queue name 56 | * 57 | * @return QueueManager 58 | */ 59 | public function setDefaultQueue($name) 60 | { 61 | if (!$this->hasQueue($name)) { 62 | throw new \InvalidArgumentException(sprintf('Unknown queue "%s"', $name)); 63 | } 64 | 65 | $this->defaultQueue = $name; 66 | 67 | return $this; 68 | } 69 | 70 | /** 71 | * Whether queue registered 72 | * 73 | * @param string $name Queue name 74 | * 75 | * @return bool 76 | */ 77 | public function hasQueue($name) 78 | { 79 | return array_key_exists($name, $this->queues); 80 | } 81 | 82 | /** 83 | * Sends a check to queue 84 | * 85 | * @param Check|CorrectionCheck $check Check instance 86 | * @param string $queueName Queue name 87 | * 88 | * @return mixed 89 | */ 90 | public function putCheck($check, $queueName = null) 91 | { 92 | if ($queueName === null) { 93 | if ($this->defaultQueue === null) { 94 | throw new \LogicException('Default queue is not set'); 95 | } 96 | $queueName = $this->defaultQueue; 97 | } 98 | 99 | if (!$this->hasQueue($queueName)) { 100 | throw new \InvalidArgumentException(sprintf('Unknown queue "%s"', $queueName)); 101 | } 102 | 103 | $path = sprintf('api/shop/v2/queues/%s/task', $this->queues[$queueName]); 104 | return $this->client->sendRequest($path, $check->asArray()); 105 | } 106 | 107 | /** 108 | * Whether queue active 109 | * 110 | * @param string $name Queue name 111 | * 112 | * @return bool 113 | */ 114 | public function isQueueActive($name) 115 | { 116 | if (!$this->hasQueue($name)) { 117 | throw new \InvalidArgumentException(sprintf('Unknown queue "%s"', $name)); 118 | } 119 | $path = sprintf('api/shop/v2/queues/%s', $this->queues[$name]); 120 | $data = $this->client->sendRequest($path); 121 | return is_array($data) && array_key_exists('state', $data) ? $data['state'] == 'active' : false; 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/v2/SectoralCheckProps.php: -------------------------------------------------------------------------------- 1 | federal_id = $federal_id; 45 | $this->date = $date; 46 | $this->number = $number; 47 | $this->value = $value; 48 | } 49 | 50 | /** 51 | * @return array 52 | */ 53 | public function asArray() 54 | { 55 | return [ 56 | 'federal_id' => $this->federal_id, 57 | 'date' => $this->date, 58 | 'number' => $this->number, 59 | 'value' => $this->value 60 | ]; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/v2/SectoralItemProps.php: -------------------------------------------------------------------------------- 1 | federal_id = $federal_id; 45 | $this->date = $date; 46 | $this->number = $number; 47 | $this->value = $value; 48 | } 49 | 50 | /** 51 | * @return array 52 | */ 53 | public function asArray() 54 | { 55 | $result = [ 56 | 'federal_id' => $this->federal_id, 57 | 'date' => $this->date, 58 | 'number' => $this->number, 59 | 'value' => $this->value 60 | ]; 61 | 62 | return $result; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/v2/TaskManager.php: -------------------------------------------------------------------------------- 1 | client = $client; 25 | } 26 | 27 | /** 28 | * Returns info about the task 29 | * 30 | * @param string $taskId Task ID 31 | * 32 | * @return mixed 33 | */ 34 | public function getTaskInfo($taskId) 35 | { 36 | $path = sprintf('api/shop/v2/tasks/%s', $taskId); 37 | return $this->client->sendRequest($path); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/v2/TaxSystem.php: -------------------------------------------------------------------------------- 1 | static::RATE_105, 90 | '7/107' => static::RATE_107, 91 | '10/110' => static::RATE_110, 92 | '20/120' => static::RATE_120, 93 | // С 1 января 2019 года ставка по налогу 18% увеличилась до 20% и больше не применяется 94 | '18' => static::RATE_20, 95 | '118' => static::RATE_120, 96 | '18/118' => static::RATE_120 97 | ]; 98 | 99 | $rate = $rateMapping[$rate] ?? $rate; 100 | 101 | if (!in_array($rate, [ 102 | static::RATE_NO, 103 | static::RATE_0, 104 | static::RATE_5, 105 | static::RATE_7, 106 | static::RATE_10, 107 | static::RATE_20, 108 | static::RATE_105, 109 | static::RATE_107, 110 | static::RATE_110, 111 | static::RATE_120 112 | ])) { 113 | throw new \InvalidArgumentException(sprintf('Unknown VAT rate: %s', $rate)); 114 | } 115 | 116 | $this->rate = $rate; 117 | } 118 | 119 | /** 120 | * @return string 121 | */ 122 | public function getRate() 123 | { 124 | return $this->rate; 125 | } 126 | } 127 | --------------------------------------------------------------------------------