-
-
Notifications
You must be signed in to change notification settings - Fork 479
/
core.py
2495 lines (2231 loc) · 84.9 KB
/
core.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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from decimal import Decimal
from typing import Optional, Union
import stripe
from django.apps import apps
from django.db import models, transaction
from django.utils import timezone
from django.utils.functional import cached_property
from django.utils.text import format_lazy
from django.utils.translation import gettext_lazy as _
from stripe.error import InvalidRequestError
from .. import enums
from ..exceptions import MultipleSubscriptionException
from ..fields import (
JSONField,
PaymentMethodForeignKey,
StripeCurrencyCodeField,
StripeDateTimeField,
StripeDecimalCurrencyAmountField,
StripeEnumField,
StripeForeignKey,
StripeIdField,
StripeQuantumCurrencyAmountField,
)
from ..managers import ChargeManager
from ..settings import djstripe_settings
from ..signals import WEBHOOK_SIGNALS
from ..utils import get_friendly_currency_amount, get_id_from_stripe_data
from .base import IdempotencyKey, StripeModel, logger
def _sanitise_price(price=None, plan=None, **kwargs):
"""
Helper for Customer.subscribe()
"""
if price and plan:
raise TypeError("price and plan arguments cannot both be defined.")
price = price or plan
if not price:
raise TypeError("you need to set either price or plan")
# Convert Price to id
if isinstance(price, StripeModel):
price = price.id
return price, kwargs
class BalanceTransaction(StripeModel):
"""
A single transaction that updates the Stripe balance.
Stripe documentation: https://stripe.com/docs/api?lang=python#balance_transaction_object
"""
stripe_class = stripe.BalanceTransaction
amount = StripeQuantumCurrencyAmountField(
help_text="Gross amount of the transaction, in cents."
)
available_on = StripeDateTimeField(
help_text=(
"The date the transaction's net funds "
"will become available in the Stripe balance."
)
)
currency = StripeCurrencyCodeField()
exchange_rate = models.DecimalField(null=True, decimal_places=6, max_digits=8)
fee = StripeQuantumCurrencyAmountField(
help_text="Fee (in cents) paid for this transaction."
)
fee_details = JSONField()
net = StripeQuantumCurrencyAmountField(
help_text="Net amount of the transaction, in cents."
)
source = StripeIdField()
reporting_category = StripeEnumField(
enum=enums.BalanceTransactionReportingCategory,
help_text=(
"More information: https://stripe.com/docs/reports/reporting-categories"
),
)
status = StripeEnumField(enum=enums.BalanceTransactionStatus)
type = StripeEnumField(enum=enums.BalanceTransactionType)
def __str__(self):
amount = get_friendly_currency_amount(self.amount / 100, self.currency)
status = enums.BalanceTransactionStatus.humanize(self.status)
return f"{amount} ({status})"
def get_source_class(self):
try:
return apps.get_model("djstripe", self.type)
except LookupError:
raise
def get_source_instance(self):
return self.get_source_class().objects.get(id=self.source)
def get_stripe_dashboard_url(self):
return self.get_source_instance().get_stripe_dashboard_url()
class Charge(StripeModel):
"""
To charge a credit or a debit card, you create a charge object. You can
retrieve and refund individual charges as well as list all charges. Charges
are identified by a unique random ID.
Stripe documentation: https://stripe.com/docs/api?lang=python#charges
"""
stripe_class = stripe.Charge
expand_fields = ["balance_transaction"]
stripe_dashboard_item_name = "payments"
amount = StripeDecimalCurrencyAmountField(help_text="Amount charged (as decimal).")
amount_captured = StripeDecimalCurrencyAmountField(
null=True,
help_text=(
"Amount (as decimal) captured (can be less than the amount attribute "
"on the charge if a partial capture was issued)."
),
)
amount_refunded = StripeDecimalCurrencyAmountField(
help_text=(
"Amount (as decimal) refunded (can be less than the amount attribute on "
"the charge if a partial refund was issued)."
)
)
application = models.CharField(
max_length=255,
blank=True,
help_text="ID of the Connect application that created the charge.",
)
application_fee = StripeForeignKey(
"ApplicationFee",
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="fee_for_charge",
help_text="The application fee (if any) for the charge.",
)
application_fee_amount = StripeDecimalCurrencyAmountField(
null=True,
blank=True,
help_text=(
"The amount (as decimal) of the application fee (if any) "
"requested for the charge."
),
)
balance_transaction = StripeForeignKey(
"BalanceTransaction",
on_delete=models.SET_NULL,
null=True,
help_text=(
"The balance transaction that describes the impact of this charge "
"on your account balance (not including refunds or disputes)."
),
)
billing_details = JSONField(
null=True,
help_text=(
"Billing information associated with the PaymentMethod at the "
"time of the transaction."
),
)
calculated_statement_descriptor = models.CharField(
max_length=22,
default="",
help_text=(
"The full statement descriptor that is passed to card networks, "
"and that is displayed on your customers' credit card and bank statements. "
"Allows you to see what the statement descriptor looks like after the "
"static and dynamic portions are combined."
),
)
captured = models.BooleanField(
default=False,
help_text=(
"If the charge was created without capturing, this boolean represents"
" whether or not it is still uncaptured or has since been captured."
),
)
currency = StripeCurrencyCodeField(
help_text="The currency in which the charge was made."
)
customer = StripeForeignKey(
"Customer",
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="charges",
help_text="The customer associated with this charge.",
)
dispute = StripeForeignKey(
"Dispute",
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="charges",
help_text="Details about the dispute if the charge has been disputed.",
)
disputed = models.BooleanField(
default=False,
help_text="Whether the charge has been disputed.",
)
failure_code = StripeEnumField(
enum=enums.ApiErrorCode,
default="",
blank=True,
help_text="Error code explaining reason for charge failure if available.",
)
failure_message = models.TextField(
max_length=5000,
default="",
blank=True,
help_text=(
"Message to user further explaining reason for charge failure if available."
),
)
fraud_details = JSONField(
help_text="Hash with information on fraud assessments for the charge.",
null=True,
blank=True,
)
invoice = StripeForeignKey(
"Invoice",
on_delete=models.CASCADE,
null=True,
related_name="charges",
help_text="The invoice this charge is for if one exists.",
)
# TODO: order (requires Order model)
on_behalf_of = StripeForeignKey(
"Account",
on_delete=models.CASCADE,
null=True,
blank=True,
related_name="charges",
help_text=(
"The account (if any) the charge was made on behalf of "
"without triggering an automatic transfer."
),
)
outcome = JSONField(
help_text="Details about whether or not the payment was accepted, and why.",
null=True,
blank=True,
)
paid = models.BooleanField(
default=False,
help_text=(
"True if the charge succeeded, "
"or was successfully authorized for later capture, False otherwise."
),
)
payment_intent = StripeForeignKey(
"PaymentIntent",
null=True,
on_delete=models.SET_NULL,
related_name="charges",
help_text="PaymentIntent associated with this charge, if one exists.",
)
payment_method = StripeForeignKey(
"PaymentMethod",
null=True,
on_delete=models.SET_NULL,
related_name="charges",
help_text="PaymentMethod used in this charge.",
)
payment_method_details = JSONField(
help_text="Details about the payment method at the time of the transaction.",
null=True,
blank=True,
)
receipt_email = models.TextField(
max_length=800, # yup, 800.
default="",
blank=True,
help_text="The email address that the receipt for this charge was sent to.",
)
receipt_number = models.CharField(
max_length=14,
default="",
blank=True,
help_text=(
"The transaction number that appears "
"on email receipts sent for this charge."
),
)
receipt_url = models.TextField(
max_length=5000,
default="",
blank=True,
help_text=(
"This is the URL to view the receipt for this charge. "
"The receipt is kept up-to-date to the latest state of the charge, "
"including any refunds. If the charge is for an Invoice, "
"the receipt will be stylized as an Invoice receipt."
),
)
refunded = models.BooleanField(
default=False,
help_text=(
"Whether or not the charge has been fully refunded. "
"If the charge is only partially refunded, "
"this attribute will still be false."
),
)
# TODO: review (requires Review model)
shipping = JSONField(
null=True, blank=True, help_text="Shipping information for the charge"
)
source = PaymentMethodForeignKey(
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="charges",
help_text="The source used for this charge.",
)
source_transfer = StripeForeignKey(
"Transfer",
null=True,
blank=True,
on_delete=models.CASCADE,
help_text=(
"The transfer which created this charge. Only present if the "
"charge came from another Stripe account."
),
related_name="+",
)
statement_descriptor = models.CharField(
max_length=22,
null=True,
blank=True,
help_text=(
"For card charges, use statement_descriptor_suffix instead. "
"Otherwise, you can use this value as the complete description of a "
"charge on your customers' statements. Must contain at least one letter, "
"maximum 22 characters."
),
)
statement_descriptor_suffix = models.CharField(
max_length=22,
null=True,
blank=True,
help_text=(
"Provides information about the charge that customers see on "
"their statements. Concatenated with the prefix (shortened descriptor) "
"or statement descriptor that's set on the account to form the "
"complete statement descriptor. "
"Maximum 22 characters for the concatenated descriptor."
),
)
status = StripeEnumField(
enum=enums.ChargeStatus, help_text="The status of the payment."
)
transfer = StripeForeignKey(
"Transfer",
on_delete=models.CASCADE,
null=True,
blank=True,
help_text=(
"The transfer to the `destination` account (only applicable if "
"the charge was created using the `destination` parameter)."
),
)
transfer_data = JSONField(
null=True,
blank=True,
help_text=(
"An optional dictionary including the account to automatically "
"transfer to as part of a destination charge."
),
)
transfer_group = models.CharField(
max_length=255,
null=True,
blank=True,
help_text="A string that identifies this transaction as part of a group.",
)
objects = ChargeManager()
def __str__(self):
amount = get_friendly_currency_amount(self.amount, self.currency)
return f"{amount} ({self.human_readable_status})"
@property
def fee(self):
if self.balance_transaction:
return self.balance_transaction.fee
@property
def human_readable_status(self) -> str:
if not self.captured:
return "Uncaptured"
elif self.disputed:
return "Disputed"
elif self.refunded:
return "Refunded"
return enums.ChargeStatus.humanize(self.status)
@property
def fraudulent(self) -> bool:
return (
self.fraud_details and list(self.fraud_details.values())[0] == "fraudulent"
)
def _calculate_refund_amount(self, amount: Optional[Decimal]) -> int:
"""
Returns the amount that can be refunded (in cents)
"""
eligible_to_refund = self.amount - (self.amount_refunded or 0)
amount_to_refund = (
min(eligible_to_refund, amount) if amount else eligible_to_refund
)
return int(amount_to_refund * 100)
def refund(
self,
amount: Decimal = None,
reason: str = None,
api_key: str = None,
stripe_account: str = None,
) -> "Refund":
"""
Initiate a refund. Returns the refund object.
:param amount: A positive decimal amount representing how much of this charge
to refund. If amount is not provided, then this will be a full refund.
Can only refund up to the unrefunded amount remaining of the charge.
:param reason: String indicating the reason for the refund.
If set, possible values are ``duplicate``, ``fraudulent``,
and ``requested_by_customer``. Specifying ``fraudulent`` as the reason
when you believe the charge to be fraudulent will
help Stripe improve their fraud detection algorithms.
"""
api_key = api_key or self.default_api_key
# Prefer passed in stripe_account if set.
if not stripe_account:
stripe_account = self._get_stripe_account_id(api_key)
refund_obj = Refund._api_create(
charge=self.id,
amount=self._calculate_refund_amount(amount=amount),
reason=reason,
api_key=api_key,
stripe_account=stripe_account,
)
return Refund.sync_from_stripe_data(
refund_obj,
api_key=api_key,
stripe_version=djstripe_settings.STRIPE_API_VERSION,
)
def capture(self, **kwargs) -> "Charge":
"""
Capture the payment of an existing, uncaptured, charge.
This is the second half of the two-step payment flow, where first you
created a charge with the capture option set to False.
See https://stripe.com/docs/api#capture_charge
"""
captured_charge = self.api_retrieve().capture(**kwargs)
return self.__class__.sync_from_stripe_data(
captured_charge, api_key=self.default_api_key
)
def _attach_objects_post_save_hook(
self,
cls,
data,
pending_relations=None,
api_key=djstripe_settings.STRIPE_SECRET_KEY,
):
super()._attach_objects_post_save_hook(
cls, data, pending_relations=pending_relations, api_key=api_key
)
cls._stripe_object_to_refunds(
target_cls=Refund, data=data, charge=self, api_key=api_key
)
# TODO Add Tests
class Mandate(StripeModel):
"""
A Mandate is a record of the permission a customer has given you to debit their payment method.
https://stripe.com/docs/api/mandates
"""
stripe_class = stripe.Mandate
customer_acceptance = JSONField(
help_text="Details about the customer's acceptance of the mandate."
)
payment_method = StripeForeignKey("paymentmethod", on_delete=models.CASCADE)
payment_method_details = JSONField(
help_text="Additional mandate information specific to the payment method type."
)
status = StripeEnumField(
enum=enums.MandateStatus,
help_text=(
"The status of the mandate, which indicates whether it can be used to"
" initiate a payment."
),
)
type = StripeEnumField(
enum=enums.MandateType,
help_text=(
"The status of the mandate, which indicates whether it can be used to"
" initiate a payment."
),
)
multi_use = JSONField(
null=True,
blank=True,
help_text=(
"If this is a `multi_use` mandate, this hash contains details about the"
" mandate."
),
)
single_use = JSONField(
null=True,
blank=True,
help_text=(
"If this is a `single_use` mandate, this hash contains details about the"
" mandate."
),
)
class Product(StripeModel):
"""
Products describe the specific goods or services you offer to your customers.
For example, you might offer a Standard and Premium version of your goods or service;
each version would be a separate Product. They can be used in conjunction with
Prices to configure pricing in Payment Links, Checkout, and Subscriptions.
Stripe documentation: https://stripe.com/docs/api?lang=python#products
"""
stripe_class = stripe.Product
stripe_dashboard_item_name = "products"
# Fields applicable to both `good` and `service`
name = models.TextField(
max_length=5000,
help_text=(
"The product's name, meant to be displayable to the customer. "
"Applicable to both `service` and `good` types."
),
)
default_price = StripeForeignKey(
"Price",
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="products",
help_text="The default price this product is associated with.",
)
type = StripeEnumField(
enum=enums.ProductType,
help_text=(
"The type of the product. The product is either of type `good`, which is "
"eligible for use with Orders and SKUs, or `service`, which is eligible "
"for use with Subscriptions and Plans."
),
)
# Fields applicable to `good` only
active = models.BooleanField(
null=True,
help_text=(
"Whether the product is currently available for purchase. "
"Only applicable to products of `type=good`."
),
)
attributes = JSONField(
null=True,
blank=True,
help_text=(
"A list of up to 5 attributes that each SKU can provide values for "
'(e.g., `["color", "size"]`). Only applicable to products of `type=good`.'
),
)
caption = models.TextField(
default="",
blank=True,
max_length=5000,
help_text=(
"A short one-line description of the product, meant to be displayable"
"to the customer. Only applicable to products of `type=good`."
),
)
deactivate_on = JSONField(
null=True,
blank=True,
help_text=(
"An array of connect application identifiers that cannot purchase "
"this product. Only applicable to products of `type=good`."
),
)
images = JSONField(
null=True,
blank=True,
help_text=(
"A list of up to 8 URLs of images for this product, meant to be "
"displayable to the customer. Only applicable to products of `type=good`."
),
)
package_dimensions = JSONField(
null=True,
blank=True,
help_text=(
"The dimensions of this product for shipping purposes. "
"A SKU associated with this product can override this value by having its "
"own `package_dimensions`. Only applicable to products of `type=good`."
),
)
shippable = models.BooleanField(
null=True,
blank=True,
help_text=(
"Whether this product is a shipped good. "
"Only applicable to products of `type=good`."
),
)
url = models.CharField(
max_length=799,
null=True,
blank=True,
help_text=(
"A URL of a publicly-accessible webpage for this product. "
"Only applicable to products of `type=good`."
),
)
# Fields available to `service` only
statement_descriptor = models.CharField(
max_length=22,
default="",
blank=True,
help_text=(
"Extra information about a product which will appear on your customer's "
"credit card statement. In the case that multiple products are billed at "
"once, the first statement descriptor will be used. "
"Only available on products of type=`service`."
),
)
unit_label = models.CharField(max_length=12, default="", blank=True)
def __str__(self):
# 1 product can have 1 or more than 1 related price
price_qs = self.prices.all()
price_count = price_qs.count()
if price_count > 1:
return f"{self.name} ({price_count} prices)"
elif price_count == 1:
return f"{self.name} ({price_qs[0].human_readable_price})"
else:
return self.name
class Customer(StripeModel):
"""
Customer objects allow you to perform recurring charges and track multiple
charges that are associated with the same customer.
Stripe documentation: https://stripe.com/docs/api?lang=python#customers
"""
stripe_class = stripe.Customer
expand_fields = ["default_source", "sources"]
stripe_dashboard_item_name = "customers"
address = JSONField(null=True, blank=True, help_text="The customer's address.")
balance = StripeQuantumCurrencyAmountField(
null=True,
blank=True,
default=0,
help_text=(
"Current balance (in cents), if any, being stored on the customer's "
"account. "
"If negative, the customer has credit to apply to the next invoice. "
"If positive, the customer has an amount owed that will be added to the "
"next invoice. The balance does not refer to any unpaid invoices; it "
"solely takes into account amounts that have yet to be successfully "
"applied to any invoice. This balance is only taken into account for "
"recurring billing purposes (i.e., subscriptions, invoices, invoice items)."
),
)
currency = StripeCurrencyCodeField(
blank=True,
default="",
help_text=(
"The currency the customer can be charged in for recurring billing purposes"
),
)
default_source = PaymentMethodForeignKey(
on_delete=models.SET_NULL, null=True, blank=True, related_name="customers"
)
delinquent = models.BooleanField(
null=True,
blank=True,
default=False,
help_text=(
"Whether or not the latest charge for the customer's "
"latest invoice has failed."
),
)
# Stripe API returns deleted customers like so:
# {
# "id": "cus_KX439W5dKrpi22",
# "object": "customer",
# "deleted": true,
# }
deleted = models.BooleanField(
default=False,
null=True,
blank=True,
help_text=(
"Whether the Customer instance has been deleted upstream in Stripe or not."
),
)
# <discount>
coupon = models.ForeignKey(
"Coupon", null=True, blank=True, on_delete=models.SET_NULL
)
coupon_start = StripeDateTimeField(
null=True,
blank=True,
editable=False,
help_text="If a coupon is present, the date at which it was applied.",
)
coupon_end = StripeDateTimeField(
null=True,
blank=True,
editable=False,
help_text=(
"If a coupon is present and has a limited duration, "
"the date that the discount will end."
),
)
# </discount>
discount = JSONField(
null=True,
blank=True,
help_text=(
"Describes the current discount active on the customer, if there is one."
),
)
email = models.TextField(max_length=5000, default="", blank=True)
invoice_prefix = models.CharField(
default="",
blank=True,
max_length=255,
help_text=(
"The prefix for the customer used to generate unique invoice numbers."
),
)
invoice_settings = JSONField(
null=True, blank=True, help_text="The customer's default invoice settings."
)
# default_payment_method is actually nested inside invoice_settings
# this field is a convenience to provide the foreign key
default_payment_method = StripeForeignKey(
"PaymentMethod",
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name="+",
help_text=(
"default payment method used for subscriptions and invoices "
"for the customer."
),
)
name = models.TextField(
max_length=5000,
default="",
blank=True,
help_text="The customer's full name or business name.",
)
phone = models.TextField(
max_length=5000,
default="",
blank=True,
help_text="The customer's phone number.",
)
preferred_locales = JSONField(
null=True,
blank=True,
help_text=(
"The customer's preferred locales (languages), ordered by preference."
),
)
shipping = JSONField(
null=True,
blank=True,
help_text="Shipping information associated with the customer.",
)
tax_exempt = StripeEnumField(
enum=enums.CustomerTaxExempt,
default="",
help_text=(
"Describes the customer's tax exemption status. When set to reverse, "
'invoice and receipt PDFs include the text "Reverse charge".'
),
)
# dj-stripe fields
subscriber = models.ForeignKey(
djstripe_settings.get_subscriber_model_string(),
blank=True,
null=True,
on_delete=models.SET_NULL,
related_name="djstripe_customers",
)
date_purged = models.DateTimeField(null=True, editable=False)
def __str__(self):
if self.subscriber:
return str(self.subscriber)
return self.name or self.description or self.id
@classmethod
def _manipulate_stripe_object_hook(cls, data):
# stripe adds a deleted attribute if the Customer has been deleted upstream
if data.get("deleted"):
logger.warning(
f"This customer ({data.get('id')}) has been deleted upstream, in Stripe"
)
else:
# set "deleted" key to False (default)
data["deleted"] = False
discount = data.get("discount")
if discount:
data["coupon_start"] = discount["start"]
data["coupon_end"] = discount["end"]
# Populate the object id for our default_payment_method field (or set it None)
data["default_payment_method"] = data.get("invoice_settings", {}).get(
"default_payment_method"
)
return data
@classmethod
def get_or_create(
cls,
subscriber,
livemode=djstripe_settings.STRIPE_LIVE_MODE,
stripe_account=None,
):
"""
Get or create a dj-stripe customer.
:param subscriber: The subscriber model instance for which to get or
create a customer.
:type subscriber: User
:param livemode: Whether to get the subscriber in live or test mode.
:type livemode: bool
"""
try:
return cls.objects.get(subscriber=subscriber, livemode=livemode), False
except cls.DoesNotExist:
action = f"create:{subscriber.pk}"
idempotency_key = djstripe_settings.get_idempotency_key(
"customer", action, livemode
)
return (
cls.create(
subscriber,
idempotency_key=idempotency_key,
stripe_account=stripe_account,
),
True,
)
@classmethod
def create(cls, subscriber, idempotency_key=None, stripe_account=None):
metadata = {}
subscriber_key = djstripe_settings.SUBSCRIBER_CUSTOMER_KEY
if subscriber_key not in ("", None):
metadata[subscriber_key] = subscriber.pk
try:
# if subscriber table has a get_full_name() method, use it as name
# ref django.contrib.auth.models.User.get_full_name
name = subscriber.get_full_name()
except AttributeError:
name = None
stripe_customer = cls._api_create(
email=subscriber.email,
name=name,
idempotency_key=idempotency_key,
metadata=metadata,
stripe_account=stripe_account,
)
customer, created = cls.objects.get_or_create(
id=stripe_customer["id"],
defaults={
"subscriber": subscriber,
"livemode": stripe_customer["livemode"],
"balance": stripe_customer.get("balance", 0),
"delinquent": stripe_customer.get("delinquent", False),
},
)
return customer
@property
def credits(self):
"""
The customer is considered to have credits if their balance is below 0.
"""
return abs(min(self.balance, 0))
@property
def customer_payment_methods(self):
"""
An iterable of all of the customer's payment methods
(sources, then legacy cards)
"""
for source in self.sources.iterator():
yield source
for card in self.legacy_cards.iterator():
yield card
@property
def pending_charges(self):
"""
The customer is considered to have pending charges if their balance is above 0.
"""
return max(self.balance, 0)
def subscribe(self, *, items=None, price=None, plan=None, **kwargs):
"""
Subscribes this customer to all the prices or plans in the items dict (Recommended).
:param items: A list of up to 20 subscription items, each with an attached price
:type list:
:param items: A dictionary of Plan (or Plan ID) or Price (or Price ID)
:type dict: The price or plan to which to subscribe the customer.
:param price: The price to which to subscribe the customer.
:type price: Price or string (price ID)
:param plan: The plan to which to subscribe the customer.
:type plan: Plan or string (plan ID)
"""
from .billing import Subscription
if (items and price) or (items and plan) or (price and plan):
raise TypeError("Please define only one of items, price or plan arguments.")
if items is None:
_items = [{"price": price}]
else:
_items = []
for item in items:
price = item.get("price", "")
plan = item.get("plan", "")
price, kwargs = _sanitise_price(price, plan, **kwargs)
if "price" in item:
_items.append({"price": price})
if "plan" in item:
_items.append({"plan": price})
stripe_subscription = Subscription._api_create(
items=_items, customer=self.id, **kwargs
)
api_key = kwargs.get("api_key") or self.default_api_key
return Subscription.sync_from_stripe_data(stripe_subscription, api_key=api_key)
def charge(
self,
amount: Decimal,