PHPackages                             subster-payments/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. subster-payments/php-sdk

ActiveLibrary[API Development](/categories/api)

subster-payments/php-sdk
========================

Official PHP SDK for Subster

v2.4.1(1w ago)0303↓71.4%MITPHPPHP ^8.1

Since Feb 26Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/subster-payments/php-sdk)[ Packagist](https://packagist.org/packages/subster-payments/php-sdk)[ Docs](https://github.com/subster-payments/php-sdk)[ RSS](/packages/subster-payments-php-sdk/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (2)Dependencies (12)Versions (23)Used By (0)

Subster PHP SDK
===============

[](#subster-php-sdk)

Официальный PHP SDK для [Subster](https://subster.ru/) — сервиса для приема платежей, автоплатежей и управления подписками. SDK помогает работать с Subster API из PHP-кода: создавать клиентов, запускать hosted checkout, открывать billing portal, менять тарифы подписок, передавать usage-based использование и получать оплаченные счета.

Полный контракт API, параметры запросов и ответы доступны в [официальной API-документации](https://subster.ru/docs/api#/).

Быстрые ссылки
--------------

[](#быстрые-ссылки)

- [Сайт продукта](https://subster.ru/)
- [API-документация](https://subster.ru/docs/api#/)
- [Changelog](CHANGELOG.md)
- [License](LICENSE.md)

Требования
----------

[](#требования)

- PHP 8.1 или выше.
- Composer.

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

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

```
composer require subster-payments/php-sdk:^2.0.1
```

### Переход со старого имени пакета

[](#переход-со-старого-имени-пакета)

Если в проекте уже установлен пакет `subster/php-sdk`, замените его на новое имя:

```
composer remove subster/php-sdk --no-update
composer require subster-payments/php-sdk:^2.0.1 -W
```

Namespace SDK остается прежним: `Subster\PhpSdk`.

### Переход с v1 на v2

[](#переход-с-v1-на-v2)

В v2 конечные значения API гидрируются в backed enum-ы SDK. Например, `$invoice->status` теперь возвращает `Subster\PhpSdk\Enums\InvoiceStatus::Paid`, а не строку `'paid'`. При создании DTO через `::from()` можно передавать как enum case, так и backing value; при прямом вызове constructor передавайте enum case.

Response dates теперь возвращаются как native `DateTimeImmutable`, без runtime-зависимости SDK от Carbon. `SubscriptionPlanChangeData` использует поля `$id`, `$checkout_session`, `$checkout_url`, а discount coupon field называется `$api_identifier`.

Laravel Boost и AI skills
-------------------------

[](#laravel-boost-и-ai-skills)

Пакет поставляется с Laravel Boost skill для AI-ассистентов. Если в вашем Laravel-приложении установлен [Laravel Boost](https://laravel.com/docs/boost), обновите skills после установки SDK:

```
php artisan boost:install --skills
```

После этого AI-ассистент сможет использовать контекст Subster PHP SDK при задачах интеграции платежей, checkout, billing portal, подписок, usage-based billing и оплаченных счетов.

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

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

Получите API-ключ в Subster и создайте клиент SDK. Ключ передается в API как Bearer token.

```
use Subster\PhpSdk\SubsterConnector;

$subster = new SubsterConnector('your-api-key');
```

Минимальный сценарий интеграции обычно состоит из двух шагов: создать клиента Subster и отправить его на hosted checkout для оплаты тарифа. Email клиента можно не передавать, если в вашем приложении его еще нет; Subster запросит email для чека на платежной странице или в billing portal при добавлении карты.

```
use Subster\PhpSdk\DataObjects\CreateCheckoutSessionData;
use Subster\PhpSdk\DataObjects\CreateCustomerData;

$customer = $subster->customers()->create(
    CreateCustomerData::from([
        'email' => 'customer@example.ru',
        'name' => 'Иван Петров',
    ])
);

$session = $subster->checkoutSessions()->create(
    CreateCheckoutSessionData::from([
        'customer' => $customer->id,
        'items' => [
            [
                'plan' => 'your-plan-id',
            ],
        ],
        'success_url' => 'https://example.ru/billing/success',
        'cancel_url' => 'https://example.ru/billing/cancel',
    ])
);

// Redirect the customer to $session->url.
```

Основные сценарии
-----------------

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

### Клиенты

[](#клиенты)

Создавайте и обновляйте клиентов аккаунта перед оформлением платежей.

```
use Subster\PhpSdk\DataObjects\CreateCustomerData;
use Subster\PhpSdk\DataObjects\UpdateCustomerData;

$customer = $subster->customers()->create(
    CreateCustomerData::from([
        'email' => 'customer@example.ru',
        'name' => 'Иван Петров',
    ])
);

$customerWithoutEmail = $subster->customers()->create(
    CreateCustomerData::from([
        'name' => 'Клиент без email',
    ])
);

$updatedCustomer = $subster->customers()->update(
    UpdateCustomerData::from([
        'id' => $customer->id,
        'name' => 'Иван Сергеевич Петров',
    ])
);
```

Если email передан как `null` или не указан, SDK не отправит поле `email` в запросе создания клиента. В обновлении клиента `email: null` также означает “не менять email”.

### Checkout-сессии

[](#checkout-сессии)

Checkout-сессия возвращает URL платежной страницы Subster. В `items` сейчас передается тариф `plan`; для разовых оплат и usage-based тарифов можно указать `quantity`.

```
use Subster\PhpSdk\DataObjects\CreateCheckoutSessionData;
use Subster\PhpSdk\DataObjects\CreateCheckoutSessionItemData;

$session = $subster->checkoutSessions()->create(
    CreateCheckoutSessionData::from([
        'customer' => 'customer-id',
        'items' => [
            CreateCheckoutSessionItemData::from([
                'plan' => 'your-one-time-plan-id',
                'quantity' => 5,
            ]),
        ],
        'success_url' => 'https://example.ru/billing/success',
        'cancel_url' => 'https://example.ru/billing/cancel',
    ])
);
```

Raw arrays также поддерживаются:

```
'items' => [
    [
        'plan' => 'your-one-time-plan-id',
        'quantity' => 5,
    ],
],
```

Если на checkout нужно сразу применить промокод, передайте `promotion_code`:

```
$session = $subster->checkoutSessions()->create(
    CreateCheckoutSessionData::from([
        'customer' => 'customer-id',
        'items' => [
            [
                'plan' => 'your-plan-id',
            ],
        ],
        'promotion_code' => 'SUMMER25',
        'success_url' => 'https://example.ru/billing/success',
    ])
);
```

Статус checkout-сессии можно получить по ее ID:

```
$status = $subster->checkoutSessions()->get('checkout-session-id');
```

### Платный trial

[](#платный-trial)

Для подписок можно передать данные trial в `subscription_data`. Допустимые единицы длительности: `hour`, `day`, `week`, `month`, `year`.

```
use Subster\PhpSdk\DataObjects\CheckoutSessionTrialData;
use Subster\PhpSdk\DataObjects\CheckoutSessionTrialDurationData;
use Subster\PhpSdk\DataObjects\CreateCheckoutSessionData;
use Subster\PhpSdk\DataObjects\CreateCheckoutSessionSubscriptionData;
use Subster\PhpSdk\Enums\CheckoutSessionTrialInterval;

$session = $subster->checkoutSessions()->create(
    CreateCheckoutSessionData::from([
        'customer' => 'customer-id',
        'items' => [
            [
                'plan' => 'your-recurring-plan-id',
            ],
        ],
        'subscription_data' => CreateCheckoutSessionSubscriptionData::from([
            'trial' => CheckoutSessionTrialData::from([
                'amount' => 100,
                'duration' => CheckoutSessionTrialDurationData::from([
                    'unit' => CheckoutSessionTrialInterval::Day,
                    'count' => 14,
                ]),
            ]),
        ]),
        'success_url' => 'https://example.ru/billing/success',
        'cancel_url' => 'https://example.ru/billing/cancel',
    ])
);
```

### Billing portal

[](#billing-portal)

Billing portal позволяет клиенту управлять подпиской, способом оплаты и счетами через hosted-страницу Subster.

```
use Subster\PhpSdk\DataObjects\CreateBillingPortalSessionData;

$portalSession = $subster->billingPortalSessions()->create(
    CreateBillingPortalSessionData::from([
        'customer' => 'customer-id',
        'return_url' => 'https://example.ru/billing',
    ])
);

// Redirect the customer to $portalSession->url.
```

### Смена тарифа подписки

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

`changePlan` меняет тариф подписки. Если требуется доплата, Subster вернет checkout URL.

```
use Subster\PhpSdk\DataObjects\ChangeSubscriptionPlanData;
use Subster\PhpSdk\Enums\SubscriptionPlanChangeMode;

$change = $subster->subscriptions()->changePlan(
    'subscription-id',
    ChangeSubscriptionPlanData::from([
        'plan' => 'target-plan-id',
        'success_url' => 'https://example.ru/billing/success',
        'cancel_url' => 'https://example.ru/billing/cancel',
    ])
);

if ($change->mode === SubscriptionPlanChangeMode::Checkout && $change->checkout_url !== null) {
    // Redirect the customer to $change->checkout_url.
}
```

По умолчанию Subster делает перерасчет при немедленном upgrade и учитывает неиспользованное время текущего периода. Для тарифов-пакетов, где клиент должен оплатить полную стоимость нового тарифа, передайте `SubscriptionPlanChangeProrationBehavior::None`.

```
use Subster\PhpSdk\Enums\SubscriptionPlanChangeProrationBehavior;

$change = $subster->subscriptions()->changePlan(
    'subscription-id',
    ChangeSubscriptionPlanData::from([
        'plan' => 'larger-package-plan-id',
        'success_url' => 'https://example.ru/billing/success',
        'proration_behavior' => SubscriptionPlanChangeProrationBehavior::None,
    ])
);
```

### Usage-based подписки

[](#usage-based-подписки)

Для usage-based подписок сначала передайте стартовое `quantity` при создании checkout-сессии. Для последующих периодов фиксируйте текущее значение использования через `recordUsage`. `quantity` — это абсолютный snapshot использования, а не дельта.

```
use Subster\PhpSdk\DataObjects\CreateCheckoutSessionData;
use Subster\PhpSdk\DataObjects\RecordSubscriptionUsageEventData;

$session = $subster->checkoutSessions()->create(
    CreateCheckoutSessionData::from([
        'customer' => 'customer-id',
        'items' => [
            [
                'plan' => 'your-usage-based-plan-id',
                'quantity' => 20,
            ],
        ],
        'success_url' => 'https://example.ru/billing/success',
        'cancel_url' => 'https://example.ru/billing/cancel',
    ])
);

$event = $subster->subscriptions()->recordUsage(
    'subscription-id',
    RecordSubscriptionUsageEventData::from([
        'quantity' => 35,
        'occurred_at' => now(),
        'idempotency_key' => 'tenant-users-2026-01-16',
        'metadata' => ['source' => 'tenant-admin'],
    ])
);
```

### Оплаченные счета

[](#оплаченные-счета)

Получайте оплаченные счета с фильтрами по клиенту, подписке и дате оплаты. Ответ включает данные клиента, подписки и позиции счета.

```
use Subster\PhpSdk\DataObjects\ListInvoicesData;
use Subster\PhpSdk\Enums\InvoiceStatus;

$invoices = $subster->invoices()->all(ListInvoicesData::from([
    'customer' => 'customer-id',
    'paid_at_gte' => '2026-01-01',
    'paid_at_lte' => '2026-01-31',
    'limit' => 10,
]));

foreach ($invoices->data as $invoice) {
    // $invoice->customer, $invoice->subscription, and $invoice->items are included.
    // $invoice->subtotal_amount, $invoice->discount_amount, and $invoice->discount show applied discounts.

    if ($invoice->status === InvoiceStatus::Paid) {
        // Sync paid invoice state.
    }
}
```

`paid_at_gte`, `paid_at_lte` и `occurred_at` принимают `DateTimeInterface` или строку. Date-only строки вроде `2026-01-31` остаются строками, поэтому подходят для календарных фильтров.

Если `$invoices->has_more` равен `true`, запросите следующую страницу с ID последнего счета:

```
$nextPage = $subster->invoices()->all(ListInvoicesData::from([
    'starting_after' => $invoices->data->items[array_key_last($invoices->data->items)]->id,
]));
```

Поля `$invoice->subtotal_amount`, `$invoice->discount_amount` и `$invoice->discount` показывают примененную скидку. Если скидки нет, `$invoice->discount_amount` равен `0.0`, а `$invoice->discount` равен `null`.

```
if ($invoice->discount) {
    echo $invoice->discount->promotion_code->code;
    echo $invoice->discount->coupon->name;
    echo $invoice->discount->coupon->api_identifier;
}
```

Позиции счета содержат nullable поле `$item->pricing_model`. Для usage-based счетов metadata может включать детали backend meter и snapshot использования, по которому был сформирован счет.

Ошибки и полный API-контракт
----------------------------

[](#ошибки-и-полный-api-контракт)

SDK использует Saloon и выбрасывает исключения для неуспешных HTTP-ответов. Для обработки ошибок ориентируйтесь на статус API-ответа и тело ошибки Subster.

Полный список endpoint-ов, обязательные поля, форматы дат, варианты валидационных ошибок и webhook-сценарии смотрите в [официальной API-документации](https://subster.ru/docs/api#/).

Тесты
-----

[](#тесты)

```
composer test
```

Changelog
---------

[](#changelog)

Список изменений находится в [CHANGELOG](CHANGELOG.md).

License
-------

[](#license)

The MIT License (MIT). See [License File](LICENSE.md) for more information.

###  Health Score

47

—

FairBetter than 93% of packages

Maintenance94

Actively maintained with recent releases

Popularity17

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~25 days

Recently: every ~8 days

Total

22

Last Release

11d ago

Major Versions

v0.0.11 → v1.0.02026-07-03

v1.0.3 → v2.0.02026-07-03

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/4862088?v=4)[Anton Antonov](/maintainers/everully)[@everully](https://github.com/everully)

---

Top Contributors

[![everully](https://avatars.githubusercontent.com/u/4862088?v=4)](https://github.com/everully "everully (26 commits)")

---

Tags

phpapiclientsdksubster

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/subster-payments-php-sdk/health.svg)

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

###  Alternatives

[kunalvarma05/dropbox-php-sdk

Dropbox PHP API V2 SDK (Unofficial)

3613.2M19](/packages/kunalvarma05-dropbox-php-sdk)[resend/resend-php

Resend PHP library.

608.3M53](/packages/resend-resend-php)[mozex/anthropic-php

PHP client for the Anthropic API: messages, streaming, tool use, thinking, web search, code execution, batches, and more.

48614.7k20](/packages/mozex-anthropic-php)[gemini-api-php/laravel

Gemini API client for Laravel

8917.7k](/packages/gemini-api-php-laravel)[google-gemini-php/symfony

Symfony Bundle for Gemini

1514.9k2](/packages/google-gemini-php-symfony)

PHPackages © 2026

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