JourneyJoker/payment/models.py
2020-01-26 11:53:25 +01:00

93 lines
3.3 KiB
Python

from django.db.models import Model, ForeignKey, DecimalField, CharField, DecimalField, UUIDField, CASCADE
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.conf import settings
from django.shortcuts import redirect
from django.urls import reverse_lazy
from polymorphic.models import PolymorphicModel
from dbsettings.models import Setting
import stripe
import uuid
from auction.models import Inquiry
PAYMENT_STATUS_AUTHORIZED = -1
PAYMENT_STATUS_SUCCESS = 0
PAYMENT_STATUS_PENDING = 1
PAYMENT_STATUS_FAILURE = 2
PAYMENT_STATUS_REFUND = 3
stripe.api_key = Setting.objects.get(key="stripe.key.secret").value # pylint: disable=no-member
class Payment(PolymorphicModel):
uuid = UUIDField(default=uuid.uuid4, primary_key=True)
content_type = ForeignKey(ContentType, on_delete=CASCADE)
object_id = CharField(max_length=255)
invoice = GenericForeignKey()
def start(self):
raise NotImplementedError("start() not implemented in %s!" % type(self).__name__)
def status(self):
raise NotImplementedError("status() not implemented in %s!" % type(self).__name__)
def capture(self):
return self.status()
def cancel(self):
invoice = self.invoice
self.delete()
return redirect(invoice.get_absolute_url() + "?status=cancelled")
class PaypalPayment(Payment):
pass
class StripePayment(Payment):
session = CharField(max_length=255, blank=True, null=True)
session_status = CharField(max_length=255, blank=True, null=True)
def start(self):
self.session = stripe.checkout.Session.create(
customer_email=self.invoice.user.user.email,
payment_method_types=['card'],
line_items=[{
'name': 'Urlaubsauktion',
'description': 'Einzahlung',
'amount': int(self.invoice.amount * 100),
'currency': self.invoice.currency,
'quantity': 1,
}],
success_url='http://localhost:8000/payment/success?gateway=stripe&session_id={CHECKOUT_SESSION_ID}',
cancel_url='https://localhost:8000/payment/failure?gateway=stripe&session_id={CHECKOUT_SESSION_ID}',
payment_intent_data= {"capture_method": "manual", },
).id
self.save()
return redirect(reverse_lazy("payment:redirect_stripe", args=[self.uuid]))
def capture(self):
session = stripe.checkout.Session.retrieve(self.session)
payment_intent = session.payment_intent
capture = stripe.PaymentIntent.capture(payment_intent)
return PAYMENT_STATUS_SUCCESS if capture.status == "succeeded" else PAYMENT_STATUS_FAILURE
def status(self):
session = stripe.checkout.Session.retrieve(self.session)
payment_intent = stripe.PaymentIntent.retrieve(session.payment_intent)
if payment_intent.status == "processing":
return PAYMENT_STATUS_PENDING
elif payment_intent.status == "succeeded":
return PAYMENT_STATUS_SUCCESS
return PAYMENT_STATUS_FAILURE
class KlarnaPayment(Payment):
pass
class DummyPayment(Payment):
def start(self):
return redirect(reverse_lazy("payment:status"))
def status(self):
return PAYMENT_STATUS_SUCCESS