Skip to main content

alfabank-sdk

Асинхронный Python SDK для Alfa API Альфа-Банка (интеграция host-to-host): выписки по счетам, сводка оборотов, информация об организации и её счетах, управление вебхуками по операциям.

  • Python >= 3.13, < 3.16 (поддерживаются 3.13, 3.14 и 3.15), полностью async (httpx), строгая типизация (pydantic v2, py.typed)
  • Деньги — Decimal, никаких float
  • Ретраи с учётом идемпотентности, опциональный rate limiter
  • Две схемы аутентификации банка: ApiKey и Bearer + шов token_provider под OAuth

⚠️ Disclaimer

Этот проект — НЕОФИЦИАЛЬНЫЙ SDK.

Он создан и поддерживается сообществом. Этот SDK не является официальным, не имеет отношения к АО «Альфа-Банк» (https://alfabank.ru), не одобрен и не спонсирован им. Все упомянутые торговые марки и названия принадлежат их законным владельцам.

Используете на свой страх и риск. Авторы и контрибьюторы не несут ответственности за любые последствия использования этой библиотеки.


This project is an UNOFFICIAL SDK.

It is community-maintained and is NOT affiliated with, endorsed by, sponsored by, or in any way officially connected with Alfa-Bank (АО «Альфа-Банк», https://alfabank.ru). All trademarks and product names mentioned belong to their respective owners.

Use at your own risk. The authors and contributors are not liable for any consequences arising from the use of this library.

Установка

uv add alfabank-sdk

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

import asyncio
from datetime import date

from alfabank import AlfaBankClient


async def main() -> None:
    async with AlfaBankClient(api_key="ВАШ_КЛЮЧ") as client:
        # Профиль организации и счета с балансами
        info = await client.customer.info()
        for account in info.accounts:
            print(account.number, account.amount_balance)

        # Выписка за дату (автопагинация)
        async for tx in client.statements.iter_transactions(
            "40702810102300000001", date(2026, 7, 1)
        ):
            print(tx.direction, tx.amount.amount if tx.amount else None, tx.payment_purpose)

        # Сводка оборотов
        summary = await client.statements.summary("40702810102300000001", date(2026, 7, 1))
        print(summary.closing_balance)


asyncio.run(main())

Аутентификация

Ровно один из трёх способов:

AlfaBankClient(api_key="...")            # Authorization: ApiKey <key>
AlfaBankClient(access_token="...")       # Authorization: Bearer <token>
AlfaBankClient(token_provider=provider)  # (a)sync callable -> значение заголовка

Варианты авторизации Alfa API:

  • ApiKey — ключ для h2h-интеграции (api_key=).
  • Bearer, Authorization Code Flow H2H — токен по коду авторизации с продлением через refresh token; обмен authorization_code и ротацию refresh выполняет OAuth-хелпер (experimental — контракт /oidc/token не проверен на живой песочнице):
from alfabank.oauth import OAuthTokenProvider

provider = OAuthTokenProvider(
    client_id="...", client_secret="...", refresh_token="...",
)
client = AlfaBankClient(token_provider=provider)
  • Client Credentials Flow — токен по client credentials не подходит для выписки и профиля организации: эти сервисы требуют пользовательского контекста Authorization Code Flow.

mTLS

Для боевого контура и песочницы банк требует mTLS: клиентский сертификат организации, в субъекте которого указан ИНН (OID 1.2.643.3.131.1.1); срок действия сертификата — до 375 дней. Для песочницы нужен отдельный тестовый сертификат из документации банка. Сертификат подключается параметрами cert/verify (PEM) или инъекцией своего httpx.AsyncClient в http_client=.

Песочница и настройка окружения

  • Пром: https://baas.alfabank.ru (PRODUCTION_BASE_URL, дефолт)
  • Песочница: https://sandbox.alfabank.ru (SANDBOX_BASE_URL)
from alfabank import SANDBOX_BASE_URL, AlfaBankClient

client = AlfaBankClient(api_key="...", base_url=SANDBOX_BASE_URL)

base_url и api_prefix настраиваются: шлюзовые пути могут отличаться в зависимости от договора с банком.

Вебхуки

webhook = await client.webhooks.create(
    "https://webhook.partner.ru/api/v1/webhook-events",
    accounts=["40702810102300000001"],  # без списка — все доступные счета
)
page = await client.webhooks.list(offset=0, limit=10)
await client.webhooks.patch(webhook.id, enabled=False)
await client.webhooks.delete(webhook.id)

Тело доставки (JSON-массив событий) разбирается типизированно:

from alfabank import parse_webhook_events

events = parse_webhook_events(payload)  # list[WebhookEvent]

Обработка ошибок

from alfabank import AlfaBankAPIError, AlfaBankRateLimitError

try:
    page = await client.statements.transactions("40702810102300000001", "2026-07-01")
except AlfaBankRateLimitError as exc:
    print("Лимит запросов, повторить через:", exc.retry_after)
except AlfaBankAPIError as exc:
    print(exc.status_code, exc.error_code, exc.request_id, exc.response_body)

Эндпоинты

Метод SDK HTTP
client.statements.transactions() GET {prefix}/statement/transactions
client.statements.iter_transactions() автопагинация по _links rel=next
client.statements.summary() GET {prefix}/statement/summary
client.customer.info() GET {prefix}/v2/customer-info
client.webhooks.create() POST {prefix}/v1/webhooks (ответ 201)
client.webhooks.list() GET {prefix}/v1/webhooks
client.webhooks.get() GET {prefix}/v1/webhooks/{id}
client.webhooks.patch() PUT {prefix}/v1/webhooks/{id} (официальный edit — PUT)
client.webhooks.delete() DELETE {prefix}/v1/webhooks/{id} (ответ 200 без тела)
client.request(method, path) произвольный запрос (escape hatch)

Вендоренные OpenAPI-спеки банка и реалистичные моки: specs/alfa-api/.

Лицензия

MIT

Metadata

Release files for alfabank-sdk 1.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for alfabank-sdk 1.1.0
File Size Uploaded Provenance Actions
alfabank_sdk-1.1.0.tar.gz 145.3 kB With provenance Details for alfabank_sdk-1.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for alfabank-sdk 1.1.0
File Interpreter ABI Platform Actions
alfabank_sdk-1.1.0-py3-none-any.whl Python 3 none any Details for alfabank_sdk-1.1.0-py3-none-any.whl

Total release size: 175.4 kB

Release files / alfabank_sdk-1.1.0.tar.gz

Download URL alfabank_sdk-1.1.0.tar.gz
Size 145.3 kB
Tags Source
SHA-256 checksum
How to use checksums
5842f29167aaa5c81367ee6a8d16f70d009d714c0ad09eb58af32c3ea78cdf88
BLAKE2b-256 checksum
How to use checksums
18678ea736cef66d73e405a799e27d3e86b7fe0421b5f744a7ea0bc82d2ddb14
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

Release files / alfabank_sdk-1.1.0-py3-none-any.whl

Download URL alfabank_sdk-1.1.0-py3-none-any.whl
Size 30.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6e64706c507a7d215b3a6ac65a0d77cb9c92ad4d308e05d1509108f7066b933e
BLAKE2b-256 checksum
How to use checksums
28a2566c4dd9831278f6e5a495c174707588457fcc27e013d0344ee01717f79c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

Security for alfabank-sdk 1.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for alfabank_sdk-1.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 29, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page