-
Notifications
You must be signed in to change notification settings - Fork 5
/
models.py
722 lines (618 loc) · 32.5 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from decimal import Decimal
from time import sleep
import simplejson as json
import six
import stripe
from dateutil.relativedelta import relativedelta
from django import dispatch
from django.conf import settings
from django.contrib.contenttypes import fields as generic
from django.contrib.contenttypes.models import ContentType
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.utils import dateformat, timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from jsonfield import JSONField
from aa_stripe.exceptions import (StripeCouponAlreadyExists, StripeMethodNotAllowed, StripeWebhookAlreadyParsed,
StripeWebhookParseError)
from aa_stripe.settings import stripe_settings
from aa_stripe.signals import stripe_charge_card_exception, stripe_charge_succeeded
from aa_stripe.utils import SafeDeleteManager, SafeDeleteModel, timestamp_to_timezone_aware_date
USER_MODEL = getattr(settings, "STRIPE_USER_MODEL", settings.AUTH_USER_MODEL)
# signals
webhook_pre_parse = dispatch.Signal(providing_args=["instance", "event_type", "event_model", "event_action"])
class StripeBasicModel(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
stripe_response = JSONField()
class Meta:
abstract = True
@python_2_unicode_compatible
class StripeCustomer(StripeBasicModel):
user = models.ForeignKey(USER_MODEL, on_delete=models.CASCADE, related_name='stripe_customers')
stripe_js_response = JSONField()
stripe_customer_id = models.CharField(max_length=255, db_index=True)
default_card = models.ForeignKey("StripeCard", null=True, blank=True, on_delete=models.PROTECT)
is_active = models.BooleanField(default=True)
is_created_at_stripe = models.BooleanField(default=False)
def __str__(self):
return self.user.email
def create_at_stripe(self):
if self.is_created_at_stripe:
raise StripeMethodNotAllowed()
stripe.api_key = stripe_settings.API_KEY
customer = stripe.Customer.create(
source=self.stripe_js_response["id"],
description="{user} id: {user.id}".format(user=self.user)
)
self.stripe_customer_id = customer["id"]
self.stripe_response = customer
self.is_created_at_stripe = True
self.save()
return self
@classmethod
def get_latest_active_customer_for_user(cls, user):
"""Returns last active stripe customer for user"""
customer = cls.objects.filter(user_id=user.id, is_active=True).last()
return customer
class Meta:
ordering = ["id"]
@python_2_unicode_compatible
class StripeCard(SafeDeleteModel, StripeBasicModel):
customer = models.ForeignKey("StripeCustomer", on_delete=models.CASCADE)
stripe_card_id = models.CharField(max_length=255, db_index=True, help_text=_("Unique card id in Stripe"))
stripe_js_response = JSONField()
last4 = models.CharField(max_length=4, help_text=_("Last 4 digits of the card"))
exp_month = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(12)],
help_text=_("Two digit number representing the card’s expiration month"))
exp_year = models.PositiveIntegerField(validators=[MinValueValidator(1900)],
help_text=_("Four digit number representing the card’s expiration year"))
is_created_at_stripe = models.BooleanField(default=False)
objects = SafeDeleteManager()
def __str__(self):
return self.stripe_card_id
def _retrieve_from_stripe(self, set_deleted=False):
"""
Retrieve card from Stripe
Will set StripeCard.is_deleted to True if card could not be fetched and the set_deleted parameter is True,
although StripeCard.save() method will not be executed.
"""
stripe.api_key = stripe_settings.API_KEY
try:
customer = stripe.Customer.retrieve(self.customer.stripe_customer_id)
return customer.sources.retrieve(self.stripe_card_id)
except stripe.error.InvalidRequestError: # means that the card is not available - does not exist
if set_deleted:
self.is_deleted = True
def _set_fields_from_stripe_object(self, stripe_object):
self.stripe_card_id = stripe_object["id"]
self.last4 = stripe_object["last4"]
self.exp_month = stripe_object["exp_month"]
self.exp_year = stripe_object["exp_year"]
self.stripe_response = stripe_object
def create_at_stripe(self):
if self.is_created_at_stripe:
raise StripeMethodNotAllowed()
stripe.api_key = stripe_settings.API_KEY
customer = stripe.Customer.retrieve(self.customer.stripe_customer_id)
card = customer.sources.create(source=self.stripe_js_response["source"])
return self.update_from_stripe_card(card)
def update_from_stripe_card(self, card):
self._set_fields_from_stripe_object(card)
self.is_created_at_stripe = True
self.save()
return self
def update_at_stripe(self, stripe_token, set_default):
is_default = self.customer.default_card.pk is self.pk
# When the card is not the default card we need to change
# the default_source attribute before setting the source attribute on customer
# because setting source attribute will overwrite the default_source
# and we do not allow unsetting the default card hence
# we overwrite set_default here if card is default
set_default = is_default if not set_default else set_default
stripe.api_key = stripe_settings.API_KEY
customer = stripe.Customer.retrieve(self.customer.stripe_customer_id)
# When a card is updated with setting source_token to source field on customer
# Stripe is genereating new card id for the card
new_card_id = None
if not is_default and set_default:
customer.default_source = self.stripe_card_id
customer.save()
customer.source = stripe_token
customer.save()
new_card_id = customer.default_source
else:
if is_default:
customer.source = stripe_token
customer.save()
new_card_id = customer.default_source
else:
original_default_source = customer.default_source
customer.default_source = self.stripe_card_id
customer.save()
customer.source = stripe_token
customer.save()
new_card_id = customer.default_source
customer.default_source = original_default_source
customer.save()
updated_card = customer.sources.retrieve(new_card_id)
self.stripe_card_id = updated_card["id"]
self.last4 = updated_card["last4"]
self.exp_month = updated_card["exp_month"]
self.exp_year = updated_card["exp_year"]
self.stripe_response = updated_card
self.save()
if not is_default and set_default:
self.customer.default_card = self
self.customer.save()
return self
def refresh_from_stripe(self):
card = self._retrieve_from_stripe(True)
if card:
self.last4 = card["last4"]
self.exp_month = card["exp_month"]
self.exp_year = card["exp_year"]
self.stripe_response = card
self.is_created_at_stripe = True
return not self.is_deleted
def delete(self, *args, **kwargs):
card = self._retrieve_from_stripe(set_deleted=True)
if card:
card.delete()
self.is_deleted = True
self.save()
return 0, {self._meta.label: 0}
@python_2_unicode_compatible
class StripeCoupon(SafeDeleteModel, StripeBasicModel):
# fields that are fetched from Stripe API
STRIPE_FIELDS = {
"amount_off", "currency", "duration", "duration_in_months", "livemode", "max_redemptions",
"percent_off", "redeem_by", "times_redeemed", "valid", "metadata", "created"
}
DURATION_FOREVER = "forever"
DURATION_ONCE = "once"
DURATION_REPEATING = "repeating"
DURATION_CHOICES = (
(DURATION_FOREVER, DURATION_FOREVER),
(DURATION_ONCE, DURATION_ONCE),
(DURATION_REPEATING, DURATION_REPEATING)
)
# choices must be lowercase, because that is how Stripe API returns currency
CURRENCY_CHOICES = (
('usd', 'USD'), ('aed', 'AED'), ('afn', 'AFN'), ('all', 'ALL'), ('amd', 'AMD'), ('ang', 'ANG'), ('aoa', 'AOA'),
('ars', 'ARS'), ('aud', 'AUD'), ('awg', 'AWG'), ('azn', 'AZN'), ('bam', 'BAM'), ('bbd', 'BBD'), ('bdt', 'BDT'),
('bgn', 'BGN'), ('bif', 'BIF'), ('bmd', 'BMD'), ('bnd', 'BND'), ('bob', 'BOB'), ('brl', 'BRL'), ('bsd', 'BSD'),
('bwp', 'BWP'), ('bzd', 'BZD'), ('cad', 'CAD'), ('cdf', 'CDF'), ('chf', 'CHF'), ('clp', 'CLP'), ('cny', 'CNY'),
('cop', 'COP'), ('crc', 'CRC'), ('cve', 'CVE'), ('czk', 'CZK'), ('djf', 'DJF'), ('dkk', 'DKK'), ('dop', 'DOP'),
('dzd', 'DZD'), ('egp', 'EGP'), ('etb', 'ETB'), ('eur', 'EUR'), ('fjd', 'FJD'), ('fkp', 'FKP'), ('gbp', 'GBP'),
('gel', 'GEL'), ('gip', 'GIP'), ('gmd', 'GMD'), ('gnf', 'GNF'), ('gtq', 'GTQ'), ('gyd', 'GYD'), ('hkd', 'HKD'),
('hnl', 'HNL'), ('hrk', 'HRK'), ('htg', 'HTG'), ('huf', 'HUF'), ('idr', 'IDR'), ('ils', 'ILS'), ('inr', 'INR'),
('isk', 'ISK'), ('jmd', 'JMD'), ('jpy', 'JPY'), ('kes', 'KES'), ('kgs', 'KGS'), ('khr', 'KHR'), ('kmf', 'KMF'),
('krw', 'KRW'), ('kyd', 'KYD'), ('kzt', 'KZT'), ('lak', 'LAK'), ('lbp', 'LBP'), ('lkr', 'LKR'), ('lrd', 'LRD'),
('lsl', 'LSL'), ('mad', 'MAD'), ('mdl', 'MDL'), ('mga', 'MGA'), ('mkd', 'MKD'), ('mmk', 'MMK'), ('mnt', 'MNT'),
('mop', 'MOP'), ('mro', 'MRO'), ('mur', 'MUR'), ('mvr', 'MVR'), ('mwk', 'MWK'), ('mxn', 'MXN'), ('myr', 'MYR'),
('mzn', 'MZN'), ('nad', 'NAD'), ('ngn', 'NGN'), ('nio', 'NIO'), ('nok', 'NOK'), ('npr', 'NPR'), ('nzd', 'NZD'),
('pab', 'PAB'), ('pen', 'PEN'), ('pgk', 'PGK'), ('php', 'PHP'), ('pkr', 'PKR'), ('pln', 'PLN'), ('pyg', 'PYG'),
('qar', 'QAR'), ('ron', 'RON'), ('rsd', 'RSD'), ('rub', 'RUB'), ('rwf', 'RWF'), ('sar', 'SAR'), ('sbd', 'SBD'),
('scr', 'SCR'), ('sek', 'SEK'), ('sgd', 'SGD'), ('shp', 'SHP'), ('sll', 'SLL'), ('sos', 'SOS'), ('srd', 'SRD'),
('std', 'STD'), ('svc', 'SVC'), ('szl', 'SZL'), ('thb', 'THB'), ('tjs', 'TJS'), ('top', 'TOP'), ('try', 'TRY'),
('ttd', 'TTD'), ('twd', 'TWD'), ('tzs', 'TZS'), ('uah', 'UAH'), ('ugx', 'UGX'), ('uyu', 'UYU'), ('uzs', 'UZS'),
('vnd', 'VND'), ('vuv', 'VUV'), ('wst', 'WST'), ('xaf', 'XAF'), ('xcd', 'XCD'), ('xof', 'XOF'), ('xpf', 'XPF'),
('yer', 'YER'), ('zar', 'ZAR'), ('zmw', 'ZMW')
)
coupon_id = models.CharField(max_length=255, help_text=_("Identifier for the coupon"))
amount_off = models.DecimalField(
blank=True, null=True, decimal_places=2, max_digits=10,
help_text=_("Amount (in the currency specified) that will be taken off the subtotal of any invoices for this"
"customer."))
currency = models.CharField(
max_length=3, choices=CURRENCY_CHOICES, blank=True, null=True,
help_text=_("If amount_off has been set, the three-letter ISO code for the currency of the amount to take "
"off."))
duration = models.CharField(
max_length=255, choices=DURATION_CHOICES,
help_text=_("Describes how long a customer who applies this coupon will get the discount."))
duration_in_months = models.PositiveIntegerField(
blank=True, null=True, help_text=_("If duration is repeating, the number of months the coupon applies. "
"Null if coupon duration is forever or once."))
livemode = models.BooleanField(
default=False, help_text=_("Flag indicating whether the object exists in live mode or test mode."))
max_redemptions = models.PositiveIntegerField(
blank=True, null=True,
help_text=_("Maximum number of times this coupon can be redeemed, in total, before it is no longer valid."))
metadata = JSONField(help_text=_("Set of key/value pairs that you can attach to an object. It can be useful for "
"storing additional information about the object in a structured format."))
percent_off = models.PositiveIntegerField(
blank=True, null=True,
help_text=_("Percent that will be taken off the subtotal of any invoicesfor this customer for the duration of "
"the coupon. For example, a coupon with percent_off of 50 will make a $100 invoice $50 instead."))
redeem_by = models.DateTimeField(
blank=True, null=True, help_text=_("Date after which the coupon can no longer be redeemed."))
times_redeemed = models.PositiveIntegerField(
default=0, help_text=_("Number of times this coupon has been applied to a customer."))
valid = models.BooleanField(
default=False,
help_text=_("Taking account of the above properties, whether this coupon can still be applied to a customer."))
created = models.DateTimeField()
is_created_at_stripe = models.BooleanField(default=False)
objects = SafeDeleteManager()
def __init__(self, *args, **kwargs):
super(StripeCoupon, self).__init__(*args, **kwargs)
self._previous_is_deleted = self.is_deleted
def __str__(self):
return self.coupon_id
def update_from_stripe_data(self, stripe_coupon, exclude_fields=None, commit=True):
"""
Update StripeCoupon object with data from stripe.Coupon without calling stripe.Coupon.retrieve.
To only update the object, set the commit param to False.
Returns the number of rows altered or None if commit is False.
"""
fields_to_update = self.STRIPE_FIELDS - set(exclude_fields or [])
update_data = {key: stripe_coupon[key] for key in fields_to_update}
for field in ["created", "redeem_by"]:
if update_data.get(field):
update_data[field] = timestamp_to_timezone_aware_date(update_data[field])
if update_data.get("amount_off"):
update_data["amount_off"] = Decimal(update_data["amount_off"]) / 100
# also make sure the object is up to date (without the need to call database)
for key, value in six.iteritems(update_data):
setattr(self, key, value)
if commit:
return StripeCoupon.objects.filter(pk=self.pk).update(**update_data)
def save(self, force_retrieve=False, *args, **kwargs):
"""
Use the force_retrieve parameter to create a new StripeCoupon object from an existing coupon created at Stripe
API or update the local object with data fetched from Stripe.
"""
stripe.api_key = stripe_settings.API_KEY
if self._previous_is_deleted != self.is_deleted and self.is_deleted:
try:
stripe_coupon = stripe.Coupon.retrieve(self.coupon_id)
# make sure to delete correct coupon
if self.created == timestamp_to_timezone_aware_date(stripe_coupon["created"]):
stripe_coupon.delete()
except stripe.error.InvalidRequestError:
# means that the coupon has already been removed from stripe
pass
return super(StripeCoupon, self).save(*args, **kwargs)
if self.pk or force_retrieve:
try:
stripe_coupon = stripe.Coupon.retrieve(self.coupon_id)
if not force_retrieve:
stripe_coupon.metadata = self.metadata
stripe_coupon.save()
if force_retrieve:
# make sure we are not creating a duplicate
coupon_qs = StripeCoupon.objects.filter(coupon_id=self.coupon_id)
if coupon_qs.filter(created=timestamp_to_timezone_aware_date(stripe_coupon["created"])).exists():
raise StripeCouponAlreadyExists
# all old coupons should be deleted
for coupon in coupon_qs:
coupon.is_deleted = True
super(StripeCoupon, coupon).save() # use super save() to call pre/post save signals
# update all fields in the local object in case someone tried to change them
self.update_from_stripe_data(stripe_coupon, exclude_fields=["metadata"] if not force_retrieve else [])
self.stripe_response = stripe_coupon
except stripe.error.InvalidRequestError:
if force_retrieve:
raise
self.is_deleted = True
else:
self.stripe_response = stripe.Coupon.create(
id=self.coupon_id,
duration=self.duration,
amount_off=int(self.amount_off * 100) if self.amount_off else None,
currency=self.currency,
duration_in_months=self.duration_in_months,
max_redemptions=self.max_redemptions,
metadata=self.metadata,
percent_off=self.percent_off,
redeem_by=int(dateformat.format(self.redeem_by, "U")) if self.redeem_by else None
)
# stripe will generate coupon_id if none was specified in the request
if not self.coupon_id:
self.coupon_id = self.stripe_response["id"]
self.created = timestamp_to_timezone_aware_date(self.stripe_response["created"])
# for future
self.is_created_at_stripe = True
return super(StripeCoupon, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
self.is_deleted = True
self.save()
return 0, {self._meta.label: 0}
class StripeCharge(StripeBasicModel):
user = models.ForeignKey(USER_MODEL, on_delete=models.CASCADE, related_name='stripe_charges')
customer = models.ForeignKey(StripeCustomer, on_delete=models.SET_NULL, null=True)
amount = models.IntegerField(null=True, help_text=_("in cents"))
is_charged = models.BooleanField(default=False)
is_refunded = models.BooleanField(default=False)
# if True, it will not be triggered through stripe_charge command
is_manual_charge = models.BooleanField(default=False)
charge_attempt_failed = models.BooleanField(default=False)
stripe_charge_id = models.CharField(max_length=255, blank=True, db_index=True)
stripe_refund_id = models.CharField(max_length=255, blank=True, db_index=True)
description = models.CharField(max_length=255, help_text=_("Description sent to Stripe"))
comment = models.CharField(max_length=255, help_text=_("Comment for internal information"))
content_type = models.ForeignKey(ContentType, null=True, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField(null=True, db_index=True)
source = generic.GenericForeignKey('content_type', 'object_id')
def charge(self):
self.refresh_from_db() # to minimize the chance of double charging
if self.is_charged:
raise StripeMethodNotAllowed("Already charged.")
stripe.api_key = stripe_settings.API_KEY
customer = StripeCustomer.get_latest_active_customer_for_user(self.user)
self.customer = customer
if customer and customer.default_card:
try:
stripe_charge = stripe.Charge.create(
amount=self.amount,
currency="usd",
source=customer.default_card.stripe_card_id,
description=self.description
)
except stripe.error.CardError as e:
self.charge_attempt_failed = True
self.is_charged = False
self.save()
stripe_charge_card_exception.send(sender=StripeCharge, instance=self, exception=e)
return # just exit.
except stripe.error.StripeError:
self.is_charged = False
self.save()
raise
self.stripe_charge_id = stripe_charge["id"]
self.stripe_response = stripe_charge
self.is_charged = True
self.save()
stripe_charge_succeeded.send(sender=StripeCharge, instance=self)
return stripe_charge
def refund(self):
stripe.api_key = stripe_settings.API_KEY
if not self.is_charged:
raise StripeMethodNotAllowed("Cannot refund not charged transaction.")
if self.is_refunded:
raise StripeMethodNotAllowed("Already refunded.")
stripe_refund = stripe.Refund.create(charge=self.stripe_charge_id)
self.is_refunded = True
self.stripe_refund_id = stripe_refund["id"]
self.save()
class StripeSubscriptionPlan(StripeBasicModel):
INTERVAL_DAY = "day"
INTERVAL_WEEK = "week"
INTERVAL_MONTH = "month"
INTERVAL_YEAR = "year"
INTERVAL_CHOICES = (
(INTERVAL_DAY, INTERVAL_DAY),
(INTERVAL_WEEK, INTERVAL_WEEK),
(INTERVAL_MONTH, INTERVAL_MONTH),
(INTERVAL_YEAR, INTERVAL_YEAR),
)
is_created_at_stripe = models.BooleanField(default=False)
source = JSONField(blank=True, help_text=_("Source of the plan, ie: {\"prescription\": 1}"))
amount = models.BigIntegerField(help_text=_("In cents. More: https://stripe.com/docs/api#create_plan-amount"))
currency = models.CharField(
max_length=3, help_text=_("3 letter ISO code, default USD, https://stripe.com/docs/api#create_plan-currency"),
default="USD")
name = models.CharField(
max_length=255, help_text=_("Name of the plan, to be displayed on invoices and in the web interface."))
interval = models.CharField(
max_length=10, help_text=_("Specifies billing frequency. Either day, week, month or year."),
choices=INTERVAL_CHOICES)
interval_count = models.IntegerField(default=1, validators=[MinValueValidator(1)])
metadata = JSONField(help_text=_("A set of key/value pairs that you can attach to a plan object. It can be useful"
" for storing additional information about the plan in a structured format."))
statement_descriptor = models.CharField(
max_length=22, help_text=_("An arbitrary string to be displayed on your customer’s credit card statement."),
blank=True)
trial_period_days = models.IntegerField(
default=0, validators=[MinValueValidator(0)],
help_text=_("Specifies a trial period in (an integer number of) days. If you include a trial period,"
" the customer won’t be billed for the first time until the trial period ends. If the customer "
"cancels before the trial period is over, she’ll never be billed at all."))
def create_at_stripe(self):
if self.is_created_at_stripe:
raise StripeMethodNotAllowed()
stripe.api_key = stripe_settings.API_KEY
try:
plan = stripe.Plan.create(
id=self.id,
amount=self.amount,
currency=self.currency,
interval=self.interval,
interval_count=self.interval_count,
name=self.name,
metadata=self.metadata,
statement_descriptor=self.statement_descriptor,
trial_period_days=self.trial_period_days
)
except stripe.error.StripeError:
self.is_created_at_stripe = False
self.save()
raise
self.stripe_response = plan
self.is_created_at_stripe = True
self.save()
return plan
class StripeSubscription(StripeBasicModel):
STATUS_TRIAL = "trialing"
STATUS_ACTIVE = "active"
STATUS_PAST_DUE = "past_due"
STATUS_CANCELED = "canceled"
STATUS_UNPAID = "unpaid"
STATUS_CHOICES = (
(STATUS_TRIAL, STATUS_TRIAL),
(STATUS_ACTIVE, STATUS_ACTIVE),
(STATUS_PAST_DUE, STATUS_PAST_DUE),
(STATUS_CANCELED, STATUS_CANCELED),
(STATUS_UNPAID, STATUS_UNPAID),
)
stripe_subscription_id = models.CharField(max_length=255, blank=True, db_index=True)
is_created_at_stripe = models.BooleanField(default=False)
plan = models.ForeignKey(StripeSubscriptionPlan, on_delete=models.CASCADE)
user = models.ForeignKey(USER_MODEL, on_delete=models.CASCADE, related_name="stripe_subscriptions")
customer = models.ForeignKey(StripeCustomer, on_delete=models.SET_NULL, null=True)
status = models.CharField(
max_length=255, help_text="https://stripe.com/docs/api/python#subscription_object-status, "
"empty if not sent created at stripe", blank=True, choices=STATUS_CHOICES)
metadata = JSONField(help_text="https://stripe.com/docs/api/python#create_subscription-metadata")
tax_percent = models.DecimalField(
default=0, validators=[MinValueValidator(0), MaxValueValidator(100)], decimal_places=2, max_digits=3,
help_text="https://stripe.com/docs/api/python#subscription_object-tax_percent")
# application_fee_percent = models.DecimalField(
# default=0, validators=[MinValueValidator(0), MaxValueValidator(100)], decimal_places=2, max_digits=3,
# help_text="https://stripe.com/docs/api/python#create_subscription-application_fee_percent")
coupon = models.ForeignKey(
StripeCoupon, blank=True, null=True, on_delete=models.SET_NULL,
help_text="https://stripe.com/docs/api/python#create_subscription-coupon")
end_date = models.DateField(null=True, blank=True, db_index=True)
canceled_at = models.DateTimeField(null=True, blank=True, db_index=True)
at_period_end = models.BooleanField(default=False)
def create_at_stripe(self):
if self.is_created_at_stripe:
raise StripeMethodNotAllowed()
stripe.api_key = stripe_settings.API_KEY
customer = StripeCustomer.get_latest_active_customer_for_user(self.user)
if customer:
data = {
"customer": customer.stripe_customer_id,
"plan": self.plan.id,
"metadata": self.metadata,
"tax_percent": self.tax_percent,
}
if self.coupon:
data["coupon"] = self.coupon.coupon_id
try:
subscription = stripe.Subscription.create(**data)
except stripe.error.StripeError:
self.is_created_at_stripe = False
self.save()
raise
self.set_stripe_data(subscription)
return subscription
def set_stripe_data(self, subscription):
self.stripe_subscription_id = subscription["id"]
# for some reason it doesnt work with subscription only
self.stripe_response = json.loads(str(subscription))
self.is_created_at_stripe = True
self.status = subscription["status"]
self.save()
def refresh_from_stripe(self):
stripe.api_key = stripe_settings.API_KEY
subscription = stripe.Subscription.retrieve(self.stripe_subscription_id)
self.set_stripe_data(subscription)
return subscription
def _stripe_cancel(self, at_period_end=False):
subscription = self.refresh_from_stripe()
if subscription["status"] != "canceled":
return subscription.delete(at_period_end=at_period_end)
def cancel(self, at_period_end=False):
sub = self._stripe_cancel(at_period_end=at_period_end)
if sub and sub["status"] == "canceled" or sub["cancel_at_period_end"]:
self.canceled_at = timezone.now()
self.status = self.STATUS_CANCELED
self.at_period_end = at_period_end
self.save()
@classmethod
def get_subcriptions_for_cancel(cls):
today = timezone.localtime(timezone.now() + relativedelta(hours=1)).date()
return cls.objects.filter(
end_date__lte=today, status=cls.STATUS_ACTIVE)
@classmethod
def end_subscriptions(cls, at_period_end=False):
# do not use in cron - one broken subscription will exit script.
# Instead please use end_subscriptions.py script.
for subscription in cls.get_subcriptions_for_cancel():
subscription.cancel(at_period_end)
sleep(0.25) # 4 requests per second tops
class StripeWebhook(models.Model):
id = models.CharField(primary_key=True, max_length=255) # id from stripe. This will prevent subsequent calls.
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
is_parsed = models.BooleanField(default=False)
raw_data = JSONField()
parse_error = models.TextField(blank=True)
def _parse_coupon_notification(self, action):
coupon_id = self.raw_data["data"]["object"]["id"]
created = timestamp_to_timezone_aware_date(self.raw_data["data"]["object"]["created"])
if action == "created":
try:
StripeCoupon.objects.all_with_deleted().get(coupon_id=coupon_id, created=created)
except StripeCoupon.DoesNotExist:
try:
StripeCoupon(coupon_id=coupon_id).save(force_retrieve=True)
except stripe.error.InvalidRequestError:
raise StripeWebhookParseError(_("Coupon with this coupon_id does not exists at Stripe API"))
except StripeCouponAlreadyExists as e:
raise StripeWebhookParseError(e.details)
else:
raise StripeWebhookParseError(StripeCouponAlreadyExists.details)
elif action == "updated":
try:
coupon = StripeCoupon.objects.get(coupon_id=coupon_id, created=created)
coupon.metadata = self.raw_data["data"]["object"]["metadata"]
super(StripeCoupon, coupon).save() # use the super method not to call Stripe API
except StripeCoupon.DoesNotExist:
pass # do not update if does not exist
elif action == "deleted":
StripeCoupon.objects.filter(coupon_id=coupon_id, created=created).delete()
def _parse_customer_source_notification(self, action):
if self.raw_data["data"]["object"]["object"] != "card":
return
stripe_card_id = self.raw_data["data"]["object"]["id"]
stripe_customer_id = self.raw_data["data"]["object"]["customer"]
try:
customer = StripeCustomer.objects.get(stripe_customer_id=stripe_customer_id)
except StripeCustomer.DoesNotExist:
raise StripeWebhookParseError(
_("There is no customer with id that is assigned to this card in our database"))
if action == "created":
try:
StripeCard.objects.all_with_deleted().get(stripe_card_id=stripe_card_id, customer=customer)
except StripeCard.DoesNotExist:
card = StripeCard(stripe_card_id=stripe_card_id, customer=customer)
if card.refresh_from_stripe():
card.save()
else:
raise StripeWebhookParseError(_("Card with this id does not exists at Stripe API"))
else:
pass # we already have the card
elif action == "updated":
try:
card = StripeCard.objects.get(stripe_card_id=stripe_card_id, customer=customer)
card.refresh_from_stripe()
card.save()
except StripeCard.DoesNotExist:
pass # do not update if does not exist
def parse(self, save=False):
if self.is_parsed:
raise StripeWebhookAlreadyParsed
event_type = self.raw_data.get("type")
try:
event_model, event_action = event_type.rsplit(".", 1)
except ValueError:
event_model, event_action = None, None
webhook_pre_parse.send(
sender=self.__class__, instance=self, event_type=event_type, event_model=event_model,
event_action=event_action)
# parse
if event_model:
if event_model == "coupon":
self._parse_coupon_notification(event_action)
elif event_model == "customer.source":
self._parse_customer_source_notification(event_action)
self.is_parsed = True
if save:
self.save()
def save(self, *args, **kwargs):
if not self.is_parsed:
try:
self.parse()
except StripeWebhookParseError as e:
self.parse_error = str(e)
return super(StripeWebhook, self).save(*args, **kwargs)
class Meta:
ordering = ["-created"]