Payment Docs
Examples

Python

Python examples

from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import RedirectResponse, JSONResponse
import requests, os

app = FastAPI(title="Example Server")

API_KEY = os.getenv("API_KEY", "demo_token")
API_URL = "https://api.example.com/v1"

# 🧾 Создание заказа
@app.post("/create-order")
def create_order(amount: float, external_id: str = None, user_id: str = None):
    payload = {
        "amount": str(amount),
        "externalId": external_id,
        "externalUserId": user_id,
        "isFeeOnUser": True,
        "purpose": f"Оплата заказа {external_id or ''}",
        "successUrl": "https://your-site.com/payment-success"
    }

    headers = {"X-Api-Token": API_KEY, "Content-Type": "application/json"}
    response = requests.post(f"{API_URL}/orders", json=payload, headers=headers)

    if response.status_code != 200:
        raise HTTPException(status_code=response.status_code, detail=response.text)

    data = response.json()
    payment_link = data.get("paymentLink")

    # Перенаправляем пользователя на страницу оплаты
    return RedirectResponse(url=payment_link)

# 🔔 Webhook обработчик
@app.post("/webhook/payments")
async def webhook(request: Request):
    body = await request.json()
    ip = request.client.host

    print("📩 Получен webhook:", body)

    status = body.get("status")
    order_id = body.get("externalId")

    if status == "COMPLETED":
        print(f"✅ Заказ {order_id} успешно оплачен!")
        # Здесь можно обновить заказ в базе данных
    elif status == "FAILED":
        print(f"❌ Ошибка при оплате заказа {order_id}")
    else:
        print(f"ℹ️ Статус заказа {order_id}: {status}")

    return JSONResponse(content={"message": "OK"})

# 🧪 Проверка API
@app.get("/")
def root():
    return {"message": "Example server is running 🚀"}