192 lines
8.2 KiB
Python
192 lines
8.2 KiB
Python
"""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})
|