PHPackages                             rarus/bonus-server-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. [HTTP &amp; Networking](/categories/http)
4. /
5. rarus/bonus-server-php-sdk

ActiveLibrary[HTTP &amp; Networking](/categories/http)

rarus/bonus-server-php-sdk
==========================

Bonus server PHP SDK

2.0.3(2mo ago)23151[1 issues](https://github.com/rarus/bonus-server-php-sdk/issues)[2 PRs](https://github.com/rarus/bonus-server-php-sdk/pulls)MITPHPPHP ~8.2.0 || ~8.3.0 || ~8.4.0CI failing

Since Aug 15Pushed 1mo ago6 watchersCompare

[ Source](https://github.com/rarus/bonus-server-php-sdk)[ Packagist](https://packagist.org/packages/rarus/bonus-server-php-sdk)[ Docs](https://rarus.ru/bonus/)[ RSS](/packages/rarus-bonus-server-php-sdk/feed)WikiDiscussions master Synced 2mo ago

READMEChangelog (10)Dependencies (13)Versions (69)Used By (0)

rarus-bonus-php-sdk
===================

[](#rarus-bonus-php-sdk)

Установка
---------

[](#установка)

```
composer require rarus/bonus-server-php-sdk^2.0
```

### Зависимости

[](#зависимости)

- PHP &gt;= [8.2+](https://www.php.net/releases/)
- ext-bcmath
- ext-curl
- ext-json

Быстрый старт
-------------

[](#быстрый-старт)

```
$client = RarusLMS::client('API_URL','API_TOKEN');

$card = $client->cards()->getById(1); // Возвращает Cards\DTO\CardDto
$user = $client->users()->getById(1); // Возвращает Users\DTO\UserDto

// Сериализация в массив
$payload = $card->toArray();
```

Расширенный пример использования
--------------------------------

[](#расширенный-пример-использования)

```
use GuzzleHttp\HandlerStack;
use GuzzleHttp\MessageFormatter;
use GuzzleHttp\Middleware;
use Money\Currency;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Rarus\LMS\SDK\RarusLMS;
use Rarus\LMS\SDK\Users\DTO\Fabric;
use Rarus\LMS\SDK\Users\DTO\Factory;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Psr16Cache;

$logger = new Logger('rarus-bonus-service');
$logger->pushHandler(
    new StreamHandler(
        getenv('LOG_FILE'),
        getenv('LOG_LEVEL'),
    )
);

$guzzleHandlerStack = HandlerStack::create();
$guzzleHandlerStack->push(
    Middleware::log(
        $logger,
        new MessageFormatter(MessageFormatter::DEBUG)
    )
);

$httpClient = new GuzzleHttp\Client([
    'base_uri' => getenv('API_URL'),
    'connect_timeout' => 10,
    'headers' => [
        'Accept' => 'application/json',
    ],
    'handler' => $guzzleHandlerStack,
]);

$psr6Cache = new FilesystemAdapter();
$psr16Cache = new Psr16Cache($psr6Cache);

$client = RarusLMS::factory()
    ->setApiKey(getenv('API_TOKEN'))
    ->setHttpClient($httpClient)
    ->setLogger($logger)
    ->setCurrency(new Currency('RUB'))
    ->setDateTimeZone(new DateTimeZone('Europe/Moscow'))
    ->setCache($psr16Cache)
    ->build();

$userDto = Factory::create()
    ->withName('Иванов Иван')
    ->withPhone('+7(900)000-00-00')
    ->withShopId(1)
    ->withEmail('test@example.com')
    ->build();

$newUser = $client->users()->createUser($userDto); // Возвращает Users\DTO\UserDto

$user = $client->users(300)->getUserById(1); // кеширует ответ на 5 мин
$card = $client->cards()->getCardById(1);

$card = $client->cards()->getById(1); // Возвращает Cards\DTO\CardDto
$user = $client->users()->getById(1); // Возвращает Users\DTO\UserDto

// Сериализация в массив
$payload = $card->toArray();
```

Денежные суммы (`moneyphp/money`)
---------------------------------

[](#денежные-суммы-moneyphpmoney)

Все денежные поля представлены типом `Money` (minor units). Пример в `CardDto`:

```
use Money\Money;
use Money\Currency;

// В fromArray:
$balance = MoneyParser::parse($data['balance'] ?? 0.0, $currency);

// В toArray (для JSON):
'balance'  => MoneyParser::toString($this->balance),
```

Примеры
-------

[](#примеры)

### Получить карту и вывести баланс

[](#получить-карту-и-вывести-баланс)

```
use Money\Currency;
$card = $client->cards()->getById(1);
$balanceMoney = $card->balance->getAmount();
echo MoneyParser::convertMoneyToString($balanceMoney, new Currency('RUB')); // 509,7050
```

### Сериализация в массив (например, для кэша)

[](#сериализация-в-массив-например-для-кэша)

```
$cached = $card->toArray();
$again = Cards\DTO\CardDto::fromArray($cached);
```

Ошибки
------

[](#ошибки)

Все HTTP/протокольные ошибки приводятся к исключениям пространства имён `RarusBonus\Exceptions`:

- `BaseException` — базовое исключение SDK, от которого наследуются все остальные типы ошибок.
- `ApiException` — ошибка, возвращённая сервером API (статус 4xx/5xx).
- `NetworkException` — ошибка сетевого уровня (таймаут, DNS, SSL и т. п.).
- `InvalidArgumentException` — ошибка, возникающая при передаче некорректных аргументов в методы SDK.
- `RuntimeException` — ошибка, возникающая во время выполнения программы (например, ошибки парсинга или логики).
- `UnknownException` — непредусмотренная ошибка, не попавшая в другие категории.

```
try {
    $user = $this->client->users()->getUserById($userId);
} catch (NetworkException $e) {
    // ошибка сетевого уровня
} catch (ApiClientException $e) {
    // ошибка, возвращённая сервером API
} catch (UnknownException $e) {
    // непредусмотренная ошибка
}
```

###  Health Score

56

—

FairBetter than 98% of packages

Maintenance77

Regular maintenance activity

Popularity17

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity95

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 62.2% 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.

###  Release Activity

Cadence

Every ~64 days

Recently: every ~16 days

Total

45

Last Release

83d ago

Major Versions

v0.8.1.1 → v1.0.1-beta2022-11-04

1.4.0 → 2.0.02025-12-23

1.4.1 → 2.0.12025-12-26

PHP version history (4 changes)0.1.2PHP &gt;=7.1

v1.0.0-betaPHP &gt;=7.2

v1.1.0PHP ^7.2|^8.0

2.0.0PHP ~8.2.0 || ~8.3.0 || ~8.4.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/ef1a771b4f75be6c3568fedead79446507ebc8c516fec5722dbf310ce3497738?d=identicon)[rarus-web](/maintainers/rarus-web)

![](https://www.gravatar.com/avatar/fd3529fc1407e725d8695205576ea633ca56191d924421b1ec5f2ace518a4e65?d=identicon)[artsapiens](/maintainers/artsapiens)

---

Top Contributors

[![rarus-web](https://avatars.githubusercontent.com/u/5276637?v=4)](https://github.com/rarus-web "rarus-web (97 commits)")[![artsapiens](https://avatars.githubusercontent.com/u/3997051?v=4)](https://github.com/artsapiens "artsapiens (30 commits)")[![eran-rarus](https://avatars.githubusercontent.com/u/25583430?v=4)](https://github.com/eran-rarus "eran-rarus (15 commits)")[![mesilov](https://avatars.githubusercontent.com/u/1843965?v=4)](https://github.com/mesilov "mesilov (9 commits)")[![kulevg](https://avatars.githubusercontent.com/u/25499212?v=4)](https://github.com/kulevg "kulevg (4 commits)")[![Absurdd](https://avatars.githubusercontent.com/u/22277525?v=4)](https://github.com/Absurdd "Absurdd (1 commits)")

---

Tags

phpapirestRarus

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/rarus-bonus-server-php-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/rarus-bonus-server-php-sdk/health.svg)](https://phpackages.com/packages/rarus-bonus-server-php-sdk)
```

###  Alternatives

[bitrix24/b24phpsdk

An official PHP library for the Bitrix24 REST API

9230.2k4](/packages/bitrix24-b24phpsdk)[huaweicloud/huaweicloud-sdk-php

Huawei Cloud SDK for PHP

1829.2k2](/packages/huaweicloud-huaweicloud-sdk-php)[onesignal/onesignal-php-api

A powerful way to send personalized messages at scale and build effective customer engagement strategies. Learn more at onesignal.com

34170.2k2](/packages/onesignal-onesignal-php-api)[ory/hydra-client-php

Documentation for all of Ory Hydra's APIs.

1710.8k](/packages/ory-hydra-client-php)

PHPackages © 2026

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