Configure shop app, admin sidebar, media routing, and Stripe dependencies
This commit is contained in:
commit
93d83a0d63
188 files changed
+9220
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,42 @@
|
||||
from django.contrib import admin
|
||||
from catalog.admin import studio
|
||||
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_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']}),
|
||||
('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']}),
|
||||
]
|
||||
|
||||
|
||||
class OrderItemInline(admin.TabularInline):
|
||||
model = OrderItem
|
||||
extra = 0
|
||||
readonly_fields = ['product', 'title_snapshot', 'unit_price_usd', 'quantity']
|
||||
|
||||
|
||||
@admin.register(Order, site=studio)
|
||||
class OrderAdmin(admin.ModelAdmin):
|
||||
list_display = ['order_id', 'email', 'status', 'gateway', 'total_usd', 'tracking_number', 'created_at']
|
||||
list_filter = ['status', 'gateway', 'created_at']
|
||||
list_editable = ['status', 'tracking_number']
|
||||
search_fields = ['order_id', 'email', 'full_name', 'gateway_session_id', 'gateway_payment_id']
|
||||
readonly_fields = ['order_id', 'user', 'gateway', 'subtotal_usd', 'shipping_usd', 'total_usd', 'gateway_session_id', 'gateway_payment_id', 'paid_at', 'created_at']
|
||||
inlines = [OrderItemInline]
|
||||
|
||||
|
||||
@admin.register(Subscription, site=studio)
|
||||
class SubscriptionAdmin(admin.ModelAdmin):
|
||||
list_display = ['email', 'product', 'status', 'gateway', 'current_period_end', 'created_at']
|
||||
list_filter = ['status', 'gateway', 'product']
|
||||
search_fields = ['email', 'gateway_sub_id', 'gateway_customer_id']
|
||||
readonly_fields = ['sub_id', 'gateway_sub_id', 'gateway_customer_id', 'created_at']
|
||||
@@ -0,0 +1,107 @@
|
||||
# Generated by Django 5.2.19 on 2026-11-22 18:26
|
||||
|
||||
import django.core.validators
|
||||
import django.db.models.deletion
|
||||
import uuid
|
||||
from decimal import Decimal
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Product',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('title', models.CharField(max_length=160)),
|
||||
('slug', models.SlugField(max_length=180, unique=True)),
|
||||
('kind', models.CharField(choices=[('physical', 'Physical Product'), ('digital', 'Digital Download'), ('subscription', 'Recurring Subscription')], default='physical', max_length=20)),
|
||||
('summary', models.CharField(blank=True, max_length=280)),
|
||||
('description', models.TextField(blank=True)),
|
||||
('image', models.ImageField(blank=True, upload_to='shop/products/')),
|
||||
('price_usd', models.DecimalField(decimal_places=2, max_digits=9, validators=[django.core.validators.MinValueValidator(Decimal('0.50'))])),
|
||||
('active', models.BooleanField(default=True)),
|
||||
('featured', models.BooleanField(default=False)),
|
||||
('position', models.PositiveIntegerField(default=0)),
|
||||
('stock', models.PositiveIntegerField(default=0, help_text='Ignored for digital and subscription items.')),
|
||||
('track_stock', models.BooleanField(default=True)),
|
||||
('shipping_usd', models.DecimalField(decimal_places=2, default=Decimal('0.00'), help_text='Flat shipping fee added once if order contains physical items.', max_digits=7)),
|
||||
('digital_file', models.FileField(blank=True, help_text='Private file unlocked after purchase.', upload_to='shop/private_digital/')),
|
||||
('billing_interval', models.CharField(choices=[('month', 'Monthly'), ('year', 'Yearly')], default='month', max_length=10)),
|
||||
('stripe_price_id', models.CharField(blank=True, help_text='Optional Stripe recurring Price ID (price_...). If blank, created dynamically.', max_length=120)),
|
||||
('paypal_plan_id', models.CharField(blank=True, help_text='Required for PayPal recurring subscriptions (P-...).', max_length=120)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
],
|
||||
options={
|
||||
'ordering': ['position', '-created_at'],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='Order',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('order_id', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
|
||||
('email', models.EmailField(max_length=254)),
|
||||
('full_name', models.CharField(blank=True, max_length=160)),
|
||||
('status', models.CharField(choices=[('pending', 'Pending Payment'), ('paid', 'Paid / Processing'), ('shipped', 'Shipped'), ('delivered', 'Delivered'), ('refunded', 'Refunded'), ('canceled', 'Canceled')], default='pending', max_length=20)),
|
||||
('gateway', models.CharField(choices=[('stripe', 'Stripe'), ('paypal', 'PayPal')], max_length=20)),
|
||||
('subtotal_usd', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=10)),
|
||||
('shipping_usd', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=8)),
|
||||
('total_usd', models.DecimalField(decimal_places=2, default=Decimal('0.00'), max_digits=10)),
|
||||
('shipping_line1', models.CharField(blank=True, max_length=200)),
|
||||
('shipping_line2', models.CharField(blank=True, max_length=200)),
|
||||
('shipping_city', models.CharField(blank=True, max_length=120)),
|
||||
('shipping_state', models.CharField(blank=True, max_length=120)),
|
||||
('shipping_postal', models.CharField(blank=True, max_length=40)),
|
||||
('shipping_country', models.CharField(blank=True, max_length=2)),
|
||||
('tracking_number', models.CharField(blank=True, max_length=120)),
|
||||
('gateway_session_id', models.CharField(blank=True, db_index=True, max_length=200)),
|
||||
('gateway_payment_id', models.CharField(blank=True, max_length=200)),
|
||||
('paid_at', models.DateTimeField(blank=True, null=True)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='shop_orders', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'ordering': ['-created_at'],
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='OrderItem',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('title_snapshot', models.CharField(max_length=160)),
|
||||
('unit_price_usd', models.DecimalField(decimal_places=2, max_digits=9)),
|
||||
('quantity', models.PositiveIntegerField(default=1)),
|
||||
('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='items', to='shop.order')),
|
||||
('product', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='shop.product')),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='Subscription',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('sub_id', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
|
||||
('email', models.EmailField(max_length=254)),
|
||||
('gateway', models.CharField(choices=[('stripe', 'Stripe'), ('paypal', 'PayPal')], max_length=20)),
|
||||
('gateway_sub_id', models.CharField(blank=True, db_index=True, max_length=200)),
|
||||
('gateway_customer_id', models.CharField(blank=True, max_length=200)),
|
||||
('status', models.CharField(choices=[('pending', 'Pending'), ('active', 'Active'), ('past_due', 'Past Due'), ('canceled', 'Canceled')], default='pending', max_length=20)),
|
||||
('current_period_end', models.DateTimeField(blank=True, null=True)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('product', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='shop.product')),
|
||||
('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='shop_subscriptions', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'ordering': ['-created_at'],
|
||||
},
|
||||
),
|
||||
]
|
||||
Whitespace-only changes.
+147
@@ -0,0 +1,147 @@
|
||||
import uuid
|
||||
from decimal import Decimal
|
||||
from django.conf import settings
|
||||
from django.core.validators import MinValueValidator
|
||||
from django.db import models
|
||||
from django.utils import timezone
|
||||
|
||||
|
||||
class Product(models.Model):
|
||||
class Kind(models.TextChoices):
|
||||
PHYSICAL = 'physical', 'Physical Product'
|
||||
DIGITAL = 'digital', 'Digital Download'
|
||||
SUBSCRIPTION = 'subscription', 'Recurring Subscription'
|
||||
|
||||
class Interval(models.TextChoices):
|
||||
MONTH = 'month', 'Monthly'
|
||||
YEAR = 'year', 'Yearly'
|
||||
|
||||
title = models.CharField(max_length=160)
|
||||
slug = models.SlugField(max_length=180, unique=True)
|
||||
kind = models.CharField(max_length=20, choices=Kind.choices, default=Kind.PHYSICAL)
|
||||
summary = models.CharField(max_length=280, blank=True)
|
||||
description = models.TextField(blank=True)
|
||||
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)
|
||||
featured = models.BooleanField(default=False)
|
||||
position = models.PositiveIntegerField(default=0)
|
||||
|
||||
# Physical inventory & shipping
|
||||
stock = models.PositiveIntegerField(default=0, help_text='Ignored for digital and subscription items.')
|
||||
track_stock = models.BooleanField(default=True)
|
||||
shipping_usd = models.DecimalField(max_digits=7, decimal_places=2, default=Decimal('0.00'),
|
||||
help_text='Flat shipping fee added once if order contains physical items.')
|
||||
|
||||
# Digital asset (served privately via authenticated/order-token view, never public /media/)
|
||||
digital_file = models.FileField(upload_to='shop/private_digital/', blank=True,
|
||||
help_text='Private file unlocked after purchase.')
|
||||
|
||||
# Subscription gateway plan IDs
|
||||
billing_interval = models.CharField(max_length=10, choices=Interval.choices, default=Interval.MONTH)
|
||||
stripe_price_id = models.CharField(max_length=120, blank=True,
|
||||
help_text='Optional Stripe recurring Price ID (price_...). If blank, created dynamically.')
|
||||
paypal_plan_id = models.CharField(max_length=120, blank=True,
|
||||
help_text='Required for PayPal recurring subscriptions (P-...).')
|
||||
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ['position', '-created_at']
|
||||
|
||||
def __str__(self):
|
||||
return f'{self.title} (${self.price_usd})'
|
||||
|
||||
@property
|
||||
def in_stock(self):
|
||||
if self.kind != self.Kind.PHYSICAL or not self.track_stock:
|
||||
return True
|
||||
return self.stock > 0
|
||||
|
||||
|
||||
class Order(models.Model):
|
||||
class Status(models.TextChoices):
|
||||
PENDING = 'pending', 'Pending Payment'
|
||||
PAID = 'paid', 'Paid / Processing'
|
||||
SHIPPED = 'shipped', 'Shipped'
|
||||
DELIVERED = 'delivered', 'Delivered'
|
||||
REFUNDED = 'refunded', 'Refunded'
|
||||
CANCELED = 'canceled', 'Canceled'
|
||||
|
||||
class Gateway(models.TextChoices):
|
||||
STRIPE = 'stripe', 'Stripe'
|
||||
PAYPAL = 'paypal', 'PayPal'
|
||||
|
||||
order_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name='shop_orders')
|
||||
email = models.EmailField()
|
||||
full_name = models.CharField(max_length=160, blank=True)
|
||||
status = models.CharField(max_length=20, choices=Status.choices, default=Status.PENDING)
|
||||
gateway = models.CharField(max_length=20, choices=Gateway.choices)
|
||||
|
||||
subtotal_usd = models.DecimalField(max_digits=10, decimal_places=2, default=Decimal('0.00'))
|
||||
shipping_usd = models.DecimalField(max_digits=8, decimal_places=2, default=Decimal('0.00'))
|
||||
total_usd = models.DecimalField(max_digits=10, decimal_places=2, default=Decimal('0.00'))
|
||||
|
||||
# Shipping details (populated for physical orders)
|
||||
shipping_line1 = models.CharField(max_length=200, blank=True)
|
||||
shipping_line2 = models.CharField(max_length=200, blank=True)
|
||||
shipping_city = models.CharField(max_length=120, blank=True)
|
||||
shipping_state = models.CharField(max_length=120, blank=True)
|
||||
shipping_postal = models.CharField(max_length=40, blank=True)
|
||||
shipping_country = models.CharField(max_length=2, blank=True)
|
||||
tracking_number = models.CharField(max_length=120, blank=True)
|
||||
|
||||
# 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)
|
||||
paid_at = models.DateTimeField(null=True, blank=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ['-created_at']
|
||||
|
||||
def __str__(self):
|
||||
return f'Order {str(self.order_id)[:8]} ({self.get_status_display()})'
|
||||
|
||||
@property
|
||||
def has_physical(self):
|
||||
return self.items.filter(product__kind=Product.Kind.PHYSICAL).exists()
|
||||
|
||||
|
||||
class OrderItem(models.Model):
|
||||
order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items')
|
||||
product = models.ForeignKey(Product, 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)
|
||||
|
||||
@property
|
||||
def line_total(self):
|
||||
return self.unit_price_usd * self.quantity
|
||||
|
||||
|
||||
class Subscription(models.Model):
|
||||
class Status(models.TextChoices):
|
||||
PENDING = 'pending', 'Pending'
|
||||
ACTIVE = 'active', 'Active'
|
||||
PAST_DUE = 'past_due', 'Past Due'
|
||||
CANCELED = 'canceled', 'Canceled'
|
||||
|
||||
sub_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name='shop_subscriptions')
|
||||
email = models.EmailField()
|
||||
product = models.ForeignKey(Product, on_delete=models.PROTECT)
|
||||
gateway = models.CharField(max_length=20, choices=Order.Gateway.choices)
|
||||
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)
|
||||
current_period_end = models.DateTimeField(null=True, blank=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ['-created_at']
|
||||
|
||||
def __str__(self):
|
||||
return f'{self.email} — {self.product.title} ({self.status})'
|
||||
@@ -0,0 +1,236 @@
|
||||
from decimal import Decimal
|
||||
import json
|
||||
import re
|
||||
from django.conf import settings
|
||||
from django.db import transaction
|
||||
from django.db.models import F
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
import stripe
|
||||
|
||||
from catalog.paypal import CheckoutError, access_token, checkout_origin, request_json, safe_approval_url
|
||||
from .models import Order, Product, Subscription
|
||||
|
||||
|
||||
def stripe_ready():
|
||||
return bool(settings.SLX_STRIPE_SECRET_KEY and checkout_origin())
|
||||
|
||||
|
||||
def paypal_ready():
|
||||
return bool(settings.SLX_PAYPAL_MODE in {'sandbox', 'live'}
|
||||
and settings.SLX_PAYPAL_CLIENT_ID
|
||||
and settings.SLX_PAYPAL_CLIENT_SECRET
|
||||
and checkout_origin())
|
||||
|
||||
|
||||
def fulfill_order(order, payment_id=''):
|
||||
with transaction.atomic():
|
||||
order = Order.objects.select_for_update().get(pk=order.pk)
|
||||
if order.status != Order.Status.PENDING:
|
||||
return order
|
||||
order.status = Order.Status.PAID
|
||||
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'])
|
||||
|
||||
for item in order.items.select_related('product'):
|
||||
prod = item.product
|
||||
if prod.kind == Product.Kind.PHYSICAL and prod.track_stock:
|
||||
Product.objects.filter(pk=prod.pk, stock__gte=item.quantity).update(
|
||||
stock=F('stock') - item.quantity
|
||||
)
|
||||
return order
|
||||
|
||||
|
||||
# --- STRIPE ---
|
||||
|
||||
def create_stripe_order_session(order):
|
||||
stripe.api_key = settings.SLX_STRIPE_SECRET_KEY
|
||||
origin = checkout_origin()
|
||||
line_items = []
|
||||
for item in order.items.select_related('product'):
|
||||
line_items.append({
|
||||
'price_data': {
|
||||
'currency': 'usd',
|
||||
'unit_amount': int(item.unit_price_usd * 100),
|
||||
'product_data': {'name': item.title_snapshot},
|
||||
},
|
||||
'quantity': item.quantity,
|
||||
})
|
||||
if order.shipping_usd > 0:
|
||||
line_items.append({
|
||||
'price_data': {
|
||||
'currency': 'usd',
|
||||
'unit_amount': int(order.shipping_usd * 100),
|
||||
'product_data': {'name': 'Shipping & Handling'},
|
||||
},
|
||||
'quantity': 1,
|
||||
})
|
||||
|
||||
kwargs = {
|
||||
'mode': 'payment',
|
||||
'line_items': line_items,
|
||||
'customer_email': order.email,
|
||||
'client_reference_id': str(order.order_id),
|
||||
'metadata': {'kind': 'order', 'order_id': str(order.order_id)},
|
||||
'success_url': origin + reverse('shop-order-detail', args=[order.order_id]) + '?paid=1',
|
||||
'cancel_url': origin + reverse('shop-cart'),
|
||||
}
|
||||
if order.has_physical:
|
||||
kwargs['shipping_address_collection'] = {'allowed_countries': ['US', 'CA', 'GB', 'AU', 'JP']}
|
||||
|
||||
session = stripe.checkout.Session.create(**kwargs)
|
||||
order.gateway_session_id = session.id
|
||||
order.save(update_fields=['gateway_session_id'])
|
||||
return session.url
|
||||
|
||||
|
||||
def create_stripe_subscription_session(sub):
|
||||
stripe.api_key = settings.SLX_STRIPE_SECRET_KEY
|
||||
origin = checkout_origin()
|
||||
prod = sub.product
|
||||
if prod.stripe_price_id:
|
||||
line_item = {'price': prod.stripe_price_id, 'quantity': 1}
|
||||
else:
|
||||
line_item = {
|
||||
'price_data': {
|
||||
'currency': 'usd',
|
||||
'unit_amount': int(prod.price_usd * 100),
|
||||
'recurring': {'interval': prod.billing_interval},
|
||||
'product_data': {'name': prod.title},
|
||||
},
|
||||
'quantity': 1,
|
||||
}
|
||||
|
||||
session = stripe.checkout.Session.create(
|
||||
mode='subscription',
|
||||
line_items=[line_item],
|
||||
customer_email=sub.email,
|
||||
client_reference_id=str(sub.sub_id),
|
||||
metadata={'kind': 'subscription', 'sub_id': str(sub.sub_id)},
|
||||
subscription_data={'metadata': {'sub_id': str(sub.sub_id)}},
|
||||
success_url= origin + reverse('shop-index') + '?subscribed=1',
|
||||
cancel_url= origin + reverse('shop-product', args=[prod.slug]),
|
||||
)
|
||||
return session.url
|
||||
|
||||
|
||||
# --- PAYPAL ---
|
||||
|
||||
def create_paypal_order(order):
|
||||
mode = settings.SLX_PAYPAL_MODE
|
||||
token = access_token(mode)
|
||||
origin = checkout_origin()
|
||||
shipping_pref = 'GET_FROM_FILE' if order.has_physical else 'NO_SHIPPING'
|
||||
|
||||
result = request_json(
|
||||
mode,
|
||||
'/v2/checkout/orders',
|
||||
token=token,
|
||||
request_id=order.order_id.hex,
|
||||
data={
|
||||
'intent': 'CAPTURE',
|
||||
'purchase_units': [{
|
||||
'reference_id': order.order_id.hex,
|
||||
'description': f'SLUMP X LAND Shop — Order {str(order.order_id)[:8]}',
|
||||
'amount': {
|
||||
'currency_code': 'USD',
|
||||
'value': f'{order.total_usd:.2f}',
|
||||
'breakdown': {
|
||||
'item_total': {'currency_code': 'USD', 'value': f'{order.subtotal_usd:.2f}'},
|
||||
'shipping': {'currency_code': 'USD', 'value': f'{order.shipping_usd:.2f}'},
|
||||
},
|
||||
},
|
||||
}],
|
||||
'payment_source': {
|
||||
'paypal': {
|
||||
'experience_context': {
|
||||
'shipping_preference': shipping_pref,
|
||||
'user_action': 'PAY_NOW',
|
||||
'return_url': origin + reverse('shop-paypal-return', args=[order.order_id]),
|
||||
'cancel_url': origin + reverse('shop-cart'),
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
pp_id = result.get('id')
|
||||
if not isinstance(pp_id, str) or not re.fullmatch(r'[A-Z0-9]{1,64}', pp_id):
|
||||
raise CheckoutError('Invalid PayPal order ID')
|
||||
for link in result.get('links', []):
|
||||
if link.get('rel') in {'payer-action', 'approve'} and safe_approval_url(mode, link.get('href')):
|
||||
order.gateway_session_id = pp_id
|
||||
order.save(update_fields=['gateway_session_id'])
|
||||
return link['href']
|
||||
raise CheckoutError('Missing PayPal approval URL')
|
||||
|
||||
|
||||
def capture_paypal_order(order):
|
||||
mode = settings.SLX_PAYPAL_MODE
|
||||
token = access_token(mode)
|
||||
endpoint = f'/v2/checkout/orders/{order.gateway_session_id}'
|
||||
try:
|
||||
result = request_json(mode, endpoint + '/capture', data={}, token=token,
|
||||
request_id=order.order_id.hex + '-cap')
|
||||
except CheckoutError:
|
||||
result = request_json(mode, endpoint, token=token)
|
||||
|
||||
if result.get('id') != order.gateway_session_id or result.get('status') != 'COMPLETED':
|
||||
raise CheckoutError('PayPal capture incomplete')
|
||||
|
||||
unit = result['purchase_units'][0]
|
||||
capture = unit['payments']['captures'][0]
|
||||
if Decimal(capture['amount']['value']) != order.total_usd:
|
||||
raise CheckoutError('Amount mismatch')
|
||||
|
||||
# Save PayPal shipping address if returned
|
||||
shipping = unit.get('shipping', {})
|
||||
addr = shipping.get('address', {})
|
||||
if addr:
|
||||
order.full_name = shipping.get('name', {}).get('full_name', order.full_name)[:160]
|
||||
order.shipping_line1 = addr.get('address_line_1', '')[:200]
|
||||
order.shipping_line2 = addr.get('address_line_2', '')[:200]
|
||||
order.shipping_city = addr.get('admin_area_2', '')[:120]
|
||||
order.shipping_state = addr.get('admin_area_1', '')[:120]
|
||||
order.shipping_postal = addr.get('postal_code', '')[:40]
|
||||
order.shipping_country = addr.get('country_code', '')[:2]
|
||||
order.save(update_fields=[
|
||||
'full_name', 'shipping_line1', 'shipping_line2',
|
||||
'shipping_city', 'shipping_state', 'shipping_postal', 'shipping_country'
|
||||
])
|
||||
|
||||
return fulfill_order(order, payment_id=capture.get('id', ''))
|
||||
|
||||
|
||||
def create_paypal_subscription(sub):
|
||||
if not sub.product.paypal_plan_id:
|
||||
raise CheckoutError('PayPal Plan ID not configured on this subscription product.')
|
||||
mode = settings.SLX_PAYPAL_MODE
|
||||
token = access_token(mode)
|
||||
origin = checkout_origin()
|
||||
result = request_json(
|
||||
mode,
|
||||
'/v1/billing/subscriptions',
|
||||
token=token,
|
||||
request_id=sub.sub_id.hex,
|
||||
data={
|
||||
'plan_id': sub.product.paypal_plan_id,
|
||||
'custom_id': str(sub.sub_id),
|
||||
'subscriber': {'email_address': sub.email},
|
||||
'application_context': {
|
||||
'user_action': 'SUBSCRIBE_NOW',
|
||||
'return_url': origin + reverse('shop-index') + '?subscribed=1',
|
||||
'cancel_url': origin + reverse('shop-product', args=[sub.product.slug]),
|
||||
},
|
||||
},
|
||||
)
|
||||
pp_sub_id = result.get('id')
|
||||
if not pp_sub_id:
|
||||
raise CheckoutError('Missing PayPal subscription ID')
|
||||
for link in result.get('links', []):
|
||||
if link.get('rel') == 'approve' and safe_approval_url(mode, link.get('href')):
|
||||
sub.gateway_sub_id = pp_sub_id
|
||||
sub.save(update_fields=['gateway_sub_id'])
|
||||
return link['href']
|
||||
raise CheckoutError('Missing PayPal subscription approval link')
|
||||
@@ -0,0 +1,17 @@
|
||||
from django.urls import path
|
||||
from . import views
|
||||
|
||||
urlpatterns = [
|
||||
path('', views.index, name='shop-index'),
|
||||
path('cart/', views.cart_view, name='shop-cart'),
|
||||
path('cart/add/<int:pk>/', views.cart_add, name='shop-cart-add'),
|
||||
path('cart/update/<int:pk>/', views.cart_update, name='shop-cart-update'),
|
||||
path('checkout/', views.checkout_start, name='shop-checkout'),
|
||||
path('subscribe/<slug:slug>/', views.subscribe_start, name='shop-subscribe'),
|
||||
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/paypal/', views.paypal_webhook, name='shop-paypal-webhook'),
|
||||
path('<slug:slug>/', views.product_detail, name='shop-product'),
|
||||
]
|
||||
+326
@@ -0,0 +1,326 @@
|
||||
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')
|
||||
Reference in new issue
Block a user