Skip to main content

Async Python library for RoboKassa payment gateway

Project description

Downloads Downloads Downloads

aiorobokassa banner

aiorobokassa

Async Python library for RoboKassa payment gateway integration

aiorobokassa is a modern async Python library for integrating with RoboKassa payment gateway. The library provides full support for RoboKassa API, including payment link generation, notification handling, invoice creation, refunds, fiscalization, and more.

โœจ Features

  • ๐Ÿš€ Full async/await support with aiohttp for high performance
  • ๐Ÿ’ณ Payment link generation with customizable parameters
  • ๐Ÿ”” Notification handling (ResultURL, SuccessURL) with signature verification
  • ๐Ÿ“„ Invoice creation via Invoice API (JWT-based)
  • ๐Ÿ’ฐ Refund operations (full and partial) via legacy XML API and modern JWT API
  • ๐Ÿงพ Fiscalization support (Receipt) with Pydantic models and enums for ะคะ—-54 compliance
  • ๐Ÿ” Signature verification (MD5, SHA256, SHA512)
  • ๐Ÿ›ก๏ธ Type hints throughout the codebase
  • โœ… Pydantic validation for all requests and responses
  • ๐Ÿงช Test mode support for development
  • ๐Ÿ—๏ธ Clean architecture (SOLID, DRY, KISS principles)

๐Ÿ”— Links

๐Ÿฆ Dependencies

Library Description
aiohttp Asynchronous HTTP Client/Server for asyncio and Python.
pydantic JSON Data Validator

๐Ÿ“ Project Structure

aiorobokassa/
โ”œโ”€โ”€ api/                    # API mixins
โ”‚   โ”œโ”€โ”€ base.py            # Base API client
โ”‚   โ”œโ”€โ”€ invoice.py        # Invoice operations
โ”‚   โ”œโ”€โ”€ payment.py        # Payment operations
โ”‚   โ””โ”€โ”€ refund.py         # Refund operations
โ”œโ”€โ”€ models/                # Pydantic models
โ”‚   โ”œโ”€โ”€ receipt.py        # Receipt models for fiscalization
โ”‚   โ””โ”€โ”€ requests.py       # Request/response models
โ”œโ”€โ”€ utils/                 # Utility functions
โ”‚   โ”œโ”€โ”€ helpers.py        # Helper functions
โ”‚   โ”œโ”€โ”€ jwt.py            # JWT token creation
โ”‚   โ”œโ”€โ”€ signature.py      # Signature calculation
โ”‚   โ””โ”€โ”€ xml.py            # XML parsing
โ”œโ”€โ”€ client.py             # Main RoboKassa client
โ”œโ”€โ”€ constants.py          # Constants
โ”œโ”€โ”€ enums.py              # Enums
โ””โ”€โ”€ exceptions.py         # Custom exceptions

๐Ÿš€ Quick Start

Installation

pip install aiorobokassa

Basic Usage

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 = await 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())

๐ŸŽฏ Supported Features

The library supports all RoboKassa API features:

  • ๐Ÿ’ณ Payments โ€” payment link generation with customizable parameters
  • ๐Ÿ”” Notifications โ€” ResultURL and SuccessURL signature verification
  • ๐Ÿ“„ Invoices โ€” create and manage invoices via Invoice API (JWT-based)
  • ๐Ÿ’ฐ Refunds โ€” full and partial refunds via legacy XML API and modern JWT API
  • ๐Ÿงพ Fiscalization โ€” receipt generation for ะคะ—-54 compliance
  • ๐Ÿ” Signatures โ€” MD5, SHA256, SHA512 signature algorithms
  • ๐Ÿงช Test Mode โ€” development and testing support

๐Ÿ“‹ Main Methods

๐Ÿ’ณ Payments

from decimal import Decimal
from aiorobokassa import RoboKassaClient

# Create payment URL
payment_url = await 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"},
)

# Verify ResultURL notification
params = client.parse_result_url_params(request_params)
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"),
)

# Verify SuccessURL redirect
params = client.parse_success_url_params(request_params)
client.verify_success_url(
    out_sum=params["out_sum"],
    inv_id=params["inv_id"],
    signature_value=params["signature_value"],
)

๐Ÿ“„ Invoices

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",
)

# Create invoice with fiscalization
invoice_items = [
    InvoiceItem(
        name="Service 1",
        quantity=1,
        cost=100.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 with items",
    invoice_items=invoice_items,
)

# Deactivate invoice
await client.deactivate_invoice(inv_id=123)

# Get invoice information list
invoices = await client.get_invoice_information_list(
    current_page=1,
    page_size=10,
    invoice_statuses=["paid", "notpaid"],
)

๐Ÿ’ฐ Refunds

from decimal import Decimal

# Legacy XML API - Full refund
refund_result = await client.create_refund(invoice_id=123)

# Legacy XML API - Partial refund
partial_refund = await client.create_refund(
    invoice_id=123,
    amount=Decimal("50.00"),
)

# Legacy XML API - Check refund status
status = await client.get_refund_status(invoice_id=123)

# Modern JWT API - Create refund (requires password3)
refund = await client.create_refund_v2(
    op_key="operation_key_from_payment",
    refund_sum=Decimal("50.00"),
)

# Modern JWT API - Get refund status
refund_status = await client.get_refund_status_v2(
    request_id=refund.request_id
)

๐Ÿงพ Fiscalization (Receipt) - ะคะ—-54

For clients using RoboKassa's cloud or cash solutions, fiscalization is required:

from aiorobokassa import (
    RoboKassaClient,
    Receipt,
    ReceiptItem,
    TaxRate,
    TaxSystem,
    PaymentMethod,
    PaymentObject,
)

# Create receipt item
item = ReceiptItem(
    name="ะขะพะฒะฐั€ 1",
    quantity=1,
    sum=Decimal("100.00"),
    tax=TaxRate.VAT10,
    payment_method=PaymentMethod.FULL_PAYMENT,
    payment_object=PaymentObject.COMMODITY,
)

# Create receipt
receipt = Receipt(
    items=[item],
    sno=TaxSystem.OSN,
)

# Create payment URL with receipt
url = await client.create_payment_url(
    out_sum=Decimal("100.00"),
    description="Payment with receipt",
    receipt=receipt,
)

๐Ÿ”” Handling Notifications

ResultURL (Server-to-Server Notification)

from aiorobokassa import RoboKassaClient, SignatureError

# In your web framework (FastAPI, Django, etc.)
async def handle_result_url(request_params: dict):
    client = RoboKassaClient(
        merchant_login="your_merchant_login",
        password1="password1",
        password2="password2",
    )

    # Parse parameters
    params = client.parse_result_url_params(request_params)

    try:
        # Verify 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"),
        )

        # Payment is valid, update order status
        invoice_id = params["inv_id"]
        amount = params["out_sum"]
        # ... update your database

        return "OK" + invoice_id  # RoboKassa expects this response
    except SignatureError:
        # Invalid signature, reject payment
        return "ERROR"

SuccessURL (User Redirect)

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"

๐Ÿ”ง Context Manager

import asyncio
from decimal import Decimal
from aiorobokassa import RoboKassaClient

async with RoboKassaClient(
    merchant_login="your_merchant_login",
    password1="password1",
    password2="password2",
    test_mode=True,
) as client:
    payment_url = await client.create_payment_url(
        out_sum=Decimal("100.00"),
        description="Test payment",
    )
    print(f"Payment URL: {payment_url}")
    # Client automatically closes

๐Ÿ› ๏ธ Installation and Setup

Requirements

  • Python 3.8+
  • aiohttp >= 3.8.0
  • pydantic >= 2.0.0

Installation via pip

pip install aiorobokassa

Installation via Poetry

poetry add aiorobokassa

๐Ÿ“– Documentation

๐Ÿ“š Full documentation is available at aiorobokassa.readthedocs.io

The documentation includes:

  • ๐Ÿ“– Installation guide
  • ๐Ÿš€ Quick start tutorial
  • ๐Ÿ“ Detailed guides (payments, notifications, invoices, refunds, fiscalization)
  • ๐Ÿ”ง API reference
  • ๐Ÿ’ก Code examples (FastAPI, Django, Flask)
  • โŒ Error handling guide

For more information about RoboKassa API, visit official RoboKassa documentation.

๐Ÿค Supporting the Project

If the library was helpful, you can support the project:

  • ๐Ÿ’ Tribute โ€” support through Telegram
  • ๐Ÿ› Report a bug โ€” GitHub Issues
  • ๐Ÿ’ฌ Contact developer โ€” Dev-Telegram

๐Ÿš€ Contributing

We welcome contributions to the library! Here's how you can help:

Quick Start for Developers

# Clone the repository
git clone https://github.com/masasibata/aiorobokassa.git
cd aiorobokassa

# Install dependencies for development
poetry install --extras dev

# Or with pip
pip install -e ".[dev]"

Available Commands

# 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

Contribution Process

  1. Fork the repository on GitHub
  2. Create a branch for your changes:
    git checkout -b feature/your-feature-name
    
  3. Make changes and ensure all checks pass:
    make all-checks
    
  4. Commit your changes:
    git add .
    git commit -m "feat: add new feature"
    
  5. Push your changes:
    git push origin feature/your-feature-name
    
  6. Create a Pull Request on GitHub

Pull Request Requirements

  • โœ… All tests pass (make test)
  • โœ… Code is formatted (make format)
  • โœ… Linting passes (make lint)
  • โœ… Type checking passes (make type-check)
  • โœ… Documentation updated (if necessary)
  • โœ… Descriptive commit message

Contribution Types

  • ๐Ÿ› Bug fixes โ€” fixing errors in code
  • โœจ New features โ€” adding new functionality
  • ๐Ÿ“š Documentation โ€” improving documentation and examples
  • โšก Optimization โ€” improving performance
  • ๐Ÿงช Tests โ€” adding or improving tests
  • ๐Ÿ”ง Infrastructure โ€” improving development tools

Commit Conventions

Use Conventional Commits:

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

Getting Help

๐Ÿ“„ License

MIT License - see LICENSE file for details.


Project details


Download files

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

Source Distribution

aiorobokassa-1.1.0.tar.gz (28.8 kB view details)

Uploaded Source

Built Distribution

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

aiorobokassa-1.1.0-py3-none-any.whl (33.6 kB view details)

Uploaded Python 3

File details

Details for the file aiorobokassa-1.1.0.tar.gz.

File metadata

  • Download URL: aiorobokassa-1.1.0.tar.gz
  • Upload date:
  • Size: 28.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.12.11 Linux/6.14.0-35-generic

File hashes

Hashes for aiorobokassa-1.1.0.tar.gz
Algorithm Hash digest
SHA256 f8cead99307c7c6f3aa332778479ff32720ec38151018e59e459a79835d42492
MD5 880c87e5bd226123cd619beed54ba26f
BLAKE2b-256 e04c32779d4e5baf3fcac88e4dfc11faedb8594b5471eea67f86559b15c4f211

See more details on using hashes here.

File details

Details for the file aiorobokassa-1.1.0-py3-none-any.whl.

File metadata

  • Download URL: aiorobokassa-1.1.0-py3-none-any.whl
  • Upload date:
  • Size: 33.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.12.11 Linux/6.14.0-35-generic

File hashes

Hashes for aiorobokassa-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6a2463f0b53d453ecd466ca8dc559b3789a5e9b08e31165d9c267213a64bb12e
MD5 bd13ea891420826f1a22ccfaadd12804
BLAKE2b-256 73485f83b23647c535dafe482e0eeae3e68f948b907ca1d2e4a2f7625671f14d

See more details on using hashes here.

Supported by

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