Configure PayPal integration and cart checkout error display

This commit is contained in:
Zach committed 2026-12-01 04:20:38 +00:00
1 parent 62065828e1
commit cf07fc5d9b
98 files changed
+1430 -281

No files matched your search

+5 -5
View File
@@ -5,16 +5,16 @@ from .models import Order, OrderItem, Product, Subscription
@admin.register(Product, site=studio)
class ProductAdmin(admin.ModelAdmin):
list_display = ['title', 'kind', 'price_usd', 'stock', 'active', 'featured', 'position']
list_filter = ['kind', 'active', 'featured']
list_display = ['title', 'kind', 'price_usd', 'stock', 'active', 'featured', 'verified_by_seller', 'position']
list_filter = ['kind', 'active', 'featured', 'verified_by_seller']
list_editable = ['price_usd', 'stock', 'active', 'position']
search_fields = ['title', 'summary']
prepopulated_fields = {'slug': ('title',)}
fieldsets = [
('Product', {'fields': ['title', 'slug', 'kind', 'summary', 'description', 'image', 'price_usd', 'active', 'featured', 'position']}),
('Product', {'fields': ['title', 'slug', 'kind', 'summary', 'description', 'image', 'price_usd', 'active', 'featured', 'verified_by_seller', 'position']}),
('Physical Inventory & Shipping', {'fields': ['track_stock', 'stock', 'shipping_usd']}),
('Digital Download', {'fields': ['digital_file']}),
('Subscription Billing', {'fields': ['billing_interval', 'stripe_price_id', 'paypal_plan_id']}),
('Digital Download', {'fields': ['digital_file', 'sample_chapter']}),
('Subscription Billing', {'fields': ['billing_interval', 'stripe_price_id', 'paypal_plan_id', 'member_tier', 'comparison']}),
]
@@ -0,0 +1,18 @@
# Generated by Django 5.2.19 on 2026-11-26 01:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='product',
name='verified_by_seller',
field=models.BooleanField(default=False, help_text='Show the Verified by Seller badge on this listing.'),
),
]
@@ -0,0 +1,45 @@
# Generated by Django 5.2.19 on 2026-11-26 11:05
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0027_alter_chapter_price_usd_managedpage'),
('shop', '0002_product_verified_by_seller'),
]
operations = [
migrations.AddField(
model_name='order',
name='stripe_live',
field=models.BooleanField(editable=False, null=True),
),
migrations.AddField(
model_name='orderitem',
name='chapter',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='catalog.chapter'),
),
migrations.AddField(
model_name='product',
name='member_tier',
field=models.PositiveSmallIntegerField(blank=True, choices=[(1, 'Early Access'), (2, 'Studio Vault')], null=True),
),
migrations.AddField(
model_name='product',
name='sample_chapter',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='shop_editions', to='catalog.chapter'),
),
migrations.AddField(
model_name='subscription',
name='entitlement_tier',
field=models.PositiveSmallIntegerField(editable=False, null=True),
),
migrations.AddField(
model_name='subscription',
name='stripe_live',
field=models.BooleanField(editable=False, null=True),
),
]
+20
View File
@@ -0,0 +1,20 @@
from decimal import Decimal
from django.db import migrations
def seed(apps, schema_editor):
Product = apps.get_model('shop', 'Product')
products = Product.objects.using(schema_editor.connection.alias)
for slug, label, tier in [('slx-monthly-early-access', 'Early Access', 1),
('slx-monthly-studio-vault', 'Studio Vault', 2)]:
if not products.filter(kind='subscription', member_tier=tier).exists():
products.get_or_create(slug=slug, defaults={
'title': f'Slump X Land Monthly · {label}', 'kind': 'subscription',
'billing_interval': 'month', 'member_tier': tier, 'price_usd': Decimal('0.50'),
'track_stock': False, 'active': False,
})
class Migration(migrations.Migration):
dependencies = [('shop', '0003_order_stripe_live_orderitem_chapter_and_more')]
operations = [migrations.RunPython(seed, migrations.RunPython.noop)]
@@ -0,0 +1,18 @@
# Generated by Django 5.2.19 on 2026-11-26 12:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0004_fan_club_products'),
]
operations = [
migrations.AddField(
model_name='product',
name='comparison',
field=models.TextField(blank=True, help_text='One benefit per line, using Feature: Details. Used on the membership comparison chart.', max_length=3000),
),
]
+18
View File
@@ -0,0 +1,18 @@
# Generated by Django 5.2.19 on 2026-11-26 13:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0005_product_comparison'),
]
operations = [
migrations.AlterField(
model_name='product',
name='member_tier',
field=models.PositiveSmallIntegerField(blank=True, choices=[(1, 'Early Access'), (2, 'Studio Vault'), (3, 'Collector’s Circle')], null=True),
),
]
+11
View File
@@ -24,7 +24,14 @@ class Product(models.Model):
image = models.ImageField(upload_to='shop/products/', blank=True)
price_usd = models.DecimalField(max_digits=9, decimal_places=2, validators=[MinValueValidator(Decimal('0.50'))])
active = models.BooleanField(default=True)
comparison = models.TextField(blank=True, max_length=3000,
help_text='One benefit per line, using Feature: Details. Used on the membership comparison chart.')
featured = models.BooleanField(default=False)
sample_chapter = models.ForeignKey('catalog.Chapter', null=True, blank=True, on_delete=models.SET_NULL,
related_name='shop_editions')
member_tier = models.PositiveSmallIntegerField(choices=[(1, 'Early Access'), (2, 'Studio Vault'), (3, 'Collector’s Circle')],
null=True, blank=True)
verified_by_seller = models.BooleanField(default=False, help_text="Show the Verified by Seller badge on this listing.")
position = models.PositiveIntegerField(default=0)
# Physical inventory & shipping
@@ -96,6 +103,7 @@ class Order(models.Model):
# Gateway tracking
gateway_session_id = models.CharField(max_length=200, blank=True, db_index=True)
gateway_payment_id = models.CharField(max_length=200, blank=True)
stripe_live = models.BooleanField(null=True, editable=False)
paid_at = models.DateTimeField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
@@ -113,6 +121,7 @@ class Order(models.Model):
class OrderItem(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items')
product = models.ForeignKey(Product, on_delete=models.PROTECT)
chapter = models.ForeignKey('catalog.Chapter', null=True, blank=True, on_delete=models.PROTECT)
title_snapshot = models.CharField(max_length=160)
unit_price_usd = models.DecimalField(max_digits=9, decimal_places=2)
quantity = models.PositiveIntegerField(default=1)
@@ -137,6 +146,8 @@ class Subscription(models.Model):
gateway_sub_id = models.CharField(max_length=200, blank=True, db_index=True)
gateway_customer_id = models.CharField(max_length=200, blank=True)
status = models.CharField(max_length=20, choices=Status.choices, default=Status.PENDING)
stripe_live = models.BooleanField(null=True, editable=False)
entitlement_tier = models.PositiveSmallIntegerField(null=True, editable=False)
current_period_end = models.DateTimeField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
+7 -5
View File
@@ -9,11 +9,12 @@ from django.utils import timezone
import stripe
from catalog.paypal import CheckoutError, access_token, checkout_origin, request_json, safe_approval_url
from catalog.shop_stripe import origin as stripe_origin
from .models import Order, Product, Subscription
def stripe_ready():
return bool(settings.SLX_STRIPE_SECRET_KEY and checkout_origin())
return bool(settings.SLX_STRIPE_SECRET_KEY and (stripe_origin() or checkout_origin()))
def paypal_ready():
@@ -23,7 +24,7 @@ def paypal_ready():
and checkout_origin())
def fulfill_order(order, payment_id=''):
def fulfill_order(order, payment_id='', stripe_live=None):
with transaction.atomic():
order = Order.objects.select_for_update().get(pk=order.pk)
if order.status != Order.Status.PENDING:
@@ -32,7 +33,8 @@ def fulfill_order(order, payment_id=''):
order.paid_at = timezone.now()
if payment_id:
order.gateway_payment_id = payment_id[:200]
order.save(update_fields=['status', 'paid_at', 'gateway_payment_id'])
order.stripe_live = stripe_live
order.save(update_fields=['status', 'paid_at', 'gateway_payment_id', 'stripe_live'])
for item in order.items.select_related('product'):
prod = item.product
@@ -47,7 +49,7 @@ def fulfill_order(order, payment_id=''):
def create_stripe_order_session(order):
stripe.api_key = settings.SLX_STRIPE_SECRET_KEY
origin = checkout_origin()
origin = stripe_origin() or checkout_origin()
line_items = []
for item in order.items.select_related('product'):
line_items.append({
@@ -88,7 +90,7 @@ def create_stripe_order_session(order):
def create_stripe_subscription_session(sub):
stripe.api_key = settings.SLX_STRIPE_SECRET_KEY
origin = checkout_origin()
origin = stripe_origin() or checkout_origin()
prod = sub.product
if prod.stripe_price_id:
line_item = {'price': prod.stripe_price_id, 'quantity': 1}
+1 -1
View File
@@ -11,7 +11,7 @@ urlpatterns = [
path('paypal/return/<uuid:order_id>/', views.paypal_return, name='shop-paypal-return'),
path('order/<uuid:order_id>/', views.order_detail, name='shop-order-detail'),
path('order/<uuid:order_id>/download/<int:item_id>/', views.download_digital, name='shop-download'),
path('webhooks/stripe/', views.stripe_webhook, name='shop-stripe-webhook'),
path('webhooks/stripe/', views.stripe_webhook, name='commerce-stripe-webhook'),
path('webhooks/paypal/', views.paypal_webhook, name='shop-paypal-webhook'),
path('<slug:slug>/', views.product_detail, name='shop-product'),
]
+60 -22
View File
@@ -1,7 +1,10 @@
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
@@ -76,10 +79,16 @@ def index(request):
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(),
'stripe_enabled': stripe_ready() and bool(settings.SLX_COMMERCE_STRIPE_WEBHOOK_SECRET),
'paypal_enabled': paypal_ready(),
})
@@ -173,9 +182,13 @@ def checkout_start(request):
@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.')
@@ -184,7 +197,7 @@ def subscribe_start(request, slug):
sub = Subscription.objects.create(
user=request.user if request.user.is_authenticated else None,
email=email,
product=product,
product=product, entitlement_tier=product.member_tier,
gateway=gateway if gateway in {'stripe', 'paypal'} else Order.Gateway.STRIPE,
)
try:
@@ -229,24 +242,27 @@ def download_digital(request, order_id, item_id):
@csrf_exempt
@require_POST
def stripe_webhook(request):
if not settings.SLX_STRIPE_WEBHOOK_SECRET:
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_STRIPE_WEBHOOK_SECRET)
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 == 'checkout.session.completed':
if etype in ('checkout.session.completed', 'checkout.session.async_payment_succeeded'):
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 {}
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]
@@ -260,23 +276,45 @@ def stripe_webhook(request):
'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 '',
)
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 in ('customer.subscription.deleted', 'invoice.payment_failed'):
sub_id = obj.get('id') if etype == 'customer.subscription.deleted' else obj.get('subscription')
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:
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)
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):