---
title: Интеграция с FastAPI
description: Подключение Payme, Click, Uzum, Paynet и Octo к проекту на FastAPI через PayTechUZ: async-настройка, модели SQLAlchemy, webhook.
source: https://pay-tech.uz/ru/docs/integrations/fastapi
---

# Интеграция с FastAPI

Полное руководство по интеграции PayTechUZ с приложениями FastAPI.

:::tip Готовые примеры проектов
Ищете готовые проекты на FastAPI? Посмотрите наши примеры:
* **[FastAPI Example](https://github.com/PayTechUz/fastapi_paytechuz)** - Полная интеграция платежей
* **[Course Bot](https://github.com/PayTechUz/Course_Bot)** - Telegram-бот с системой подписки
:::

## Установка

Установите PayTechUZ с поддержкой FastAPI:

```bash
pip install paytechuz[fastapi]
```

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

Настройте модели базы данных:

```python
from datetime import datetime, timezone

from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Column, Integer, String, Float, DateTime, ForeignKey

from paytechuz.integrations.fastapi import Base as PaymentsBase
from paytechuz.integrations.fastapi.models import run_migrations

# Создание движка базы данных
SQLALCHEMY_DATABASE_URL = "sqlite:///./payments.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL)

# Создание базового декларативного класса
Base = declarative_base()

# Создание модели заказа
class Order(Base):
    __tablename__ = "orders"

    id = Column(Integer, primary_key=True, index=True)
    product_name = Column(String, index=True)
    total_amount = Column(Float)
    created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))

# Создание модели счёта
class Invoice(Base):
    __tablename__ = "invoices"

    id = Column(Integer, primary_key=True, index=True)
    order_id = Column(Integer, ForeignKey("orders.id"))
    amount = Column(Float)
    status = Column(String, default="pending")
    created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))

    order = relationship("Order")

# Создание таблиц платежей с помощью run_migrations
run_migrations(engine)

# Создание таблиц заказов и счетов
Base.metadata.create_all(bind=engine)

# Создание сессии
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
```

## Создание обработчиков вебхуков:

```python
from fastapi import FastAPI, Request, Depends
from sqlalchemy.orm import Session
from paytechuz.integrations.fastapi import (
    PaymeWebhookHandler, 
    ClickWebhookHandler, 
)

app = FastAPI()

# Зависимость для получения сессии базы данных
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

class CustomPaymeWebhookHandler(PaymeWebhookHandler):
    def successfully_payment(self, params, transaction):
        invoice = self.db.query(Invoice).filter(Invoice.id == transaction.account_id).first()
        invoice.status = "paid"
        self.db.commit()

    def cancelled_payment(self, params, transaction):
        invoice = self.db.query(Invoice).filter(Invoice.id == transaction.account_id).first()
        invoice.status = "cancelled"
        self.db.commit()

class CustomClickWebhookHandler(ClickWebhookHandler):
    def successfully_payment(self, params, transaction):
        invoice = self.db.query(Invoice).filter(Invoice.id == transaction.account_id).first()
        invoice.status = "paid"
        self.db.commit()

    def cancelled_payment(self, params, transaction):
        invoice = self.db.query(Invoice).filter(Invoice.id == transaction.account_id).first()
        invoice.status = "cancelled"
        self.db.commit()

    def successfully_payment(self, params, transaction):
        invoice = self.db.query(Invoice).filter(Invoice.id == transaction.account_id).first()
        invoice.status = "paid"
        self.db.commit()

    def cancelled_payment(self, params, transaction):
        invoice = self.db.query(Invoice).filter(Invoice.id == transaction.account_id).first()
        invoice.status = "cancelled"
        self.db.commit()

@app.post("/payments/payme/webhook")
async def payme_webhook(request: Request, db: Session = Depends(get_db)):
    handler = CustomPaymeWebhookHandler(
        db=db,
        payme_id="your_merchant_id",
        payme_key="your_merchant_key",
        account_model=Invoice,
        account_field='id',
        amount_field='amount'
    )
    return await handler.handle_webhook(request)

@app.post("/payments/click/webhook")
async def click_webhook(request: Request, db: Session = Depends(get_db)):
    handler = CustomClickWebhookHandler(
        db=db,
        service_id="your_service_id",
        secret_key="your_secret_key",
        account_model=Invoice,
        account_field='id',
        one_time_payment=True
    )
    return await handler.handle_webhook(request)

## Создание платёжных ссылок

```python
import os
from pydantic import BaseModel
from paytechuz.gateways.payme import PaymeGateway
from paytechuz.gateways.click import ClickGateway
    amount: float
    payment_type: str  # 'payme', 'click', или 'paynet'
    return_url: str = None

@app.post("/order/create")
def create_order(order_data: OrderCreate, db: Session = Depends(get_db)):
    # 1. Создание заказа
    order = Order(
        product_name=order_data.product_name, 
        total_amount=order_data.amount
    )
    db.add(order)
    db.commit()
    db.refresh(order)

    # 2. Создание счёта, связанного с заказом
    invoice = Invoice(
        order_id=order.id, 
        amount=order.total_amount,
        status="pending"
    )
    db.add(invoice)
    db.commit()
    db.refresh(invoice)

    payment_url = None

    # 3. Генерация платёжной ссылки в зависимости от типа оплаты
    if order_data.payment_type == 'payme':
        gateway = PaymeGateway(
            payme_id='your_payme_id',
            payme_key='your_payme_key',
            is_test_mode=True
        )
        payment_url = gateway.create_payment(
            id=invoice.id,
            amount=invoice.amount,
            return_url="https://example.com/success",
            account_field_name="id" # ваше поле аккаунта payme
        )

    elif order_data.payment_type == 'click':
        gateway = ClickGateway(
            service_id='your_click_service_id',
            merchant_id='your_click_merchant_id',
            merchant_user_id='your_click_merchant_user_id',
            secret_key='your_click_secret_key',
            is_test_mode=True
        )
        payment_url = gateway.create_payment(
            id=invoice.id,
            amount=invoice.amount,
            return_url="https://example.com/success"
        )

    elif order_data.payment_type == 'paynet':
        gateway = PaynetGateway(
            merchant_id='your_paynet_merchant_id',
            service_id='your_paynet_service_id',
            secret_key='your_paynet_secret_key', 
            is_test_mode=True
        )
# Формат URL: https://app.paynet.uz/?m={merchant_id}&c={payment_id}&a={amount}
        payment_url = gateway.create_payment(
            id=invoice.id,  # ID платежа (параметр c)
            amount=invoice.amount  # сумма в тийинах (опционально, параметр a)
        )
        # Или без суммы (сумма будет настроена на стороне Paynet)
        # payment_url = gateway.create_payment(id=invoice.id)

    return {
        "order_id": order.id, 
        "invoice_id": invoice.id, 
        "payment_url": payment_url
    }
```

## Следующие шаги

- **[Примеры](/docs/examples)** - Полные рабочие примеры
- **[Начало работы](/docs/getting-started/installation)** - Базовое руководство по установке
- **[Интеграция с Django](/docs/integrations/django)** - Альтернативная интеграция с фреймворком
