Skip to main content

Tochka API wrapper for Python built on top of httpx and pydantic

Project description

tochka_py

Tochka API docs - Sandbox docs

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

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

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

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

Установка

pip install tochka_py

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

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

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)

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)

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

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

Структура API

from tochka_py import TochkaClient

TochkaClient:

  • 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(...)
  • 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(...)

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

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

  • AuthenticationError
  • RequestValidationError
  • NotFoundError
  • ServerError

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

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

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

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

uv run pytest tests

Запуск integration:

uv run pytest tests -m integration

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tochka_py-0.0.2.tar.gz (17.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tochka_py-0.0.2-py3-none-any.whl (15.5 kB view details)

Uploaded Python 3

File details

Details for the file tochka_py-0.0.2.tar.gz.

File metadata

  • Download URL: tochka_py-0.0.2.tar.gz
  • Upload date:
  • Size: 17.0 kB
  • Tags: Source
  • Uploaded using 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}

File hashes

Hashes for tochka_py-0.0.2.tar.gz
Algorithm Hash digest
SHA256 3f8d7da85cedb0cf9a660460faa922cb1fda3fe3f40c4d8101e39b05febb33c9
MD5 4ad25a4f800777f5927eb6f54e01e463
BLAKE2b-256 800d519f1d875352f39a81b54242c9285bc61044b2905a4271829b64934c9af6

See more details on using hashes here.

File details

Details for the file tochka_py-0.0.2-py3-none-any.whl.

File metadata

  • Download URL: tochka_py-0.0.2-py3-none-any.whl
  • Upload date:
  • Size: 15.5 kB
  • Tags: Python 3
  • Uploaded using 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}

File hashes

Hashes for tochka_py-0.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 68ee6b8c897a04b31dc19f713e02e0ebda317b37a1764226c0f653767d79191b
MD5 9966ddf339aad26a8608e9dd98401c69
BLAKE2b-256 94a71ee4c0ba261653446e080f78d7a56bbe035bab19883a8b1022a5c594b813

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page