### Install aiorobokassa from Source Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/installation.md Clone the repository and install the library in editable mode for development. ```bash git clone https://github.com/masasibata/aiorobokassa.git cd aiorobokassa pip install -e . ``` -------------------------------- ### Install aiorobokassa with Development Dependencies (Poetry) Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/installation.md Install the library with development extras using Poetry. ```bash poetry install --extras dev ``` -------------------------------- ### Install and Build Docs with Poetry Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/README.md Installs documentation dependencies using Poetry and builds the HTML documentation. Navigate to the 'docs' directory before building. ```bash # Install documentation dependencies poetry install --extras docs # Build documentation cd docs poetry run sphinx-build -b html . _build/html ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/masasibata/aiorobokassa/blob/main/README.md Clone the repository and install development dependencies using Poetry or pip. ```bash git clone https://github.com/masasibata/aiorobokassa.git cd aiorobokassa poetry install --extras dev pip install -e ".[dev]" ``` -------------------------------- ### Verify aiorobokassa Installation Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/installation.md Import the library and print its version to confirm a successful installation. ```python import aiorobokassa print(aiorobokassa.__version__) ``` -------------------------------- ### Install aiorobokassa with Development Dependencies (pip) Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/installation.md Install the library along with extra dependencies required for development and testing using pip. ```bash pip install aiorobokassa[dev] ``` -------------------------------- ### Basic FastAPI Setup for RoboKassa Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/examples/fastapi.md This snippet demonstrates the fundamental setup for integrating RoboKassa with FastAPI. It includes initializing the RoboKassaClient and defining endpoints for creating payments, handling result notifications, and managing success redirects. Ensure your merchant credentials and passwords are correctly configured. ```python from fastapi import FastAPI, Request from fastapi.responses import RedirectResponse from decimal import Decimal from aiorobokassa import RoboKassaClient, SignatureError app = FastAPI() # Initialize client (you might want to use dependency injection) client = RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", ) @app.post("/payment/create") async def create_payment(order_id: int, amount: Decimal): """Create payment URL for order.""" payment_url = client.create_payment_url( out_sum=amount, description=f"Payment for order #{order_id}", inv_id=order_id, user_parameters={"order_id": str(order_id)}, ) return {"payment_url": payment_url} @app.post("/payment/result") async def handle_result_url(request: Request): """Handle ResultURL notification from RoboKassa.""" params = dict(request.query_params) parsed = client.parse_result_url_params(params) try: client.verify_result_url( out_sum=parsed["out_sum"], inv_id=parsed["inv_id"], signature_value=parsed["signature_value"], shp_params=parsed.get("shp_params"), ) # Update order status in database order_id = parsed["inv_id"] # ... update database return f"OK{order_id}" except SignatureError: return "ERROR" @app.get("/payment/success") async def handle_success_url(request: Request): """Handle SuccessURL redirect.""" params = dict(request.query_params) parsed = client.parse_success_url_params(params) try: client.verify_success_url( out_sum=parsed["out_sum"], inv_id=parsed["inv_id"], signature_value=parsed["signature_value"], shp_params=parsed.get("shp_params"), ) return {"status": "success", "invoice_id": parsed["inv_id"]} except SignatureError: return {"status": "error", "message": "Invalid signature"} ``` -------------------------------- ### Conventional Commit Examples Source: https://github.com/masasibata/aiorobokassa/blob/main/README.md Examples of commit messages following the Conventional Commits specification. ```bash feat: add new payment method support fix: resolve timeout issue in payment creation docs: update API documentation test: add tests for refund functionality refactor: improve error handling ``` -------------------------------- ### Complete Error Handling Example in Python Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/error-handling.md Demonstrates comprehensive error handling for client configuration, payment URL creation, and API interactions. Includes logging and graceful failure. ```python from aiorobokassa import ( RoboKassaClient, SignatureError, APIError, ValidationError, ConfigurationError, ) from decimal import Decimal import logging logger = logging.getLogger(__name__) async def process_payment(amount: Decimal, description: str): try: client = RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", ) except ConfigurationError as e: logger.error(f"Invalid configuration: {e}") return None try: url = client.create_payment_url( out_sum=amount, description=description, ) return url except ValidationError as e: logger.error(f"Invalid payment data: {e}") return None except APIError as e: logger.error(f"API error: {e.status_code} - {e.response}") return None finally: await client.close() ``` -------------------------------- ### Install aiorobokassa from PyPI Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/installation.md Use this command to install the latest stable version of aiorobokassa using pip. ```bash pip install aiorobokassa ``` -------------------------------- ### Install aiorobokassa via Poetry Source: https://github.com/masasibata/aiorobokassa/blob/main/README.md Use this command to add the aiorobokassa library to your project managed by Poetry. ```bash poetry add aiorobokassa ``` -------------------------------- ### Create Invoice with Fiscalization Items Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/invoices.md This example demonstrates how to create an invoice that includes detailed fiscalization items, specifying name, quantity, cost, tax rate, payment method, and payment object for each item. ```python invoice_items = [ InvoiceItem( name="Service 1", quantity=1, cost=50.0, tax=TaxRate.VAT20, payment_method=PaymentMethod.FULL_PAYMENT, payment_object=PaymentObject.SERVICE, ), InvoiceItem( name="Service 2", quantity=2, cost=25.0, tax=TaxRate.VAT20, payment_method=PaymentMethod.FULL_PAYMENT, payment_object=PaymentObject.SERVICE, ), ] result = await client.create_invoice( out_sum=Decimal("100.00"), description="Invoice for services", invoice_items=invoice_items, ) ``` -------------------------------- ### Create Payment URL with Custom Parameters Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/notifications.md Example of creating a payment URL that includes custom parameters (shp_*) for later retrieval in notifications. These parameters are crucial for signature calculation. ```python # When creating payment URL url = client.create_payment_url( out_sum=Decimal("100.00"), description="Payment", user_parameters={"user_id": "123", "order_id": "456"}, ) ``` -------------------------------- ### FastAPI Dependency Injection for RoboKassaClient Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/examples/fastapi.md This example shows how to use FastAPI's dependency injection system to manage the RoboKassaClient instance. This approach is recommended for better testability and cleaner code organization. The `get_client` function provides a reusable way to obtain a configured client. ```python from fastapi import Depends from aiorobokassa import RoboKassaClient def get_client() -> RoboKassaClient: return RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", ) @app.post("/payment/create") async def create_payment( order_id: int, amount: Decimal, client: RoboKassaClient = Depends(get_client), ): payment_url = client.create_payment_url( out_sum=amount, description=f"Payment for order #{order_id}", inv_id=order_id, ) return {"payment_url": payment_url} ``` -------------------------------- ### Flask Payment Creation and Result Handling Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/examples/flask.md This snippet demonstrates a complete Flask application setup for integrating with RoboKassa. It includes endpoints for creating payment URLs and handling the result notifications from RoboKassa, including signature verification. ```python from flask import Flask, request, jsonify, redirect from decimal import Decimal from aiorobokassa import RoboKassaClient, SignatureError app = Flask(__name__) @app.route("/payment/create", methods=["POST"]) async def create_payment(): """Create payment URL.""" data = request.json order_id = data["order_id"] amount = Decimal(data["amount"]) client = RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", ) try: payment_url = client.create_payment_url( out_sum=amount, description=f"Payment for order #{order_id}", inv_id=order_id, ) return jsonify({"payment_url": payment_url}) finally: await client.close() @app.route("/payment/result", methods=["POST", "GET"]) async def handle_result_url(): """Handle ResultURL notification.""" params = request.args.to_dict() if request.method == "GET" else request.form.to_dict() client = RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", ) try: parsed = client.parse_result_url_params(params) client.verify_result_url( out_sum=parsed["out_sum"], inv_id=parsed["inv_id"], signature_value=parsed["signature_value"], shp_params=parsed.get("shp_params"), ) # Update order status return f"OK{parsed['inv_id']}" except SignatureError: return "ERROR" finally: await client.close() ``` -------------------------------- ### Get Invoice Information List Source: https://github.com/masasibata/aiorobokassa/blob/main/README.md Retrieves a list of invoices with pagination and filtering by status. Supports specifying current page, page size, and desired statuses. ```python # Get invoice information list invoices = await client.get_invoice_information_list( current_page=1, page_size=10, invoice_statuses=["paid", "notpaid"], ) ``` -------------------------------- ### Create Payment URL View Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/examples/django.md This Django view handles POST requests to create a payment URL using RoboKassaClient. Ensure you have aiorobokassa installed and replace placeholder credentials. ```python from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_http_methods from decimal import Decimal from aiorobokassa import RoboKassaClient, SignatureError import asyncio @csrf_exempt @require_http_methods(["POST"]) async def create_payment(request): """Create payment URL.""" order_id = request.POST.get("order_id") amount = Decimal(request.POST.get("amount")) client = RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", ) try: payment_url = client.create_payment_url( out_sum=amount, description=f"Payment for order #{order_id}", inv_id=int(order_id), ) return JsonResponse({"payment_url": payment_url}) finally: await client.close() ``` -------------------------------- ### Build Docs with Makefile Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/README.md Provides commands to build, serve locally, and clean documentation files using the Makefile from the project root. ```bash # Build documentation make docs # Build and serve locally make docs-serve # Clean build files make docs-clean ``` -------------------------------- ### Initialize RoboKassaClient Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/quickstart.md Import necessary modules and initialize the RoboKassaClient. Use test_mode=True for development. ```python import asyncio from decimal import Decimal from aiorobokassa import RoboKassaClient async def main(): client = RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", test_mode=True, # Use test mode for development ) # Your code here await client.close() asyncio.run(main()) ``` -------------------------------- ### Available Development Commands Source: https://github.com/masasibata/aiorobokassa/blob/main/README.md Run tests, code quality checks, build artifacts, and manage documentation using make commands. ```bash # Testing make test # Run tests make test-cov # Tests with code coverage make test-fast # Fast tests without coverage # Code Quality make lint # Linting (Black) make format # Format code make type-check # Type checking (MyPy) make all-checks # All quality checks # Build and Publish make build # Build package make clean # Clean artifacts # Documentation make docs # Build documentation make docs-serve # Local documentation server ``` -------------------------------- ### Get Invoice List Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/invoices.md Retrieves a list of invoices with various filtering options. ```APIDOC ## Get Invoice List ### Description Retrieves a paginated list of invoices with the ability to filter by status, type, date range, sum, and keywords. ### Method POST (implied by client.get_invoice_information_list) ### Endpoint Not explicitly defined, but the operation is performed via the `get_invoice_information_list` method of the `RoboKassaClient`. ### Parameters #### Request Body (implied by method arguments) - **current_page** (integer) - Optional - The current page number for pagination. - **page_size** (integer) - Optional - The number of invoices per page. - **invoice_statuses** (list of string) - Optional - A list of invoice statuses to filter by (e.g., "paid", "notpaid"). - **invoice_types** (list of string) - Optional - A list of invoice types to filter by (e.g., "onetime"). - **keywords** (string) - Optional - Keywords to search within invoice descriptions. - **date_from** (string) - Optional - The start date for filtering invoices (ISO 8601 format). - **date_to** (string) - Optional - The end date for filtering invoices (ISO 8601 format). - **is_ascending** (boolean) - Optional - Whether to sort results in ascending order. - **sum_from** (float) - Optional - The minimum sum for filtering invoices. - **sum_to** (float) - Optional - The maximum sum for filtering invoices. ### Response No specific response format is detailed for success, but it is implied to return a list of invoice information matching the filter criteria. ``` -------------------------------- ### RoboKassaClient Initialization Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/api/client.md Initialize the RoboKassa client with your merchant credentials and optional configuration. ```APIDOC ## RoboKassaClient Constructor ### Description Initializes the RoboKassa client for interacting with the RoboKassa API. ### Parameters - **merchant_login** (str) - Required - Merchant login from RoboKassa. - **password1** (str) - Required - Password #1 for signature calculation. - **password2** (str) - Required - Password #2 for ResultURL verification. - **password3** (str | None) - Optional - Password #3 for refund API (required for refunds). - **test_mode** (bool) - Optional - Enable test mode. Defaults to False. - **session** (aiohttp.ClientSession | None) - Optional - An aiohttp session to use for requests. If not provided, a new session will be created. - **timeout** (aiohttp.ClientTimeout | None) - Optional - Timeout configuration for requests. - **base_url_override** (str | None) - Optional - Allows overriding the default base URL, useful for testing. ### Raises - **ConfigurationError** - If the provided configuration is invalid. ``` -------------------------------- ### Get Refund Status via Modern JWT API Source: https://github.com/masasibata/aiorobokassa/blob/main/README.md Retrieves the status of a refund using the modern JWT API, requiring the request ID of the refund operation. ```python # Modern JWT API - Get refund status refund_status = await client.get_refund_status_v2( request_id=refund.request_id ) ``` -------------------------------- ### Use RoboKassaClient as Context Manager Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/quickstart.md The recommended way to use the client is with an async context manager, which ensures proper resource management. ```python import asyncio from decimal import Decimal from aiorobokassa import RoboKassaClient async def main(): async with RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", test_mode=True, ) as client: # Your code here pass asyncio.run(main()) ``` -------------------------------- ### Handle Result URL View Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/examples/django.md This Django view processes incoming ResultURL notifications from RoboKassa, verifies the signature, and updates the order status. It supports both GET and POST requests. ```python from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_http_methods from decimal import Decimal from aiorobokassa import RoboKassaClient, SignatureError import asyncio @csrf_exempt @require_http_methods(["POST", "GET"]) async def handle_result_url(request): """Handle ResultURL notification.""" params = request.GET.dict() if request.method == "GET" else request.POST.dict() client = RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", ) try: parsed = client.parse_result_url_params(params) client.verify_result_url( out_sum=parsed["out_sum"], inv_id=parsed["inv_id"], signature_value=parsed["signature_value"], shp_params=parsed.get("shp_params"), ) # Update order status order_id = parsed["inv_id"] # ... update database return HttpResponse(f"OK{order_id}") except SignatureError: return HttpResponse("ERROR") finally: await client.close() ``` -------------------------------- ### Basic RoboKassa Client Usage Source: https://github.com/masasibata/aiorobokassa/blob/main/README.md Initialize the RoboKassa client with your merchant credentials and test mode setting. Use this to generate payment URLs for your customers. Remember to close the client session when done. ```python import asyncio from decimal import Decimal from aiorobokassa import RoboKassaClient async def main(): # Initialize client client = RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", test_mode=True, # Use test mode for development ) # Create payment URL payment_url = client.create_payment_url( out_sum=Decimal("100.00"), description="Test payment", inv_id=123, email="customer@example.com", ) print(f"Payment URL: {payment_url}") # Close client session await client.close() asyncio.run(main()) ``` -------------------------------- ### Get Refund Status (API v2 - JWT) Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/refunds.md Retrieves the status of a refund initiated via the v2 API using its `request_id`. Returns Pydantic models with detailed status information. ```python refund_status = await client.get_refund_status_v2( request_id=refund.request_id, ) print(f"Refund status: {refund_status.label}") print(f"Refund amount: {refund_status.amount}") ``` -------------------------------- ### RoboKassaClient Initialization Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/api/client.md Initializes the RoboKassaClient with merchant credentials and optional configuration for test mode, session, timeout, and base URL override. ```APIDOC ## RoboKassaClient ### `__init__` Initialize RoboKassa client. #### Parameters: * **merchant_login** (str) - Merchant login from RoboKassa * **password1** (str) - Password #1 for signature calculation * **password2** (str) - Password #2 for ResultURL verification * **password3** (str | None) - Password #3 for refund API (optional, required for refunds) * **test_mode** (bool) - Enable test mode (default: False) * **session** (aiohttp.ClientSession | None) - Optional aiohttp session (will be created if not provided) * **timeout** (aiohttp.ClientTimeout | None) - Optional timeout for requests * **base_url_override** (str | None) - Override base URL (for testing) #### Raises: * [**ConfigurationError**](exceptions.md#id5) - If configuration is invalid ``` -------------------------------- ### Get Invoice Information List Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/invoices.md Retrieve a list of invoices with various filtering options, including status, type, date range, sum range, and keywords. Sorting by ascending or descending order is also supported. ```python from datetime import datetime result = await client.get_invoice_information_list( current_page=1, page_size=10, invoice_statuses=["paid", "notpaid"], invoice_types=["onetime"], keywords="services", date_from="2025-01-01T00:00:00+00:00", date_to="2025-12-31T23:59:59+00:00", is_ascending=True, sum_from=10.0, sum_to=1000.0, ) ``` -------------------------------- ### Create a Basic Invoice Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/invoices.md Use this snippet to create a simple one-time invoice. Ensure you have initialized RoboKassaClient with your merchant credentials. ```python from decimal import Decimal from aiorobokassa import RoboKassaClient, InvoiceType from aiorobokassa.models.requests import InvoiceItem from aiorobokassa.enums import TaxRate, PaymentMethod, PaymentObject async with RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", ) as client: result = await client.create_invoice( out_sum=Decimal("100.00"), description="Invoice for services", invoice_type=InvoiceType.ONE_TIME, inv_id=12345, culture="ru", ) print(f"Invoice created: {result}") print(f"Invoice URL: {result['url']}") ``` -------------------------------- ### Stage and Commit Changes Source: https://github.com/masasibata/aiorobokassa/blob/main/README.md Stage all changes and commit them with a descriptive message. ```bash git add . git commit -m "feat: add new feature" ``` -------------------------------- ### Generate Basic Payment URL with RoboKassa Client Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/payments.md Use this snippet to create a simple payment URL. Ensure you have initialized the RoboKassaClient with your merchant credentials. ```python from decimal import Decimal from aiorobokassa import RoboKassaClient async with RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", ) as client: url = client.create_payment_url( out_sum=Decimal("100.00"), description="Payment for order #123", ) ``` -------------------------------- ### Create Simple Invoice Source: https://github.com/masasibata/aiorobokassa/blob/main/README.md Creates a one-time invoice with a specified sum and description. Requires culture parameter. ```python from aiorobokassa import RoboKassaClient, InvoiceType from aiorobokassa.models.requests import InvoiceItem from aiorobokassa.enums import TaxRate, PaymentMethod, PaymentObject # Create simple invoice result = await client.create_invoice( out_sum=Decimal("100.00"), description="Invoice payment", invoice_type=InvoiceType.ONE_TIME, inv_id=123, culture="ru", ) ``` -------------------------------- ### Basic Fiscalization (Receipt) Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/payments.md Include receipt data for fiscalization compliance. Ensure all required fields for items and tax information are provided. ```python receipt_data = { "sno": "osn", "items": [ { "name": "Товар", "quantity": 1, "sum": 100, "tax": "vat10", }, ], } url = client.create_payment_url( out_sum=Decimal("100.00"), description="Payment", receipt=receipt_data, ) ``` -------------------------------- ### Create Payment URL with SHA256 Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/signatures.md Use SHA256 for creating a payment URL. Ensure the RoboKassaClient is initialized with necessary credentials. ```python from aiorobokassa import RoboKassaClient, SignatureAlgorithm async with RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", ) as client: # Use SHA256 url = client.create_payment_url( out_sum=Decimal("100.00"), description="Payment", signature_algorithm=SignatureAlgorithm.SHA256, ) ``` -------------------------------- ### Split Payment with All Parameters Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/payments.md Utilize all available parameters for split payments, including merchant comments, shop parameters, customer email, currency, language, test mode, expiration date, and signature algorithm. ```python shop_params = [ {"name": "param1", "value": "value1"}, {"name": "param2", "value": "value2"}, ] url = client.create_split_payment_url( out_amount=Decimal("100.50"), merchant_id="master_merchant", split_merchants=split_merchants, merchant_comment="Split payment for order #123", shop_params=shop_params, email="customer@example.com", inc_curr="BankCard", language="ru", is_test=True, expiration_date="2024-12-31T23:59:59", signature_algorithm=SignatureAlgorithm.SHA256, ) ``` -------------------------------- ### Handle Custom Parameters in Notification Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/notifications.md Demonstrates how to extract and use custom parameters (shp_*) from notification parameters and the importance of including them in signature verification. ```python # In notification handler params = client.parse_result_url_params(request_params) # Extract shp_params user_id = params["shp_params"]["user_id"] # "123" order_id = params["shp_params"]["order_id"] # "456" # IMPORTANT: Pass shp_params when verifying signature client.verify_result_url( out_sum=params["out_sum"], inv_id=params["inv_id"], signature_value=params["signature_value"], shp_params=params.get("shp_params"), # Required if shp_params were used ) ``` -------------------------------- ### Create a Feature Branch Source: https://github.com/masasibata/aiorobokassa/blob/main/README.md Create a new branch for your feature development. ```bash git checkout -b feature/your-feature-name ``` -------------------------------- ### Handle ConfigurationError in Python Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/error-handling.md Catch ConfigurationError for issues with client initialization, such as invalid merchant credentials or weak passwords. Ensure your client is configured correctly before use. ```python from aiorobokassa import ConfigurationError try: client = RoboKassaClient( merchant_login="", # Invalid: empty login password1="short", # Invalid: too short password2="password2", ) except ConfigurationError as e: print(f"Configuration error: {e}") ``` -------------------------------- ### Create Payment URL with Receipt Source: https://github.com/masasibata/aiorobokassa/blob/main/README.md Generates a payment URL that includes fiscalization data by embedding a `Receipt` object. ```python # Create payment URL with receipt url = client.create_payment_url( out_sum=Decimal("100.00"), description="Payment with receipt", receipt=receipt, ) ``` -------------------------------- ### Create Payment URL Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/examples/basic-usage.md Generates a payment URL for a given amount, description, and invoice ID. Ensure you have the RoboKassaClient initialized with your merchant credentials and test mode enabled if necessary. ```python import asyncio from decimal import Decimal from aiorobokassa import RoboKassaClient async def main(): async with RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", test_mode=True, ) as client: url = client.create_payment_url( out_sum=Decimal("100.00"), description="Test payment", inv_id=123, ) print(f"Payment URL: {url}") asyncio.run(main()) ``` -------------------------------- ### Create Payment URL with SHA512 Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/signatures.md Use SHA512 for creating a payment URL, providing the highest level of security. Ensure the RoboKassaClient is initialized. ```python from aiorobokassa import RoboKassaClient, SignatureAlgorithm async with RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", ) as client: # Use SHA512 url = client.create_payment_url( out_sum=Decimal("100.00"), description="Payment", signature_algorithm=SignatureAlgorithm.SHA512, ) ``` -------------------------------- ### Create Invoice with Redirect URLs Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/invoices.md Configure success and fail redirect URLs for an invoice, specifying the HTTP method for each. This allows users to be redirected to specific pages after payment or failure. ```python result = await client.create_invoice( out_sum=Decimal("100.00"), description="Invoice for services", success_url="https://example.com/success", success_url_method="GET", fail_url="https://example.com/fail", fail_url_method="POST", ) ``` -------------------------------- ### Create Full Refund via Legacy XML API Source: https://github.com/masasibata/aiorobokassa/blob/main/README.md Initiates a full refund for a given invoice ID using the legacy XML API. ```python # Legacy XML API - Full refund refund_result = await client.create_refund(invoice_id=123) ``` -------------------------------- ### Create a Payment URL Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/quickstart.md Generate a payment URL to redirect users to RoboKassa for completing a payment. Ensure you have initialized the client using a context manager. ```python async with RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", test_mode=True, ) as client: payment_url = client.create_payment_url( out_sum=Decimal("100.00"), description="Test payment", inv_id=123, email="customer@example.com", ) print(f"Payment URL: {payment_url}") ``` -------------------------------- ### Create Full Refund (API v1) Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/refunds.md Initiates a full refund for a given invoice ID. Ensure the RoboKassaClient is properly initialized with merchant credentials. ```python from aiorobokassa import RoboKassaClient async with RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", ) as client: result = await client.create_refund( invoice_id=12345, ) print(f"Refund result: {result}") ``` -------------------------------- ### Create Full Refund (API v2 - JWT) Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/refunds.md Initiates a full refund using the modern JWT-based API v2. Requires `password3` to be configured in RoboKassaClient. Uses `op_key` from the original payment. ```python from decimal import Decimal from aiorobokassa import RoboKassaClient async with RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", password3="password3", # Required for refund v2 ) as client: # Full refund refund = await client.create_refund_v2( op_key="operation_key_from_payment", ) print(f"Refund request ID: {refund.request_id}") ``` -------------------------------- ### Enable Test Mode Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/payments.md Activate test mode for development and integration testing. Payments will not be processed in this mode. ```python client = RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", test_mode=True, # Enable test mode ) ``` -------------------------------- ### Generate Payment URL with Customer Email Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/payments.md Specify a customer's email address to automatically send them a payment receipt. ```python url = client.create_payment_url( out_sum=Decimal("100.00"), description="Payment for order #123", inv_id=12345, email="customer@example.com", ) ``` -------------------------------- ### Create Invoice Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/examples/basic-usage.md Creates an invoice for a payment. This is typically used for scenarios where you need to pre-generate an invoice before the customer initiates payment. ```python import asyncio from decimal import Decimal from aiorobokassa import RoboKassaClient async def main(): async with RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", ) as client: result = await client.create_invoice( out_sum=Decimal("100.00"), description="Invoice payment", inv_id=123, ) print(f"Invoice created: {result}") asyncio.run(main()) ``` -------------------------------- ### Django URL Configuration Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/examples/django.md This snippet shows how to configure the URL patterns in Django's urls.py to map specific URL paths to the create_payment and handle_result_url views. ```python # urls.py from django.urls import path from . import views urlpatterns = [ path("payment/create/", views.create_payment, name="create_payment"), path("payment/result/", views.handle_result_url, name="result_url"), ] ``` -------------------------------- ### Create Partial Refund (API v1) Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/refunds.md Creates a partial refund by specifying the exact amount to be refunded. The amount should be a Decimal type. ```python from decimal import Decimal result = await client.create_refund( invoice_id=12345, amount=Decimal("50.00"), # Refund only 50.00 ) ``` -------------------------------- ### RoboKassaClient Methods Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/api/client.md Provides methods for interacting with the RoboKassa payment gateway, including payment link generation, notification handling, invoice creation, and refunds. ```APIDOC ## RoboKassaClient Methods ### `clear_sensitive_data()` Clear sensitive data from memory. #### Returns: * None ``` -------------------------------- ### Create Partial Refund via Legacy XML API Source: https://github.com/masasibata/aiorobokassa/blob/main/README.md Initiates a partial refund for a given invoice ID, specifying the refund amount, using the legacy XML API. ```python # Legacy XML API - Partial refund partial_refund = await client.create_refund( invoice_id=123, amount=Decimal("50.00"), ) ``` -------------------------------- ### Handle RoboKassa SuccessURL Redirects Source: https://github.com/masasibata/aiorobokassa/blob/main/README.md Implement this function to handle user redirects after a successful payment. It verifies the payment signature and displays a success message to the user. Requires correct merchant credentials. ```python from aiorobokassa import RoboKassaClient, SignatureError async def handle_success_url(request_params: dict): client = RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", ) params = client.parse_success_url_params(request_params) try: client.verify_success_url( out_sum=params["out_sum"], inv_id=params["inv_id"], signature_value=params["signature_value"], shp_params=params.get("shp_params"), ) # Show success page to user return "Payment successful!" except SignatureError: return "Payment verification failed" ``` -------------------------------- ### aiorobokassa.utils.helpers.build_url Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/api/utils.md Builds a URL with query parameters, ensuring they are properly URL-encoded. The SignatureValue should be the last parameter. ```APIDOC ## build_url ### Description Build URL with query parameters. Parameters are properly URL-encoded. SignatureValue should be last. ### Parameters #### Path Parameters None #### Query Parameters - **base_url** (str) - Required - Base URL - **params** (Dict[str, str | None]) - Required - Dictionary of query parameters (None values are skipped) ### Request Example ```json { "base_url": "https://example.com/pay", "params": { "mrh_login": "test_login", "out_summ": "100.00", "inv_id": "123", "SignatureValue": "some_signature" } } ``` ### Response #### Success Response (200) - **url** (str) - The constructed URL with query parameters. ### Response Example ```json { "url": "https://example.com/pay?mrh_login=test_login&out_summ=100.00&inv_id=123&SignatureValue=some_signature" } ``` ``` -------------------------------- ### Create Payment URL Source: https://github.com/masasibata/aiorobokassa/blob/main/README.md Generates a payment URL with customizable parameters. Supports user-defined parameters for tracking. ```python from decimal import Decimal from aiorobokassa import RoboKassaClient # Create payment URL payment_url = client.create_payment_url( out_sum=Decimal("100.00"), description="Payment for order #12345", inv_id=12345, email="customer@example.com", culture="ru", user_parameters={"user_id": "123", "order_id": "456"}, ) ``` -------------------------------- ### Create Partial Refund (API v2 - JWT) Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/refunds.md Creates a partial refund using API v2 by specifying the `refund_sum`. The amount should be a Decimal. ```python refund = await client.create_refund_v2( op_key="operation_key_from_payment", refund_sum=Decimal("50.00"), # Partial refund amount ) ``` -------------------------------- ### Basic Split Payment Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/payments.md Create a split payment URL for distributing payments among multiple merchants. Specify the master merchant and the amounts for each split merchant. ```python split_merchants = [ { "id": "merchant1", "amount": 50.00, }, { "id": "merchant2", "amount": 50.50, }, ] url = client.create_split_payment_url( out_amount=Decimal("100.50"), merchant_id="master_merchant", split_merchants=split_merchants, ) ``` -------------------------------- ### Generate Payment URL with Language and Encoding Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/payments.md Specify the desired language (e.g., 'en' or 'ru') and character encoding for the payment page. ```python url = client.create_payment_url( out_sum=Decimal("100.00"), description="Payment for order #123", culture="en", # or "ru" encoding="utf-8", ) ``` -------------------------------- ### Create Receipt Source: https://github.com/masasibata/aiorobokassa/blob/main/README.md Constructs a fiscal receipt object containing a list of items and the tax system used. ```python # Create receipt receipt = Receipt( items=[item], sno=TaxSystem.OSN, ) ``` -------------------------------- ### Generate Payment URL with Custom Parameters Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/payments.md Add custom user parameters (prefixed with 'Shp_') to the payment URL. These will be available in subsequent notifications. ```python url = client.create_payment_url( out_sum=Decimal("100.00"), description="Payment for order #123", inv_id=12345, user_parameters={ "user_id": "123", "order_id": "456", }, ) ``` -------------------------------- ### Choose Signature Algorithm Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/payments.md Specify the signature algorithm for payment requests. SHA256 or SHA512 are recommended over MD5 for production environments. ```python from aiorobokassa import RoboKassaClient, SignatureAlgorithm url = client.create_payment_url( out_sum=Decimal("100.00"), description="Payment for order #123", signature_algorithm=SignatureAlgorithm.SHA256, ) ``` -------------------------------- ### Split Payment with Receipt Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/payments.md Combine split payments with fiscalization by providing receipt details for individual merchants. Ensure correct `TaxRate`, `TaxSystem`, `PaymentMethod`, and `PaymentObject` are used. ```python from aiorobokassa.models.receipt import Receipt, ReceiptItem from aiorobokassa.enums import TaxRate, TaxSystem, PaymentMethod, PaymentObject receipt = Receipt( items=[ ReceiptItem( name="Item 1", quantity=1, cost=50.0, tax=TaxRate.VAT20, payment_method=PaymentMethod.FULL_PAYMENT, payment_object=PaymentObject.COMMODITY, ) ], sno=TaxSystem.OSN, ) split_merchants = [ { "id": "merchant1", "amount": 50.00, "invoice_id": 100, "receipt": receipt, }, { "id": "merchant2", "amount": 50.50, }, ] url = client.create_split_payment_url( out_amount=Decimal("100.50"), merchant_id="master_merchant", split_merchants=split_merchants, ) ``` -------------------------------- ### Fiscalization (Receipt) Source: https://github.com/masasibata/aiorobokassa/blob/main/README.md Methods for creating receipts for ФЗ-54 compliance, used in conjunction with payment URL generation. ```APIDOC ## Fiscalization (Receipt) - ФЗ-54 ### Description Methods for creating receipts for ФЗ-54 compliance, used in conjunction with payment URL generation. ### Methods - `create_payment_url` (with `receipt` parameter) ### Parameters for `ReceiptItem` - **name** (string) - Required - The name of the item. - **quantity** (float) - Required - The quantity of the item. - **sum** (Decimal) - Required - The total sum for the item. - **tax** (TaxRate) - Required - The tax rate applied to the item. - **payment_method** (PaymentMethod) - Required - The payment method for the item. - **payment_object** (PaymentObject) - Required - The payment object type for the item. ### Parameters for `Receipt` - **items** (list[ReceiptItem]) - Required - A list of `ReceiptItem` objects. - **sno** (TaxSystem) - Required - The tax system used (e.g., OSN). ``` -------------------------------- ### create_refund Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/api/client.md Initiates a refund for a given invoice ID. Supports optional amount and signature algorithm. ```APIDOC ## async create_refund(invoice_id: int, amount: Decimal | None = None, signature_algorithm: str | SignatureAlgorithm = 'MD5') -> Dict[str, str] ### Description Create refund for invoice. ### Parameters #### Path Parameters - **invoice_id** (int) - Required - The ID of the invoice to refund. - **amount** (Decimal | None) - Optional - The amount to refund. If omitted, a full refund is processed. - **signature_algorithm** (str | SignatureAlgorithm) - Optional - The signature algorithm to use (default: 'MD5'). ``` -------------------------------- ### Push Changes to Remote Source: https://github.com/masasibata/aiorobokassa/blob/main/README.md Push your local feature branch to the remote repository. ```bash git push origin feature/your-feature-name ``` -------------------------------- ### Handle ResultURL with Django Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/notifications.md This Django view handles server notifications from RoboKassa. It verifies the payment signature and returns an HTTP response indicating success or error. ```python from django.http import HttpResponse from aiorobokassa import RoboKassaClient, SignatureError def handle_result_url(request): client = RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", ) params = client.parse_result_url_params(request.GET.dict()) try: client.verify_result_url( out_sum=params["out_sum"], inv_id=params["inv_id"], signature_value=params["signature_value"], shp_params=params.get("shp_params"), ) # Update database return HttpResponse(f"OK{params['inv_id']}") except SignatureError: return HttpResponse("ERROR") ``` -------------------------------- ### Handle Refund Errors (API v1) Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/refunds.md Demonstrates how to catch and handle potential API errors during refund processing using a try-except block. Catches APIError and logs the status code and response. ```python from aiorobokassa import APIError try: result = await client.create_refund( invoice_id=12345, amount=Decimal("50.00"), ) except APIError as e: print(f"Refund failed: {e.status_code} - {e.response}") ``` -------------------------------- ### Handle SuccessURL Redirect Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/notifications.md Process user redirects after a successful payment with this function. It verifies the signature using password1 before displaying a success message. ```python from aiorobokassa import RoboKassaClient, SignatureError async def handle_success_url(request_params: dict): client = RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", ) params = client.parse_success_url_params(request_params) try: client.verify_success_url( out_sum=params["out_sum"], inv_id=params["inv_id"], signature_value=params["signature_value"], shp_params=params.get("shp_params"), ) # Show success page return "Payment successful!" except SignatureError: return "Payment verification failed" ``` -------------------------------- ### RefundRequest Model Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/api/models.md Model for initiating a refund using the legacy XML API. Requires the invoice ID and the refund amount. ```APIDOC ## RefundRequest ### Description Model for refund request (legacy XML API). ### Fields - **amount** (Decimal | None) - Optional - **invoice_id** (int) - Required ### Methods - **validate_amount()**: Validate refund amount is positive if specified. ``` -------------------------------- ### Handle ResultURL with FastAPI Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/notifications.md Use this snippet to handle server-to-server notifications from RoboKassa using FastAPI. It verifies the signature and returns 'OK{invoice_id}' upon success. ```python from fastapi import FastAPI, Request from aiorobokassa import RoboKassaClient, SignatureError app = FastAPI() client = RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", ) @app.post("/payment/result") async def handle_result_url(request: Request): params = dict(request.query_params) parsed = client.parse_result_url_params(params) try: client.verify_result_url( out_sum=parsed["out_sum"], inv_id=parsed["inv_id"], signature_value=parsed["signature_value"], shp_params=parsed.get("shp_params"), ) # Payment is valid, update your database invoice_id = parsed["inv_id"] amount = parsed["out_sum"] # ... update order status in database return f"OK{invoice_id}" except SignatureError: return "ERROR" ``` -------------------------------- ### Parse SuccessURL Parameters Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/guides/notifications.md Helper method to parse parameters from RoboKassa's SuccessURL redirect. The structure is identical to ResultURL parameters. ```python # Parse SuccessURL parameters params = client.parse_success_url_params(request_params) # Same structure as above ``` -------------------------------- ### Process Refund Source: https://github.com/masasibata/aiorobokassa/blob/main/docs/examples/basic-usage.md Initiates a refund for a given invoice ID. You can perform a full refund by omitting the amount or a partial refund by specifying the desired amount. ```python import asyncio from decimal import Decimal from aiorobokassa import RoboKassaClient async def main(): async with RoboKassaClient( merchant_login="your_merchant_login", password1="password1", password2="password2", ) as client: # Full refund result = await client.create_refund(invoice_id=123) print(f"Refund: {result}") # Partial refund result = await client.create_refund( invoice_id=123, amount=Decimal("50.00"), ) print(f"Partial refund: {result}") asyncio.run(main()) ```