"""Stripe Checkout session endpoint. Requires STRIPE_SECRET_KEY.""" import json import logging from django.conf import settings from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from .checkout_helpers import build_checkout_params logger = logging.getLogger(__name__) def _error(message, status): return JsonResponse({'error': message}, status=status) @csrf_exempt @require_POST def create_checkout_session(request): if not settings.STRIPE_SECRET_KEY: return _error('Payment processing is not configured', 500) try: body = json.loads(request.body or b'{}') except ValueError: return _error('Invalid JSON body', 400) try: import stripe except ImportError: return _error('Payment provider SDK is not installed', 503) base_url = (settings.SITE_BASE_URL or request.build_absolute_uri('/')).rstrip('/') params, problem = build_checkout_params(body, base_url) if problem: return _error(problem, 400) try: session = stripe.checkout.Session.create(api_key=settings.STRIPE_SECRET_KEY, **params) except stripe.StripeError as exc: logger.exception('Stripe checkout error') return _error(getattr(exc, 'user_message', None) or 'Payment provider error', 502) return JsonResponse({'url': session.url})