Metadata-Version: 2.4
Name: pytonpay
Version: 0.1.0
Summary: Universal, framework-agnostic Python SDK & Webhook Engine for TON and USDT payments
Author: Anvarjon Khojimatov
License: MIT License
        
        Copyright (c) 2026 Anvarjon Khojimatov
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: crypto,payment,sdk,telegram,ton,tonapi,toncenter,usdt,webhook
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Office/Business :: Financial
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Requires-Dist: httpx>=0.24.0
Requires-Dist: pydantic-settings>=2.0.0
Requires-Dist: pydantic>=2.0.0
Provides-Extra: aiogram
Requires-Dist: aiogram>=3.0.0; extra == 'aiogram'
Provides-Extra: all
Requires-Dist: aiogram>=3.0.0; extra == 'all'
Requires-Dist: django>=4.0.0; extra == 'all'
Requires-Dist: fastapi>=0.95.0; extra == 'all'
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'dev'
Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
Requires-Dist: pytest>=7.0.0; extra == 'dev'
Provides-Extra: django
Requires-Dist: django>=4.0.0; extra == 'django'
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.95.0; extra == 'fastapi'
Description-Content-Type: text/markdown

<div align="center">

# 🚀 pytonpay

**Universal, Framework-Agnostic Python SDK & Webhook Engine for TON Blockchain Payments**

[![PyPI Version](https://img.shields.io/pypi/v/pytonpay.svg?style=flat-square&color=0088cc)](https://pypi.org/project/pytonpay/)
[![Python Version](https://img.shields.io/badge/python-3.10%2B-blue.svg?style=flat-square)](https://python.org)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=flat-square)](LICENSE)
[![TON Ecosystem](https://img.shields.io/badge/Blockchain-TON%20%2F%20USDT-0088cc?style=flat-square)](https://ton.org)
[![Build Status](https://img.shields.io/badge/tests-passing-brightgreen.svg?style=flat-square)](tests)

[Overview](#-overview) • [Key Features](#-key-features) • [Quickstart](#-quickstart) • [Contrib Adapters](#-contrib-adapters) • [Testing](#-testing)

</div>

---

## 💎 Overview

`pytonpay` is a high-level, framework-agnostic Python SDK and Webhook Engine designed to integrate TON (The Open Network) and USDT payments into any Python backend service or bot in under 5 minutes.

Whether you are building a Telegram Bot with **Aiogram**, an API with **FastAPI**, or a web platform with **Django**, `pytonpay` provides a pluggable, type-safe, and asynchronous interface to receive TON and USDT payments seamlessly.

---

## 🔥 Key Features

- 🔌 **Framework-Agnostic**: Pure Python 3.10+ core with zero forced framework dependencies.
- ⚡ **Dual Client Architecture**: Native `Async` (`PyTonPay`) and `Sync` (`SyncPyTonPay`) clients powered by `httpx`.
- 🛡️ **Strict Pydantic V2 Type Safety**: 100% data validation with Pydantic V2 models for invoices, events, and headers.
- 🔌 **Pluggable Blockchain Providers**: Seamlessly switch between **TonCenter V3** and **TonAPI.io** (Mainnet & Testnet support).
- 🔐 **HMAC-SHA256 Security**: Built-in, constant-time cryptographic Webhook signature generation and verification.
- 📲 **DeepLinks & QR Code Engine**: Automated `ton://transfer`, Tonkeeper, Telegram Wallet payment link generation & SVG/PNG QR codes.
- 📦 **Ready-Made Contrib Adapters**: 1-line integrations for **FastAPI**, **Django**, and **Aiogram 3.x**.

---

## 📦 Installation

Install `pytonpay` via PyPI:

```bash
pip install pytonpay
```

Install with optional framework dependencies:

```bash
# FastAPI support
pip install "pytonpay[fastapi]"

# Django support
pip install "pytonpay[django]"

# Aiogram 3.x Telegram Bot support
pip install "pytonpay[aiogram]"

# Install all adapters
pip install "pytonpay[all]"
```

---

## 🚀 Quickstart

### 1. Pure Async Python & FastAPI Usage

```python
from fastapi import FastAPI
from pytonpay import PyTonPay, Currency
from pytonpay.contrib.fastapi import PyTonPayWebhookDependency
from pytonpay.types import WebhookPayload

MERCHANT_WALLET = "EQCD39VS5jcCavNptmMKw1U5w3424Ap8BGS9p52m0l_TONPAY"
SECRET_KEY = "your_super_secret_hmac_key"

app = FastAPI(title="TON Payment Store")
client = PyTonPay(merchant_wallet=MERCHANT_WALLET, secret_key=SECRET_KEY, testnet=True)
webhook_validator = PyTonPayWebhookDependency(client)

@app.post("/create-invoice")
async def create_invoice(amount: float, order_id: str):
    invoice = await client.create_invoice(
        amount=amount,
        currency=Currency.TON,
        order_id=order_id,
        description=f"Order #{order_id}",
    )
    return {
        "invoice_id": invoice.id,
        "pay_url": invoice.pay_url,
        "qr_code": invoice.qr_code_url,
    }

@app.post("/webhook")
async def webhook_handler(payload: WebhookPayload = webhook_validator):
    if payload.event == "invoice.paid":
        print(f"Order #{payload.invoice.order_id} is PAID! Tx: {payload.invoice.tx_hash}")
    return {"status": "ok", "invoice_id": payload.invoice.id}
```

### 2. Aiogram 3.x Telegram Bot Usage

```python
import asyncio
from aiogram import Bot, Dispatcher, F
from aiogram.types import Message, CallbackQuery
from pytonpay import PyTonPay, Currency
from pytonpay.contrib.aiogram import PyTonPayMiddleware, send_invoice_message

pay_client = PyTonPay(
    merchant_wallet="EQCD39VS5jcCavNptmMKw1U5w3424Ap8BGS9p52m0l_TONPAY",
    secret_key="your_super_secret_hmac_key",
    testnet=True,
)

dp = Dispatcher()
dp.update.middleware(PyTonPayMiddleware(pay_client))

@dp.message(F.text == "/buy")
async def buy_handler(message: Message, pytonpay: PyTonPay):
    invoice = await pytonpay.create_invoice(
        amount=1.5,
        currency=Currency.TON,
        order_id=f"tg_{message.from_user.id}",
        description="VIP Subscription",
    )
    await send_invoice_message(message=message, invoice=invoice)

@dp.callback_query(F.data.startswith("check_pay:"))
async def check_payment_handler(callback: CallbackQuery, pytonpay: PyTonPay):
    invoice_id = callback.data.split(":")[1]
    invoice = await pytonpay.verify_invoice(invoice_id)
    if invoice.status == "PAID":
        await callback.message.edit_text(f"Payment Confirmed for Order #{invoice.order_id}!")
    else:
        await callback.answer("Payment not detected yet on TON blockchain.", show_alert=True)
```

### 3. Django Webhook Integration

```python
from pytonpay import SyncPyTonPay
from pytonpay.contrib.django import PyTonPayWebhookView
from pytonpay.types import WebhookPayload

sync_client = SyncPyTonPay(
    merchant_wallet="EQCD39VS5jcCavNptmMKw1U5w3424Ap8BGS9p52m0l_TONPAY",
    secret_key="your_super_secret_hmac_key",
    testnet=True,
)

class MerchantWebhookView(PyTonPayWebhookView):
    client = sync_client

    def on_paid(self, payload: WebhookPayload) -> None:
        print(f"Order {payload.invoice.order_id} paid on-chain! Tx: {payload.invoice.tx_hash}")

    def on_expired(self, payload: WebhookPayload) -> None:
        print(f"Invoice {payload.invoice.id} expired.")
```

---

## 🧪 Testing

`pytonpay` includes a complete Pytest suite. To run the unit tests:

```bash
# Clone the repository
git clone https://github.com/your-username/pytonpay.git
cd pytonpay

# Create virtualenv and install dev dependencies
python3 -m venv .venv
source .venv/bin/activate
pip install -e ".[all,dev]"

# Run pytest
pytest -v
```

---

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.