Skip to content

Instantly share code, notes, and snippets.

@dhruvbaldawa
Created January 31, 2018 05:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhruvbaldawa/84e826234b3bd62892c145092e44f751 to your computer and use it in GitHub Desktop.
Save dhruvbaldawa/84e826234b3bd62892c145092e44f751 to your computer and use it in GitHub Desktop.
class Payment(models.Model):
STATE_CHOICES = (
('started', 'Started'),
('captured', 'Captured'),
('completed', 'Completed'),
# we introduce a new "incomplete" state
('incomplete', 'Incomplete'),
)
def can_complete(self):
# We can complete both captured and incomplete payments
return self.state in ('captured', 'incomplete')
def can_retry(self):
# We can only retry incomplete payments
return self.state == 'incomplete'
def capture(self):
if self.can_capture():
try:
self.contact_payment_gateway()
except PaymentGatewayException:
# We can mark a payment as incomplete if we couldn't
# capture it from the payment gateway
self.state = 'incomplete'
self.save()
return
self.state = 'captured'
self.save()
else:
raise ValueError()
def retry(self):
# We can call retry() to complete the payment if we it is incomplete
if self.can_retry():
self.complete()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment