239 lines
8.9 KiB
Python
239 lines
8.9 KiB
Python
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 catalog.shop_stripe import origin as stripe_origin
|
|
from .models import Order, Product, Subscription
|
|
|
|
|
|
def stripe_ready():
|
|
return bool(settings.SLX_STRIPE_SECRET_KEY and (stripe_origin() or 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='', stripe_live=None):
|
|
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.stripe_live = stripe_live
|
|
order.save(update_fields=['status', 'paid_at', 'gateway_payment_id', 'stripe_live'])
|
|
|
|
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 = stripe_origin() or 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 = stripe_origin() or 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')
|