365 lines
16 KiB
Python
365 lines
16 KiB
Python
from datetime import datetime, timezone as utc
|
|
from decimal import Decimal
|
|
import json
|
|
from django.conf import settings
|
|
from django.contrib import messages
|
|
from django.contrib.auth.decorators import login_required
|
|
from django.db import transaction
|
|
from django.http import FileResponse, Http404, HttpResponse, HttpResponseBadRequest
|
|
from django.shortcuts import get_object_or_404, redirect, render
|
|
from django.utils import timezone
|
|
from django.views.decorators.csrf import csrf_exempt
|
|
from django.views.decorators.http import require_POST, require_safe
|
|
import stripe
|
|
|
|
from catalog.paypal import CheckoutError, access_token, request_json
|
|
from .models import Order, OrderItem, Product, Subscription
|
|
from .payments import (
|
|
capture_paypal_order,
|
|
create_paypal_order,
|
|
create_paypal_subscription,
|
|
create_stripe_order_session,
|
|
create_stripe_subscription_session,
|
|
fulfill_order,
|
|
paypal_ready,
|
|
stripe_ready,
|
|
)
|
|
|
|
CART_SESSION_KEY = 'slx_shop_cart'
|
|
|
|
|
|
def _get_cart(request):
|
|
raw = request.session.get(CART_SESSION_KEY, {})
|
|
return {str(k): int(v) for k, v in raw.items() if int(v) > 0}
|
|
|
|
|
|
def _save_cart(request, cart):
|
|
request.session[CART_SESSION_KEY] = cart
|
|
request.session.modified = True
|
|
|
|
|
|
def _cart_summary(cart):
|
|
products = Product.objects.filter(pk__in=cart.keys(), active=True).exclude(kind=Product.Kind.SUBSCRIPTION)
|
|
items = []
|
|
subtotal = Decimal('0.00')
|
|
shipping = Decimal('0.00')
|
|
has_physical = False
|
|
|
|
for prod in products:
|
|
qty = min(cart[str(prod.pk)], prod.stock) if (prod.kind == Product.Kind.PHYSICAL and prod.track_stock) else cart[str(prod.pk)]
|
|
if qty <= 0:
|
|
continue
|
|
line = prod.price_usd * qty
|
|
subtotal += line
|
|
if prod.kind == Product.Kind.PHYSICAL:
|
|
has_physical = True
|
|
shipping = max(shipping, prod.shipping_usd)
|
|
items.append({'product': prod, 'quantity': qty, 'line_total': line})
|
|
|
|
return {
|
|
'items': items,
|
|
'subtotal': subtotal,
|
|
'shipping': shipping,
|
|
'total': subtotal + shipping,
|
|
'has_physical': has_physical,
|
|
}
|
|
|
|
|
|
@require_safe
|
|
def index(request):
|
|
products = Product.objects.filter(active=True)
|
|
cart_count = sum(_get_cart(request).values())
|
|
return render(request, 'shop/index.html', {
|
|
'products': products,
|
|
'cart_count': cart_count,
|
|
})
|
|
|
|
|
|
@require_safe
|
|
def product_detail(request, slug):
|
|
product = get_object_or_404(Product, slug=slug, active=True)
|
|
cart_count = sum(_get_cart(request).values())
|
|
from catalog.fans import live
|
|
from catalog.models import Chapter
|
|
chapter = live(Chapter).filter(pk=product.sample_chapter_id, publisher_url='').first()
|
|
return render(request, 'shop/product.html', {
|
|
'sample_chapter': chapter,
|
|
'editions': Product.objects.filter(active=True, kind=Product.Kind.PHYSICAL, sample_chapter=chapter).exclude(pk=product.pk) if chapter else (),
|
|
'related_products': Product.objects.filter(active=True).exclude(pk=product.pk)[:6],
|
|
'product': product,
|
|
'cart_count': cart_count,
|
|
'stripe_enabled': stripe_ready() and bool(settings.SLX_COMMERCE_STRIPE_WEBHOOK_SECRET),
|
|
'paypal_enabled': paypal_ready(),
|
|
})
|
|
|
|
|
|
@require_POST
|
|
def cart_add(request, pk):
|
|
product = get_object_or_404(Product, pk=pk, active=True)
|
|
if product.kind == Product.Kind.SUBSCRIPTION:
|
|
return redirect('shop-product', slug=product.slug)
|
|
if not product.in_stock:
|
|
messages.error(request, 'That item is currently out of stock.')
|
|
return redirect('shop-product', slug=product.slug)
|
|
|
|
qty = max(1, min(20, int(request.POST.get('quantity', 1))))
|
|
cart = _get_cart(request)
|
|
new_qty = cart.get(str(product.pk), 0) + qty
|
|
if product.kind == Product.Kind.PHYSICAL and product.track_stock:
|
|
new_qty = min(new_qty, product.stock)
|
|
cart[str(product.pk)] = new_qty
|
|
_save_cart(request, cart)
|
|
messages.success(request, f'Added {product.title} to your cart.')
|
|
return redirect('shop-cart')
|
|
|
|
|
|
@require_POST
|
|
def cart_update(request, pk):
|
|
cart = _get_cart(request)
|
|
qty = int(request.POST.get('quantity', 0))
|
|
if qty <= 0:
|
|
cart.pop(str(pk), None)
|
|
else:
|
|
cart[str(pk)] = min(20, qty)
|
|
_save_cart(request, cart)
|
|
return redirect('shop-cart')
|
|
|
|
|
|
@require_safe
|
|
def cart_view(request):
|
|
summary = _cart_summary(_get_cart(request))
|
|
return render(request, 'shop/cart.html', {
|
|
**summary,
|
|
'stripe_enabled': stripe_ready(),
|
|
'paypal_enabled': paypal_ready(),
|
|
})
|
|
|
|
|
|
@require_POST
|
|
def checkout_start(request):
|
|
gateway = request.POST.get('gateway', '').lower()
|
|
email = (request.user.email if request.user.is_authenticated and request.user.email else request.POST.get('email', '')).strip()
|
|
if not email or '@' not in email:
|
|
messages.error(request, 'Please enter a valid email address for receipts and downloads.')
|
|
return redirect('shop-cart')
|
|
|
|
summary = _cart_summary(_get_cart(request))
|
|
if not summary['items']:
|
|
messages.error(request, 'Your cart is empty.')
|
|
return redirect('shop-index')
|
|
|
|
order = Order.objects.create(
|
|
user=request.user if request.user.is_authenticated else None,
|
|
email=email,
|
|
full_name=request.POST.get('full_name', '').strip()[:160],
|
|
gateway=gateway if gateway in {'stripe', 'paypal'} else Order.Gateway.STRIPE,
|
|
subtotal_usd=summary['subtotal'],
|
|
shipping_usd=summary['shipping'],
|
|
total_usd=summary['total'],
|
|
)
|
|
for row in summary['items']:
|
|
OrderItem.objects.create(
|
|
order=order,
|
|
product=row['product'],
|
|
title_snapshot=row['product'].title,
|
|
unit_price_usd=row['product'].price_usd,
|
|
quantity=row['quantity'],
|
|
)
|
|
|
|
try:
|
|
if gateway == 'stripe' and stripe_ready():
|
|
url = create_stripe_order_session(order)
|
|
_save_cart(request, {})
|
|
return redirect(url)
|
|
if gateway == 'paypal' and paypal_ready():
|
|
url = create_paypal_order(order)
|
|
_save_cart(request, {})
|
|
return redirect(url)
|
|
messages.error(request, 'Selected payment gateway is not configured yet.')
|
|
except Exception:
|
|
messages.error(request, 'Unable to initialize payment checkout. Please try again.')
|
|
return redirect('shop-cart')
|
|
|
|
|
|
@require_POST
|
|
@login_required
|
|
def subscribe_start(request, slug):
|
|
product = get_object_or_404(Product, slug=slug, active=True, kind=Product.Kind.SUBSCRIPTION)
|
|
gateway = request.POST.get('gateway', '').lower()
|
|
if product.member_tier and (gateway != 'stripe' or not stripe_ready() or not settings.SLX_COMMERCE_STRIPE_WEBHOOK_SECRET):
|
|
messages.error(request, 'Fan Club subscriptions require Stripe checkout.')
|
|
return redirect('shop-product', slug=slug)
|
|
email = (request.user.email if request.user.is_authenticated and request.user.email else request.POST.get('email', '')).strip()
|
|
if not email or '@' not in email:
|
|
messages.error(request, 'Please enter a valid email address to subscribe.')
|
|
return redirect('shop-product', slug=slug)
|
|
|
|
sub = Subscription.objects.create(
|
|
user=request.user if request.user.is_authenticated else None,
|
|
email=email,
|
|
product=product, entitlement_tier=product.member_tier,
|
|
gateway=gateway if gateway in {'stripe', 'paypal'} else Order.Gateway.STRIPE,
|
|
)
|
|
try:
|
|
if gateway == 'stripe' and stripe_ready():
|
|
return redirect(create_stripe_subscription_session(sub))
|
|
if gateway == 'paypal' and paypal_ready():
|
|
return redirect(create_paypal_subscription(sub))
|
|
messages.error(request, 'Selected subscription gateway is not configured.')
|
|
except Exception:
|
|
messages.error(request, 'Could not start subscription checkout.')
|
|
return redirect('shop-product', slug=slug)
|
|
|
|
|
|
@require_safe
|
|
def paypal_return(request, order_id):
|
|
order = get_object_or_404(Order, order_id=order_id, gateway=Order.Gateway.PAYPAL)
|
|
if order.status == Order.Status.PENDING:
|
|
try:
|
|
capture_paypal_order(order)
|
|
except CheckoutError:
|
|
messages.error(request, 'PayPal payment could not be verified yet.')
|
|
return redirect('shop-order-detail', order_id=order.order_id)
|
|
|
|
|
|
@require_safe
|
|
def order_detail(request, order_id):
|
|
order = get_object_or_404(Order, order_id=order_id)
|
|
return render(request, 'shop/order.html', {'order': order})
|
|
|
|
|
|
@require_safe
|
|
def download_digital(request, order_id, item_id):
|
|
order = get_object_or_404(Order, order_id=order_id, status__in=[Order.Status.PAID, Order.Status.SHIPPED, Order.Status.DELIVERED])
|
|
item = get_object_or_404(OrderItem, pk=item_id, order=order, product__kind=Product.Kind.DIGITAL)
|
|
if not item.product.digital_file:
|
|
raise Http404
|
|
return FileResponse(item.product.digital_file.open('rb'), as_attachment=True)
|
|
|
|
|
|
# --- WEBHOOKS ---
|
|
|
|
@csrf_exempt
|
|
@require_POST
|
|
def stripe_webhook(request):
|
|
if not settings.SLX_COMMERCE_STRIPE_WEBHOOK_SECRET:
|
|
return HttpResponseBadRequest('Webhook secret not configured')
|
|
stripe.api_key = settings.SLX_STRIPE_SECRET_KEY
|
|
sig = request.META.get('HTTP_STRIPE_SIGNATURE', '')
|
|
try:
|
|
event = stripe.Webhook.construct_event(request.body, sig, settings.SLX_COMMERCE_STRIPE_WEBHOOK_SECRET)
|
|
except Exception:
|
|
return HttpResponseBadRequest('Invalid signature')
|
|
|
|
from catalog.chapter_access import stripe_live_mode
|
|
if event.get('livemode') != stripe_live_mode():
|
|
return HttpResponseBadRequest('Stripe mode mismatch')
|
|
etype = event['type']
|
|
obj = event['data']['object']
|
|
if etype in ('checkout.session.completed', 'checkout.session.async_payment_succeeded'):
|
|
meta = obj.get('metadata') or {}
|
|
if meta.get('kind') == 'order' and obj.get('payment_status') == 'paid':
|
|
order = Order.objects.filter(gateway=Order.Gateway.STRIPE, gateway_session_id=obj.get('id', '')).first()
|
|
if (order and str(order.order_id) == meta.get('order_id') and obj.get('currency') == 'usd'
|
|
and obj.get('amount_total') == int(order.total_usd * 100)):
|
|
shipping = obj.get('shipping_details') or (obj.get('collected_information') or {}).get('shipping_details') or {}
|
|
addr = shipping.get('address') or {}
|
|
if addr:
|
|
order.full_name = (shipping.get('name') or order.full_name)[:160]
|
|
order.shipping_line1 = (addr.get('line1') or '')[:200]
|
|
order.shipping_line2 = (addr.get('line2') or '')[:200]
|
|
order.shipping_city = (addr.get('city') or '')[:120]
|
|
order.shipping_state = (addr.get('state') or '')[:120]
|
|
order.shipping_postal = (addr.get('postal_code') or '')[:40]
|
|
order.shipping_country = (addr.get('country') or '')[:2]
|
|
order.save(update_fields=[
|
|
'full_name', 'shipping_line1', 'shipping_line2',
|
|
'shipping_city', 'shipping_state', 'shipping_postal', 'shipping_country'
|
|
])
|
|
fulfill_order(order, payment_id=obj.get('payment_intent') or obj['id'], stripe_live=event['livemode'])
|
|
elif meta.get('kind') == 'subscription' and obj.get('subscription'):
|
|
sync_stripe_subscription(obj['subscription'], event['livemode'], meta.get('sub_id'))
|
|
|
|
elif etype == 'charge.refunded' and obj.get('refunded') and obj.get('payment_intent'):
|
|
Order.objects.filter(gateway=Order.Gateway.STRIPE, stripe_live=event['livemode'],
|
|
gateway_payment_id=obj['payment_intent']).update(status=Order.Status.REFUNDED)
|
|
elif etype in ('customer.subscription.updated', 'customer.subscription.deleted',
|
|
'invoice.paid', 'invoice.payment_failed'):
|
|
sub_id = obj.get('id') if etype.startswith('customer.subscription.') else (
|
|
obj.get('subscription') or ((obj.get('parent') or {}).get('subscription_details') or {}).get('subscription'))
|
|
if sub_id:
|
|
sync_stripe_subscription(sub_id, event['livemode'])
|
|
return HttpResponse('ok')
|
|
|
|
|
|
def sync_stripe_subscription(remote_id, live_mode, checkout_ref=None):
|
|
with transaction.atomic():
|
|
rows = Subscription.objects.select_for_update().filter(gateway=Order.Gateway.STRIPE)
|
|
sub = rows.filter(gateway_sub_id=remote_id, stripe_live=live_mode).first()
|
|
if sub is None and checkout_ref:
|
|
sub = rows.filter(sub_id=checkout_ref, gateway_sub_id='').first()
|
|
if not sub:
|
|
return
|
|
current = stripe.Subscription.retrieve(remote_id)
|
|
if current.get('livemode') != live_mode or (current.get('metadata') or {}).get('sub_id') != str(sub.sub_id):
|
|
return
|
|
state = current.get('status')
|
|
periods = [item.get('current_period_end') for item in (current.get('items') or {}).get('data', [])]
|
|
period = current.get('current_period_end') or min((v for v in periods if v), default=None)
|
|
sub.status = (Subscription.Status.ACTIVE if state == 'active' else Subscription.Status.CANCELED
|
|
if state in {'canceled', 'incomplete_expired'} else Subscription.Status.PAST_DUE)
|
|
sub.current_period_end = datetime.fromtimestamp(period, tz=utc.utc) if period else None
|
|
sub.gateway_sub_id = remote_id
|
|
sub.gateway_customer_id = current.get('customer') or ''
|
|
sub.stripe_live = live_mode
|
|
sub.save(update_fields=['status', 'current_period_end', 'gateway_sub_id', 'gateway_customer_id', 'stripe_live'])
|
|
|
|
|
|
@csrf_exempt
|
|
@require_POST
|
|
def paypal_webhook(request):
|
|
if not paypal_ready() or not settings.SLX_PAYPAL_WEBHOOK_ID:
|
|
return HttpResponseBadRequest('PayPal webhook not configured')
|
|
try:
|
|
body = json.loads(request.body)
|
|
mode = settings.SLX_PAYPAL_MODE
|
|
token = access_token(mode)
|
|
verify = request_json(
|
|
mode,
|
|
'/v1/notifications/verify-webhook-signature',
|
|
token=token,
|
|
data={
|
|
'auth_algo': request.META.get('HTTP_PAYPAL_AUTH_ALGO', ''),
|
|
'cert_url': request.META.get('HTTP_PAYPAL_CERT_URL', ''),
|
|
'transmission_id': request.META.get('HTTP_PAYPAL_TRANSMISSION_ID', ''),
|
|
'transmission_sig': request.META.get('HTTP_PAYPAL_TRANSMISSION_SIG', ''),
|
|
'transmission_time': request.META.get('HTTP_PAYPAL_TRANSMISSION_TIME', ''),
|
|
'webhook_id': settings.SLX_PAYPAL_WEBHOOK_ID,
|
|
'webhook_event': body,
|
|
},
|
|
)
|
|
if verify.get('verification_status') != 'SUCCESS':
|
|
return HttpResponseBadRequest('Invalid PayPal signature')
|
|
except Exception:
|
|
return HttpResponseBadRequest('Verification failed')
|
|
|
|
event_type = body.get('event_type', '')
|
|
resource = body.get('resource') or {}
|
|
|
|
if event_type == 'PAYMENT.CAPTURE.COMPLETED':
|
|
custom_id = resource.get('custom_id') or ''
|
|
order = Order.objects.filter(gateway_session_id=resource.get('supplementary_data', {}).get('related_ids', {}).get('order_id', '')).first()
|
|
if order:
|
|
fulfill_order(order, payment_id=resource.get('id', ''))
|
|
elif event_type == 'BILLING.SUBSCRIPTION.ACTIVATED':
|
|
pp_sub_id = resource.get('id', '')
|
|
custom_id = resource.get('custom_id', '')
|
|
qs = Subscription.objects.filter(sub_id=custom_id) if custom_id else Subscription.objects.filter(gateway_sub_id=pp_sub_id)
|
|
qs.update(status=Subscription.Status.ACTIVE, gateway_sub_id=pp_sub_id)
|
|
elif event_type in ('BILLING.SUBSCRIPTION.CANCELLED', 'BILLING.SUBSCRIPTION.SUSPENDED'):
|
|
pp_sub_id = resource.get('id', '')
|
|
if pp_sub_id:
|
|
Subscription.objects.filter(gateway_sub_id=pp_sub_id).update(status=Subscription.Status.CANCELED)
|
|
|
|
return HttpResponse('ok')
|