Skip to main content

yookassa-telegram

Интеграция платежей YooKassa с Telegram-ботами (aiogram 3.x).

Лёгкая встраиваемая библиотека для создания платежей, формирования чеков (54-ФЗ), обработки вебхуков и управления возвратами.


🔧 Особенности

  • Поддержка создания и подтверждения платежей через YooKassa
  • Генерация чеков (54‑ФЗ) и обработка налоговых данных
  • Интеграция с aiogram: отправка сообщений с клавиатурами для оплаты
  • Встроенная логика retry и обработка ошибок для запросов к YooKassa SDK
  • Абстракция хранилища платежей: in-memory, JSON и возможность реализовать своё
  • Обработчик webhook с проверкой подписи и callback-ами

Документация описана в API.md.

Установка

Установите с PyPI:

pip install yookassa-telegram

Требования:

  • Python 3.10+
  • aiogram
  • aiohttp
  • yookassa

Зависимости перечислены в pyproject.toml.


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

Настройка через переменные окружения (пример .env):

YOOKASSA_SHOP_ID=123456
YOOKASSA_SECRET_KEY=test_xxxxx
YOOKASSA_RETURN_URL=https://example.com/payment/return
YOOKASSA_WEBHOOK_URL=https://example.com/webhook
YOOKASSA_IS_TEST=true
YOOKASSA_ENABLE_RECEIPTS=true
YOOKASSA_INN=1234567890

Пример использования с aiogram:

from aiogram import Bot, Dispatcher
from yookassa_telegram_integration.config import YooKassaConfig
from yookassa_telegram_integration.yookassa_client import YooKassaClient
from yookassa_telegram_integration.payment_service import PaymentService
from yookassa_telegram_integration.receipt_service import ReceiptService
from yookassa_telegram_integration.refund_service import RefundService
from yookassa_telegram_integration.telegram_integration import (
    TelegramPaymentIntegration, create_payment_router
)
from yookassa_telegram_integration.storage import InMemoryPaymentStorage

config = YooKassaConfig.from_env()
client = YooKassaClient(config)
storage = InMemoryPaymentStorage()
payment_service = PaymentService(config, storage, client)
receipt_service = ReceiptService(config)
refund_service = RefundService(config, storage, client)

integration = TelegramPaymentIntegration(
    config,
    payment_service,
    receipt_service,
    refund_service,
    storage
)

router = create_payment_router(integration)
# Включите router в ваш Dispatcher
# dp.include_router(router)

Пример отправки сообщения с кнопкой оплаты:

await integration.send_payment_message(
    message,  # aiogram.types.Message
    amount=150.0,
    description='Оплата подписки',
    order_id='order_12345',
    user_email='user@example.com'
)

Конфигурация

Ключевые настройки хранятся в YooKassaConfig:

  • shop_id и secret_key — данные магазина YooKassa
  • return_url — URL для возврата пользователя после платежа
  • webhook_url — URL для webhook уведомлений
  • enable_receipts, inn, default_tax_system — опции для 54-ФЗ
  • auto_capture — автоматически подтверждать платежи

Используйте YooKassaConfig.from_env() для загрузки из переменных окружения.


Webhook (обработчик уведомлений)

WebhookHandler обеспечивает парсинг уведомлений, проверку и обновление статуса платежа, а также регистрацию Callback-ов для конкретных событий.

Пример использования:

from yookassa_telegram_integration.webhook_handler import (
    create_webhook_handler, WebhookEventType
)

async def on_success(notification):
    print('Оплата успешна', notification.payment_id)

handler = create_webhook_handler(
    config,
    on_payment_succeeded=on_success
)

# В ручном веб-сервере / на фреймворке передайте тело запроса в handler.handle_webhook
# notification = await handler.handle_webhook(payload, headers)

Хранилище (Storage)

Доступны реализации:

  • InMemoryPaymentStorage — для разработки и тестов
  • JSONFilePaymentStorage — для простого прототипирования

Для production рекомендуется реализовать свой PaymentStorage


Примеры

Подтверждение платежа:

from yookassa_telegram_integration.payment_service import PaymentService
await payment_service.capture_payment(payment_id)

Отмена платежа:

await payment_service.cancel_payment(payment_id)

Создание возврата:

from yookassa_telegram_integration.models import RefundData
await refund_service.create_refund(
    RefundData(
        payment_id='payment_123',
        amount=100.0,
        currency='RUB',
        description='Возврат по ошибке'
    ),
    idempotency_key='refund_key_123'
)

Contributing

PR и issue приветствуются. Пожалуйста, используйте ветку main как основу

Перед PR выполните:

black .
mypy .
pytest

Контакт

Автор: rerowros · Email: rerowros@gmail.com

Поддержка/Issues: https://github.com/Rerowros/yookassa-telegram/issues

Metadata

Release files for yookassa-telegram 1.2.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 yookassa-telegram 1.2.0
File Size Uploaded Provenance
yookassa_telegram-1.2.0.tar.gz 34.2 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for yookassa-telegram 1.2.0
File Interpreter ABI Platform
yookassa_telegram-1.2.0-py3-none-any.whl Python 3 none any Details

Total release size: 77.3 kB

Release files / yookassa_telegram-1.2.0.tar.gz

Download URL yookassa_telegram-1.2.0.tar.gz
Size 34.2 kB
Tags Source
SHA-256 checksum
How to use checksums
6bff1784a33760d36a9917519464b5370ef1ea4e75518aa499231aa3dc925a7a
BLAKE2b-256 checksum
How to use checksums
231fe3d19b18a0f35cfb334973738c44cc846e731cd119f6bdd495e23a4405c2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.7

Release files / yookassa_telegram-1.2.0-py3-none-any.whl

Download URL yookassa_telegram-1.2.0-py3-none-any.whl
Size 43.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b3b5c71f7c431f0958220e582b8f660eadfea2bb5ee62e871e44136827fcb18b
BLAKE2b-256 checksum
How to use checksums
b82f32f02c025682841af1c208cbaeb0306f7a4c8eec187c1e7208324f76445c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.7

Security for yookassa-telegram 1.2.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.

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