> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dodopayments.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python

> Pythonic 인터페이스와 현대적인 async/await 지원을 통해 Python 애플리케이션에 Dodo Payments를 통합하세요.

Python SDK는 Dodo Payments API에 대한 파이썬 인터페이스를 제공하며, 요청 및 응답에 대한 타입 정의를 포함한 동기 및 비동기 클라이언트를 제공합니다. Python 3.9 이상을 지원하며, 포괄적인 테스트 커버리지를 포함합니다.

## 설치

pip를 사용하여 SDK를 설치하세요:

```bash theme={null}
pip install dodopayments
```

aiohttp를 사용하여 비동기 성능을 향상시키려면:

```bash theme={null}
pip install dodopayments[aiohttp]
```

<Info>
  SDK는 Python 3.9 이상을 필요로 합니다. 최고의 경험과 보안 업데이트를 위해 최신 안정 버전의 Python 사용을 권장합니다.
</Info>

## 빠른 시작

### 동기 클라이언트

```python theme={null}
import os
from dodopayments import DodoPayments

client = DodoPayments(
    bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"),  # This is the default and can be omitted
    environment="test_mode",  # defaults to "live_mode"
)

checkout_session_response = client.checkout_sessions.create(
    product_cart=[
        {
            "product_id": "product_id",
            "quantity": 1
        }
    ],
)
print(checkout_session_response.session_id)
```

### 비동기 클라이언트

```python theme={null}
import os
import asyncio
from dodopayments import AsyncDodoPayments

client = AsyncDodoPayments(
    bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"),
    environment="test_mode",
)

async def main() -> None:
    checkout_session_response = await client.checkout_sessions.create(
        product_cart=[
            {
                "product_id": "product_id",
                "quantity": 1,
            }
        ],
    )
    print(checkout_session_response.session_id)

asyncio.run(main())
```

<Warning>
  API 키는 항상 환경 변수에 안전하게 저장하세요. 버전 관리 시스템에 커밋하지 마세요.
</Warning>

## 주요 기능

<CardGroup cols={2}>
  <Card title="Pythonic Interface" icon="code">
    PEP 8 지침과 Python 관례를 따르는 깔끔하고 표현에 맞는 Python 코드
  </Card>

  <Card title="Async/Await" icon="bolt">
    asyncio와 선택적 aiohttp 통합을 통한 비동기 작업의 완전한 지원
  </Card>

  <Card title="Type Hints" icon="check">
    IDE 지원을 향상시키고 mypy로 타입 검사를 수행하기 위한 완전한 타입 힌트
  </Card>

  <Card title="Auto-Pagination" icon="arrows-rotate">
    단순한 반복을 통한 목록 응답에 대한 자동 페이지 처리
  </Card>
</CardGroup>

## 구성

### 환경 변수

환경 변수를 사용하여 구성하세요:

```bash .env theme={null}
DODO_PAYMENTS_API_KEY=your_api_key_here
```

### 타임아웃

요청 타임아웃을 전역적으로 또는 요청별로 구성하세요:

```python theme={null}
import httpx
from dodopayments import DodoPayments

# Configure default for all requests (default is 1 minute)
client = DodoPayments(
    timeout=20.0,  # 20 seconds
)

# More granular control
client = DodoPayments(
    timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0),
)

# Override per-request
client.with_options(timeout=5.0).checkout_sessions.create(
    product_cart=[
        {
            "product_id": "product_id",
            "quantity": 1,
        }
    ],
)
```

### 재시도

자동 재시도 동작을 구성하세요:

```python theme={null}
from dodopayments import DodoPayments

# Configure default for all requests (default is 2)
client = DodoPayments(
    max_retries=0,  # disable retries
)

# Override per-request
client.with_options(max_retries=5).checkout_sessions.create(
    product_cart=[
        {
            "product_id": "product_id",
            "quantity": 1,
        }
    ],
)
```

## 일반 작업

### 체크아웃 세션 생성

체크아웃 세션을 생성하세요:

```python theme={null}
session = client.checkout_sessions.create(
    product_cart=[
        {
            "product_id": "prod_123",
            "quantity": 1
        }
    ],
    return_url="https://yourdomain.com/return"
)

print(f"Checkout URL: {session.checkout_url}")
```

### 고객 관리

고객 정보를 생성하고 검색하세요:

```python theme={null}
# Create a customer
customer = client.customers.create(
    email="customer@example.com",
    name="John Doe",
    metadata={
        "user_id": "12345"
    }
)

# Retrieve customer
customer = client.customers.retrieve("cus_123")
print(f"Customer: {customer.name} ({customer.email})")
```

### 구독 처리

정기 구독을 생성하고 관리하세요:

```python theme={null}
# Create a subscription
subscription = client.subscriptions.create(
    billing={
        "country": "US",
        "city": "San Francisco",
        "state": "CA",
        "street": "1 Market St",
        "zipcode": "94105",
    },
    customer={"customer_id": "cus_123"},  # or {"email": "...", "name": "..."} for a new customer
    product_id="pdt_456",
    quantity=1,
)

# Charge an on-demand subscription
# product_price is in the lowest currency denomination (e.g., 2500 = $25.00 USD)
charge_response = client.subscriptions.charge(
    subscription_id=subscription.subscription_id,
    product_price=2500,
)

# Retrieve usage history (for metered subscriptions)
usage_history = client.subscriptions.retrieve_usage_history(
    subscription_id=subscription.subscription_id,
    start_date="2024-01-01T00:00:00Z",
)
```

<Info>
  `billing`에는 최소한 2자리 ISO 국가 코드가 필요합니다. `customer`는 기존 고객을 연결하기 위한 `{"customer_id": ...}` 또는 새 고객을 생성하기 위한 `{"email": ..., "name": ...}`를 허용합니다. `product_price`는 가장 낮은 통화 단위로 표시됩니다.
</Info>

## 사용 기반 과금

### 사용량 이벤트 수집

사용 기반 과금을 위한 맞춤 이벤트 추적:

```python theme={null}
response = client.usage_events.ingest(
    events=[
        {
            "event_id": "api_call_12345",
            "customer_id": "cus_abc123",
            "event_name": "api_request",
            "timestamp": "2024-01-15T10:30:00Z",
            "metadata": {
                "endpoint": "/api/v1/users",
                "method": "GET",
                "tokens_used": "150"
            }
        }
    ]
)
```

### 이벤트 목록 및 검색

```python theme={null}
# Get a specific event
event = client.usage_events.retrieve("api_call_12345")

# List events with filtering
events = client.usage_events.list(
    customer_id="cus_abc123",
    event_name="api_request",
    limit=20
)

for event in events.data:
    print(f"Event: {event.event_id} at {event.timestamp}")
```

## 페이지네이션

### 자동 페이지네이션

모든 항목을 자동으로 반복:

```python theme={null}
from dodopayments import DodoPayments

client = DodoPayments()
all_payments = []

# Automatically fetches more pages as needed
for payment in client.payments.list():
    all_payments.append(payment)
print(all_payments)
```

### 비동기 페이지네이션

```python theme={null}
import asyncio
from dodopayments import AsyncDodoPayments

client = AsyncDodoPayments()

async def main() -> None:
    all_payments = []
    # Iterate through items across all pages
    async for payment in client.payments.list():
        all_payments.append(payment)
    print(all_payments)

asyncio.run(main())
```

### 수동 페이지네이션

페이지네이션에 대한 더 많은 제어:

```python theme={null}
# Access items from current page
first_page = client.payments.list()
for payment in first_page.items:
    print(payment.brand_id)

# Check for more pages
if first_page.has_next_page():
    next_page = first_page.get_next_page()
    print(f"Fetched {len(next_page.items)} more items")
```

## HTTP 클라이언트 구성

기본 `httpx` 클라이언트 사용자 정의:

```python theme={null}
import httpx
from dodopayments import DodoPayments, DefaultHttpxClient

client = DodoPayments(
    base_url="http://my.test.server.example.com:8083",
    http_client=DefaultHttpxClient(
        proxy="http://my.test.proxy.example.com",
        transport=httpx.HTTPTransport(local_address="0.0.0.0"),
    ),
)
```

## aiohttp와 함께 비동기 처리

향상된 비동기 성능을 위해 aiohttp 사용:

```python theme={null}
import asyncio
from dodopayments import DefaultAioHttpClient
from dodopayments import AsyncDodoPayments

async def main() -> None:
    async with AsyncDodoPayments(
        bearer_token="My Bearer Token",
        http_client=DefaultAioHttpClient(),
    ) as client:
        checkout_session_response = await client.checkout_sessions.create(
            product_cart=[
                {
                    "product_id": "product_id",
                    "quantity": 1,
                }
            ],
        )
        print(checkout_session_response.session_id)

asyncio.run(main())
```

## 로깅

환경 변수를 설정하여 로깅 활성화:

```bash theme={null}
export DODO_PAYMENTS_LOG=info
```

또는 디버그 수준 로깅:

```bash theme={null}
export DODO_PAYMENTS_LOG=debug
```

## 프레임워크 통합

### FastAPI

```python theme={null}
from fastapi import FastAPI, HTTPException
from dodopayments import AsyncDodoPayments
from pydantic import BaseModel
import os

app = FastAPI()
dodo = AsyncDodoPayments(bearer_token=os.getenv("DODO_API_KEY"))

class CheckoutRequest(BaseModel):
    product_id: str
    quantity: int

@app.post("/create-checkout")
async def create_checkout(request: CheckoutRequest):
    try:
        session = await dodo.checkout_sessions.create(
            product_cart=[{
                "product_id": request.product_id,
                "quantity": request.quantity
            }],
            return_url="https://yourdomain.com/return"
        )
        return {"checkout_url": session.checkout_url}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))
```

### Django

```python theme={null}
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt
from dodopayments import DodoPayments
import os
import json

client = DodoPayments(bearer_token=os.getenv("DODO_PAYMENTS_API_KEY"))

@csrf_exempt
@require_POST
def create_checkout(request):
    try:
        data = json.loads(request.body)
        session = client.checkout_sessions.create(
            product_cart=[{
                "product_id": data.get("product_id"),
                "quantity": data.get("quantity", 1)
            }],
            return_url="https://yourdomain.com/return"
        )
        return JsonResponse({
            "status": "success",
            "checkout_url": session.checkout_url,
            "session_id": session.session_id
        })
    except Exception as e:
        return JsonResponse({
            "status": "error",
            "message": str(e)
        }, status=400)
```

## 리소스

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-python">
    소스 코드 보기 및 기여
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    전체 API 문서
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/bYqAp4ayYh">
    도움 받기 및 개발자와 연결하기
  </Card>

  <Card title="Report Issues" icon="bug" href="https://github.com/dodopayments/dodopayments-python/issues">
    버그 신고 또는 기능 요청
  </Card>
</CardGroup>

## 지원

Python SDK에 대한 도움이 필요하신가요?

* **Discord**: 실시간 지원을 위해 [커뮤니티 서버](https://discord.gg/bYqAp4ayYh)에 가입하세요
* **이메일**: [support@dodopayments.com](mailto:support@dodopayments.com)으로 연락하세요
* **GitHub**: [저장소](https://github.com/dodopayments/dodopayments-python)에 문제를 등록하세요

## 기여

기여를 환영합니다! 시작하려면 [기여 가이드라인](https://github.com/dodopayments/dodopayments-python/blob/main/CONTRIBUTING.md)을 확인하세요.
