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
@@ -0,0 +1,234 @@
|
||||
"""Hosted PayPal checkout; no card details pass through SLX."""
|
||||
import base64
|
||||
from decimal import Decimal, InvalidOperation
|
||||
import json
|
||||
import re
|
||||
from urllib.error import URLError
|
||||
from urllib.parse import urlsplit
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.db import transaction
|
||||
from django.db.models import Q
|
||||
from django.http import Http404
|
||||
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.http import require_POST, require_safe
|
||||
|
||||
from .fans import live
|
||||
from .models import BookListing, Chapter, ChapterPurchase
|
||||
|
||||
BASE = {'sandbox': 'https://api-m.sandbox.paypal.com', 'live': 'https://api-m.paypal.com'}
|
||||
HOSTS = {'sandbox': {'www.sandbox.paypal.com', 'sandbox.paypal.com'},
|
||||
'live': {'www.paypal.com', 'paypal.com'}}
|
||||
|
||||
|
||||
class CheckoutError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def checkout_origin():
|
||||
try:
|
||||
origin = urlsplit(settings.SLX_PAYPAL_ORIGIN)
|
||||
except ValueError:
|
||||
return ''
|
||||
if (origin.scheme == 'https' and origin.netloc and origin.hostname in settings.ALLOWED_HOSTS
|
||||
and not origin.username and not origin.password and not origin.query
|
||||
and not origin.fragment and origin.path in ('', '/')):
|
||||
return f'https://{origin.netloc}'
|
||||
return ''
|
||||
|
||||
|
||||
def checkout_ready():
|
||||
return bool(settings.SLX_PAYPAL_MODE in BASE and settings.SLX_PAYPAL_CLIENT_ID
|
||||
and settings.SLX_PAYPAL_CLIENT_SECRET and checkout_origin())
|
||||
|
||||
|
||||
def entitled_chapters(user):
|
||||
qs = live(Chapter)
|
||||
if user.is_staff and user.has_perm('catalog.view_chapter'):
|
||||
return qs
|
||||
free = Q(price_usd__isnull=True) | Q(price_usd=0)
|
||||
if not user.is_authenticated:
|
||||
return qs.filter(free)
|
||||
mode = 'sandbox' if settings.SLX_PAYPAL_MODE == 'sandbox' else 'live'
|
||||
paid = ChapterPurchase.objects.filter(user=user, mode=mode, paid_at__isnull=False, revoked=False)
|
||||
return qs.filter(free | Q(pk__in=paid.values('chapter_id')))
|
||||
|
||||
|
||||
def request_json(mode, endpoint, *, data=None, token=None, request_id=None):
|
||||
headers = {'Accept': 'application/json'}
|
||||
if token:
|
||||
headers['Authorization'] = f'Bearer {token}'
|
||||
else:
|
||||
credentials = f'{settings.SLX_PAYPAL_CLIENT_ID}:{settings.SLX_PAYPAL_CLIENT_SECRET}'.encode()
|
||||
headers['Authorization'] = 'Basic ' + base64.b64encode(credentials).decode()
|
||||
if request_id:
|
||||
headers['PayPal-Request-Id'] = request_id
|
||||
headers['Prefer'] = 'return=representation'
|
||||
if isinstance(data, dict):
|
||||
headers['Content-Type'] = 'application/json'
|
||||
data = json.dumps(data).encode()
|
||||
elif data is not None:
|
||||
headers['Content-Type'] = 'application/x-www-form-urlencoded'
|
||||
req = Request(BASE[mode] + endpoint, data=data, headers=headers)
|
||||
try:
|
||||
with urlopen(req, timeout=10) as response:
|
||||
result = json.loads(response.read())
|
||||
if not isinstance(result, dict):
|
||||
raise ValueError
|
||||
return result
|
||||
except (URLError, OSError, ValueError) as exc:
|
||||
raise CheckoutError from exc
|
||||
|
||||
|
||||
def access_token(mode):
|
||||
result = request_json(mode, '/v1/oauth2/token', data=b'grant_type=client_credentials')
|
||||
token = result.get('access_token')
|
||||
if not isinstance(token, str) or not token:
|
||||
raise CheckoutError
|
||||
return token
|
||||
|
||||
|
||||
def safe_approval_url(mode, url):
|
||||
if not isinstance(url, str) or len(url) > 500:
|
||||
return False
|
||||
try:
|
||||
parts = urlsplit(url)
|
||||
return parts.scheme == 'https' and parts.netloc.lower() in HOSTS[mode]
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def create_order(row):
|
||||
token = access_token(row.mode)
|
||||
callback = checkout_origin() + reverse('paypal-return', args=[row.checkout_id])
|
||||
result = request_json(row.mode, '/v2/checkout/orders', token=token, request_id=row.checkout_id.hex,
|
||||
data={
|
||||
'intent': 'CAPTURE',
|
||||
'purchase_units': [{
|
||||
'reference_id': row.checkout_id.hex,
|
||||
'description': f'SLUMP X LAND — Chapter {row.chapter.number}',
|
||||
'amount': {'currency_code': 'USD', 'value': str(row.amount)},
|
||||
}],
|
||||
'payment_source': {'paypal': {'experience_context': {
|
||||
'shipping_preference': 'NO_SHIPPING', 'user_action': 'PAY_NOW',
|
||||
'return_url': callback, 'cancel_url': checkout_origin() + reverse('chapter', args=[row.chapter.number]),
|
||||
}}},
|
||||
})
|
||||
order = result.get('id')
|
||||
if not isinstance(order, str) or not re.fullmatch(r'[A-Z0-9]{1,64}', order):
|
||||
raise CheckoutError
|
||||
for link in result.get('links', []):
|
||||
if link.get('rel') in {'payer-action', 'approve'} and safe_approval_url(row.mode, link.get('href')):
|
||||
return order, link['href']
|
||||
raise CheckoutError
|
||||
|
||||
|
||||
def checked_capture(row, result):
|
||||
if result.get('id') != row.paypal_order_id or result.get('status') != 'COMPLETED':
|
||||
raise CheckoutError
|
||||
try:
|
||||
unit, = result['purchase_units']
|
||||
capture, = unit['payments']['captures']
|
||||
amount = capture['amount']
|
||||
capture_id = capture['id']
|
||||
if (unit.get('reference_id') == row.checkout_id.hex
|
||||
and capture['status'] == 'COMPLETED' and amount['currency_code'] == 'USD'
|
||||
and Decimal(amount['value']) == row.amount
|
||||
and re.fullmatch(r'[A-Z0-9]{1,64}', capture_id)):
|
||||
return capture_id
|
||||
except (KeyError, TypeError, ValueError, InvalidOperation):
|
||||
pass
|
||||
raise CheckoutError
|
||||
|
||||
|
||||
def capture_order(row):
|
||||
token = access_token(row.mode)
|
||||
endpoint = '/v2/checkout/orders/' + row.paypal_order_id
|
||||
try:
|
||||
result = request_json(row.mode, endpoint + '/capture', data={}, token=token,
|
||||
request_id=row.checkout_id.hex + '-capture')
|
||||
except CheckoutError:
|
||||
# A response can be lost after PayPal captures the order. Check the same order, never charge again.
|
||||
result = request_json(row.mode, endpoint, token=token)
|
||||
return checked_capture(row, result)
|
||||
|
||||
|
||||
@require_POST
|
||||
@login_required
|
||||
@never_cache
|
||||
def start(request, number):
|
||||
chapter = get_object_or_404(live(Chapter), number=number, price_usd__gt=0, publisher_url='')
|
||||
if entitled_chapters(request.user).filter(pk=chapter.pk).exists():
|
||||
return redirect('chapter', number=number)
|
||||
if not checkout_ready():
|
||||
raise Http404
|
||||
row, _ = ChapterPurchase.objects.get_or_create(user=request.user, chapter=chapter,
|
||||
mode=settings.SLX_PAYPAL_MODE, defaults={'amount': chapter.price_usd})
|
||||
try:
|
||||
with transaction.atomic():
|
||||
row = ChapterPurchase.objects.select_for_update().get(pk=row.pk)
|
||||
if row.revoked:
|
||||
return render(request, 'paypal-result.html', {'purchase': row, 'revoked': True}, status=403)
|
||||
if row.paid_at:
|
||||
return redirect('chapter', number=number)
|
||||
if not row.paypal_order_id:
|
||||
row.paypal_order_id, row.approval_url = create_order(row)
|
||||
row.save(update_fields=['paypal_order_id', 'approval_url'])
|
||||
if not safe_approval_url(row.mode, row.approval_url):
|
||||
raise CheckoutError
|
||||
return redirect(row.approval_url)
|
||||
except CheckoutError:
|
||||
return render(request, 'paypal-result.html', {'purchase': row, 'start_failed': True}, status=502)
|
||||
|
||||
|
||||
@require_safe
|
||||
@login_required
|
||||
@never_cache
|
||||
def returned(request, checkout_id):
|
||||
row = get_object_or_404(ChapterPurchase, checkout_id=checkout_id, user=request.user,
|
||||
paypal_order_id=request.GET.get('token', '')[:64])
|
||||
if not row.paypal_order_id:
|
||||
raise Http404
|
||||
if row.paid_at and not row.revoked:
|
||||
return redirect('chapter', number=row.chapter.number)
|
||||
return render(request, 'paypal-result.html', {'purchase': row, 'revoked': row.revoked})
|
||||
|
||||
|
||||
@require_POST
|
||||
@login_required
|
||||
@never_cache
|
||||
def finish(request, checkout_id):
|
||||
try:
|
||||
with transaction.atomic():
|
||||
row = get_object_or_404(ChapterPurchase.objects.select_for_update(),
|
||||
checkout_id=checkout_id, user=request.user)
|
||||
if row.revoked:
|
||||
return render(request, 'paypal-result.html', {'purchase': row, 'revoked': True}, status=403)
|
||||
if row.paid_at:
|
||||
return redirect('chapter', number=row.chapter.number)
|
||||
if not row.paypal_order_id or not checkout_ready() or row.mode != settings.SLX_PAYPAL_MODE:
|
||||
raise Http404
|
||||
get_object_or_404(live(Chapter), pk=row.chapter_id, price_usd__gt=0, publisher_url='')
|
||||
row.capture_id = capture_order(row)
|
||||
row.paid_at = timezone.now()
|
||||
row.save(update_fields=['capture_id', 'paid_at'])
|
||||
except CheckoutError:
|
||||
return render(request, 'paypal-result.html', {'purchase': row, 'verify_failed': True}, status=502)
|
||||
return redirect('chapter', number=row.chapter.number)
|
||||
|
||||
|
||||
@require_safe
|
||||
def books(request):
|
||||
listings = BookListing.objects.filter(visible=True).prefetch_related('variants')
|
||||
groups = {key: {'key': key, 'name': label, 'products': []} for key, label in BookListing.Category.choices}
|
||||
for product in listings:
|
||||
variants = list(product.variants.all())
|
||||
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']]})
|
||||
Reference in new issue
Block a user