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

> Tích hợp Dodo Payments vào các ứng dụng Python của bạn với giao diện Pythonic và hỗ trợ async/await hiện đại

SDK Python cung cấp một giao diện Pythonic cho API Dodo Payments, cung cấp cả khách hàng đồng bộ và không đồng bộ với các định nghĩa kiểu cho các yêu cầu và phản hồi. Nó hỗ trợ Python 3.9+ và bao gồm phạm vi kiểm tra toàn diện.

## Cài đặt

Cài đặt SDK bằng pip:

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

Để cải thiện hiệu suất async với aiohttp:

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

<Info>
  SDK yêu cầu Python 3.9 trở lên. Chúng tôi khuyên nên dùng phiên bản Python ổn định mới nhất để có trải nghiệm tốt nhất và các bản cập nhật bảo mật.
</Info>

## Bắt đầu nhanh

### Khách hàng đồng bộ

```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)
```

### Khách hàng bất đồng bộ

```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>
  Luôn lưu trữ khóa API của bạn một cách an toàn bằng biến môi trường. Đừng bao giờ đưa chúng vào hệ thống quản lý phiên bản.
</Warning>

## Tính năng chính

<CardGroup cols={2}>
  <Card title="Pythonic Interface" icon="code">
    Mã Python sạch, theo phong cách và tuân thủ hướng dẫn PEP 8 cùng các quy ước của Python
  </Card>

  <Card title="Async/Await" icon="bolt">
    Hỗ trợ đầy đủ cho các thao tác bất đồng bộ với asyncio và tích hợp tùy chọn aiohttp
  </Card>

  <Card title="Type Hints" icon="check">
    Gợi ý kiểu đầy đủ để hỗ trợ IDE tốt hơn và kiểm tra kiểu với mypy
  </Card>

  <Card title="Auto-Pagination" icon="arrows-rotate">
    Phân trang tự động cho các phản hồi danh sách với vòng lặp đơn giản
  </Card>
</CardGroup>

## Cấu hình

### Biến môi trường

Cấu hình bằng cách sử dụng biến môi trường:

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

### Thời gian chờ

Cấu hình thời gian chờ yêu cầu toàn cục hoặc theo yêu cầu:

```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,
        }
    ],
)
```

### Thử lại

Cấu hình hành vi thử lại tự động:

```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,
        }
    ],
)
```

## Các hoạt động phổ biến

### Tạo phiên thanh toán

Tạo một phiên thanh toán:

```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}")
```

### Quản lý khách hàng

Tạo và truy xuất thông tin khách hàng:

```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})")
```

### Xử lý đăng ký

Tạo và quản lý các đăng ký định kỳ:

```python theme={null}
# Create a subscription
subscription = client.subscriptions.create(
    customer_id="cus_123",
    product_id="prod_456",
    price_id="price_789"
)

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

## Thanh toán dựa trên mức sử dụng

### Nhập sự kiện sử dụng

Theo dõi các sự kiện tùy chỉnh cho thanh toán dựa trên mức sử dụng:

```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"
            }
        }
    ]
)
```

### Liệt kê và truy xuất sự kiện

```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}")
```

## Phân trang

### Phân trang tự động

Lặp qua tất cả các mục một cách tự động:

```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)
```

### Phân trang bất đồng bộ

```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())
```

### Phân trang thủ công

Để kiểm soát nhiều hơn về phân trang:

```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")
```

## Cấu hình HTTP Client

Customize the underlying `httpx` client:

```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"),
    ),
)
```

## Async với aiohttp

Sử dụng aiohttp để cải thiện hiệu suất bất đồng bộ:

```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())
```

## Ghi log

Bật ghi log bằng cách thiết lập biến môi trường:

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

Hoặc để ghi log ở mức độ gỡ lỗi:

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

## Tích hợp Framework

### 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.url}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))
```

```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))
```

```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.url,
            "session_id": session.session_id
        })
    except Exception as e:
        return JsonResponse({
            "status": "error",
            "message": str(e)
        }, status=400)
```

```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">
    Xem mã nguồn và đóng góp
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Tài liệu API đầy đủ
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/bYqAp4ayYh">
    Nhận trợ giúp và kết nối với các nhà phát triển
  </Card>

  <Card title="Report Issues" icon="bug" href="https://github.com/dodopayments/dodopayments-python/issues">
    Báo lỗi hoặc yêu cầu tính năng
  </Card>
</CardGroup>

## Hỗ trợ

Cần trợ giúp với SDK Python?

* **Discord**: Tham gia [máy chủ cộng đồng](https://discord.gg/bYqAp4ayYh) của chúng tôi để được hỗ trợ theo thời gian thực
* **Email**: Liên hệ với chúng tôi tại [support@dodopayments.com](mailto:support@dodopayments.com)
* **GitHub**: Mở một sự cố trên [kho lưu trữ](https://github.com/dodopayments/dodopayments-python)

## Đóng góp

Chúng tôi hoan nghênh các đóng góp! Kiểm tra [hướng dẫn đóng góp](https://github.com/dodopayments/dodopayments-python/blob/main/CONTRIBUTING.md) để bắt đầu.

Chúng tôi hoan nghênh các đóng góp! Hãy kiểm tra [hướng dẫn đóng góp](https://github.com/dodopayments/dodopayments-python/blob/main/CONTRIBUTING.md) để bắt đầu.
