Files
ev-charging-backend/app/services/payment.py
2026-04-18 05:59:31 +09:00

116 lines
3.7 KiB
Python

"""토스페이먼츠 결제 서비스
결제 흐름:
1. 프론트에서 토스 결제 UI 호출 (클라이언트 키 사용)
2. 사용자 카드 입력 → paymentKey 발급
3. 백엔드에서 confirm API 호출 → 실제 청구 확정 (시크릿 키 사용)
4. 승인 확인 후 OCPP RemoteStartTransaction 전송
"""
import base64
import logging
from typing import Optional
import httpx
from app.config import get_settings
logger = logging.getLogger(__name__)
settings = get_settings()
TOSS_API_BASE = "https://api.tosspayments.com/v1"
class TossPaymentService:
def __init__(self):
# 시크릿 키를 Base64 인코딩 (Basic Auth)
secret = settings.TOSS_SECRET_KEY
encoded = base64.b64encode(f"{secret}:".encode()).decode()
self.headers = {
"Authorization": f"Basic {encoded}",
"Content-Type": "application/json",
}
async def confirm_payment(
self, payment_key: str, order_id: str, amount: int
) -> dict:
"""결제 최종 승인 (confirm)
프론트에서 결제 완료 후 paymentKey, orderId, amount를 전달받아
토스 서버에 최종 승인 요청.
Returns:
토스 응답 dict (성공 시 status="DONE")
"""
payload = {
"paymentKey": payment_key,
"orderId": order_id,
"amount": amount,
}
async with httpx.AsyncClient(timeout=15.0) as client:
resp = await client.post(
f"{TOSS_API_BASE}/payments/confirm",
headers=self.headers,
json=payload,
)
data = resp.json()
if resp.status_code == 200:
logger.info(f"결제 승인 성공: {order_id} / {amount}")
return {"success": True, "data": data}
else:
logger.error(f"결제 승인 실패: {data}")
return {
"success": False,
"error_code": data.get("code", "UNKNOWN"),
"message": data.get("message", "결제 승인 실패"),
}
async def get_payment(self, payment_key: str) -> Optional[dict]:
"""결제 상세 조회"""
async with httpx.AsyncClient(timeout=10.0) as client:
resp = await client.get(
f"{TOSS_API_BASE}/payments/{payment_key}",
headers=self.headers,
)
if resp.status_code == 200:
return resp.json()
return None
async def cancel_payment(
self,
payment_key: str,
cancel_reason: str = "사용자 취소",
cancel_amount: Optional[int] = None,
) -> dict:
"""결제 취소 / 부분 환불
Args:
payment_key: 토스 paymentKey
cancel_reason: 취소 사유
cancel_amount: 부분 취소 금액 (None이면 전액 취소)
"""
payload = {"cancelReason": cancel_reason}
if cancel_amount is not None:
payload["cancelAmount"] = cancel_amount
async with httpx.AsyncClient(timeout=15.0) as client:
resp = await client.post(
f"{TOSS_API_BASE}/payments/{payment_key}/cancel",
headers=self.headers,
json=payload,
)
data = resp.json()
if resp.status_code == 200:
logger.info(f"결제 취소 성공: {payment_key}")
return {"success": True, "data": data}
else:
logger.error(f"결제 취소 실패: {data}")
return {"success": False, "message": data.get("message")}
toss_service = TossPaymentService()