327 lines
13 KiB
Python
327 lines
13 KiB
Python
from decimal import Decimal
|
|
import json
|
|
from django.conf import settings
|
|
from django.contrib import messages
|
|
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())
|
|
return render(request, 'shop/product.html', {
|
|
'product': product,
|
|
'cart_count': cart_count,
|
|
'stripe_enabled': stripe_ready(),
|
|
'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
|
|
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()
|
|
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,
|
|
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_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_STRIPE_WEBHOOK_SECRET)
|
|
except Exception:
|
|
return HttpResponseBadRequest('Invalid signature')
|
|
|
|
etype = event['type']
|
|
obj = event['data']['object']
|
|
|
|
if etype == 'checkout.session.completed':
|
|
meta = obj.get('metadata') or {}
|
|
if meta.get('kind') == 'order' and meta.get('order_id'):
|
|
order = Order.objects.filter(order_id=meta['order_id']).first()
|
|
if order:
|
|
shipping = obj.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.get('id', ''))
|
|
elif meta.get('kind') == 'subscription' and meta.get('sub_id'):
|
|
Subscription.objects.filter(sub_id=meta['sub_id']).update(
|
|
status=Subscription.Status.ACTIVE,
|
|
gateway_sub_id=obj.get('subscription') or '',
|
|
gateway_customer_id=obj.get('customer') or '',
|
|
)
|
|
|
|
elif etype in ('customer.subscription.deleted', 'invoice.payment_failed'):
|
|
sub_id = obj.get('id') if etype == 'customer.subscription.deleted' else obj.get('subscription')
|
|
if sub_id:
|
|
new_status = Subscription.Status.CANCELED if etype == 'customer.subscription.deleted' else Subscription.Status.PAST_DUE
|
|
Subscription.objects.filter(gateway_sub_id=sub_id).update(status=new_status)
|
|
|
|
return HttpResponse('ok')
|
|
|
|
|
|
@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')
|