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

> Intégrez Dodo Payments dans vos applications Python avec une interface Pythonique et un support moderne async/await

Le SDK Python offre une interface Pythonique à l'API Dodo Payments, fournissant à la fois des clients synchrones et asynchrones avec des définitions de types pour les requêtes et les réponses. Il prend en charge Python 3.9+ et inclut une couverture de test complète.

## Installation

Installez le SDK en utilisant pip :

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

Pour des performances async améliorées avec aiohttp :

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

<Info>
  Le SDK nécessite Python 3.9 ou une version supérieure. Nous recommandons d'utiliser la dernière version stable de Python pour bénéficier de la meilleure expérience et des mises à jour de sécurité.
</Info>

## Démarrage rapide

### Client synchrone

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

### Client asynchrone

```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>
  Stockez toujours vos clés d'API de manière sécurisée en utilisant des variables d'environnement. Ne les committez jamais dans le contrôle de version.
</Warning>

## Fonctionnalités principales

<CardGroup cols={2}>
  <Card title="Pythonic Interface" icon="code">
    Code Python propre et idiomatique respectant les directives PEP 8 et les conventions Python
  </Card>

  <Card title="Async/Await" icon="bolt">
    Prise en charge complète des opérations asynchrones avec asyncio et intégration aiohttp facultative
  </Card>

  <Card title="Type Hints" icon="check">
    Annotations de type complètes pour une meilleure prise en charge par les IDE et la vérification de type avec mypy
  </Card>

  <Card title="Auto-Pagination" icon="arrows-rotate">
    Pagination automatique des réponses listées avec une itération simple
  </Card>
</CardGroup>

## Configuration

### Variables d'environnement

Configurez en utilisant des variables d'environnement :

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

### Délais d'attente

Configurez les délais d'attente des requêtes globalement ou par requête :

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

### Réessais

Configurez le comportement de réessai automatique :

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

## Opérations courantes

### Créer une session de paiement

Générez une session de paiement :

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

### Gérer les clients

Créez et récupérez des informations sur les clients :

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

### Gérer les abonnements

Créez et gérez des abonnements récurrents :

```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` nécessite au minimum le code pays ISO à deux lettres. `customer` accepte soit `{"customer_id": ...}` pour attacher un client existant, soit `{"email": ..., "name": ...}` pour en créer un nouveau. `product_price` est dans la plus petite unité monétaire.
</Info>

## Facturation à l'usage

### Intégrer les événements d'usage

Suivez des événements personnalisés pour la facturation à l'usage :

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

### Lister et récupérer les événements

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

## Pagination

### Pagination automatique

Parcourez tous les éléments automatiquement :

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

### Pagination asynchrone

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

### Pagination manuelle

Pour plus de contrôle sur la pagination :

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

## Configuration du client HTTP

Personnalisez le client `httpx` sous-jacent :

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

## Asynchrone avec aiohttp

Utilisez aiohttp pour des performances asynchrones améliorées :

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

## Journalisation

Activez la journalisation en définissant la variable d'environnement :

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

Ou pour une journalisation de niveau débogage :

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

## Intégration au 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.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)
```

## Ressources

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-python">
    Voir le code source et contribuer
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Documentation complète de l'API
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/bYqAp4ayYh">
    Obtenez de l'aide et connectez-vous avec les développeurs
  </Card>

  <Card title="Report Issues" icon="bug" href="https://github.com/dodopayments/dodopayments-python/issues">
    Signalez des bogues ou demandez des fonctionnalités
  </Card>
</CardGroup>

## Support

Besoin d'aide avec le SDK Python ?

* **Discord** : Rejoignez notre [serveur communautaire](https://discord.gg/bYqAp4ayYh) pour un support en temps réel
* **Email** : Contactez-nous à [support@dodopayments.com](mailto:support@dodopayments.com)
* **GitHub** : Ouvrez une issue sur le [repository](https://github.com/dodopayments/dodopayments-python)

## Contribuer

Vos contributions sont les bienvenues ! Consultez les [directives de contribution](https://github.com/dodopayments/dodopayments-python/blob/main/CONTRIBUTING.md) pour commencer.
