### Database Integration Example (Partial) Source: https://github.com/masasibata/aioyookassa/blob/main/docs/examples/advanced_payment_example.md This is a partial example demonstrating the setup for integrating payment information with a database. It includes necessary imports for payment creation and status handling. ```python import asyncio from aioyookassa import YooKassa from aioyookassa.types.payment import Money, Confirmation from aioyookassa.types.enum import Currency, ConfirmationType, PaymentStatus from aioyookassa.types.params import CreatePaymentParams ``` -------------------------------- ### Webhook Server for Quick Start Source: https://github.com/masasibata/aioyookassa/blob/main/docs/index.md Use this snippet for a quick setup of a webhook server to handle incoming notifications. It automatically registers callbacks for specific events. ```python from aioyookassa.contrib.webhook_server import WebhookServer from aioyookassa.core.webhook_handler import WebhookHandler from aioyookassa.types.enum import WebhookEvent from aioyookassa.types.payment import Payment handler = WebhookHandler() @handler.register_callback(WebhookEvent.PAYMENT_SUCCEEDED) async def on_payment_succeeded(payment: Payment): print(f"✅ Платеж {payment.id} успешно выполнен") # Ваша бизнес-логика server = WebhookServer(handler=handler) server.run(host="0.0.0.0", port=8080) ``` -------------------------------- ### Install Dependencies Source: https://github.com/masasibata/aioyookassa/blob/main/docs/contributing.md Install project dependencies using Poetry (recommended) or pip. ```bash # Используя Poetry (рекомендуется) > poetry install > # Или используя pip > pip install -e ".[dev]" ``` -------------------------------- ### Install aioyookassa from Source Source: https://github.com/masasibata/aioyookassa/blob/main/docs/installation.md Install the latest version of aioyookassa directly from its GitHub repository. ```bash pip install git+https://github.com/masasibata/aioyookassa.git ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/masasibata/aioyookassa/blob/main/README.md Clone the repository and install development dependencies using make install-dev. ```bash git clone https://github.com/masasibata/aioyookassa.git cd aioyookassa make install-dev ``` -------------------------------- ### Create and Process Payouts in Python Source: https://github.com/masasibata/aioyookassa/blob/main/docs/examples/payouts-example.md This comprehensive example shows how to create payouts to a bank card, via SBP, and to a YooMoney wallet. It also demonstrates how to retrieve the status of a payout. Ensure you have the YooKassa library installed and your API credentials configured. ```python import asyncio from aioyookassa import YooKassa from aioyookassa.types.payment import Money from aioyookassa.types.enum import Currency from aioyookassa.types.params import ( CreatePayoutParams, BankCardPayoutDestinationData, BankCardPayoutCardData, SbpPayoutDestinationData, YooMoneyPayoutDestinationData ) async def process_payouts(): """Обработка выплат через различные способы.""" async with YooKassa(api_key="your_api_key", shop_id=12345) as client: # 1. Выплата на банковскую карту print("Создание выплаты на банковскую карту...") params = CreatePayoutParams( amount=Money(value=1000.00, currency=Currency.RUB), payout_destination_data=BankCardPayoutDestinationData( card=BankCardPayoutCardData(number="5555555555554477") ), description="Выплата по договору #12345" ) payout = await client.payouts.create_payout(params) print(f"✅ Выплата создана: {payout.id}") print(f"📊 Статус: {payout.status}") # 2. Выплата через СБП print("\nСоздание выплаты через СБП...") # Сначала получаем список банков СБП banks = await client.sbp_banks.get_sbp_banks() if banks.list: bank_id = banks.list[0].bank_id # Используем первый банк из списка params = CreatePayoutParams( amount=Money(value=2000.00, currency=Currency.RUB), payout_destination_data=SbpPayoutDestinationData( bank_id=bank_id, phone="79000000000" ), description="Выплата через СБП" ) payout = await client.payouts.create_payout(params) print(f"✅ Выплата через СБП создана: {payout.id}") # 3. Выплата на кошелек ЮMoney print("\nСоздание выплаты на кошелек ЮMoney...") params = CreatePayoutParams( amount=Money(value=1500.00, currency=Currency.RUB), payout_destination_data=YooMoneyPayoutDestinationData( account_number="41001614575714" ), description="Выплата на кошелек" ) payout = await client.payouts.create_payout(params) print(f"✅ Выплата на кошелек создана: {payout.id}") # 4. Проверка статуса выплаты payout_info = await client.payouts.get_payout(payout.id) print(f"\n📊 Информация о выплате:") print(f" ID: {payout_info.id}") print(f" Статус: {payout_info.status}") print(f" Сумма: {payout_info.amount.value} {payout_info.amount.currency}") if payout_info.succeeded_at: print(f" Выполнена: {payout_info.succeeded_at}") if __name__ == "__main__": asyncio.run(process_payouts()) ``` -------------------------------- ### Full Migration Example (Old Code) Source: https://github.com/masasibata/aioyookassa/blob/main/docs/changelog.md This is an example of the old code structure (v0.x) for processing payments. ```python import asyncio from aioyookassa.core.client import YooKassa from aioyookassa.types import Confirmation from aioyookassa.types.payment import Money from aioyookassa.types.enum import ConfirmationType, Currency async def process_payment(): async with YooKassa(‘token’, 12345) as client: confirmation = Confirmation(type=ConfirmationType.REDIRECT, return_url=’[https://example.com](https://example.com)’) payment = await client.create_payment( amount=PaymentAmount(value=100, currency=Currency.RUB), description=’Test payment’, confirmation=confirmation ) payments = await client.get_payments() for payment in payments.list: print(payment.id) payment_info = await client.get_payment(payment.id) print(payment_info.status) ``` -------------------------------- ### Full Migration Example (New Code) Source: https://github.com/masasibata/aioyookassa/blob/main/docs/changelog.md This is an example of the new code structure (v1.0+) after migration, demonstrating updated API access and date handling. ```python import asyncio from datetime import datetime from aioyookassa import YooKassa from aioyookassa.types.payment import Money, Confirmation async def process_payment(): async with YooKassa(api_key=’token’, shop_id=12345) as client: confirmation = Confirmation( type=ConfirmationType.REDIRECT, return_url=’[https://example.com](https://example.com)’ ) payment = await client.payments.create_payment( amount=PaymentAmount(value=100, currency=Currency.RUB), description=’Test payment’, confirmation=confirmation ) payments = await client.payments.get_payments( created_at=datetime.now() ) for payment in payments.list: print(payment.id) payment_info = await client.payments.get_payment(payment.id) print(payment_info.status) ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/masasibata/aioyookassa/blob/main/docs/contributing.md Install pre-commit hooks to automatically format and lint code before commits. ```bash > pre-commit install ``` -------------------------------- ### Python Docstring Example (Google Style) Source: https://github.com/masasibata/aioyookassa/blob/main/docs/contributing.md Example of a Python function with a docstring following Google style, including arguments, return values, raised exceptions, and an example usage. ```python def create_payment(self, amount: PaymentAmount, description: str) -> Payment: """ Создание нового платежа. Args: amount: Сумма платежа description: Описание платежа Returns: Созданный платеж Raises: APIError: При ошибке API InvalidRequestError: При неверном запросе Example: >>> from aioyookassa.types.enum import Currency >>> payment = await client.payments.create_payment( ... amount=PaymentAmount(value=100, currency=Currency.RUB), ... description="Test payment" ... ) """ pass ``` -------------------------------- ### Install aioyookassa with pip Source: https://github.com/masasibata/aioyookassa/blob/main/docs/installation.md Use this command to install the stable version of the aioyookassa library. ```bash pip install aioyookassa ``` -------------------------------- ### Install aioyookassa Source: https://github.com/masasibata/aioyookassa/blob/main/docs/index.md Install the aioyookassa library using pip. Ensure you are using version 2.0.0 or higher. ```bash pip install aioyookassa>=2.0.0 ``` -------------------------------- ### Create Full Payment Example Source: https://github.com/masasibata/aioyookassa/blob/main/docs/getting-started/api-modules.md Demonstrates creating a payment with comprehensive details including payment method, confirmation, recipient, receipt, and metadata. ```python from aioyookassa.types.payment import ( PaymentAmount, Confirmation, PaymentMethod, CardInfo, Recipient, Customer, Receipt, PaymentItem ) from aioyookassa.types.enum import ( ConfirmationType, Currency, PaymentMethodType, PaymentSubject, PaymentMode ) async def create_full_payment(): # Настройка способа оплаты card_info = CardInfo( first_six="123456", last_four="7890", expiry_month="12", expiry_year="2025", card_type="Visa" ) payment_method = PaymentMethod( type=PaymentMethodType.CARD, id="pm_123456", saved=False, card=card_info ) # Настройка подтверждения confirmation = Confirmation( type=ConfirmationType.REDIRECT, return_url="https://example.com/success" ) # Настройка получателя recipient = Recipient( account_id="123456789", gateway_id="123456" ) # Настройка клиента customer = Customer( full_name="Иван Иванов", email="ivan@example.com", phone="+79001234567" ) # Настройка чека receipt = Receipt( customer=customer, items=[ PaymentItem( description="Товар", quantity=1, amount=PaymentAmount(value=100.00, currency=Currency.RUB), vat_code=1, payment_subject=PaymentSubject.COMMODITY, payment_mode=PaymentMode.FULL_PAYMENT ) ], tax_system_code=1 ) # Создание платежа from aioyookassa.types.params import CreatePaymentParams params = CreatePaymentParams( amount=PaymentAmount(value=100.00, currency=Currency.RUB), description="Оплата заказа #12345", payment_method=payment_method, confirmation=confirmation, recipient=recipient, receipt=receipt, metadata={"order_id": "12345", "user_id": "67890"} ) payment = await client.payments.create_payment(params) return payment ``` -------------------------------- ### Verify aioyookassa Installation Source: https://github.com/masasibata/aioyookassa/blob/main/docs/installation.md Run this Python script to confirm that the aioyookassa library has been installed successfully and can establish a connection. ```python import asyncio from aioyookassa import YooKassa async def test_connection(): client = YooKassa(api_key="test_key", shop_id=12345) print("aioyookassa успешно установлена!") await client.close() asyncio.run(test_connection()) ``` -------------------------------- ### Create and Get Deals Source: https://github.com/masasibata/aioyookassa/blob/main/README.md Create a secure deal with specified fee moments and descriptions, or retrieve a list of existing deals. ```python from aioyookassa.types.params import CreateDealParams from aioyookassa.types.enum import FeeMoment # Создание безопасной сделки params = CreateDealParams( fee_moment=FeeMoment.PAYMENT_SUCCEEDED, description="Безопасная сделка" ) deal = await client.deals.create_deal(params) # Получение списка сделок deals = await client.deals.get_deals() ``` -------------------------------- ### Create Self-Employed Source: https://github.com/masasibata/aioyookassa/blob/main/docs/getting-started/examples.md This example demonstrates how to register a self-employed individual. It requires an ITN and a confirmation URL. ```python import asyncio from aioyookassa import YooKassa from aioyookassa.types.params import ( CreateSelfEmployedParams, SelfEmployedConfirmationData ) async def create_self_employed(): async with YooKassa('your_api_key', 12345) as client: params = CreateSelfEmployedParams( itn="123456789012", confirmation=SelfEmployedConfirmationData( type="redirect", confirmation_url="https://example.com/confirm" ) ) self_employed = await client.self_employed.create_self_employed(params) print(f"Self-Employed ID: {self_employed.id}") print(f"Status: {self_employed.status}") asyncio.run(create_self_employed()) ``` -------------------------------- ### WebhookServer Quick Start Source: https://github.com/masasibata/aioyookassa/blob/main/docs/api-reference/webhook-handler-api.md Sets up a basic aiohttp WebhookServer for handling YooKassa notifications. Includes registering a callback for payment succeeded events. ```python from aioyookassa.contrib.webhook_server import WebhookServer from aioyookassa.core.webhook_handler import WebhookHandler from aioyookassa.types.enum import WebhookEvent handler = WebhookHandler() @handler.register_callback(WebhookEvent.PAYMENT_SUCCEEDED) async def on_payment(payment): print(f"Payment {payment.id} succeeded") server = WebhookServer(handler=handler) server.run(host="0.0.0.0", port=8080) ``` -------------------------------- ### Update Dependencies Source: https://github.com/masasibata/aioyookassa/blob/main/docs/changelog.md Ensure you have the correct versions of aioyookassa, pydantic, and aiohttp installed. ```bash pip install aioyookassa==1.0.0 pip install pydantic>=2.0.0 pip install aiohttp>=3.9.0 ``` -------------------------------- ### Install aioyookassa with Poetry Source: https://github.com/masasibata/aioyookassa/blob/main/docs/installation.md If you are managing dependencies with Poetry, use this command to add aioyookassa to your project. ```bash poetry add aioyookassa ``` -------------------------------- ### Create and Get Deals Source: https://context7.com/masasibata/aioyookassa/llms.txt Handles the creation of secure deals (escrow) for marketplaces and retrieves a list of deals with filtering options. ```python from aioyookassa.types.params import CreateDealParams, GetDealsParams from aioyookassa.types.enum import FeeMoment, DealStatus async def deals_example(): async with YooKassa(api_key="test_XXX", shop_id=123456) as client: # Создание сделки params = CreateDealParams( type="safe_deal", fee_moment=FeeMoment.PAYMENT_SUCCEEDED, description="Сделка по продаже товара №555", metadata={"seller_id": "seller_42"}, ) deal = await client.deals.create_deal(params) print(f"ID сделки: {deal.id}") print(f"Статус: {deal.status}") # open / closed # Список сделок с фильтрацией filter_params = GetDealsParams( status=DealStatus.OPEN, full_text_search="товар", limit=20, ) result = await client.deals.get_deals(filter_params) for d in result.list: print(f" {d.id}: {d.description}") ``` -------------------------------- ### Create Payment with Saved Method Source: https://github.com/masasibata/aioyookassa/blob/main/docs/getting-started/examples.md This example shows how to create a payment using a previously saved payment method ID. Ensure the `payment_method_id` is valid. ```python import asyncio from aioyookassa import YooKassa from aioyookassa.types.payment import Money, Confirmation from aioyookassa.types.enum import Currency, ConfirmationType from aioyookassa.types.params import CreatePaymentParams async def create_payment_with_saved_method(): async with YooKassa('your_api_key', 12345) as client: params = CreatePaymentParams( amount=Money(value=1500.00, currency=Currency.RUB), payment_method_id="saved_payment_method_id", description="Платеж с сохраненной картой", confirmation=Confirmation( type=ConfirmationType.REDIRECT, return_url="https://example.com/return" ) ) payment = await client.payments.create_payment(params) print(f"Payment ID: {payment.id}") asyncio.run(create_payment_with_saved_method()) ``` -------------------------------- ### Create and Get Webhooks Source: https://github.com/masasibata/aioyookassa/blob/main/README.md Create a new webhook for a specific event and URL, or retrieve a list of configured webhooks. Requires an OAuth token. ```python from aioyookassa.types.params import CreateWebhookParams from aioyookassa.types.enum import WebhookEvent # Создание webhook (требует OAuth токен) params = CreateWebhookParams( event=WebhookEvent.PAYMENT_SUCCEEDED, url="https://example.com/webhook" ) webhook = await client.webhooks.create_webhook( params=params, oauth_token="your_oauth_token" ) # Получение списка webhooks webhooks = await client.webhooks.get_webhooks(oauth_token="your_oauth_token") ``` -------------------------------- ### Documentation Commands Source: https://github.com/masasibata/aioyookassa/blob/main/README.md Build the project documentation or serve it locally for preview. ```bash make docs ``` ```bash make docs-serve ``` -------------------------------- ### Integration Test Example for Payment Creation Source: https://github.com/masasibata/aioyookassa/blob/main/docs/contributing.md An integration test for the payment creation process, using unittest.mock.patch to mock the API call and assert the result. ```python import pytest from unittest.mock import AsyncMock, patch from aioyookassa import YooKassa @pytest.mark.asyncio async def test_create_payment_integration(): """Test payment creation with mocked API.""" with patch('aioyookassa.core.api.payments.PaymentsAPI.create_payment') as mock_create: mock_create.return_value = AsyncMock() mock_create.return_value.id = "test_payment_id" from aioyookassa.types.enum import Currency client = YooKassa(api_key="test", shop_id=12345) payment = await client.payments.create_payment( amount=PaymentAmount(value=100, currency=Currency.RUB), description="Test" ) assert payment.id == "test_payment_id" mock_create.assert_called_once() ``` -------------------------------- ### Conventional Commits Examples Source: https://github.com/masasibata/aioyookassa/blob/main/README.md Examples of commit messages following the Conventional Commits specification. ```bash feat: add new payment method support ``` ```bash fix: resolve timeout issue in payment creation ``` ```bash docs: update API documentation ``` ```bash test: add tests for refund functionality ``` ```bash refactor: improve error handling ``` -------------------------------- ### Initialize YooKassa Client Source: https://context7.com/masasibata/aioyookassa/llms.txt Demonstrates basic and advanced initialization of the YooKassa client, including configuration for timeouts, proxies, and logging. Shows usage as an asynchronous context manager. ```python import asyncio from aiohttp import ClientTimeout from aioyookassa import YooKassa # Базовая инициализация client = YooKassa(api_key="test_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", shop_id=123456) # Расширенная конфигурация client = YooKassa( api_key="test_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", shop_id=123456, timeout=ClientTimeout(total=60, connect=10, sock_read=50), proxy="http://proxy.example.com:8080", enable_logging=True, ) # Использование как контекстный менеджер (автозакрытие сессии) async def main(): async with YooKassa(api_key="test_XXX", shop_id=123456) as client: settings = await client.get_me() print(settings.account_id) # ID магазина print(settings.status) # active / disabled asyncio.run(main()) ``` -------------------------------- ### YooKassa Client Initialization Source: https://context7.com/masasibata/aioyookassa/llms.txt Demonstrates how to initialize the YooKassa client with basic and advanced configurations, including using it as a context manager. ```APIDOC ## YooKassa Client Initialization Main client providing access to all API modules. Supports context manager, timeouts, connection pooling, proxy, and logging. ```python import asyncio from aiohttp import ClientTimeout from aioyookassa import YooKassa # Basic initialization client = YooKassa(api_key="test_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", shop_id=123456) # Extended configuration client = YooKassa( api_key="test_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", shop_id=123456, timeout=ClientTimeout(total=60, connect=10, sock_read=50), proxy="http://proxy.example.com:8080", enable_logging=True, ) # Using as a context manager (auto-closing session) async def main(): async with YooKassa(api_key="test_XXX", shop_id=123456) as client: settings = await client.get_me() print(settings.account_id) # Shop ID print(settings.status) # active / disabled asyncio.run(main()) ``` ``` -------------------------------- ### Create Payment Linked to a Deal Source: https://github.com/masasibata/aioyookassa/blob/main/docs/getting-started/examples.md This example shows how to create a payment that is linked to a previously created secure deal. First, a deal is created, then a payment is made referencing the deal ID. ```python import asyncio from aioyookassa import YooKassa from aioyookassa.types.payment import Money, Confirmation from aioyookassa.types.enum import Currency, ConfirmationType from aioyookassa.types.params import CreatePaymentParams async def create_payment_with_deal(): async with YooKassa('your_api_key', 12345) as client: # Сначала создаем сделку deal = await client.deals.create_deal( CreateDealParams( fee_moment=FeeMoment.PAYMENT_SUCCEEDED, description="Сделка для платежа" ) ) # Создаем платеж с привязкой к сделке params = CreatePaymentParams( amount=Money(value=10000.00, currency=Currency.RUB), confirmation=Confirmation( type=ConfirmationType.REDIRECT, return_url="https://example.com/return" ), description="Платеж по сделке", deal=deal.id ) payment = await client.payments.create_payment(params) print(f"Payment ID: {payment.id}") print(f"Deal ID: {deal.id}") asyncio.run(create_payment_with_deal()) ``` -------------------------------- ### Complete Payment Processing Example Source: https://github.com/masasibata/aioyookassa/blob/main/docs/getting-started/api-modules.md Demonstrates the full lifecycle of a payment, including creation, status check, receipt generation, and optional refund. Assumes necessary imports and client initialization. ```python from aioyookassa.types.payment import PaymentItem from aioyookassa.types.enum import ( ConfirmationType, Currency, PaymentSubject, PaymentMode ) async def process_complete_payment(): """Полный цикл обработки платежа с чеком и возвратом.""" try: # 1. Создание платежа from aioyookassa.types.params import CreatePaymentParams params = CreatePaymentParams( amount=PaymentAmount(value=1000.00, currency=Currency.RUB), description="Комплексный платеж", confirmation=Confirmation(type=ConfirmationType.REDIRECT, return_url="https://example.com") ) payment = await client.payments.create_payment(params) print(f"✅ Платеж создан: {payment.id}") # 2. Ожидание оплаты (в реальном приложении через webhook) await asyncio.sleep(2) # 3. Проверка статуса payment_info = await client.payments.get_payment(payment.id) if payment_info.status == PaymentStatus.SUCCEEDED: # 4. Создание чека from aioyookassa.types.params import CreateReceiptParams params = CreateReceiptParams( payment_id=payment.id, items=[ PaymentItem( description="Товар", quantity=1, amount=PaymentAmount(value=1000.00, currency=Currency.RUB), vat_code=1, payment_subject=PaymentSubject.COMMODITY, payment_mode=PaymentMode.FULL_PAYMENT ) ], tax_system_code=1 ) receipt = await client.receipts.create_receipt(params) print(f"✅ Чек создан: {receipt.id}") # 5. Создание возврата (если нужно) if should_refund: from aioyookassa.types.params import CreateRefundParams params = CreateRefundParams( payment_id=payment.id, amount=PaymentAmount(value=500.00, currency=Currency.RUB), description="Частичный возврат" ) refund = await client.refunds.create_refund(params) print(f"✅ Возврат создан: {refund.id}") except Exception as e: print(f"❌ Ошибка: {e}") raise ``` -------------------------------- ### Get Refund Source: https://github.com/masasibata/aioyookassa/blob/main/docs/api-reference/refunds-api.md Retrieves information about a specific refund. ```APIDOC ## get_refund ### Description Retrieves information about a specific refund. ### Method GET (assumed, based on retrieval action) ### Endpoint /refunds/{refund_id} (assumed, based on API name and parameter) ### Parameters #### Path Parameters - **refund_id** (string) - Required - The ID of the refund to retrieve. ### Request Example ```python refund = await client.refunds.get_refund("refund_id") ``` ### Response #### Success Response (200) - **refund** (object) - Details of the specified refund. ``` -------------------------------- ### Client Initialization Source: https://github.com/masasibata/aioyookassa/blob/main/docs/api-reference/yookassa-client.md Demonstrates how to initialize the YooKassa client with API key and shop ID, supporting both integer and string shop IDs. ```APIDOC ## Client Initialization ### Description Initialize the YooKassa client with your API key and shop ID. The shop ID can be provided as an integer or a string. ### Code Example ```python from aioyookassa import YooKassa # With API key and integer shop ID client = YooKassa(api_key="your_api_key", shop_id=12345) # With API key and string shop ID client = YooKassa(api_key="your_api_key", shop_id="12345") ``` ``` -------------------------------- ### Get Refunds Source: https://github.com/masasibata/aioyookassa/blob/main/docs/api-reference/refunds-api.md Retrieves a list of refunds with filtering capabilities. ```APIDOC ## get_refunds ### Description Retrieves a list of refunds with the ability to filter. ### Method GET (assumed, based on retrieval action) ### Endpoint /refunds (assumed, based on API name) ### Parameters #### Query Parameters - **payment_id** (string) - Optional - Filter refunds by payment ID. - **status** (string) - Optional - Filter refunds by status (e.g., 'succeeded'). - **limit** (integer) - Optional - The maximum number of refunds to return. ### Request Example ```python from aioyookassa.types.params import GetRefundsParams params = GetRefundsParams( payment_id="payment_id", status="succeeded", limit=10 ) refunds = await client.refunds.get_refunds(params) ``` ### Response #### Success Response (200) - **refunds** (array) - A list of refund objects. ``` -------------------------------- ### Full Example: Create and Manage YooKassa Deals Source: https://github.com/masasibata/aioyookassa/blob/main/docs/examples/deals-example.md This Python script demonstrates the complete workflow for managing secure deals using the aioyookassa library. It covers creating a deal, fetching its details, listing deals with filters, and querying deals within a specific date range. Ensure you have your API key and shop ID configured. ```python import asyncio from datetime import datetime, timedelta from aioyookassa import YooKassa from aioyookassa.types.params import CreateDealParams, GetDealsParams from aioyookassa.types.enum import FeeMoment, DealStatus async def process_deals(): """Обработка безопасных сделок.""" async with YooKassa(api_key="your_api_key", shop_id=12345) as client: # 1. Создание безопасной сделки print("Создание безопасной сделки...") params = CreateDealParams( fee_moment=FeeMoment.PAYMENT_SUCCEEDED, # Комиссия после успешной оплаты description="Безопасная сделка для продажи товара", metadata={"order_id": "12345", "product_id": "67890"} ) deal = await client.deals.create_deal(params) print(f"✅ Сделка создана: {deal.id}") print(f"📊 Статус: {deal.status}") print(f"💰 Баланс: {deal.balance.value} {deal.balance.currency}") print(f"💵 Баланс выплаты: {deal.payout_balance.value} {deal.payout_balance.currency}") # 2. Получение информации о сделке deal_info = await client.deals.get_deal(deal.id) print(f"\n📋 Информация о сделке:") print(f" ID: {deal_info.id}") print(f" Статус: {deal_info.status}") print(f" Момент комиссии: {deal_info.fee_moment}") print(f" Создана: {deal_info.created_at}") print(f" Истекает: {deal_info.expires_at}") # 3. Получение списка сделок с фильтрацией print("\nПолучение списка открытых сделок...") params = GetDealsParams( status=DealStatus.OPENED, limit=10 ) deals = await client.deals.get_deals(params) if deals.list: print(f"📊 Найдено сделок: {len(deals.list)}") for deal in deals.list: print(f" - {deal.id}: {deal.status}, баланс {deal.balance.value} {deal.balance.currency}") else: print(" Сделки не найдены") # 4. Получение сделок за последний месяц print("\nПолучение сделок за последний месяц...") month_ago = datetime.now() - timedelta(days=30) params = GetDealsParams( created_at_gte=month_ago, limit=20 ) recent_deals = await client.deals.get_deals(params) print(f"📊 Сделок за месяц: {len(recent_deals.list) if recent_deals.list else 0}") if __name__ == "__main__": asyncio.run(process_deals()) ``` -------------------------------- ### YooKassa Client Source: https://github.com/masasibata/aioyookassa/blob/main/docs/api-reference/index.md Information about the main YooKassa Client and examples of its usage. ```APIDOC ## YooKassa Client ### Description Provides access to the core functionalities of the YooKassa API. ### Usage Examples Refer to the [YooKassa Client usage examples](yookassa-client.md#id1) for practical implementation details. ``` -------------------------------- ### Get Receipt Source: https://github.com/masasibata/aioyookassa/blob/main/docs/api-reference/receipts-api.md Retrieves information about a specific fiscal receipt by its ID. ```APIDOC ## get_receipt ### Description Retrieves information about a specific fiscal receipt. ### Method `GET` (implied by client.receipts.get_receipt) ### Endpoint `/receipts/{receipt_id}` (inferred, actual endpoint not specified) ### Parameters #### Path Parameters - **receipt_id** (string) - Required - The unique identifier of the receipt to retrieve. ### Request Example ```python receipt = await client.receipts.get_receipt("receipt_id") ``` ### Response #### Success Response (200) - **receipt** (object) - The receipt object with detailed information. ``` -------------------------------- ### Get Receipts Source: https://github.com/masasibata/aioyookassa/blob/main/docs/api-reference/receipts-api.md Retrieves a list of fiscal receipts with filtering capabilities. ```APIDOC ## get_receipts ### Description Retrieves a list of fiscal receipts with filtering capabilities. ### Method `GET` (implied by client.receipts.get_receipts) ### Endpoint `/receipts` (inferred, actual endpoint not specified) ### Parameters #### Query Parameters - **params** (GetReceiptsParams) - Required - Parameters for filtering receipts, including payment ID, status, and limit. ### Request Example ```python from aioyookassa.types.params import GetReceiptsParams from aioyookassa.types.enum import ReceiptStatus params = GetReceiptsParams( payment_id="payment_id", status=ReceiptStatus.SUCCEEDED, limit=10 ) receipts = await client.receipts.get_receipts(params) ``` ### Response #### Success Response (200) - **receipts** (array) - A list of receipt objects. ``` -------------------------------- ### Handle Various Payment Statuses Source: https://github.com/masasibata/aioyookassa/blob/main/docs/examples/advanced_payment_example.md This example demonstrates how to handle all possible payment statuses, including pending, waiting for capture, succeeded, and canceled. It also shows how to capture a payment and access cancellation details. ```python import asyncio from aioyookassa import YooKassa from aioyookassa.types.enum import PaymentStatus async def handle_payment_status(payment_id: str): async with YooKassa(api_key="your_api_key", shop_id=12345) as client: payment = await client.payments.get_payment(payment_id) if payment.status == PaymentStatus.PENDING: print("⏳ Платеж ожидает оплаты") print(f"URL для оплаты: {payment.confirmation.url}") elif payment.status == PaymentStatus.WAITING_FOR_CAPTURE: print("⏸️ Платеж ожидает подтверждения") # Подтверждаем платеж captured = await client.payments.capture_payment(payment_id) print(f"✅ Платеж подтвержден: {captured.status}") elif payment.status == PaymentStatus.SUCCEEDED: print("✅ Платеж успешно выполнен") if payment.succeeded_at: print(f"Время выполнения: {payment.succeeded_at}") elif payment.status == PaymentStatus.CANCELED: print("❌ Платеж отменен") if payment.cancellation_details: print(f"Причина: {payment.cancellation_details.reason}") print(f"Партия: {payment.cancellation_details.party}") asyncio.run(handle_payment_status("payment_id")) ``` -------------------------------- ### Get Invoice Source: https://github.com/masasibata/aioyookassa/blob/main/docs/api-reference/invoices-api.md Retrieve information about a specific invoice using its ID. ```python invoice = await client.invoices.get_invoice("invoice_id") ``` -------------------------------- ### Get Shop Settings with client.get_me() Source: https://context7.com/masasibata/aioyookassa/llms.txt Retrieves shop or gateway settings, including account ID, status, and type. Shows how to fetch settings for a sub-account using the `on_behalf_of` parameter. ```python async def show_shop_info(): async with YooKassa(api_key="test_XXX", shop_id=123456) as client: settings = await client.get_me() print(f"ID: {settings.account_id}") print(f"Статус: {settings.status}") print(f"Тип: {settings.account_type}") # Для Split-платежей: получить данные субмагазина sub_settings = await client.get_me(on_behalf_of="987654") print(f"Субмагазин: {sub_settings.account_id}") ``` -------------------------------- ### Full Payment Lifecycle Example in Python Source: https://github.com/masasibata/aioyookassa/blob/main/docs/examples/basic-payment.md This snippet demonstrates the complete process of creating, checking, and capturing a payment. It includes error handling for common API issues. Use this for a comprehensive understanding of payment flows. ```python import asyncio from datetime import datetime from aioyookassa import YooKassa from aioyookassa.types.payment import Money, Confirmation from aioyookassa.types.enum import PaymentStatus, ConfirmationType, Currency from aioyookassa.types.params import CreatePaymentParams, GetPaymentsParams from aioyookassa.exceptions import APIError, NotFound async def process_payment(): """Обработка платежа с полным циклом.""" # Инициализация клиента async with YooKassa(api_key="your_api_key", shop_id=12345) as client: try: # 1. Создание платежа print("Создание платежа...") params = CreatePaymentParams( amount=Money(value=1000.00, currency=Currency.RUB), confirmation=Confirmation( type=ConfirmationType.REDIRECT, return_url="https://example.com/success" ), description="Оплата заказа #12345", metadata={"order_id": "12345", "user_id": "67890"} ) payment = await client.payments.create_payment(params) print(f"✅ Платеж создан: {payment.id}") print(f"🔗 URL для оплаты: {payment.confirmation.url}") # 2. Ожидание оплаты (в реальном приложении это делается через webhook) print("Ожидание оплаты...") await asyncio.sleep(2) # Имитация ожидания # 3. Проверка статуса платежа payment_info = await client.payments.get_payment(payment.id) print(f"📊 Статус платежа: {payment_info.status}") # 4. Подтверждение платежа (если нужно) if payment_info.status == PaymentStatus.WAITING_FOR_CAPTURE: print("Подтверждение платежа...") captured_payment = await client.payments.capture_payment(payment.id) print(f"✅ Платеж подтвержден: {captured_payment.status}") # 5. Получение списка платежей за сегодня today = datetime.now() params = GetPaymentsParams( created_at=today, status=PaymentStatus.SUCCEEDED, limit=5 ) recent_payments = await client.payments.get_payments(params) print(f"📈 Успешных платежей сегодня: {len(recent_payments.list)}") except NotFound: print("❌ Платеж не найден") except APIError as e: print(f"❌ Ошибка API: {e}") except Exception as e: print(f"❌ Неожиданная ошибка: {e}") # Запуск if __name__ == "__main__": asyncio.run(process_payment()) ``` -------------------------------- ### Get Receipt Source: https://github.com/masasibata/aioyookassa/blob/main/docs/getting-started/api-modules.md Use this to retrieve information about a specific receipt using its ID. ```python # Получение информации о чеке receipt = await client.receipts.get_receipt("receipt_id") ``` -------------------------------- ### Using Context Manager Source: https://github.com/masasibata/aioyookassa/blob/main/docs/api-reference/yookassa-client.md Illustrates how to use the YooKassa client as an asynchronous context manager for automatic resource management. ```APIDOC ## Using Context Manager ### Description Utilize the YooKassa client as an asynchronous context manager. This ensures that the client is properly closed after use, handling resource management automatically. ### Code Example ```python async with YooKassa(api_key="your_key", shop_id=12345) as client: # Interact with the API payment = await client.payments.create_payment(...) # The client will be automatically closed upon exiting the 'async with' block ``` ``` -------------------------------- ### Get Specific Payment Source: https://github.com/masasibata/aioyookassa/blob/main/docs/api-reference/payments-api.md Retrieve information about a specific payment using its ID. ```python payment = await client.payments.get_payment("payment_id") ``` -------------------------------- ### Get Invoices List Source: https://github.com/masasibata/aioyookassa/blob/main/docs/getting-started/api-modules.md Use this to retrieve a list of invoices, with an optional limit parameter. ```python # Получение списка счетов invoices = await client.invoices.get_invoices(limit=10) ``` -------------------------------- ### Run a Dedicated Webhook HTTP Server Source: https://context7.com/masasibata/aioyookassa/llms.txt This example demonstrates how to set up and run a complete aiohttp server for handling YooKassa webhooks, including IP validation and a predefined `/webhook` route. It requires `aioyookassa` and `aiohttp`. ```python from aioyookassa.contrib.webhook_server import WebhookServer from aioyookassa.core.webhook_handler import WebhookHandler from aioyookassa.types.enum import WebhookEvent from aioyookassa.types.payment import Payment from aioyookassa.types.payout import Payout handler = WebhookHandler() @handler.register_callback(WebhookEvent.PAYMENT_SUCCEEDED) async def on_payment(payment: Payment): print(f"Оплата: {payment.id} — {payment.amount.value} ₽") @handler.register_callback(WebhookEvent.PAYOUT_SUCCEEDED) async def on_payout(payout: Payout): print(f"Выплата: {payout.id} — {payout.amount.value} ₽") # Запуск сервера (блокирующий вызов) server = WebhookServer(handler=handler, validate_ip=True) server.run(host="0.0.0.0", port=8080) # Интеграция с существующим aiohttp-приложением from aiohttp import web app = web.Application() webhook_server = WebhookServer(handler=handler) inner_app = webhook_server.create_app() app.add_subapp("/yookassa/", inner_app) web.run_app(app, port=8000) ``` -------------------------------- ### Run Tests Source: https://github.com/masasibata/aioyookassa/blob/main/README.md Execute tests for the project. Use 'test-cov' for coverage and 'test-fast' for quick tests without coverage. ```bash make test ``` ```bash make test-cov ``` ```bash make test-fast ``` -------------------------------- ### Get Refund Information Source: https://github.com/masasibata/aioyookassa/blob/main/docs/examples/refunds_example.md Retrieves detailed information about a specific refund using its ID. ```APIDOC ## Get Refund Information ### Description Retrieves detailed information about a specific refund using its ID. ### Method `client.refunds.get_refund(refund_id: str)` ### Parameters #### Path Parameters - **refund_id** (str) - Required - The unique identifier of the refund. ### Request Example ```python await client.refunds.get_refund("refund_id") ``` ### Response #### Success Response (200) Returns a Refund object containing details such as ID, payment ID, amount, currency, status, description, and potentially succeeded_at or cancellation_details. ### Response Example ```json { "id": "refund_id", "payment_id": "payment_id", "amount": { "value": "100.00", "currency": "RUB" }, "status": "succeeded", "description": "Refund for order 123", "created_at": "2023-10-27T10:00:00+00:00", "succeeded_at": "2023-10-27T10:05:00+00:00" } ``` ``` -------------------------------- ### Lint Code with Flake8 Source: https://github.com/masasibata/aioyookassa/blob/main/docs/contributing.md Check the codebase for style guide violations using Flake8. ```bash > poetry run flake8 aioyookassa tests ``` -------------------------------- ### Run All Quality Checks Source: https://github.com/masasibata/aioyookassa/blob/main/README.md Execute all defined quality checks for the project using the 'all-checks' make target. ```bash make all-checks ``` -------------------------------- ### Get Refund Information Source: https://github.com/masasibata/aioyookassa/blob/main/docs/getting-started/api-modules.md Retrieve the details of a specific refund using its unique refund identifier. ```python # Получение информации о возврате refund = await client.refunds.get_refund("refund_id") ``` -------------------------------- ### Get Payment Methods Source: https://github.com/masasibata/aioyookassa/blob/main/docs/getting-started/api-modules.md Retrieve a list of available payment methods or details for a specific payment method. ```python # Получение списка способов оплаты methods = await client.payment_methods.get_payment_methods() # Получение конкретного способа оплаты method = await client.payment_methods.get_payment_method("method_id") ``` -------------------------------- ### Build and Publish Package to PyPI Source: https://github.com/masasibata/aioyookassa/blob/main/docs/contributing.md Commands to build the project package and publish it to the Python Package Index (PyPI). ```bash poetry build poetry publish ```