PHPackages                             demonzarov/mesilov-bitrix24-php-sdk - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. demonzarov/mesilov-bitrix24-php-sdk

AbandonedArchivedLibrary[API Development](/categories/api)

demonzarov/mesilov-bitrix24-php-sdk
===================================

A powerful PHP library for the Bitrix24 REST API

08PHP

Since Aug 9Pushed 2y agoCompare

[ Source](https://github.com/demonzarov/mesilov-bitrix24-php-sdk)[ Packagist](https://packagist.org/packages/demonzarov/mesilov-bitrix24-php-sdk)[ RSS](/packages/demonzarov-mesilov-bitrix24-php-sdk/feed)WikiDiscussions master Synced today

READMEChangelogDependenciesVersions (1)Used By (0)

Bitrix24 REST API PHP SDK
=========================

[](#bitrix24-rest-api-php-sdk)

[![License](https://camo.githubusercontent.com/2a7fa6b5dc7724d0cfec3be5acaea40124da12360fa322523b50dfd3edb88533/68747470733a2f2f706f7365722e707567782e6f72672f6d6573696c6f762f62697472697832342d7068702d73646b2f6c6963656e73652e737667)](https://packagist.org/packages/mesilov/bitrix24-php-sdk) [![Total Downloads](https://camo.githubusercontent.com/3a6609b78c0fc30082f06931baf4a76a06ed78956cfe5f69b02cb25680bb785a/68747470733a2f2f706f7365722e707567782e6f72672f6d6573696c6f762f62697472697832342d7068702d73646b2f646f776e6c6f6164732e737667)](https://packagist.org/packages/mesilov/bitrix24-php-sdk)[![Latest Stable Version](https://camo.githubusercontent.com/dd98300e67c5ebe98a37ddb7601b988d767522d5a9581cba5e8f4df9feab8531/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d6573696c6f762f62697472697832342d7068702d73646b2e737667)](https://packagist.org/packages/mesilov/bitrix24-php-sdk)

A powerful PHP library for the Bitrix24 REST API

### Build status

[](#build-status)

CI\\CD [status](https://github.com/mesilov/bitrix24-php-sdk/actions) on `master`[![phpstan check](https://github.com/mesilov/bitrix24-php-sdk/actions/workflows/phpstan.yml/badge.svg)](https://github.com/mesilov/bitrix24-php-sdk/actions/workflows/phpstan.yml)[![unit-tests status](https://github.com/mesilov/bitrix24-php-sdk/actions/workflows/phpunit.yml/badge.svg)](https://github.com/mesilov/bitrix24-php-sdk/actions/workflows/phpunit.yml)[![integration-tests status](https://github.com/mesilov/bitrix24-php-sdk/actions/workflows/integration.yml/badge.svg)](https://github.com/mesilov/bitrix24-php-sdk/actions/workflows/integration.yml)Integration tests run in GitHub actions with real Bitrix24 portal

### BITRIX24-PHP-SDK Documentation

[](#bitrix24-php-sdk-documentation)

- [Russian](/docs/RU/documentation.md)
- [English](/docs/EN/documentation.md)

### BITRIX24-PHP-SDK ✨FEATURES✨

[](#bitrix24-php-sdk-features)

Support both auth modes:

- work with auth tokens for Bitrix24 applications in marketplace
- work with incoming webhooks for simple integration projects for current portal

Low-level tools to devs:

- Domain core events:
    - Access Token expired
    - Bitrix24 portal domain url changed
- Rate-limit strategy
- Retry strategy for safe methods

API - level features

- Auto renew access tokens
- List queries with «start=-1» support
- offline queues

Performance improvements 🚀

- Batch queries implemented with [PHP Generators](https://www.php.net/manual/en/language.generators.overview.php) – constant low memory and low CPI usage
    - batch read data from bitrix24
    - batch write data to bitrix24
    - write and read in one batch package
    - composite batch queries to many entities (work in progress)
- read without count flag

### Development principles

[](#development-principles)

- Good developer experience
    - auto-completion of methods at the IDE
    - typed method call signatures
    - typed results of method calls
    - helpers for typical operations
- Good documentation
    - documentation on the operation of a specific method containing a link to the official documentation
    - documentation for working with the SDK
- Performance first:
    - minimal impact on client code
    - ability to work with large amounts of data with constant memory consumption
    - efficient operation of the API using butch requests
- Modern technology stack
    - based on [Symfony HttpClient](https://symfony.com/doc/current/http_client.html)
    - actual PHP versions language features
- Reliable:
    - test coverage: unit, integration, contract
    - typical examples typical for different modes of operation and they are optimized for memory \\ performance

### Sponsors

[](#sponsors)

Help bitrix24-php-sdk by [boosty.to/bitrix24-php-sdk](https://boosty.to/bitrix24-php-sdk) its development!

### Architecture

[](#architecture)

### Abstraction layers

[](#abstraction-layers)

```
- http protocol
- json data
- symfony http client
- \Bitrix24\SDK\Core\ApiClient - work with b24 rest-api endpoints
    input: arrays \ strings
    output: Symfony\Contracts\HttpClient\ResponseInterface, operate with strings
    process: network operations
- \Bitrix24\SDK\Services\Main - work with b24 rest-api entities
    input: arrays \ strings (?) or queries?
    output: b24 response dto
    process: b24 entities, operate with

```

### File Structure

[](#file-structure)

```
    /Core
        ApiClient.php - default api-client, work on http abstraction layer, return - Symfony\Contracts\HttpClient\ResponseInterface
    /Services
        /CRM
            /Deals
                /Client
                    Deals.php
                /Exceptions
        /Tasks
        …
        Main.php - default bitrix24 rest api service provide basic funcions, work with data transfer objects

```

### Requirements

[](#requirements)

- php: &gt;=7.4
- ext-json: \*
- ext-curl: \*

### Example

[](#example)

### Installation

[](#installation)

Add `"mesilov/bitrix24-php-sdk": "2.x"` to `composer.json` of your application. Or clone repo to your project.

### Tests

[](#tests)

Tests locate in folder `tests` and we have two test types. In folder tests create file `.env.local` and fill environment variables from `.env`.

#### Unit tests

[](#unit-tests)

**Fast**, in-memory tests without a network I\\O For run unit tests you must call in command line

```
composer phpunit-run-unit-test
```

#### Integration tests

[](#integration-tests)

**Slow** tests with full lifecycle with your **test** Bitrix24 portal via webhook.

❗️Do not run integration tests with production portals ❗️

For run integration test you must:

1. Create [new Bitrix24 portal](https://www.bitrix24.ru/create.php?p=255670) for development tests
2. Go to left menu, click «Sitemap»
3. Find menu item «Developer resources»
4. Click on menu item «Other»
5. Click on menu item «Inbound webhook»
6. Assign all permisions with webhook and click «save» button
7. Create file `/tests/.env.local` with same settings, see comments in `/tests/.env` file.

```
APP_ENV=dev
BITRIX24_WEBHOOK=https:// your portal webhook url
INTEGRATION_TEST_LOG_LEVEL=500
```

8. call in command line

```
composer composer phpunit-run-integration-tests
```

#### PHP Static Analysis Tool – phpstan

[](#php-static-analysis-tool--phpstan)

Call in command line

```
 composer phpstan-analyse
```

### Submitting bugs and feature requests

[](#submitting-bugs-and-feature-requests)

Bugs and feature request are tracked on [GitHub](https://github.com/mesilov/bitrix24-php-sdk/issues)

### License

[](#license)

bitrix24-php-sdk is licensed under the MIT License - see the `MIT-LICENSE.txt` file for details

### Author

[](#author)

Maxim Mesilov -  -
See also the list of [contributors](https://github.com/mesilov/bitrix24-php-sdk/graphs/contributors) which participated in this project.

### Need custom Bitrix24 application?

[](#need-custom-bitrix24-application)

email:

### Documentation

[](#documentation)

[Bitrix24 API documentation - Russian](http://dev.1c-bitrix.ru/rest_help/)

[Bitrix24 API documentation - English](https://training.bitrix24.com/rest_help/)

[Register new Bitrix24 account](https://www.bitrix24.ru/create.php?p=255670)

Русский
-------

[](#русский)

### Принципы по которым ведётся разработка

[](#принципы-по-которым-ведётся-разработка)

- хороший DX (Developer Experience)
    - автодополнение методов на уровне IDE
    - типизированные сигнатуры вызова методов
    - типизированные результаты вызова методов – используются нативные типы: int, array, bool, string
    - хелперы для типовых операций
- хорошая документация
    - документация по работе конкретного метода содержащая ссылку на офф документацию
    - документация по работе с SDK
- производительность:
    - минимальное влияние на клиентский код
    - возможность работать с большими объёмами данных с константным потреблением памяти
    - эффективная работа c API с использованием батч-запросов
- современный стек технологий:
    - библиотеки для работы с сетью и возможностью асинхронной работы
    - фичи новых версий PHP
- надёжной:
    - покрытие тестами: unit, интеграционные, контрактные
    - есть типовые примеры характерные для разных режимов работы и они оптимизированы по памяти \\ быстродействию

### Спонсоры

[](#спонсоры)

Помогите развитию bitrix24-php-sdk подписавшись на [boosty.to/bitrix24-php-sdk](https://boosty.to/bitrix24-php-sdk)!

### Ключевые особенности

[](#ключевые-особенности)

### Слои SDK

[](#слои-sdk)

### Service – API-интерфейс для работы с конкретной сущностью

[](#service--api-интерфейс-для-работы-с-конкретной-сущностью)

Зона ответственности:

- контракт на API-методы сущности

Входящие данные:

- сигнатура вызова конкретного API-метода

Возвращаемый результат:

- `Core\Response` (????) **к обсуждению**

В зависимости от метода может быть разный возвращаемый результат:

- результат выполнения операции типа bool
- идентификатор созданной сущности типа int
- сущность + пользовательские поля с префиксами UF\_ типа array
- массив сущностей типа array
- пустой массив как результат пустого фильтра.

Если возвращать `Core\Response`, то в клиентском коде будут проблемы:

- длинные цепочки в клиентском коде для получения возвращаемого результата

```
// добавили сделку в Б24
$dealId = $dealsService->add($newDeal)->getResponseData()->getResult()->getResultData()[0];
// получили массив сделок
$deals = $dealsService->list([], [], [], 0)->getResponseData()->getResult()->getResultData();
```

- отсутствие релевантной вызываемому методу типизации возвращаемого результата.

Ожидание:

```
 add(array $newDeal):int // идентификатор новой сделки
 list(array $order, array $filter, array $select, int $start):array //массив сделок + постраничка
 get(int $dealId):array // конкретная сделка
```

Текущая реализация — возвращается унифицированный результат:

```
add(array $newDeal):Core\Response
list(array $order, array $filter, array $select, int $start):Core\Response
```

#### Core – вызов произвольных API-методов

[](#core--вызов-произвольных-api-методов)

Зона ответственности:

- вызов **произвольных** API-методов
- обработка ошибок уровня API
- запрос нового токена и повторение запроса, если получили ошибку `expired_token`

Входящие данные:

- `string $apiMethod` – название api-метода
- `array $parameters = []` – аргументы метода

Возвращаемый результат: `Core\Response` – **унифицированный** объект-обёртка, содержит:

- `Symfony\Contracts\HttpClient\ResponseInterface` — объект ответа от сервера, может быть асинхронным
- `Core\Commands\Command` — информация о команде\\аргументах которая была исполнена, используется при разборе пакетных запросов.

Для получения результата запроса к API используется метод `Response::getResponseData`, который декодирует тело ответа вызвав метод `Symfony\Contracts\HttpClient::toArray`Возвращается стандартизированный DTO `ResponseData` от API-сервера с полями:

- `Result` - DTO c результатом исполнения запроса;
- `Time` — DTO c таймингом прохождения запроса через сервера Битрикс24;
- `Pagination` — DTO постраничной навигации с полями `next` и `total`;

В случае обнаружения ошибок уровня домена будет выброшено соответствующее типизированное исключение.

Объект `Result` содержит метод `getResultData`, который возвращает массив с результатом исполнения API-запроса. В зависимости от вызванного метода там может быть:

- результат выполнения операции типа bool
- идентификатор созданной сущности типа int
- сущность + пользовательские поля с префиксами UF\_ типа array
- массив сущностей типа array
- пустой массив как результат пустого фильтра.

#### ApiClient — работа с сетью и эндпоинтами API-серверов

[](#apiclient--работа-с-сетью-и-эндпоинтами-api-серверов)

Зона ответственности:

- передача данных по сети
- соблюдение контракта на эндпоинты с которыми идёт работы
- «подпись» запросов токенами \\ передача их в нужные входящие адреса если используется авторизация по вебхукам

Используется: Symfony HttpClient

Входящие данные:

- тип http-запроса
- массив с параметрами

Возвращаемые результаты: — `Symfony\Contracts\HttpClient\ResponseInterface`

#### Формат передачи данных по сети

[](#формат-передачи-данных-по-сети)

JSON по HTTP/2 или HTTP/1.1

Спонсоры
--------

[](#спонсоры-1)

### Тесты

[](#тесты)

Тесты расположены в папке `tests` и бывают двух типов: юнит и интеграционные. В папке `tests` создайте файл `.env.local` и заполните переменные из файла `.env`.

#### Юнит тесты

[](#юнит-тесты)

**Быстрые**, выполняются без сетевого взаимодействия с Битрикс 24.

```
composer phpunit-run-unit-test
```

#### Интеграционные тесты

[](#интеграционные-тесты)

**Медленные** тесты покрывают полный жизненный цикл CRUD операций подключение к Битрикс 24 происходи с помощью веб-хука.

❗ Не запускайте интеграционные тесты на ваших production порталах они удалят все ваши данные ❗️

Для запуска интеграционных тестов вам нужно:

1. Создать [Новый портал Битрикс 24](https://www.bitrix24.ru/create.php?p=255670) для запуска тестов.
2. Перейти в левое меню и нажать "Карта сайта".
3. Найти меню для "Разработчиков"
4. Кликнуть в меню «Другое»
5. Кликнуть в меню «Входящий веб-хук»
6. Выбрать все нужные расширения и нажать кнопку "сохранить".
7. Создать файл `/tests/.env.local` с переменными окружения которые скопировать из файла `/tests/.env` .

```
APP_ENV=dev
BITRIX24_WEBHOOK=https:// your portal webhook url
INTEGRATION_TEST_LOG_LEVEL=500
```

8. Запуск из командной строки.

```
composer composer phpunit-run-integration-tests
```

#### Статический анализ кодовой базы – phpstan

[](#статический-анализ-кодовой-базы--phpstan)

Запуск из командной строки.

```
 composer phpstan-analyse
```

###  Health Score

16

—

LowBetter than 4% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity22

Early-stage or recently created project

 Bus Factor1

Top contributor holds 77.9% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/8440810?v=4)[Dmitriy Smirnov](/maintainers/demonzarov)[@demonzarov](https://github.com/demonzarov)

---

Top Contributors

[![mesilov](https://avatars.githubusercontent.com/u/1843965?v=4)](https://github.com/mesilov "mesilov (471 commits)")[![KarlsonComplete](https://avatars.githubusercontent.com/u/61900565?v=4)](https://github.com/KarlsonComplete "KarlsonComplete (24 commits)")[![camaxtly](https://avatars.githubusercontent.com/u/11616039?v=4)](https://github.com/camaxtly "camaxtly (23 commits)")[![drumrock](https://avatars.githubusercontent.com/u/10419376?v=4)](https://github.com/drumrock "drumrock (19 commits)")[![xUJYx](https://avatars.githubusercontent.com/u/25051595?v=4)](https://github.com/xUJYx "xUJYx (10 commits)")[![bbreukelen](https://avatars.githubusercontent.com/u/1590898?v=4)](https://github.com/bbreukelen "bbreukelen (10 commits)")[![yugene](https://avatars.githubusercontent.com/u/877115?v=4)](https://github.com/yugene "yugene (7 commits)")[![b24io-sdk](https://avatars.githubusercontent.com/u/32178121?v=4)](https://github.com/b24io-sdk "b24io-sdk (5 commits)")[![leonvv](https://avatars.githubusercontent.com/u/475544?v=4)](https://github.com/leonvv "leonvv (4 commits)")[![Aracon](https://avatars.githubusercontent.com/u/8439007?v=4)](https://github.com/Aracon "Aracon (3 commits)")[![valga](https://avatars.githubusercontent.com/u/23472603?v=4)](https://github.com/valga "valga (3 commits)")[![slepic](https://avatars.githubusercontent.com/u/8199404?v=4)](https://github.com/slepic "slepic (2 commits)")[![umanshield](https://avatars.githubusercontent.com/u/13598059?v=4)](https://github.com/umanshield "umanshield (2 commits)")[![MrDeff](https://avatars.githubusercontent.com/u/22890988?v=4)](https://github.com/MrDeff "MrDeff (2 commits)")[![demonzarov](https://avatars.githubusercontent.com/u/8440810?v=4)](https://github.com/demonzarov "demonzarov (2 commits)")[![andreybolonin](https://avatars.githubusercontent.com/u/2576509?v=4)](https://github.com/andreybolonin "andreybolonin (2 commits)")[![nook-ru](https://avatars.githubusercontent.com/u/444489?v=4)](https://github.com/nook-ru "nook-ru (2 commits)")[![damianoporta](https://avatars.githubusercontent.com/u/7131996?v=4)](https://github.com/damianoporta "damianoporta (2 commits)")[![OAPrilepa](https://avatars.githubusercontent.com/u/5359198?v=4)](https://github.com/OAPrilepa "OAPrilepa (2 commits)")[![alexeyshockov](https://avatars.githubusercontent.com/u/203120?v=4)](https://github.com/alexeyshockov "alexeyshockov (1 commits)")

### Embed Badge

![Health badge](/badges/demonzarov-mesilov-bitrix24-php-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/demonzarov-mesilov-bitrix24-php-sdk/health.svg)](https://phpackages.com/packages/demonzarov-mesilov-bitrix24-php-sdk)
```

###  Alternatives

[exsyst/swagger

A php library to manipulate Swagger specifications

35916.4M7](/packages/exsyst-swagger)[hubspot/api-client

Hubspot API client

24016.2M20](/packages/hubspot-api-client)[pocketmine/bedrock-protocol

An implementation of the Minecraft: Bedrock Edition protocol in PHP

172445.0k15](/packages/pocketmine-bedrock-protocol)[botman/driver-telegram

Telegram driver for BotMan

93459.5k6](/packages/botman-driver-telegram)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
