Python SDK는 Dodo Payments API에 대한 Pythonic 인터페이스를 제공하며, 요청 및 응답에 대한 타입 정의가 포함된 동기 및 비동기 클라이언트를 제공합니다. Python 3.7 이상을 지원하며, 포괄적인 테스트 커버리지를 포함합니다.
pip를 사용하여 SDK를 설치하세요:
aiohttp를 사용하여 비동기 성능을 향상시키려면:
pip install dodopayments[aiohttp]
SDK는 Python 3.7 이상이 필요합니다. 최상의 경험과 보안 업데이트를 위해 최신 안정 버전의 Python을 사용하는 것을 권장합니다.
빠른 시작
동기 클라이언트
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)
비동기 클라이언트
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())
API 키는 항상 환경 변수를 사용하여 안전하게 저장하세요. 버전 관리에 커밋하지 마세요.
주요 기능
Pythonic 인터페이스 PEP 8 가이드라인과 Python 관습을 따르는 깔끔하고 관용적인 Python 코드
Async/Await asyncio와 선택적 aiohttp 통합을 통한 비동기 작업에 대한 완전한 지원
타입 힌트 mypy와 함께 더 나은 IDE 지원 및 타입 검사를 위한 완전한 타입 힌트
자동 페이지네이션 간단한 반복을 통한 목록 응답의 자동 페이지네이션
환경 변수
환경 변수를 사용하여 구성하세요:
DODO_PAYMENTS_API_KEY = your_api_key_here
타임아웃
요청 타임아웃을 전역적으로 또는 요청별로 구성하세요:
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" : 0 ,
}
],
)
재시도
자동 재시도 동작을 구성하세요:
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" : 0 ,
}
],
)
일반 작업
체크아웃 세션 생성
체크아웃 세션을 생성하세요:
session = client.checkout_sessions.create(
product_cart = [
{
"product_id" : "prod_123" ,
"quantity" : 1
}
],
return_url = "https://yourdomain.com/return"
)
print ( f "Checkout URL: { session.url } " )
고객 관리
고객 정보를 생성하고 검색하세요:
# Create a customer
customer = client.customers.create(
email = "[email protected] " ,
name = "John Doe" ,
metadata = {
"user_id" : "12345"
}
)
# Retrieve customer
customer = client.customers.retrieve( "cus_123" )
print ( f "Customer: { customer.name } ( { customer.email } )" )
구독 처리
정기 구독을 생성하고 관리하세요:
# 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"
)
사용 기반 청구
사용 이벤트 수집
사용 기반 청구를 위한 사용자 정의 이벤트를 추적하세요:
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"
}
}
]
)
이벤트 목록 및 검색
# 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 } " )
페이지네이션
자동 페이지네이션
모든 항목을 자동으로 반복하세요:
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)
비동기 페이지네이션
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())
수동 페이지네이션
페이지네이션에 대한 더 많은 제어를 위해:
# 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 클라이언트를 사용자 정의하세요:
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를 사용하세요:
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" : 0 ,
}
],
)
print (checkout_session_response.session_id)
asyncio.run(main())
환경 변수를 설정하여 로깅을 활성화하세요:
export DODO_PAYMENTS_LOG = info
또는 디버그 수준의 로깅을 위해:
export DODO_PAYMENTS_LOG = debug
프레임워크 통합
FastAPI
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))
Django
from django.http import JsonResponse
from dodopayments import DodoPayments
import os
dodo = DodoPayments( bearer_token = os.getenv( "DODO_API_KEY" ))
def create_payment ( request ):
try :
payment = dodo.payments.create(
amount = 5000 ,
currency = "USD" ,
customer_id = request.user.customer_id
)
return JsonResponse({
"status" : "success" ,
"payment_id" : payment.id
})
except Exception as e:
return JsonResponse({
"status" : "error" ,
"message" : str (e)
}, status = 400 )
리소스
Python SDK에 도움이 필요하신가요?
기여를 환영합니다! 시작하려면 기여 가이드라인 을 확인하세요.