Skip to main content

tochka_py

Tochka API docs - Sandbox docs

Python-клиент для Tochka API на базе httpx и pydantic.

Сейчас библиотека покрывает:

  • tochka_py.accounts - работа со счетами: list
  • tochka_py.customers - работа с клиентами: list, get
  • tochka_py.statements - работа с выписками: init, get, wait_until_ready, init_and_wait
  • tochka_py.invoice - полный lifecycle работы со счетами: create, get_file, send_to_email, get_payment_status, delete
  • tochka_py.closing_documents - работа с закрывающими документами: create, get_file, send_to_email, delete
  • tochka_py.webhook - управление webhook-подписками и верификация входящих webhook JWT: create, edit, get, send_test, delete, WebhookVerifier

Поддерживаются синхронные и асинхронные вызовы, единый transport и типизированные модели запросов и ответов.

Также доступен CLI tochka-py для управления webhook-подписками.

Установка

pip install tochka_py

Требуется Python >=3.10.

Если запускаете CLI из репозитория и команда tochka-py отдает старую версию, активируйте локальное окружение через source .venv/bin/activate.

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

from tochka_py import TochkaClient
from tochka_py.invoice.types import (
    ContentInvoice,
    CounterpartType,
    InvoiceCreateRequest,
    InvoiceCreateRequestData,
    InvoiceModel,
    NdsKind,
    PositionModel,
    SecondSideModel,
    UnitCode,
)

request = InvoiceCreateRequestData(
    data=InvoiceCreateRequest(
        account_id="12345123451234512345/044525104",
        customer_code="1234567ab",
        second_side=SecondSideModel(
            tax_code="7707083893",
            type=CounterpartType.COMPANY,
            second_side_name='ООО "Покупатель"',
        ),
        content=ContentInvoice(
            invoice=InvoiceModel(
                number="42",
                total_amount=1000.0,
                positions=[
                    PositionModel(
                        position_name="Консультационные услуги",
                        unit_code=UnitCode.PIECE,
                        nds_kind=NdsKind.WITHOUT_NDS,
                        price=1000.0,
                        quantity=1,
                        total_amount=1000.0,
                    )
                ],
            )
        ),
    )
)

with TochkaClient(token="your_token") as client:
    response = client.invoice.create_sync(request)

print(response.data.document_id)

Получение PDF, статуса оплаты, отправка на email и удаление:

from tochka_py.invoice.types import SendDocumentToEmailRequest

document_id = response.data.document_id
customer_code = request.customer_code

with TochkaClient(token="your_token") as client:
    payment_status = client.invoice.get_payment_status_sync(customer_code, document_id)
    pdf_file = client.invoice.get_file_sync(customer_code, document_id)
    email_result = client.invoice.send_to_email_sync(
        customer_code,
        document_id,
        SendDocumentToEmailRequest(email="test@example.com"),
    )
    delete_result = client.invoice.delete_sync(customer_code, document_id)

print(payment_status.data.payment_status)
print(pdf_file.filename, pdf_file.content_type, len(pdf_file.content))
print(email_result.data.result, delete_result.data.result)

Closing Documents

Создание закрывающего документа, например акта:

from decimal import Decimal

from tochka_py import TochkaClient
from tochka_py.closing_documents.types import (
    ActModel,
    ClosingDocumentCreateRequest,
    ContentAct,
    SecondSideModel,
)
from tochka_py.invoice.types import CounterpartType, NdsKind, PositionModel, UnitCode

request = ClosingDocumentCreateRequest(
    account_id="12345123451234512345/044525104",
    customer_code="1234567ab",
    second_side=SecondSideModel(
        tax_code="7707083893",
        type=CounterpartType.COMPANY,
    ),
    content=ContentAct(
        act=ActModel(
            number="ACT-42",
            total_amount=Decimal("1000.00"),
            positions=[
                PositionModel(
                    position_name="Консультационные услуги",
                    unit_code=UnitCode.PIECE,
                    nds_kind=NdsKind.WITHOUT_NDS,
                    price=Decimal("1000.00"),
                    quantity=Decimal("1"),
                    total_amount=Decimal("1000.00"),
                )
            ],
        )
    ),
)

with TochkaClient(token="your_token") as client:
    response = client.closing_documents.create_sync(request)

print(response.data.document_id)

Statements

Создание выписки и ожидание готовности одним вызовом:

from datetime import date

from tochka_py import TochkaClient
from tochka_py.statements.types import StatementInitParameters, StatementInitRequest

request = StatementInitRequest(
    statement=StatementInitParameters(
        account_id="12345123451234512345/044525104",
        start_date_time=date(2024, 1, 1),
        end_date_time=date(2024, 1, 31),
    )
)

with TochkaClient(token="your_token") as client:
    response = client.statements.init_and_wait_sync(request, poll_interval=1.0, timeout=60.0)

statement = response.data.statements[0]
print(statement.statement_id, statement.status, len(statement.transactions or []))

Webhooks

Управление webhook-подпиской:

from tochka_py import TochkaClient
from tochka_py.webhook.types import WebhookSubscription, WebhookType

with TochkaClient(token="your_token") as client:
    response = client.webhooks.create_sync(
        client_id="your_app_client_id",
        request=WebhookSubscription(
            webhooks_list=[
                WebhookType.INCOMING_PAYMENT,
                WebhookType.OUTGOING_PAYMENT,
            ],
            url="https://app.example.com/tochka/webhook",
        ),
    )

print(response.data.webhooks_list, response.data.url)

Верификация и парсинг входящего webhook JWT:

from tochka_py.webhook.verifier import WebhookVerifier

raw_webhook_jwt = request_body.decode()

with WebhookVerifier() as verifier:
    payload = verifier.decode_sync(raw_webhook_jwt)

print(payload.webhook_type, payload.customer_code)

CLI

Повесить webhook одной командой:

export TOCHKA_API_TOKEN=your_token
tochka-py webhook set \
  --client-id your_app_client_id \
  --url https://app.example.com/tochka/webhook \
  --event incomingPayment \
  --event outgoingPayment

Получить список счетов:

tochka-py accounts list

Получить список клиентов и карточку клиента:

tochka-py customers list
tochka-py customers get --customer-code 1234567ab

Посмотреть текущую подписку:

tochka-py webhook get --client-id your_app_client_id

Отправить тестовый webhook:

tochka-py webhook test --client-id your_app_client_id --event incomingPayment

Удалить подписку:

tochka-py webhook delete --client-id your_app_client_id

CLI использует:

  • TOCHKA_API_TOKEN для токена
  • TOCHKA_BASE_URL для переопределения base URL
  • --sandbox для переключения на https://enter.tochka.com/sandbox/v2 и дефолтный токен sandbox.jwt.token

Для sandbox можно использовать:

  • base URL: https://enter.tochka.com/sandbox/v2
  • токен: sandbox.jwt.token

Структура API

from tochka_py import TochkaClient

TochkaClient:

  • statements.init_sync(...)
  • statements.init(...)
  • statements.get_sync(...)
  • statements.get(...)
  • statements.wait_until_ready_sync(...)
  • statements.wait_until_ready(...)
  • statements.init_and_wait_sync(...)
  • statements.init_and_wait(...)
  • invoice.create_sync(...)
  • invoice.create(...)
  • invoice.get_file_sync(...)
  • invoice.get_file(...)
  • invoice.send_to_email_sync(...)
  • invoice.send_to_email(...)
  • invoice.get_payment_status_sync(...)
  • invoice.get_payment_status(...)
  • invoice.delete_sync(...)
  • invoice.delete(...)
  • closing_documents.create_sync(...)
  • closing_documents.create(...)
  • closing_documents.get_file_sync(...)
  • closing_documents.get_file(...)
  • closing_documents.send_to_email_sync(...)
  • closing_documents.send_to_email(...)
  • closing_documents.delete_sync(...)
  • closing_documents.delete(...)
  • webhooks.create_sync(...)
  • webhooks.create(...)
  • webhooks.edit_sync(...)
  • webhooks.edit(...)
  • webhooks.get_sync(...)
  • webhooks.get(...)
  • webhooks.send_test_sync(...)
  • webhooks.send_test(...)
  • webhooks.delete_sync(...)
  • webhooks.delete(...)
  • webhooks.set_sync(...)
  • webhooks.set(...)

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

Библиотека поднимает исключения из tochka_py.core.errors, например:

  • AuthenticationError
  • RequestValidationError
  • NotFoundError
  • ServerError

У исключений доступны поля product, http_status, code, request_id и raw.

Интеграционные тесты для sandbox

По умолчанию интеграционные тесты отключены.

Sandbox-интеграции лежат в tests/sandbox/ и разбиты по продуктам:

  • test_accounts.py
  • test_customers.py
  • test_statements.py
  • test_invoice.py
  • test_closing_documents.py

Запуск unit-тестов:

uv run pytest tests

Запуск integration:

uv run pytest tests -m integration

Запуск отдельного sandbox-модуля:

uv run pytest tests/sandbox/test_statements.py -m integration

Metadata

Release files for tochka_py 0.0.6

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

Source distribution (sdist)

Source distribution for tochka_py 0.0.6
File Size Uploaded Provenance
tochka_py-0.0.6.tar.gz 64.1 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for tochka_py 0.0.6
File Interpreter ABI Platform
tochka_py-0.0.6-py3-none-any.whl Python 3 none any Details

Total release size: 93.4 kB

Release files / tochka_py-0.0.6.tar.gz

Download URL tochka_py-0.0.6.tar.gz
Size 64.1 kB
Tags Source
SHA-256 checksum
How to use checksums
1411fda60baec20c92d789a3e2fdabf9d50a6ded654d5ed52fa7b0e709c1a7a6
BLAKE2b-256 checksum
How to use checksums
d380413ef44a0fa88257138ee8fa7479439b8e7a6be90a3581f6f0cb5aedcbd2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.10.1 {"installer":{"name":"uv","version":"0.10.1","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / tochka_py-0.0.6-py3-none-any.whl

Download URL tochka_py-0.0.6-py3-none-any.whl
Size 29.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3a3dc81346d367a8cfc77d8b609863ccdada734a4a9f4bfe47b9bc642fbb2941
BLAKE2b-256 checksum
How to use checksums
dd6caf37a428cf261442699f606d60bbc7f72919c60ef65ca1698f4844991d46
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.10.1 {"installer":{"name":"uv","version":"0.10.1","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for tochka_py 0.0.6

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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