Restore and lock in shop app, admin sidebar, media routing, and Stripe
This commit is contained in:
1 parent
93d83a0d63
commit
3cfea85499
15 files changed
+486
-73
No files matched your search
+35
-9
@@ -16,7 +16,7 @@ from django.utils.html import format_html
|
||||
from .models import SiteSettings, Chapter, Page, Entry, DiscussionComment, FanNotice, ChapterReview, SeriesReview, BookListing, ChapterPurchase, StreamComment, FanMembership, SupportCredit, AIChapterReview
|
||||
from .fans import live, notify
|
||||
from .newsletter_admin import CampaignAdmin, SubscriberAdmin
|
||||
from .models import NewsletterCampaign, NewsletterSubscriber, PageBackground, FloatingArtwork, ProductVariant, PageSharePreview
|
||||
from .models import NewsletterCampaign, NewsletterSubscriber, PageBackground, FloatingArtwork, ProductVariant, PageSharePreview, ShopOrder
|
||||
from .backgrounds import PAGE_CHOICES
|
||||
from .sharing import validate_share_path
|
||||
from .uploads import ShareImageUploadField
|
||||
@@ -47,13 +47,7 @@ class Studio(admin.AdminSite):
|
||||
]),
|
||||
('Community', [('◎', 'Fan memberships', 'fanmembership', None), ('◈', 'Verified support', 'supportcredit', None), ('◉', 'Moderate comments', 'discussioncomment', None), ('★', 'Moderate chapter reviews', 'chapterreview', None), ('★', 'Moderate series reviews', 'seriesreview', None), ('◉', 'Stream comments', 'streamcomment', None)]),
|
||||
('Newsletter', [('✉', 'Campaigns', 'newslettercampaign', None), ('◎', 'Subscribers', 'newslettersubscriber', None)]),
|
||||
('Commerce', [
|
||||
('▤', 'Shop products', 'shop.product', None),
|
||||
('◈', 'Orders', 'shop.order', None),
|
||||
('◎', 'Subscriptions', 'shop.subscription', None),
|
||||
('▤', 'Book listings', 'booklisting', None),
|
||||
('◈', 'Chapter purchases', 'chapterpurchase', None),
|
||||
]),
|
||||
('Commerce', [('▤', 'Products', 'booklisting', None), ('▧', 'Shop orders', 'shoporder', None), ('◈', 'Chapter purchases', 'chapterpurchase', None)]),
|
||||
('Studio', [('◈', 'Site settings', 'sitesettings', None), ('▧', 'Page backgrounds', 'pagebackground', None), ('✦', 'Floating artwork', 'floatingartwork', None), ('↗', 'Link previews', 'pagesharepreview', None)]),
|
||||
]
|
||||
groups = []
|
||||
@@ -624,12 +618,44 @@ class PageSharePreviewAdmin(admin.ModelAdmin):
|
||||
|
||||
@admin.register(BookListing, site=studio)
|
||||
class BookListingAdmin(admin.ModelAdmin):
|
||||
list_display = ['title', 'category', 'visible']
|
||||
list_display = ['title', 'category', 'price_usd', 'visible']
|
||||
list_editable = ['price_usd']
|
||||
list_filter = ['category', 'visible']
|
||||
search_fields = ['title']
|
||||
inlines = [ProductVariantInline]
|
||||
|
||||
|
||||
@admin.register(ShopOrder, site=studio)
|
||||
class ShopOrderAdmin(admin.ModelAdmin):
|
||||
list_display = ['reference', 'item', 'amount_usd', 'status', 'livemode', 'fulfilled', 'created_at']
|
||||
list_filter = ['status', 'livemode', 'fulfilled']
|
||||
search_fields = ['item', 'email', '=reference', '=stripe_session', '=payment_intent']
|
||||
fields = ['reference', 'item', 'amount_usd', 'status', 'livemode', 'email', 'stripe_session',
|
||||
'payment_intent', 'stripe_dashboard', 'created_at', 'paid_at', 'fulfilled']
|
||||
readonly_fields = fields[:-1]
|
||||
|
||||
@admin.display(description='Amount', ordering='amount_cents')
|
||||
def amount_usd(self, obj):
|
||||
return f'${obj.amount_cents // 100}.{obj.amount_cents % 100:02d}'
|
||||
|
||||
@admin.display(description='Order in Stripe')
|
||||
def stripe_dashboard(self, obj):
|
||||
if obj and obj.payment_intent:
|
||||
path = 'payments/' if obj.livemode else 'test/payments/'
|
||||
return format_html('<a href="{}">View in Stripe</a>',
|
||||
'https://dashboard.stripe.com/' + path + obj.payment_intent)
|
||||
return 'Available after payment.'
|
||||
|
||||
def get_readonly_fields(self, request, obj=None):
|
||||
return self.fields if obj and obj.status != ShopOrder.Status.PAID else self.readonly_fields
|
||||
|
||||
def has_add_permission(self, request):
|
||||
return False
|
||||
|
||||
def has_delete_permission(self, request, obj=None):
|
||||
return False
|
||||
|
||||
|
||||
@admin.register(ChapterPurchase, site=studio)
|
||||
class ChapterPurchaseAdmin(admin.ModelAdmin):
|
||||
list_display = ['chapter', 'user', 'mode', 'amount', 'paid_at', 'revoked']
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# Generated by Django 5.2.19 on 2026-11-23 22:47
|
||||
|
||||
import catalog.models
|
||||
import django.core.validators
|
||||
import uuid
|
||||
from decimal import Decimal
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('catalog', '0024_page_share_previews'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='ShopOrder',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('reference', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
|
||||
('item', models.CharField(max_length=320)),
|
||||
('amount_cents', models.PositiveIntegerField()),
|
||||
('livemode', models.BooleanField()),
|
||||
('status', models.CharField(choices=[('open', 'Awaiting payment'), ('paid', 'Paid'), ('expired', 'Expired'), ('failed', 'Checkout unavailable')], db_index=True, default='open', max_length=10)),
|
||||
('stripe_session', models.CharField(blank=True, max_length=255, null=True, unique=True)),
|
||||
('payment_intent', models.CharField(blank=True, max_length=255)),
|
||||
('email', models.EmailField(blank=True, max_length=254)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('paid_at', models.DateTimeField(blank=True, null=True)),
|
||||
('fulfilled', models.BooleanField(default=False)),
|
||||
],
|
||||
options={
|
||||
'ordering': ['-created_at'],
|
||||
},
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='booklisting',
|
||||
name='price_usd',
|
||||
field=models.DecimalField(blank=True, decimal_places=2, help_text='Charged by Stripe when this product has no variants.', max_digits=8, null=True, validators=[django.core.validators.MinValueValidator(Decimal('0.50'))], verbose_name='Stripe price (USD)'),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='booklisting',
|
||||
name='ships',
|
||||
field=models.BooleanField(default=True, help_text='Collect a shipping address at Stripe Checkout.', verbose_name='Ship this product'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='productvariant',
|
||||
name='paypal_url',
|
||||
field=models.URLField(blank=True, validators=[catalog.models.validate_book_checkout], verbose_name='PayPal Payment Link'),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='productvariant',
|
||||
name='price_usd',
|
||||
field=models.DecimalField(blank=True, decimal_places=2, help_text='Charged by Stripe. If using a PayPal link, set the PayPal price separately.', max_digits=8, null=True, validators=[django.core.validators.MinValueValidator(Decimal('0.01'))], verbose_name='Price (USD)'),
|
||||
),
|
||||
]
|
||||
+29
-3
@@ -476,6 +476,9 @@ class BookListing(models.Model):
|
||||
cover = art_field(verbose_name='Product image', blank=True)
|
||||
paypal_url = models.URLField('PayPal Payment Link', blank=True, validators=[validate_book_checkout],
|
||||
help_text='Use for a product with no variants. When variants exist, each uses its own link.')
|
||||
price_usd = models.DecimalField('Stripe price (USD)', max_digits=8, decimal_places=2, null=True, blank=True,
|
||||
validators=[MinValueValidator(Decimal('0.50'))], help_text='Charged by Stripe when this product has no variants.')
|
||||
ships = models.BooleanField('Ship this product', default=True, help_text='Collect a shipping address at Stripe Checkout.')
|
||||
visible = models.BooleanField(default=False)
|
||||
|
||||
class Meta:
|
||||
@@ -507,10 +510,10 @@ class ProductVariant(models.Model):
|
||||
option = models.CharField('Edition / size / color', max_length=90, blank=True,
|
||||
help_text='Optional. For example: XL / Black, Signed copy, or Blue pressing.')
|
||||
art = art_field(verbose_name='Variant image', blank=True, help_text='Leave blank to use the main product image.')
|
||||
price_usd = models.DecimalField('Display price (USD)', max_digits=8, decimal_places=2, null=True, blank=True,
|
||||
price_usd = models.DecimalField('Price (USD)', max_digits=8, decimal_places=2, null=True, blank=True,
|
||||
validators=[MinValueValidator(Decimal('0.01'))],
|
||||
help_text='Optional. Enter the same price you set in PayPal; this field does not change the checkout price.')
|
||||
paypal_url = models.URLField('PayPal Payment Link', validators=[validate_book_checkout])
|
||||
help_text='Charged by Stripe. If using a PayPal link, set the PayPal price separately.')
|
||||
paypal_url = models.URLField('PayPal Payment Link', blank=True, validators=[validate_book_checkout])
|
||||
visible = models.BooleanField(default=True)
|
||||
order = models.PositiveSmallIntegerField('Display order', default=0, help_text='Lower numbers appear first.')
|
||||
|
||||
@@ -522,6 +525,29 @@ class ProductVariant(models.Model):
|
||||
return f'{label} · {self.option}' if self.option else label
|
||||
|
||||
|
||||
class ShopOrder(models.Model):
|
||||
class Status(models.TextChoices):
|
||||
OPEN = 'open', 'Awaiting payment'
|
||||
PAID = 'paid', 'Paid'
|
||||
EXPIRED = 'expired', 'Expired'
|
||||
FAILED = 'failed', 'Checkout unavailable'
|
||||
|
||||
reference = models.UUIDField(default=uuid4, unique=True, editable=False)
|
||||
item = models.CharField(max_length=320)
|
||||
amount_cents = models.PositiveIntegerField()
|
||||
livemode = models.BooleanField()
|
||||
status = models.CharField(max_length=10, choices=Status, default=Status.OPEN, db_index=True)
|
||||
stripe_session = models.CharField(max_length=255, unique=True, null=True, blank=True)
|
||||
payment_intent = models.CharField(max_length=255, blank=True)
|
||||
email = models.EmailField(blank=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
paid_at = models.DateTimeField(null=True, blank=True)
|
||||
fulfilled = models.BooleanField(default=False)
|
||||
|
||||
class Meta:
|
||||
ordering = ['-created_at']
|
||||
|
||||
|
||||
class ChapterPurchase(models.Model):
|
||||
user = models.ForeignKey('auth.User', on_delete=models.PROTECT)
|
||||
chapter = models.ForeignKey(Chapter, on_delete=models.PROTECT, related_name='purchases')
|
||||
|
||||
+3
-1
@@ -231,4 +231,6 @@ def books(request):
|
||||
product.store_variants = [v for v in variants if v.visible]
|
||||
product.legacy_checkout = product.paypal_url if not variants else ''
|
||||
groups[product.category]['products'].append(product)
|
||||
return render(request, 'books.html', {'product_groups': [g for g in groups.values() if g['products']]})
|
||||
from .shop_stripe import ready
|
||||
return render(request, 'books.html', {'product_groups': [g for g in groups.values() if g['products']],
|
||||
'stripe_shop_ready': ready()})
|
||||
@@ -0,0 +1,191 @@
|
||||
"""Hosted Stripe checkout for Studio shop orders."""
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
from decimal import Decimal
|
||||
from urllib.parse import urlencode, urlsplit
|
||||
from uuid import UUID
|
||||
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||
from urllib.error import URLError
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import transaction
|
||||
from django.http import Http404, HttpResponse
|
||||
from django.shortcuts import get_object_or_404, redirect, render
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
from django.views.decorators.cache import never_cache
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from django.views.decorators.http import require_POST, require_safe
|
||||
|
||||
from .models import BookListing, ProductVariant, ShopOrder
|
||||
|
||||
|
||||
class CheckoutError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class NoRedirect(HTTPRedirectHandler):
|
||||
def redirect_request(self, *args, **kwargs):
|
||||
return None
|
||||
|
||||
|
||||
def origin():
|
||||
try:
|
||||
url = urlsplit(settings.SLX_STRIPE_ORIGIN)
|
||||
if (url.scheme == 'https' and url.hostname in settings.ALLOWED_HOSTS and url.netloc == url.hostname
|
||||
and url.path in ('', '/') and not url.query and not url.fragment):
|
||||
return f'https://{url.netloc}'
|
||||
except ValueError:
|
||||
pass
|
||||
return ''
|
||||
|
||||
|
||||
def live_mode():
|
||||
return settings.SLX_STRIPE_SECRET_KEY.startswith(('sk_live_', 'rk_live_'))
|
||||
|
||||
|
||||
def ready():
|
||||
return bool(origin() and settings.SLX_STRIPE_WEBHOOK_SECRET.startswith('whsec_') and
|
||||
settings.SLX_STRIPE_SECRET_KEY.startswith(('sk_test_', 'sk_live_', 'rk_test_', 'rk_live_')))
|
||||
|
||||
|
||||
def valid_price(price):
|
||||
return price is not None and price >= Decimal('0.50')
|
||||
|
||||
|
||||
def request_session(order, collect_shipping):
|
||||
params = {
|
||||
'mode': 'payment', 'payment_method_types[0]': 'card',
|
||||
'success_url': origin() + reverse('shop-stripe-receipt', args=[order.reference]),
|
||||
'cancel_url': origin() + reverse('books'),
|
||||
'client_reference_id': str(order.reference),
|
||||
'metadata[slx_shop_order]': str(order.reference),
|
||||
'line_items[0][quantity]': 1,
|
||||
'line_items[0][price_data][currency]': 'usd',
|
||||
'line_items[0][price_data][unit_amount]': order.amount_cents,
|
||||
'line_items[0][price_data][product_data][name]': order.item,
|
||||
}
|
||||
if collect_shipping:
|
||||
countries = [c.strip().upper() for c in settings.SLX_STRIPE_SHIP_COUNTRIES if c.strip()]
|
||||
if not countries or not all(re.fullmatch(r'[A-Z]{2}', country) for country in countries):
|
||||
raise CheckoutError
|
||||
for i, code in enumerate(countries):
|
||||
params[f'shipping_address_collection[allowed_countries][{i}]'] = code
|
||||
request = Request('https://api.stripe.com/v1/checkout/sessions', data=urlencode(params).encode(),
|
||||
headers={'Authorization': 'Bearer ' + settings.SLX_STRIPE_SECRET_KEY,
|
||||
'Idempotency-Key': str(order.reference),
|
||||
'Content-Type': 'application/x-www-form-urlencoded'})
|
||||
try:
|
||||
with build_opener(NoRedirect()).open(request, timeout=8) as response:
|
||||
data = json.load(response)
|
||||
session = data['id']
|
||||
url = urlsplit(data['url'])
|
||||
if not re.fullmatch(r'cs_(test|live)_[A-Za-z0-9_]{1,200}', session):
|
||||
raise CheckoutError
|
||||
if (data.get('livemode') is not order.livemode or url.scheme != 'https'
|
||||
or url.netloc != 'checkout.stripe.com' or not url.path.startswith('/c/')):
|
||||
raise CheckoutError
|
||||
return session, data['url']
|
||||
except (URLError, OSError, ValueError, KeyError, TypeError, AttributeError) as exc:
|
||||
raise CheckoutError from exc
|
||||
|
||||
|
||||
@never_cache
|
||||
@require_POST
|
||||
def checkout(request, product_id, variant_id):
|
||||
if not ready():
|
||||
return render(request, 'shop-order.html', {'unavailable': True}, status=503)
|
||||
product = get_object_or_404(BookListing, pk=product_id, visible=True)
|
||||
if variant_id:
|
||||
variant = get_object_or_404(ProductVariant, pk=variant_id, product=product, visible=True)
|
||||
else:
|
||||
if product.variants.exists():
|
||||
raise Http404
|
||||
variant = None
|
||||
price = variant.price_usd if variant else product.price_usd
|
||||
if not valid_price(price):
|
||||
raise Http404
|
||||
item = f'{product.title} · {variant}' if variant else product.title
|
||||
order = ShopOrder.objects.create(item=item, amount_cents=int(price * 100), livemode=live_mode())
|
||||
try:
|
||||
session, url = request_session(order, product.ships and not (variant and variant.format == ProductVariant.Format.DIGITAL))
|
||||
except CheckoutError:
|
||||
ShopOrder.objects.filter(pk=order.pk, status=ShopOrder.Status.OPEN).update(status=ShopOrder.Status.FAILED)
|
||||
return render(request, 'shop-order.html', {'unavailable': True}, status=502)
|
||||
ShopOrder.objects.filter(pk=order.pk, stripe_session__isnull=True).update(stripe_session=session)
|
||||
return redirect(url)
|
||||
|
||||
|
||||
def valid_signature(body, header):
|
||||
parts = {}
|
||||
for value in header.split(','):
|
||||
key, sep, val = value.partition('=')
|
||||
if sep:
|
||||
parts.setdefault(key, []).append(val)
|
||||
try:
|
||||
ts, = parts['t']
|
||||
if not ts.isascii() or not ts.isdecimal() or len(ts) > 12 or abs(time.time() - int(ts)) > 300:
|
||||
return False
|
||||
except (KeyError, ValueError):
|
||||
return False
|
||||
expected = hmac.new(settings.SLX_STRIPE_WEBHOOK_SECRET.encode(),
|
||||
ts.encode() + b'.' + body, hashlib.sha256).hexdigest()
|
||||
return any(v.isascii() and hmac.compare_digest(expected, v) for v in parts.get('v1', []))
|
||||
|
||||
|
||||
@csrf_exempt
|
||||
@require_POST
|
||||
def webhook(request):
|
||||
if not settings.SLX_STRIPE_WEBHOOK_SECRET.startswith('whsec_'):
|
||||
return HttpResponse(status=503)
|
||||
body = request.body
|
||||
if len(body) > 1024 * 1024 or not valid_signature(body, request.headers.get('Stripe-Signature', '')):
|
||||
return HttpResponse(status=400)
|
||||
try:
|
||||
event = json.loads(body)
|
||||
kind = event['type']
|
||||
if kind not in ('checkout.session.completed', 'checkout.session.expired', 'checkout.session.async_payment_succeeded'):
|
||||
return HttpResponse(status=200)
|
||||
session = event['data']['object']
|
||||
metadata = session.get('metadata') or {}
|
||||
reference = metadata.get('slx_shop_order')
|
||||
if not reference:
|
||||
return HttpResponse(status=200)
|
||||
sid = session['id']
|
||||
if (not re.fullmatch(r'cs_(test|live)_[A-Za-z0-9_]{1,200}', sid)
|
||||
or session.get('client_reference_id') != reference or session.get('mode') != 'payment'):
|
||||
return HttpResponse(status=400)
|
||||
reference = UUID(reference)
|
||||
except (ValueError, KeyError, TypeError, AttributeError):
|
||||
return HttpResponse(status=400)
|
||||
with transaction.atomic():
|
||||
order = ShopOrder.objects.select_for_update().filter(reference=reference).first()
|
||||
if not order:
|
||||
return HttpResponse(status=200)
|
||||
if (event.get('livemode') is not order.livemode or session.get('livemode') is not order.livemode
|
||||
or not sid.startswith('cs_live_' if order.livemode else 'cs_test_')
|
||||
or (order.stripe_session and order.stripe_session != sid)
|
||||
or session.get('currency') != 'usd' or session.get('amount_total') != order.amount_cents):
|
||||
return HttpResponse(status=400)
|
||||
if order.status != ShopOrder.Status.PAID:
|
||||
if kind == 'checkout.session.expired':
|
||||
order.status = ShopOrder.Status.EXPIRED
|
||||
elif session.get('payment_status') == 'paid':
|
||||
order.status = ShopOrder.Status.PAID
|
||||
order.paid_at = timezone.now()
|
||||
order.payment_intent = str(session.get('payment_intent') or '')[:255]
|
||||
details = session.get('customer_details')
|
||||
order.email = str((details.get('email') if isinstance(details, dict) else '') or '')[:254]
|
||||
order.stripe_session = sid
|
||||
order.save(update_fields=['status', 'paid_at', 'payment_intent', 'email', 'stripe_session'])
|
||||
return HttpResponse(status=200)
|
||||
|
||||
|
||||
@never_cache
|
||||
@require_safe
|
||||
def receipt(request, reference):
|
||||
order = get_object_or_404(ShopOrder, reference=reference)
|
||||
return render(request, 'shop-order.html', {'paid': order.status == ShopOrder.Status.PAID})
|
||||
Reference in new issue
Block a user