Configure PayPal integration and cart checkout error display
This commit is contained in:
1 parent
62065828e1
commit
cf07fc5d9b
98 files changed
+1430
-281
No files matched your search
+60
-22
@@ -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):
|
||||
|
||||
Reference in new issue
Block a user