> ## 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

> 将 Dodo Payments 集成到您的 Python 应用程序中，提供 Pythonic 接口和现代的 async/await 支持

Python SDK 提供了一个 Pythonic 接口来访问 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` 至少需要两位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)以开始。
