21 KiB
21 KiB
Subtask: Payment Integration Module
Parent Task: Decomp/004 Subtask ID: Decomp-004-04 Dependencies: Decomp-004-01 (Database Schema), Decomp-004-03 (Inventory Reservation)
Description
Implement payment integration module supporting multiple payment providers (Stripe, PayPal, etc.). Handle payment processing, idempotency, webhooks, and refund operations.
Requirements
- Support multiple payment providers
- Process one-time payments
- Handle payment methods (cards, digital wallets)
- Idempotent payment processing
- Webhook signature verification
- Refund processing
- Payment status tracking
- PCI compliance (tokenization)
Technical Specifications
Payment provider interface:
from abc import ABC, abstractmethod
from typing import Optional, Dict, Any, List
from dataclasses import dataclass
from enum import Enum
from decimal import Decimal
class PaymentStatus(Enum):
"""Payment status values."""
PENDING = "pending"
SUCCEEDED = "succeeded"
FAILED = "failed"
REFUNDED = "refunded"
PARTIALLY_REFUNDED = "partially_refunded"
class PaymentMethod(Enum):
"""Payment method types."""
CARD = "card"
BANK_TRANSFER = "bank_transfer"
PAYPAL = "paypal"
APPLE_PAY = "apple_pay"
GOOGLE_PAY = "google_pay"
@dataclass
class PaymentRequest:
"""Request to process a payment."""
amount: Decimal
currency: str
payment_method: str # Tokenized payment method ID
payment_method_type: PaymentMethod
customer_id: int
order_id: int
description: str = None
metadata: Dict[str, Any] = None
idempotency_key: str = None
@dataclass
class PaymentResult:
"""Result of payment processing."""
success: bool
transaction_id: str
status: PaymentStatus
amount: Decimal
currency: str
failure_reason: Optional[str] = None
provider_data: Dict[str, Any] = None
requires_action: bool = False
next_action: Optional[str] = None
@dataclass
class RefundRequest:
"""Request to process a refund."""
transaction_id: str
amount: Optional[Decimal] = None # None = full refund
reason: str = None
@dataclass
class RefundResult:
"""Result of refund processing."""
success: bool
refund_id: str
amount: Decimal
status: str
failure_reason: Optional[str] = None
class PaymentProvider(ABC):
"""Abstract base class for payment providers."""
@abstractmethod
async def create_payment_intent(
self,
request: PaymentRequest
) -> PaymentResult:
"""Create a payment intent."""
pass
@abstractmethod
async def confirm_payment(
self,
payment_intent_id: str,
payment_method: str
) -> PaymentResult:
"""Confirm a payment intent."""
pass
@abstractmethod
async def get_payment_status(
self,
payment_intent_id: str
) -> PaymentResult:
"""Get current payment status."""
pass
@abstractmethod
async def refund_payment(
self,
request: RefundRequest
) -> RefundResult:
"""Process a refund."""
pass
@abstractmethod
async def verify_webhook_signature(
self,
payload: bytes,
signature: str
) -> bool:
"""Verify webhook signature."""
pass
@abstractmethod
def parse_webhook_event(self, payload: bytes) -> Dict[str, Any]:
"""Parse webhook event."""
pass
Stripe implementation:
import stripe
import hmac
import hashlib
import json
from typing import Dict, Any
class StripeProvider(PaymentProvider):
"""Stripe payment provider implementation."""
def __init__(self, api_key: str, webhook_secret: str = None):
stripe.api_key = api_key
self.webhook_secret = webhook_secret
async def create_payment_intent(self, request: PaymentRequest) -> PaymentResult:
"""Create a Stripe PaymentIntent."""
try:
intent_params = {
"amount": int(request.amount * 100), # Convert to cents
"currency": request.currency.lower(),
"payment_method": request.payment_method,
"confirm": True,
"metadata": {
"order_id": str(request.order_id),
"customer_id": str(request.customer_id)
}
}
if request.idempotency_key:
intent_params["idempotency_key"] = request.idempotency_key
if request.description:
intent_params["description"] = request.description
intent = stripe.PaymentIntent.create(**intent_params)
return self._map_payment_result(intent)
except stripe.error.CardError as e:
return PaymentResult(
success=False,
transaction_id=intent.id if 'intent' in locals() else None,
status=PaymentStatus.FAILED,
amount=request.amount,
currency=request.currency,
failure_reason=e.user_message,
provider_data={"error_code": e.code}
)
except Exception as e:
return PaymentResult(
success=False,
transaction_id=None,
status=PaymentStatus.FAILED,
amount=request.amount,
currency=request.currency,
failure_reason=str(e)
)
async def confirm_payment(
self,
payment_intent_id: str,
payment_method: str
) -> PaymentResult:
"""Confirm a Stripe PaymentIntent."""
try:
intent = stripe.PaymentIntent.confirm(
payment_intent_id,
payment_method=payment_method
)
return self._map_payment_result(intent)
except stripe.error.StripeError as e:
return PaymentResult(
success=False,
transaction_id=payment_intent_id,
status=PaymentStatus.FAILED,
amount=Decimal("0"),
currency="USD",
failure_reason=str(e)
)
async def get_payment_status(
self,
payment_intent_id: str
) -> PaymentResult:
"""Get Stripe PaymentIntent status."""
try:
intent = stripe.PaymentIntent.retrieve(payment_intent_id)
return self._map_payment_result(intent)
except stripe.error.StripeError as e:
return PaymentResult(
success=False,
transaction_id=payment_intent_id,
status=PaymentStatus.FAILED,
amount=Decimal("0"),
currency="USD",
failure_reason=str(e)
)
async def refund_payment(self, request: RefundRequest) -> RefundResult:
"""Process a Stripe refund."""
try:
refund_params = {
"payment_intent": request.transaction_id
}
if request.amount:
refund_params["amount"] = int(request.amount * 100)
if request.reason:
refund_params["reason"] = request.reason
refund = stripe.Refund.create(**refund_params)
return RefundResult(
success=refund.status == "succeeded",
refund_id=refund.id,
amount=Decimal(str(refund.amount / 100)),
status=refund.status
)
except stripe.error.StripeError as e:
return RefundResult(
success=False,
refund_id=None,
amount=Decimal("0"),
status="failed",
failure_reason=str(e)
)
async def verify_webhook_signature(
self,
payload: bytes,
signature: str
) -> bool:
"""Verify Stripe webhook signature."""
if not self.webhook_secret:
return False
try:
stripe.Webhook.construct_signature(
payload,
signature,
self.webhook_secret
)
return True
except ValueError:
return False
def parse_webhook_event(self, payload: bytes) -> Dict[str, Any]:
"""Parse Stripe webhook event."""
return json.loads(payload)
def _map_payment_result(self, intent) -> PaymentResult:
"""Map Stripe PaymentIntent to PaymentResult."""
status_map = {
"succeeded": PaymentStatus.SUCCEEDED,
"processing": PaymentStatus.PENDING,
"requires_payment_method": PaymentStatus.FAILED,
"requires_confirmation": PaymentStatus.PENDING,
"requires_action": PaymentStatus.PENDING,
"canceled": PaymentStatus.FAILED,
}
status = status_map.get(intent.status, PaymentStatus.PENDING)
return PaymentResult(
success=status == PaymentStatus.SUCCEEDED,
transaction_id=intent.id,
status=status,
amount=Decimal(str(intent.amount / 100)),
currency=intent.currency.upper(),
requires_action=intent.status == "requires_action",
next_action=self._get_next_action(intent),
provider_data={
"client_secret": intent.client_secret,
"last_payment_error": (
intent.last_payment_error.message
if intent.last_payment_error else None
)
}
)
def _get_next_action(self, intent) -> Optional[str]:
"""Get next action required from PaymentIntent."""
if intent.next_action:
if intent.next_action.type == "use_stripe_sdk":
return "stripe_sdk"
elif intent.next_action.type == "redirect_to_url":
return "redirect"
return None
Payment service:
from datetime import datetime, timezone
import uuid
import logging
logger = logging.getLogger(__name__)
class PaymentService:
"""Service for processing payments through multiple providers."""
def __init__(self, db):
self.db = db
self.providers: Dict[str, PaymentProvider] = {}
def register_provider(self, name: str, provider: PaymentProvider):
"""Register a payment provider."""
self.providers[name] = provider
logger.info(f"Registered payment provider: {name}")
async def create_payment(
self,
order_id: int,
amount: Decimal,
currency: str,
payment_method: str,
payment_method_type: PaymentMethod,
provider: str = "stripe",
customer_id: int = None,
idempotency_key: str = None
) -> PaymentResult:
"""Create and process a payment."""
provider_instance = self.providers.get(provider)
if not provider_instance:
raise ValueError(f"Unknown payment provider: {provider}")
# Generate idempotency key if not provided
if not idempotency_key:
idempotency_key = f"{order_id}_{uuid.uuid4()}"
request = PaymentRequest(
amount=amount,
currency=currency,
payment_method=payment_method,
payment_method_type=payment_method_type,
customer_id=customer_id,
order_id=order_id,
idempotency_key=idempotency_key
)
# Process payment
result = await provider_instance.create_payment_intent(request)
# Record transaction in database
await self._record_payment_transaction(
order_id=order_id,
transaction_id=result.transaction_id,
provider=provider,
payment_method=payment_method_type.value,
amount=amount,
currency=currency,
status=result.status.value,
failure_reason=result.failure_reason,
provider_data=result.provider_data
)
return result
async def confirm_payment(
self,
transaction_id: str,
payment_method: str,
provider: str = "stripe"
) -> PaymentResult:
"""Confirm a pending payment."""
provider_instance = self.providers.get(provider)
if not provider_instance:
raise ValueError(f"Unknown payment provider: {provider}")
result = await provider_instance.confirm_payment(transaction_id, payment_method)
# Update transaction status
await self._update_payment_status(
transaction_id,
result.status.value,
result.failure_reason
)
return result
async def refund_payment(
self,
transaction_id: str,
amount: Decimal = None,
reason: str = None
) -> RefundResult:
"""Process a refund."""
# Get transaction details
async with self.db.acquire() as conn:
transaction = await conn.fetchrow(
"""SELECT * FROM payment_transactions
WHERE transaction_id = $1""",
transaction_id
)
if not transaction:
raise ValueError(f"Transaction not found: {transaction_id}")
provider_name = transaction["provider"]
order_id = transaction["order_id"]
provider_instance = self.providers.get(provider_name)
if not provider_instance:
raise ValueError(f"Unknown payment provider: {provider_name}")
request = RefundRequest(
transaction_id=transaction_id,
amount=amount,
reason=reason
)
result = await provider_instance.refund_payment(request)
# Record refund
if result.success:
await self._record_refund(
payment_transaction_id=transaction["id"],
refund_id=result.refund_id,
amount=result.amount,
reason=reason
)
# Update order refunded amount
await self._update_order_refund(order_id, result.amount)
return result
async def handle_webhook(
self,
provider: str,
payload: bytes,
signature: str
) -> Dict[str, Any]:
"""Handle payment webhook."""
provider_instance = self.providers.get(provider)
if not provider_instance:
raise ValueError(f"Unknown payment provider: {provider}")
# Verify signature
if not await provider_instance.verify_webhook_signature(payload, signature):
raise ValueError("Invalid webhook signature")
# Parse event
event = provider_instance.parse_webhook_event(payload)
# Process event
await self._process_webhook_event(provider, event)
return {"status": "processed", "event_type": event.get("type")}
async def _process_webhook_event(self, provider: str, event: Dict[str, Any]):
"""Process a webhook event."""
event_type = event.get("type")
data = event.get("data", {})
if event_type == "payment_intent.succeeded":
await self._handle_payment_succeeded(provider, data)
elif event_type == "payment_intent.payment_failed":
await self._handle_payment_failed(provider, data)
elif event_type == "charge.refunded":
await self._handle_refund_succeeded(provider, data)
async def _handle_payment_succeeded(self, provider: str, data: Dict):
"""Handle successful payment webhook."""
intent = data.get("object", {})
transaction_id = intent.get("id")
order_id = intent.get("metadata", {}).get("order_id")
async with self.db.acquire() as conn:
# Update transaction status
await conn.execute(
"""UPDATE payment_transactions
SET status = 'succeeded', processed_at = NOW()
WHERE transaction_id = $1""",
transaction_id
)
# Update order status
await conn.execute(
"""UPDATE orders
SET status = 'paid',
paid_amount = paid_amount + $1,
paid_at = NOW()
WHERE id = $2""",
Decimal(str(intent.get("amount", 0))) / 100,
order_id
)
logger.info(f"Payment succeeded: {transaction_id} for order {order_id}")
async def _handle_payment_failed(self, provider: str, data: Dict):
"""Handle failed payment webhook."""
intent = data.get("object", {})
transaction_id = intent.get("id")
async with self.db.acquire() as conn:
await conn.execute(
"""UPDATE payment_transactions
SET status = 'failed',
failure_reason = $1,
processed_at = NOW()
WHERE transaction_id = $2""",
intent.get("last_payment_error", {}).get("message", "Unknown error"),
transaction_id
)
logger.warning(f"Payment failed: {transaction_id}")
async def _handle_refund_succeeded(self, provider: str, data: Dict):
"""Handle refund webhook."""
charge = data.get("object", {})
payment_intent_id = charge.get("payment_intent")
async with self.db.acquire() as conn:
# Record refund
transaction = await conn.fetchrow(
"SELECT id, order_id FROM payment_transactions WHERE transaction_id = $1",
payment_intent_id
)
if transaction:
await conn.execute(
"""INSERT INTO refunds
(payment_transaction_id, refund_id, amount, status, processed_at)
VALUES ($1, $2, $3, 'succeeded', NOW())""",
transaction["id"],
charge.get("id"),
Decimal(str(charge.get("amount", 0))) / 100
)
# Update order
await conn.execute(
"""UPDATE orders
SET refunded_amount = refunded_amount + $1
WHERE id = $2""",
Decimal(str(charge.get("amount", 0))) / 100,
transaction["order_id"]
)
logger.info(f"Refund succeeded: {charge.get('id')}")
async def _record_payment_transaction(
self,
order_id: int,
transaction_id: str,
provider: str,
payment_method: str,
amount: Decimal,
currency: str,
status: str,
failure_reason: str = None,
provider_data: Dict = None
):
"""Record payment transaction in database."""
async with self.db.acquire() as conn:
await conn.execute(
"""INSERT INTO payment_transactions
(order_id, transaction_id, provider, payment_method,
amount, currency, status, failure_reason, metadata)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)""",
order_id, transaction_id, provider, payment_method,
amount, currency, status, failure_reason,
json.dumps(provider_data) if provider_data else None
)
async def _update_payment_status(
self,
transaction_id: str,
status: str,
failure_reason: str = None
):
"""Update payment transaction status."""
async with self.db.acquire() as conn:
await conn.execute(
"""UPDATE payment_transactions
SET status = $1, failure_reason = $2
WHERE transaction_id = $3""",
status, failure_reason, transaction_id
)
async def _record_refund(
self,
payment_transaction_id: int,
refund_id: str,
amount: Decimal,
reason: str = None
):
"""Record refund in database."""
async with self.db.acquire() as conn:
await conn.execute(
"""INSERT INTO refunds
(payment_transaction_id, refund_id, amount, reason)
VALUES ($1, $2, $3, $4)""",
payment_transaction_id, refund_id, amount, reason
)
async def _update_order_refund(self, order_id: int, amount: Decimal):
"""Update order refund amount."""
async with self.db.acquire() as conn:
await conn.execute(
"""UPDATE orders
SET refunded_amount = refunded_amount + $1
WHERE id = $2""",
amount, order_id
)
Acceptance Criteria
- Payments can be processed through Stripe
- Payment transactions are recorded in database
- Idempotency prevents duplicate charges
- Webhook signatures are verified
- Refunds process correctly
- Order status updates on payment success
- Multiple providers can be supported
Notes
Trade-offs:
- Synchronous vs async payment confirmation: Async for 3D Secure
- Immediate vs deferred order creation: Reserve inventory before payment
Security:
- Never log full card details
- Use tokenization (Stripe.js)
- Verify all webhooks
Alternatives considered:
- Build own payment processing: Rejected (PCI compliance too complex)
- Braintree vs Stripe: Stripe has better API