Skip to content

Models

Models hold the bulk of the functionality included in the dj-stripe package. Each model is tied closely to its corresponding object in the stripe dashboard. Fields that are not implemented for each model have a short reason behind the decision in the docstring for each model.

Core Resources

Attributes

djstripe.models.core.FileUpload = File module-attribute

Classes

djstripe.models.core.BalanceTransaction

Bases: StripeModel

A single transaction that updates the Stripe balance.

Stripe documentation: https://stripe.com/docs/api?lang=python#balance_transaction_object

Source code in djstripe/models/core.py
 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
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()

Attributes

djstripe.models.core.BalanceTransaction.amount = StripeQuantumCurrencyAmountField(help_text='Gross amount of the transaction, in cents.') class-attribute instance-attribute
djstripe.models.core.BalanceTransaction.available_on = StripeDateTimeField(help_text="The date the transaction's net funds will become available in the Stripe balance.") class-attribute instance-attribute
djstripe.models.core.BalanceTransaction.currency = StripeCurrencyCodeField() class-attribute instance-attribute
djstripe.models.core.BalanceTransaction.exchange_rate = models.DecimalField(null=True, decimal_places=6, max_digits=8) class-attribute instance-attribute
djstripe.models.core.BalanceTransaction.fee = StripeQuantumCurrencyAmountField(help_text='Fee (in cents) paid for this transaction.') class-attribute instance-attribute
djstripe.models.core.BalanceTransaction.fee_details = JSONField() class-attribute instance-attribute
djstripe.models.core.BalanceTransaction.net = StripeQuantumCurrencyAmountField(help_text='Net amount of the transaction, in cents.') class-attribute instance-attribute
djstripe.models.core.BalanceTransaction.reporting_category = StripeEnumField(enum=enums.BalanceTransactionReportingCategory, help_text='More information: https://stripe.com/docs/reports/reporting-categories') class-attribute instance-attribute
djstripe.models.core.BalanceTransaction.source = StripeIdField() class-attribute instance-attribute
djstripe.models.core.BalanceTransaction.status = StripeEnumField(enum=enums.BalanceTransactionStatus) class-attribute instance-attribute
djstripe.models.core.BalanceTransaction.stripe_class = stripe.BalanceTransaction class-attribute instance-attribute
djstripe.models.core.BalanceTransaction.type = StripeEnumField(enum=enums.BalanceTransactionType) class-attribute instance-attribute

Functions

djstripe.models.core.BalanceTransaction.__str__()
Source code in djstripe/models/core.py
90
91
92
93
def __str__(self):
    amount = get_friendly_currency_amount(self.amount / 100, self.currency)
    status = enums.BalanceTransactionStatus.humanize(self.status)
    return f"{amount} ({status})"
djstripe.models.core.BalanceTransaction.get_source_class()
Source code in djstripe/models/core.py
95
96
97
98
99
def get_source_class(self):
    try:
        return apps.get_model("djstripe", self.type)
    except LookupError:
        raise
djstripe.models.core.BalanceTransaction.get_source_instance()
Source code in djstripe/models/core.py
101
102
def get_source_instance(self):
    return self.get_source_class().objects.get(id=self.source)
djstripe.models.core.BalanceTransaction.get_stripe_dashboard_url()
Source code in djstripe/models/core.py
104
105
def get_stripe_dashboard_url(self):
    return self.get_source_instance().get_stripe_dashboard_url()

djstripe.models.core.Charge

Bases: 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

Source code in djstripe/models/core.py
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
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
        )

Attributes

djstripe.models.core.Charge.amount = StripeDecimalCurrencyAmountField(help_text='Amount charged (as decimal).') class-attribute instance-attribute
djstripe.models.core.Charge.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).') class-attribute instance-attribute
djstripe.models.core.Charge.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).') class-attribute instance-attribute
djstripe.models.core.Charge.application = models.CharField(max_length=255, blank=True, help_text='ID of the Connect application that created the charge.') class-attribute instance-attribute
djstripe.models.core.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.') class-attribute instance-attribute
djstripe.models.core.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.') class-attribute instance-attribute
djstripe.models.core.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).') class-attribute instance-attribute
djstripe.models.core.Charge.billing_details = JSONField(null=True, help_text='Billing information associated with the PaymentMethod at the time of the transaction.') class-attribute instance-attribute
djstripe.models.core.Charge.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.") class-attribute instance-attribute
djstripe.models.core.Charge.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.') class-attribute instance-attribute
djstripe.models.core.Charge.currency = StripeCurrencyCodeField(help_text='The currency in which the charge was made.') class-attribute instance-attribute
djstripe.models.core.Charge.customer = StripeForeignKey('Customer', on_delete=models.SET_NULL, null=True, blank=True, related_name='charges', help_text='The customer associated with this charge.') class-attribute instance-attribute
djstripe.models.core.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.') class-attribute instance-attribute
djstripe.models.core.Charge.disputed = models.BooleanField(default=False, help_text='Whether the charge has been disputed.') class-attribute instance-attribute
djstripe.models.core.Charge.expand_fields = ['balance_transaction'] class-attribute instance-attribute
djstripe.models.core.Charge.failure_code = StripeEnumField(enum=enums.ApiErrorCode, default='', blank=True, help_text='Error code explaining reason for charge failure if available.') class-attribute instance-attribute
djstripe.models.core.Charge.failure_message = models.TextField(max_length=5000, default='', blank=True, help_text='Message to user further explaining reason for charge failure if available.') class-attribute instance-attribute
djstripe.models.core.Charge.fee property
djstripe.models.core.Charge.fraud_details = JSONField(help_text='Hash with information on fraud assessments for the charge.', null=True, blank=True) class-attribute instance-attribute
djstripe.models.core.Charge.fraudulent: bool property
djstripe.models.core.Charge.human_readable_status: str property
djstripe.models.core.Charge.invoice = StripeForeignKey('Invoice', on_delete=models.CASCADE, null=True, related_name='charges', help_text='The invoice this charge is for if one exists.') class-attribute instance-attribute
djstripe.models.core.Charge.objects = ChargeManager() class-attribute instance-attribute
djstripe.models.core.Charge.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.') class-attribute instance-attribute
djstripe.models.core.Charge.outcome = JSONField(help_text='Details about whether or not the payment was accepted, and why.', null=True, blank=True) class-attribute instance-attribute
djstripe.models.core.Charge.paid = models.BooleanField(default=False, help_text='True if the charge succeeded, or was successfully authorized for later capture, False otherwise.') class-attribute instance-attribute
djstripe.models.core.Charge.payment_intent = StripeForeignKey('PaymentIntent', null=True, on_delete=models.SET_NULL, related_name='charges', help_text='PaymentIntent associated with this charge, if one exists.') class-attribute instance-attribute
djstripe.models.core.Charge.payment_method = StripeForeignKey('PaymentMethod', null=True, on_delete=models.SET_NULL, related_name='charges', help_text='PaymentMethod used in this charge.') class-attribute instance-attribute
djstripe.models.core.Charge.payment_method_details = JSONField(help_text='Details about the payment method at the time of the transaction.', null=True, blank=True) class-attribute instance-attribute
djstripe.models.core.Charge.receipt_email = models.TextField(max_length=800, default='', blank=True, help_text='The email address that the receipt for this charge was sent to.') class-attribute instance-attribute
djstripe.models.core.Charge.receipt_number = models.CharField(max_length=14, default='', blank=True, help_text='The transaction number that appears on email receipts sent for this charge.') class-attribute instance-attribute
djstripe.models.core.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.') class-attribute instance-attribute
djstripe.models.core.Charge.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.') class-attribute instance-attribute
djstripe.models.core.Charge.shipping = JSONField(null=True, blank=True, help_text='Shipping information for the charge') class-attribute instance-attribute
djstripe.models.core.Charge.source = PaymentMethodForeignKey(on_delete=models.SET_NULL, null=True, blank=True, related_name='charges', help_text='The source used for this charge.') class-attribute instance-attribute
djstripe.models.core.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='+') class-attribute instance-attribute
djstripe.models.core.Charge.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.") class-attribute instance-attribute
djstripe.models.core.Charge.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.") class-attribute instance-attribute
djstripe.models.core.Charge.status = StripeEnumField(enum=enums.ChargeStatus, help_text='The status of the payment.') class-attribute instance-attribute
djstripe.models.core.Charge.stripe_class = stripe.Charge class-attribute instance-attribute
djstripe.models.core.Charge.stripe_dashboard_item_name = 'payments' class-attribute instance-attribute
djstripe.models.core.Charge.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).') class-attribute instance-attribute
djstripe.models.core.Charge.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.') class-attribute instance-attribute
djstripe.models.core.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.') class-attribute instance-attribute

Functions

djstripe.models.core.Charge.__str__()
Source code in djstripe/models/core.py
391
392
393
def __str__(self):
    amount = get_friendly_currency_amount(self.amount, self.currency)
    return f"{amount} ({self.human_readable_status})"
djstripe.models.core.Charge.capture(**kwargs)

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

Source code in djstripe/models/core.py
466
467
468
469
470
471
472
473
474
475
476
477
478
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
    )
djstripe.models.core.Charge.refund(amount=None, reason=None, api_key=None, stripe_account=None)

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.

Source code in djstripe/models/core.py
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
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,
    )

djstripe.models.core.Customer

Bases: 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

Source code in djstripe/models/core.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
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)

    class Meta(StripeModel.Meta):
        unique_together = ("subscriber", "livemode", "djstripe_owner_account")

    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,
        *,
        application_fee: Decimal = None,
        source: Union[str, StripeModel] = None,
        **kwargs,
    ) -> Charge:
        """
        Creates a charge for this customer.

        :param amount: The amount to charge.
        :type amount: Decimal. Precision is 2; anything more will be ignored.
        :param source: The source to use for this charge.
            Must be a source attributed to this customer. If None, the customer's
            default source is used. Can be either the id of the source or
            the source object itself.
        :type source: string, Source
        """

        if not isinstance(amount, Decimal):
            raise ValueError("You must supply a decimal value representing dollars.")

        # Convert Source to id
        if source and isinstance(source, StripeModel):
            source = source.id

        stripe_charge = Charge._api_create(
            customer=self.id,
            amount=int(amount * 100),  # Convert dollars into cents
            application_fee=(
                int(application_fee * 100) if application_fee else None
            ),  # Convert dollars into cents
            source=source,
            **kwargs,
        )

        api_key = kwargs.get("api_key") or self.default_api_key
        return Charge.sync_from_stripe_data(stripe_charge, api_key=api_key)

    def add_invoice_item(
        self,
        amount,
        currency,
        description=None,
        discountable=None,
        invoice=None,
        metadata=None,
        subscription=None,
    ):
        """
        Adds an arbitrary charge or credit to the customer's upcoming invoice.
        Different than creating a charge. Charges are separate bills that get
        processed immediately. Invoice items are appended to the customer's next
        invoice. This is extremely useful when adding surcharges to subscriptions.

        :param amount: The amount to charge.
        :type amount: Decimal. Precision is 2; anything more will be ignored.
        :param currency: 3-letter ISO code for currency
        :type currency: string
        :param description: An arbitrary string.
        :type description: string
        :param discountable: Controls whether discounts apply to this invoice item.
            Defaults to False for prorations or negative invoice items,
            and True for all other invoice items.
        :type discountable: boolean
        :param invoice: An existing invoice to add this invoice item to.
            When left blank, the invoice item will be added to the next upcoming \
             scheduled invoice. \
             Use this when adding invoice items in response to an \
             ``invoice.created`` webhook. You cannot add an invoice \
            item to an invoice that has already been paid, attempted or closed.
        :type invoice: Invoice or string (invoice ID)
        :param metadata: A set of key/value pairs useful for storing
            additional information.
        :type metadata: dict
        :param subscription: A subscription to add this invoice item to.
            When left blank, the invoice item will be be added to the next upcoming \
            scheduled invoice. When set, scheduled invoices for subscriptions other \
            than the specified subscription will ignore the invoice item. \
            Use this when you want to express that an invoice item has been accrued \
            within the context of a particular subscription.
        :type subscription: Subscription or string (subscription ID)

        .. Notes:
        .. if you're using ``Customer.add_invoice_item()`` instead of
        .. ``Customer.add_invoice_item()``, ``invoice`` and ``subscriptions``
        .. can only be strings
        """
        from .billing import InvoiceItem

        if not isinstance(amount, Decimal):
            raise ValueError("You must supply a decimal value representing dollars.")

        # Convert Invoice to id
        if invoice is not None and isinstance(invoice, StripeModel):
            invoice = invoice.id

        # Convert Subscription to id
        if subscription is not None and isinstance(subscription, StripeModel):
            subscription = subscription.id

        stripe_invoiceitem = InvoiceItem._api_create(
            amount=int(amount * 100),  # Convert dollars into cents
            currency=currency,
            customer=self.id,
            description=description,
            discountable=discountable,
            invoice=invoice,
            metadata=metadata,
            subscription=subscription,
        )

        return InvoiceItem.sync_from_stripe_data(
            stripe_invoiceitem, api_key=self.default_api_key
        )

    def add_card(self, source, set_default=True):
        """
        Adds a card to this customer's account.

        :param source: Either a token, like the ones returned by our Stripe.js, or a
            dictionary containing a user's credit card details.
            Stripe will automatically validate the card.
        :type source: string, dict
        :param set_default: Whether or not to set the source as the customer's
            default source
        :type set_default: boolean

        """
        from .payment_methods import DjstripePaymentMethod

        stripe_customer = self.api_retrieve()
        new_stripe_payment_method = stripe_customer.sources.create(source=source)

        if set_default:
            stripe_customer.default_source = new_stripe_payment_method["id"]
            stripe_customer.save()

        new_payment_method = DjstripePaymentMethod.from_stripe_object(
            new_stripe_payment_method
        )

        # Change the default source
        if set_default:
            self.default_source = new_payment_method
            self.save()

        return new_payment_method.resolve()

    def add_payment_method(self, payment_method, set_default=True):
        """
        Adds an already existing payment method to this customer's account

        :param payment_method: PaymentMethod to be attached to the customer
        :type payment_method: str, PaymentMethod
        :param set_default: If true, this will be set as the default_payment_method
        :type set_default: bool
        :rtype: PaymentMethod
        """
        from .payment_methods import PaymentMethod

        stripe_customer = self.api_retrieve()
        payment_method = PaymentMethod.attach(payment_method, stripe_customer)

        if set_default:
            stripe_customer["invoice_settings"][
                "default_payment_method"
            ] = payment_method.id
            stripe_customer.save()

            # Refresh self from the stripe customer, this should have two effects:
            # 1) sets self.default_payment_method (we rely on logic in
            # Customer._manipulate_stripe_object_hook to do this)
            # 2) updates self.invoice_settings.default_payment_methods
            self.sync_from_stripe_data(stripe_customer, api_key=self.default_api_key)
            self.refresh_from_db()

        return payment_method

    def purge(self):
        """Customers are soft deleted as deleted customers are still accessible by the
        Stripe API and sync for all RelatedModels would fail"""
        try:
            self._api_delete()
        except InvalidRequestError as exc:
            if "No such customer:" in str(exc):
                # The exception was thrown because the stripe customer was already
                # deleted on the stripe side, ignore the exception
                pass
            else:
                # The exception was raised for another reason, re-raise it
                raise

        # toggle the deleted flag on Customer to indicate it has been
        # deleted upstream in Stripe
        self.deleted = True

        if self.subscriber:
            # Delete the idempotency key used by Customer.create()
            # So re-creating a customer for this subscriber before the key expires
            # doesn't return the older Customer data
            idempotency_key_action = f"customer:create:{self.subscriber.pk}"
            IdempotencyKey.objects.filter(action=idempotency_key_action).delete()

        self.subscriber = None

        # Remove sources
        self.default_source = None
        for source in self.legacy_cards.all():
            source.remove()

        for source in self.sources.all():
            source.detach()

        self.date_purged = timezone.now()
        self.save()

    def _get_valid_subscriptions(self):
        """Get a list of this customer's valid subscriptions."""

        return [
            subscription
            for subscription in self.subscriptions.all()
            if subscription.is_valid()
        ]

    def is_subscribed_to(self, product: Union[Product, str]) -> bool:
        """
        Checks to see if this customer has an active subscription to the given product.

        :param product: The product for which to check for an active subscription.
        :type product: Product or string (product ID)

        :returns: True if there exists an active subscription, False otherwise.
        """

        if isinstance(product, StripeModel):
            product = product.id

        for subscription in self._get_valid_subscriptions():
            for item in subscription.items.all():
                if item.price and item.price.product.id == product:
                    return True
        return False

    def has_any_active_subscription(self):
        """
        Checks to see if this customer has an active subscription to any plan.

        :returns: True if there exists an active subscription, False otherwise.
        """

        return len(self._get_valid_subscriptions()) != 0

    @property
    def active_subscriptions(self):
        """
        Returns active subscriptions
        (subscriptions with an active status that end in the future).
        """
        return self.subscriptions.filter(
            status=enums.SubscriptionStatus.active,
            current_period_end__gt=timezone.now(),
        )

    @property
    def valid_subscriptions(self):
        """
        Returns this customer's valid subscriptions
        (subscriptions that aren't canceled or incomplete_expired).
        """
        return self.subscriptions.exclude(
            status__in=[
                enums.SubscriptionStatus.canceled,
                enums.SubscriptionStatus.incomplete_expired,
            ]
        )

    @property
    def subscription(self):
        """
        Shortcut to get this customer's subscription.

        :returns: None if the customer has no subscriptions, the subscription if
            the customer has a subscription.
        :raises MultipleSubscriptionException: Raised if the customer has multiple
            subscriptions.
            In this case, use ``Customer.subscriptions`` instead.
        """

        subscriptions = self.valid_subscriptions

        if subscriptions.count() > 1:
            raise MultipleSubscriptionException(
                "This customer has multiple subscriptions. Use Customer.subscriptions "
                "to access them."
            )
        else:
            return subscriptions.first()

    def send_invoice(self, **kwargs):
        """
        Pay and send the customer's latest invoice.

        :returns: True if an invoice was able to be created and paid, False otherwise
            (typically if there was nothing to invoice).
        """
        from .billing import Invoice

        try:
            invoice = Invoice._api_create(customer=self.id)
            invoice.pay(**kwargs)
            return True
        except InvalidRequestError:  # TODO: Check this for a more
            #                           specific error message.
            return False  # There was nothing to invoice

    def retry_unpaid_invoices(self, **kwargs):
        """Attempt to retry collecting payment on the customer's unpaid invoices."""

        self._sync_invoices()
        for invoice in self.invoices.filter(auto_advance=True).exclude(status="paid"):
            try:
                invoice.retry(**kwargs)  # Always retry unpaid invoices
            except InvalidRequestError as exc:
                if str(exc) != "Invoice is already paid":
                    raise

    def add_coupon(self, coupon, idempotency_key=None):
        """
        Add a coupon to a Customer.

        The coupon can be a Coupon object, or a valid Stripe Coupon ID.
        """
        if isinstance(coupon, StripeModel):
            coupon = coupon.id

        stripe_customer = self.api_retrieve()
        stripe_customer["coupon"] = coupon
        stripe_customer.save(idempotency_key=idempotency_key)
        return self.__class__.sync_from_stripe_data(
            stripe_customer, api_key=self.default_api_key
        )

    def upcoming_invoice(self, **kwargs):
        """Gets the upcoming preview invoice (singular) for this customer.

        See `Invoice.upcoming() <#djstripe.Invoice.upcoming>`__.

        The ``customer`` argument to the ``upcoming()`` call is automatically set
         by this method.
        """
        from .billing import Invoice

        kwargs["customer"] = self
        return Invoice.upcoming(**kwargs)

    def _attach_objects_post_save_hook(
        self,
        cls,
        data,
        pending_relations=None,
        api_key=djstripe_settings.STRIPE_SECRET_KEY,
    ):
        from .billing import Coupon
        from .payment_methods import DjstripePaymentMethod

        super()._attach_objects_post_save_hook(
            cls, data, pending_relations=pending_relations, api_key=api_key
        )

        save = False

        customer_sources = data.get("sources")
        sources = {}
        if customer_sources:
            # Have to create sources before we handle the default_source
            # We save all of them in the `sources` dict, so that we can find them
            # by id when we look at the default_source (we need the source type).
            for source in customer_sources["data"]:
                obj, _ = DjstripePaymentMethod._get_or_create_source(
                    source, source["object"], api_key=api_key
                )
                sources[source["id"]] = obj

        discount = data.get("discount")
        if discount:
            coupon, _created = Coupon._get_or_create_from_stripe_object(
                discount, "coupon", api_key=api_key
            )
            if coupon and coupon != self.coupon:
                self.coupon = coupon
                save = True
        elif self.coupon:
            self.coupon = None
            save = True

        if save:
            self.save()

    def _attach_objects_hook(
        self, cls, data, current_ids=None, api_key=djstripe_settings.STRIPE_SECRET_KEY
    ):
        # When we save a customer to Stripe, we add a reference to its Django PK
        # in the `django_account` key. If we find that, we re-attach that PK.
        subscriber_key = djstripe_settings.SUBSCRIBER_CUSTOMER_KEY
        if subscriber_key in ("", None):
            # Disabled. Nothing else to do.
            return

        subscriber_id = data.get("metadata", {}).get(subscriber_key)
        if subscriber_id:
            cls = djstripe_settings.get_subscriber_model()
            try:
                # We have to perform a get(), instead of just attaching the PK
                # blindly as the object may have been deleted or not exist.
                # Attempting to save that would cause an IntegrityError.
                self.subscriber = cls.objects.get(pk=subscriber_id)
            except (cls.DoesNotExist, ValueError):
                logger.warning(
                    "Could not find subscriber %r matching customer %r",
                    subscriber_id,
                    self.id,
                )
                self.subscriber = None

    # SYNC methods should be dropped in favor of the master sync infrastructure proposed
    def _sync_invoices(self, **kwargs):
        from .billing import Invoice

        api_key = kwargs.get("api_key") or self.default_api_key
        for stripe_invoice in Invoice.api_list(customer=self.id, **kwargs):
            Invoice.sync_from_stripe_data(stripe_invoice, api_key=api_key)

    def _sync_charges(self, **kwargs):
        api_key = kwargs.get("api_key") or self.default_api_key
        for stripe_charge in Charge.api_list(customer=self.id, **kwargs):
            Charge.sync_from_stripe_data(stripe_charge, api_key=api_key)

    def _sync_cards(self, **kwargs):
        from .payment_methods import Card

        api_key = kwargs.get("api_key") or self.default_api_key
        for stripe_card in Card.api_list(customer=self, **kwargs):
            Card.sync_from_stripe_data(stripe_card, api_key=api_key)

    def _sync_subscriptions(self, **kwargs):
        from .billing import Subscription

        api_key = kwargs.get("api_key") or self.default_api_key
        for stripe_subscription in Subscription.api_list(
            customer=self.id, status="all", **kwargs
        ):
            Subscription.sync_from_stripe_data(stripe_subscription, api_key=api_key)

Attributes

djstripe.models.core.Customer.active_subscriptions property

Returns active subscriptions (subscriptions with an active status that end in the future).

djstripe.models.core.Customer.address = JSONField(null=True, blank=True, help_text="The customer's address.") class-attribute instance-attribute
djstripe.models.core.Customer.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).") class-attribute instance-attribute
djstripe.models.core.Customer.coupon = models.ForeignKey('Coupon', null=True, blank=True, on_delete=models.SET_NULL) class-attribute instance-attribute
djstripe.models.core.Customer.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.') class-attribute instance-attribute
djstripe.models.core.Customer.coupon_start = StripeDateTimeField(null=True, blank=True, editable=False, help_text='If a coupon is present, the date at which it was applied.') class-attribute instance-attribute
djstripe.models.core.Customer.credits property

The customer is considered to have credits if their balance is below 0.

djstripe.models.core.Customer.currency = StripeCurrencyCodeField(blank=True, default='', help_text='The currency the customer can be charged in for recurring billing purposes') class-attribute instance-attribute
djstripe.models.core.Customer.customer_payment_methods property

An iterable of all of the customer's payment methods (sources, then legacy cards)

djstripe.models.core.Customer.date_purged = models.DateTimeField(null=True, editable=False) class-attribute instance-attribute
djstripe.models.core.Customer.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.') class-attribute instance-attribute
djstripe.models.core.Customer.default_source = PaymentMethodForeignKey(on_delete=models.SET_NULL, null=True, blank=True, related_name='customers') class-attribute instance-attribute
djstripe.models.core.Customer.deleted = models.BooleanField(default=False, null=True, blank=True, help_text='Whether the Customer instance has been deleted upstream in Stripe or not.') class-attribute instance-attribute
djstripe.models.core.Customer.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.") class-attribute instance-attribute
djstripe.models.core.Customer.discount = JSONField(null=True, blank=True, help_text='Describes the current discount active on the customer, if there is one.') class-attribute instance-attribute
djstripe.models.core.Customer.email = models.TextField(max_length=5000, default='', blank=True) class-attribute instance-attribute
djstripe.models.core.Customer.expand_fields = ['default_source', 'sources'] class-attribute instance-attribute
djstripe.models.core.Customer.invoice_prefix = models.CharField(default='', blank=True, max_length=255, help_text='The prefix for the customer used to generate unique invoice numbers.') class-attribute instance-attribute
djstripe.models.core.Customer.invoice_settings = JSONField(null=True, blank=True, help_text="The customer's default invoice settings.") class-attribute instance-attribute
djstripe.models.core.Customer.name = models.TextField(max_length=5000, default='', blank=True, help_text="The customer's full name or business name.") class-attribute instance-attribute
djstripe.models.core.Customer.pending_charges property

The customer is considered to have pending charges if their balance is above 0.

djstripe.models.core.Customer.phone = models.TextField(max_length=5000, default='', blank=True, help_text="The customer's phone number.") class-attribute instance-attribute
djstripe.models.core.Customer.preferred_locales = JSONField(null=True, blank=True, help_text="The customer's preferred locales (languages), ordered by preference.") class-attribute instance-attribute
djstripe.models.core.Customer.shipping = JSONField(null=True, blank=True, help_text='Shipping information associated with the customer.') class-attribute instance-attribute
djstripe.models.core.Customer.stripe_class = stripe.Customer class-attribute instance-attribute
djstripe.models.core.Customer.stripe_dashboard_item_name = 'customers' class-attribute instance-attribute
djstripe.models.core.Customer.subscriber = models.ForeignKey(djstripe_settings.get_subscriber_model_string(), blank=True, null=True, on_delete=models.SET_NULL, related_name='djstripe_customers') class-attribute instance-attribute
djstripe.models.core.Customer.subscription property

Shortcut to get this customer's subscription.

:returns: None if the customer has no subscriptions, the subscription if the customer has a subscription. :raises MultipleSubscriptionException: Raised if the customer has multiple subscriptions. In this case, use Customer.subscriptions instead.

djstripe.models.core.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".') class-attribute instance-attribute
djstripe.models.core.Customer.valid_subscriptions property

Returns this customer's valid subscriptions (subscriptions that aren't canceled or incomplete_expired).

Classes

djstripe.models.core.Customer.Meta

Bases: Meta

Source code in djstripe/models/core.py
835
836
class Meta(StripeModel.Meta):
    unique_together = ("subscriber", "livemode", "djstripe_owner_account")
Attributes
djstripe.models.core.Customer.Meta.unique_together = ('subscriber', 'livemode', 'djstripe_owner_account') class-attribute instance-attribute

Functions

djstripe.models.core.Customer.__str__()
Source code in djstripe/models/core.py
838
839
840
841
842
def __str__(self):
    if self.subscriber:
        return str(self.subscriber)

    return self.name or self.description or self.id
djstripe.models.core.Customer.add_card(source, set_default=True)

Adds a card to this customer's account.

:param source: Either a token, like the ones returned by our Stripe.js, or a dictionary containing a user's credit card details. Stripe will automatically validate the card. :type source: string, dict :param set_default: Whether or not to set the source as the customer's default source :type set_default: boolean

Source code in djstripe/models/core.py
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
def add_card(self, source, set_default=True):
    """
    Adds a card to this customer's account.

    :param source: Either a token, like the ones returned by our Stripe.js, or a
        dictionary containing a user's credit card details.
        Stripe will automatically validate the card.
    :type source: string, dict
    :param set_default: Whether or not to set the source as the customer's
        default source
    :type set_default: boolean

    """
    from .payment_methods import DjstripePaymentMethod

    stripe_customer = self.api_retrieve()
    new_stripe_payment_method = stripe_customer.sources.create(source=source)

    if set_default:
        stripe_customer.default_source = new_stripe_payment_method["id"]
        stripe_customer.save()

    new_payment_method = DjstripePaymentMethod.from_stripe_object(
        new_stripe_payment_method
    )

    # Change the default source
    if set_default:
        self.default_source = new_payment_method
        self.save()

    return new_payment_method.resolve()
djstripe.models.core.Customer.add_coupon(coupon, idempotency_key=None)

Add a coupon to a Customer.

The coupon can be a Coupon object, or a valid Stripe Coupon ID.

Source code in djstripe/models/core.py
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
def add_coupon(self, coupon, idempotency_key=None):
    """
    Add a coupon to a Customer.

    The coupon can be a Coupon object, or a valid Stripe Coupon ID.
    """
    if isinstance(coupon, StripeModel):
        coupon = coupon.id

    stripe_customer = self.api_retrieve()
    stripe_customer["coupon"] = coupon
    stripe_customer.save(idempotency_key=idempotency_key)
    return self.__class__.sync_from_stripe_data(
        stripe_customer, api_key=self.default_api_key
    )
djstripe.models.core.Customer.add_invoice_item(amount, currency, description=None, discountable=None, invoice=None, metadata=None, subscription=None)

Adds an arbitrary charge or credit to the customer's upcoming invoice. Different than creating a charge. Charges are separate bills that get processed immediately. Invoice items are appended to the customer's next invoice. This is extremely useful when adding surcharges to subscriptions.

:param amount: The amount to charge. :type amount: Decimal. Precision is 2; anything more will be ignored. :param currency: 3-letter ISO code for currency :type currency: string :param description: An arbitrary string. :type description: string :param discountable: Controls whether discounts apply to this invoice item. Defaults to False for prorations or negative invoice items, and True for all other invoice items. :type discountable: boolean :param invoice: An existing invoice to add this invoice item to. When left blank, the invoice item will be added to the next upcoming scheduled invoice. Use this when adding invoice items in response to an invoice.created webhook. You cannot add an invoice item to an invoice that has already been paid, attempted or closed. :type invoice: Invoice or string (invoice ID) :param metadata: A set of key/value pairs useful for storing additional information. :type metadata: dict :param subscription: A subscription to add this invoice item to. When left blank, the invoice item will be be added to the next upcoming scheduled invoice. When set, scheduled invoices for subscriptions other than the specified subscription will ignore the invoice item. Use this when you want to express that an invoice item has been accrued within the context of a particular subscription. :type subscription: Subscription or string (subscription ID)

.. Notes: .. if you're using Customer.add_invoice_item() instead of .. Customer.add_invoice_item(), invoice and subscriptions .. can only be strings

Source code in djstripe/models/core.py
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
def add_invoice_item(
    self,
    amount,
    currency,
    description=None,
    discountable=None,
    invoice=None,
    metadata=None,
    subscription=None,
):
    """
    Adds an arbitrary charge or credit to the customer's upcoming invoice.
    Different than creating a charge. Charges are separate bills that get
    processed immediately. Invoice items are appended to the customer's next
    invoice. This is extremely useful when adding surcharges to subscriptions.

    :param amount: The amount to charge.
    :type amount: Decimal. Precision is 2; anything more will be ignored.
    :param currency: 3-letter ISO code for currency
    :type currency: string
    :param description: An arbitrary string.
    :type description: string
    :param discountable: Controls whether discounts apply to this invoice item.
        Defaults to False for prorations or negative invoice items,
        and True for all other invoice items.
    :type discountable: boolean
    :param invoice: An existing invoice to add this invoice item to.
        When left blank, the invoice item will be added to the next upcoming \
         scheduled invoice. \
         Use this when adding invoice items in response to an \
         ``invoice.created`` webhook. You cannot add an invoice \
        item to an invoice that has already been paid, attempted or closed.
    :type invoice: Invoice or string (invoice ID)
    :param metadata: A set of key/value pairs useful for storing
        additional information.
    :type metadata: dict
    :param subscription: A subscription to add this invoice item to.
        When left blank, the invoice item will be be added to the next upcoming \
        scheduled invoice. When set, scheduled invoices for subscriptions other \
        than the specified subscription will ignore the invoice item. \
        Use this when you want to express that an invoice item has been accrued \
        within the context of a particular subscription.
    :type subscription: Subscription or string (subscription ID)

    .. Notes:
    .. if you're using ``Customer.add_invoice_item()`` instead of
    .. ``Customer.add_invoice_item()``, ``invoice`` and ``subscriptions``
    .. can only be strings
    """
    from .billing import InvoiceItem

    if not isinstance(amount, Decimal):
        raise ValueError("You must supply a decimal value representing dollars.")

    # Convert Invoice to id
    if invoice is not None and isinstance(invoice, StripeModel):
        invoice = invoice.id

    # Convert Subscription to id
    if subscription is not None and isinstance(subscription, StripeModel):
        subscription = subscription.id

    stripe_invoiceitem = InvoiceItem._api_create(
        amount=int(amount * 100),  # Convert dollars into cents
        currency=currency,
        customer=self.id,
        description=description,
        discountable=discountable,
        invoice=invoice,
        metadata=metadata,
        subscription=subscription,
    )

    return InvoiceItem.sync_from_stripe_data(
        stripe_invoiceitem, api_key=self.default_api_key
    )
djstripe.models.core.Customer.add_payment_method(payment_method, set_default=True)

Adds an already existing payment method to this customer's account

:param payment_method: PaymentMethod to be attached to the customer :type payment_method: str, PaymentMethod :param set_default: If true, this will be set as the default_payment_method :type set_default: bool :rtype: PaymentMethod

Source code in djstripe/models/core.py
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
def add_payment_method(self, payment_method, set_default=True):
    """
    Adds an already existing payment method to this customer's account

    :param payment_method: PaymentMethod to be attached to the customer
    :type payment_method: str, PaymentMethod
    :param set_default: If true, this will be set as the default_payment_method
    :type set_default: bool
    :rtype: PaymentMethod
    """
    from .payment_methods import PaymentMethod

    stripe_customer = self.api_retrieve()
    payment_method = PaymentMethod.attach(payment_method, stripe_customer)

    if set_default:
        stripe_customer["invoice_settings"][
            "default_payment_method"
        ] = payment_method.id
        stripe_customer.save()

        # Refresh self from the stripe customer, this should have two effects:
        # 1) sets self.default_payment_method (we rely on logic in
        # Customer._manipulate_stripe_object_hook to do this)
        # 2) updates self.invoice_settings.default_payment_methods
        self.sync_from_stripe_data(stripe_customer, api_key=self.default_api_key)
        self.refresh_from_db()

    return payment_method
djstripe.models.core.Customer.charge(amount, *, application_fee=None, source=None, **kwargs)

Creates a charge for this customer.

:param amount: The amount to charge. :type amount: Decimal. Precision is 2; anything more will be ignored. :param source: The source to use for this charge. Must be a source attributed to this customer. If None, the customer's default source is used. Can be either the id of the source or the source object itself. :type source: string, Source

Source code in djstripe/models/core.py
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
def charge(
    self,
    amount: Decimal,
    *,
    application_fee: Decimal = None,
    source: Union[str, StripeModel] = None,
    **kwargs,
) -> Charge:
    """
    Creates a charge for this customer.

    :param amount: The amount to charge.
    :type amount: Decimal. Precision is 2; anything more will be ignored.
    :param source: The source to use for this charge.
        Must be a source attributed to this customer. If None, the customer's
        default source is used. Can be either the id of the source or
        the source object itself.
    :type source: string, Source
    """

    if not isinstance(amount, Decimal):
        raise ValueError("You must supply a decimal value representing dollars.")

    # Convert Source to id
    if source and isinstance(source, StripeModel):
        source = source.id

    stripe_charge = Charge._api_create(
        customer=self.id,
        amount=int(amount * 100),  # Convert dollars into cents
        application_fee=(
            int(application_fee * 100) if application_fee else None
        ),  # Convert dollars into cents
        source=source,
        **kwargs,
    )

    api_key = kwargs.get("api_key") or self.default_api_key
    return Charge.sync_from_stripe_data(stripe_charge, api_key=api_key)
djstripe.models.core.Customer.create(subscriber, idempotency_key=None, stripe_account=None) classmethod
Source code in djstripe/models/core.py
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
@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
djstripe.models.core.Customer.get_or_create(subscriber, livemode=djstripe_settings.STRIPE_LIVE_MODE, stripe_account=None) classmethod

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

Source code in djstripe/models/core.py
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
@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,
        )
djstripe.models.core.Customer.has_any_active_subscription()

Checks to see if this customer has an active subscription to any plan.

:returns: True if there exists an active subscription, False otherwise.

Source code in djstripe/models/core.py
1247
1248
1249
1250
1251
1252
1253
1254
def has_any_active_subscription(self):
    """
    Checks to see if this customer has an active subscription to any plan.

    :returns: True if there exists an active subscription, False otherwise.
    """

    return len(self._get_valid_subscriptions()) != 0
djstripe.models.core.Customer.is_subscribed_to(product)

Checks to see if this customer has an active subscription to the given product.

:param product: The product for which to check for an active subscription. :type product: Product or string (product ID)

:returns: True if there exists an active subscription, False otherwise.

Source code in djstripe/models/core.py
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
def is_subscribed_to(self, product: Union[Product, str]) -> bool:
    """
    Checks to see if this customer has an active subscription to the given product.

    :param product: The product for which to check for an active subscription.
    :type product: Product or string (product ID)

    :returns: True if there exists an active subscription, False otherwise.
    """

    if isinstance(product, StripeModel):
        product = product.id

    for subscription in self._get_valid_subscriptions():
        for item in subscription.items.all():
            if item.price and item.price.product.id == product:
                return True
    return False
djstripe.models.core.Customer.purge()

Customers are soft deleted as deleted customers are still accessible by the Stripe API and sync for all RelatedModels would fail

Source code in djstripe/models/core.py
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
def purge(self):
    """Customers are soft deleted as deleted customers are still accessible by the
    Stripe API and sync for all RelatedModels would fail"""
    try:
        self._api_delete()
    except InvalidRequestError as exc:
        if "No such customer:" in str(exc):
            # The exception was thrown because the stripe customer was already
            # deleted on the stripe side, ignore the exception
            pass
        else:
            # The exception was raised for another reason, re-raise it
            raise

    # toggle the deleted flag on Customer to indicate it has been
    # deleted upstream in Stripe
    self.deleted = True

    if self.subscriber:
        # Delete the idempotency key used by Customer.create()
        # So re-creating a customer for this subscriber before the key expires
        # doesn't return the older Customer data
        idempotency_key_action = f"customer:create:{self.subscriber.pk}"
        IdempotencyKey.objects.filter(action=idempotency_key_action).delete()

    self.subscriber = None

    # Remove sources
    self.default_source = None
    for source in self.legacy_cards.all():
        source.remove()

    for source in self.sources.all():
        source.detach()

    self.date_purged = timezone.now()
    self.save()
djstripe.models.core.Customer.retry_unpaid_invoices(**kwargs)

Attempt to retry collecting payment on the customer's unpaid invoices.

Source code in djstripe/models/core.py
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
def retry_unpaid_invoices(self, **kwargs):
    """Attempt to retry collecting payment on the customer's unpaid invoices."""

    self._sync_invoices()
    for invoice in self.invoices.filter(auto_advance=True).exclude(status="paid"):
        try:
            invoice.retry(**kwargs)  # Always retry unpaid invoices
        except InvalidRequestError as exc:
            if str(exc) != "Invoice is already paid":
                raise
djstripe.models.core.Customer.send_invoice(**kwargs)

Pay and send the customer's latest invoice.

:returns: True if an invoice was able to be created and paid, False otherwise (typically if there was nothing to invoice).

Source code in djstripe/models/core.py
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
def send_invoice(self, **kwargs):
    """
    Pay and send the customer's latest invoice.

    :returns: True if an invoice was able to be created and paid, False otherwise
        (typically if there was nothing to invoice).
    """
    from .billing import Invoice

    try:
        invoice = Invoice._api_create(customer=self.id)
        invoice.pay(**kwargs)
        return True
    except InvalidRequestError:  # TODO: Check this for a more
        #                           specific error message.
        return False  # There was nothing to invoice
djstripe.models.core.Customer.subscribe(*, 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)

Source code in djstripe/models/core.py
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
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)
djstripe.models.core.Customer.upcoming_invoice(**kwargs)

Gets the upcoming preview invoice (singular) for this customer.

See Invoice.upcoming() <#djstripe.Invoice.upcoming>__.

The customer argument to the upcoming() call is automatically set by this method.

Source code in djstripe/models/core.py
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
def upcoming_invoice(self, **kwargs):
    """Gets the upcoming preview invoice (singular) for this customer.

    See `Invoice.upcoming() <#djstripe.Invoice.upcoming>`__.

    The ``customer`` argument to the ``upcoming()`` call is automatically set
     by this method.
    """
    from .billing import Invoice

    kwargs["customer"] = self
    return Invoice.upcoming(**kwargs)

djstripe.models.core.Dispute

Bases: StripeModel

A dispute occurs when a customer questions your charge with their card issuer. When this happens, you're given the opportunity to respond to the dispute with evidence that shows that the charge is legitimate

Stripe documentation: https://stripe.com/docs/api?lang=python#disputes

Source code in djstripe/models/core.py
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
class Dispute(StripeModel):
    """
    A dispute occurs when a customer questions your charge with their
    card issuer. When this happens, you're given the opportunity to
    respond to the dispute with evidence that shows that the charge is legitimate

    Stripe documentation: https://stripe.com/docs/api?lang=python#disputes
    """

    stripe_class = stripe.Dispute
    stripe_dashboard_item_name = "payments"

    amount = StripeQuantumCurrencyAmountField(
        help_text=(
            "Disputed amount (in cents). Usually the amount of the charge, "
            "but can differ "
            "(usually because of currency fluctuation or because only part of "
            "the order is disputed)."
        )
    )
    balance_transaction = StripeForeignKey(
        "BalanceTransaction",
        null=True,
        on_delete=models.CASCADE,
        related_name="disputes",
        help_text=(
            "Balance transaction that describes the impact on your account balance."
        ),
    )
    balance_transactions = JSONField(
        default=list,
        help_text=(
            "List of 0, 1 or 2 Balance Transactions that show funds withdrawn and"
            " reinstated to your Stripe account as a result of this dispute."
        ),
    )
    # charge is nullable to avoid infinite sync as Charge model has a dispute field as well
    charge = StripeForeignKey(
        "Charge",
        null=True,
        on_delete=models.CASCADE,
        related_name="disputes",
        help_text="The charge that was disputed",
    )
    currency = StripeCurrencyCodeField()
    evidence = JSONField(help_text="Evidence provided to respond to a dispute.")
    evidence_details = JSONField(help_text="Information about the evidence submission.")
    is_charge_refundable = models.BooleanField(
        help_text=(
            "If true, it is still possible to refund the disputed payment. "
            "Once the payment has been fully refunded, no further funds will "
            "be withdrawn from your Stripe account as a result of this dispute."
        )
    )
    payment_intent = StripeForeignKey(
        "PaymentIntent",
        null=True,
        on_delete=models.CASCADE,
        related_name="disputes",
        help_text="The PaymentIntent that was disputed",
    )
    reason = StripeEnumField(enum=enums.DisputeReason)
    status = StripeEnumField(enum=enums.DisputeStatus)

    def __str__(self):
        amount = get_friendly_currency_amount(self.amount / 100, self.currency)
        status = enums.DisputeStatus.humanize(self.status)
        return f"{amount} ({status}) "

    def get_stripe_dashboard_url(self) -> str:
        """Get the stripe dashboard url for this object."""
        return (
            f"{self._get_base_stripe_dashboard_url()}"
            f"{self.stripe_dashboard_item_name}/{self.payment_intent.id}"
        )

    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
        )

        # Retrieve and save files from the dispute.evidence object.
        # todo find a better way of retrieving and syncing File Type fields from Dispute object
        for field in (
            "cancellation_policy",
            "customer_communication",
            "customer_signature",
            "duplicate_charge_documentation",
            "receipt",
            "refund_policy",
            "service_documentation",
            "shipping_documentation",
            "uncategorized_file",
        ):
            file_upload_id = self.evidence.get(field, None)
            if file_upload_id:
                try:
                    File.sync_from_stripe_data(
                        File(id=file_upload_id).api_retrieve(api_key=api_key),
                        api_key=api_key,
                    )
                except stripe.error.PermissionError:
                    # No permission to retrieve the data with the key
                    # Log a warning message
                    logger.warning(
                        "No permission to retrieve the File Evidence Object."
                    )
                except stripe.error.InvalidRequestError:
                    raise

        # iterate and sync every balance transaction
        for stripe_balance_transaction in self.balance_transactions:
            BalanceTransaction.sync_from_stripe_data(
                stripe_balance_transaction, api_key=api_key
            )

Attributes

djstripe.models.core.Dispute.amount = StripeQuantumCurrencyAmountField(help_text='Disputed amount (in cents). Usually the amount of the charge, but can differ (usually because of currency fluctuation or because only part of the order is disputed).') class-attribute instance-attribute
djstripe.models.core.Dispute.balance_transaction = StripeForeignKey('BalanceTransaction', null=True, on_delete=models.CASCADE, related_name='disputes', help_text='Balance transaction that describes the impact on your account balance.') class-attribute instance-attribute
djstripe.models.core.Dispute.balance_transactions = JSONField(default=list, help_text='List of 0, 1 or 2 Balance Transactions that show funds withdrawn and reinstated to your Stripe account as a result of this dispute.') class-attribute instance-attribute
djstripe.models.core.Dispute.charge = StripeForeignKey('Charge', null=True, on_delete=models.CASCADE, related_name='disputes', help_text='The charge that was disputed') class-attribute instance-attribute
djstripe.models.core.Dispute.currency = StripeCurrencyCodeField() class-attribute instance-attribute
djstripe.models.core.Dispute.evidence = JSONField(help_text='Evidence provided to respond to a dispute.') class-attribute instance-attribute
djstripe.models.core.Dispute.evidence_details = JSONField(help_text='Information about the evidence submission.') class-attribute instance-attribute
djstripe.models.core.Dispute.is_charge_refundable = models.BooleanField(help_text='If true, it is still possible to refund the disputed payment. Once the payment has been fully refunded, no further funds will be withdrawn from your Stripe account as a result of this dispute.') class-attribute instance-attribute
djstripe.models.core.Dispute.payment_intent = StripeForeignKey('PaymentIntent', null=True, on_delete=models.CASCADE, related_name='disputes', help_text='The PaymentIntent that was disputed') class-attribute instance-attribute
djstripe.models.core.Dispute.reason = StripeEnumField(enum=enums.DisputeReason) class-attribute instance-attribute
djstripe.models.core.Dispute.status = StripeEnumField(enum=enums.DisputeStatus) class-attribute instance-attribute
djstripe.models.core.Dispute.stripe_class = stripe.Dispute class-attribute instance-attribute
djstripe.models.core.Dispute.stripe_dashboard_item_name = 'payments' class-attribute instance-attribute

Functions

djstripe.models.core.Dispute.__str__()
Source code in djstripe/models/core.py
1522
1523
1524
1525
def __str__(self):
    amount = get_friendly_currency_amount(self.amount / 100, self.currency)
    status = enums.DisputeStatus.humanize(self.status)
    return f"{amount} ({status}) "
djstripe.models.core.Dispute.get_stripe_dashboard_url()

Get the stripe dashboard url for this object.

Source code in djstripe/models/core.py
1527
1528
1529
1530
1531
1532
def get_stripe_dashboard_url(self) -> str:
    """Get the stripe dashboard url for this object."""
    return (
        f"{self._get_base_stripe_dashboard_url()}"
        f"{self.stripe_dashboard_item_name}/{self.payment_intent.id}"
    )

djstripe.models.core.Event

Bases: StripeModel

Events are Stripe's way of letting you know when something interesting happens in your account. When an interesting event occurs, a new Event object is created and POSTed to the configured webhook URL if the Event type matches.

Stripe documentation: https://stripe.com/docs/api/events?lang=python

Source code in djstripe/models/core.py
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
class Event(StripeModel):
    """
    Events are Stripe's way of letting you know when something interesting
    happens in your account.
    When an interesting event occurs, a new Event object is created and POSTed
    to the configured webhook URL if the Event type matches.

    Stripe documentation: https://stripe.com/docs/api/events?lang=python
    """

    stripe_class = stripe.Event
    stripe_dashboard_item_name = "events"

    api_version = models.CharField(
        max_length=64,
        blank=True,
        help_text=(
            "the API version at which the event data was "
            "rendered. Blank for old entries only, all new entries will have this value"
        ),
    )
    data = JSONField(
        help_text=(
            "data received at webhook. data should be considered to be garbage "
            "until validity check is run and valid flag is set"
        )
    )
    request_id = models.CharField(
        max_length=50,
        help_text=(
            "Information about the request that triggered this event, "
            "for traceability purposes. If empty string then this is an old entry "
            "without that data. If Null then this is not an old entry, but a Stripe "
            "'automated' event with no associated request."
        ),
        default="",
        blank=True,
    )
    idempotency_key = models.TextField(default="", blank=True)
    type = models.CharField(max_length=250, help_text="Stripe's event description code")

    def __str__(self):
        return f"type={self.type}, id={self.id}"

    def _attach_objects_hook(
        self, cls, data, current_ids=None, api_key=djstripe_settings.STRIPE_SECRET_KEY
    ):
        if self.api_version is None:
            # as of api version 2017-02-14, the account.application.deauthorized
            # event sends None as api_version.
            # If we receive that, store an empty string instead.
            # Remove this hack if this gets fixed upstream.
            self.api_version = ""

        request_obj = data.get("request", None)
        if isinstance(request_obj, dict):
            # Format as of 2017-05-25
            self.request_id = request_obj.get("id") or ""
            self.idempotency_key = request_obj.get("idempotency_key") or ""
        else:
            # Format before 2017-05-25
            self.request_id = request_obj or ""

    @classmethod
    def process(cls, data, api_key=djstripe_settings.STRIPE_SECRET_KEY):
        qs = cls.objects.filter(id=data["id"])
        if qs.exists():
            return qs.first()

        # Rollback any DB operations in the case of failure so
        # we will retry creating and processing the event the
        # next time the webhook fires.
        with transaction.atomic():
            # process the event and create an Event Object
            ret = cls._create_from_stripe_object(data, api_key=api_key)
            ret.invoke_webhook_handlers()
            return ret

    def invoke_webhook_handlers(self):
        """
        Invokes any webhook handlers that have been registered for this event
        based on event type or event sub-type.

        See event handlers registered in the ``djstripe.event_handlers`` module
        (or handlers registered in djstripe plugins or contrib packages).
        """

        webhooks.call_handlers(event=self)

        signal = WEBHOOK_SIGNALS.get(self.type)
        if signal:
            return signal.send(sender=Event, event=self)

    @cached_property
    def parts(self):
        """Gets the event category/verb as a list of parts."""
        return str(self.type).split(".")

    @cached_property
    def category(self):
        """Gets the event category string (e.g. 'customer')."""
        return self.parts[0]

    @cached_property
    def verb(self):
        """Gets the event past-tense verb string (e.g. 'updated')."""
        return ".".join(self.parts[1:])

    @property
    def customer(self):
        data = self.data["object"]
        if data["object"] == "customer":
            customer_id = get_id_from_stripe_data(data.get("id"))
        else:
            customer_id = get_id_from_stripe_data(data.get("customer"))

        if customer_id:
            return Customer._get_or_retrieve(
                id=customer_id,
                stripe_account=getattr(self.djstripe_owner_account, "id", None),
                api_key=self.default_api_key,
            )

Attributes

djstripe.models.core.Event.api_version = models.CharField(max_length=64, blank=True, help_text='the API version at which the event data was rendered. Blank for old entries only, all new entries will have this value') class-attribute instance-attribute
djstripe.models.core.Event.customer property
djstripe.models.core.Event.data = JSONField(help_text='data received at webhook. data should be considered to be garbage until validity check is run and valid flag is set') class-attribute instance-attribute
djstripe.models.core.Event.idempotency_key = models.TextField(default='', blank=True) class-attribute instance-attribute
djstripe.models.core.Event.request_id = models.CharField(max_length=50, help_text="Information about the request that triggered this event, for traceability purposes. If empty string then this is an old entry without that data. If Null then this is not an old entry, but a Stripe 'automated' event with no associated request.", default='', blank=True) class-attribute instance-attribute
djstripe.models.core.Event.stripe_class = stripe.Event class-attribute instance-attribute
djstripe.models.core.Event.stripe_dashboard_item_name = 'events' class-attribute instance-attribute
djstripe.models.core.Event.type = models.CharField(max_length=250, help_text="Stripe's event description code") class-attribute instance-attribute

Functions

djstripe.models.core.Event.__str__()
Source code in djstripe/models/core.py
1622
1623
def __str__(self):
    return f"type={self.type}, id={self.id}"
djstripe.models.core.Event.category()

Gets the event category string (e.g. 'customer').

Source code in djstripe/models/core.py
1679
1680
1681
1682
@cached_property
def category(self):
    """Gets the event category string (e.g. 'customer')."""
    return self.parts[0]
djstripe.models.core.Event.invoke_webhook_handlers()

Invokes any webhook handlers that have been registered for this event based on event type or event sub-type.

See event handlers registered in the djstripe.event_handlers module (or handlers registered in djstripe plugins or contrib packages).

Source code in djstripe/models/core.py
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
def invoke_webhook_handlers(self):
    """
    Invokes any webhook handlers that have been registered for this event
    based on event type or event sub-type.

    See event handlers registered in the ``djstripe.event_handlers`` module
    (or handlers registered in djstripe plugins or contrib packages).
    """

    webhooks.call_handlers(event=self)

    signal = WEBHOOK_SIGNALS.get(self.type)
    if signal:
        return signal.send(sender=Event, event=self)
djstripe.models.core.Event.parts()

Gets the event category/verb as a list of parts.

Source code in djstripe/models/core.py
1674
1675
1676
1677
@cached_property
def parts(self):
    """Gets the event category/verb as a list of parts."""
    return str(self.type).split(".")
djstripe.models.core.Event.process(data, api_key=djstripe_settings.STRIPE_SECRET_KEY) classmethod
Source code in djstripe/models/core.py
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
@classmethod
def process(cls, data, api_key=djstripe_settings.STRIPE_SECRET_KEY):
    qs = cls.objects.filter(id=data["id"])
    if qs.exists():
        return qs.first()

    # Rollback any DB operations in the case of failure so
    # we will retry creating and processing the event the
    # next time the webhook fires.
    with transaction.atomic():
        # process the event and create an Event Object
        ret = cls._create_from_stripe_object(data, api_key=api_key)
        ret.invoke_webhook_handlers()
        return ret
djstripe.models.core.Event.verb()

Gets the event past-tense verb string (e.g. 'updated').

Source code in djstripe/models/core.py
1684
1685
1686
1687
@cached_property
def verb(self):
    """Gets the event past-tense verb string (e.g. 'updated')."""
    return ".".join(self.parts[1:])

djstripe.models.core.File

Bases: StripeModel

This is an object representing a file hosted on Stripe's servers. The file may have been uploaded by yourself using the create file request (for example, when uploading dispute evidence) or it may have been created by Stripe (for example, the results of a Sigma scheduled query).

Stripe documentation: https://stripe.com/docs/api/files?lang=python

Source code in djstripe/models/core.py
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
class File(StripeModel):
    """
    This is an object representing a file hosted on Stripe's servers.
    The file may have been uploaded by yourself using the create file request
    (for example, when uploading dispute evidence) or it may have been created by
    Stripe (for example, the results of a Sigma scheduled query).

    Stripe documentation: https://stripe.com/docs/api/files?lang=python
    """

    stripe_class = stripe.File

    filename = models.CharField(
        max_length=255,
        help_text="A filename for the file, suitable for saving to a filesystem.",
    )
    purpose = StripeEnumField(
        enum=enums.FilePurpose, help_text="The purpose of the uploaded file."
    )
    size = models.IntegerField(help_text="The size in bytes of the file upload object.")
    type = StripeEnumField(
        enum=enums.FileType, help_text="The type of the file returned."
    )
    url = models.CharField(
        max_length=200,
        help_text="A read-only URL where the uploaded file can be accessed.",
    )

    @classmethod
    def is_valid_object(cls, data):
        return data and data.get("object") in ("file", "file_upload")

    def __str__(self):
        return f"{self.filename}, {enums.FilePurpose.humanize(self.purpose)}"

Attributes

djstripe.models.core.File.filename = models.CharField(max_length=255, help_text='A filename for the file, suitable for saving to a filesystem.') class-attribute instance-attribute
djstripe.models.core.File.purpose = StripeEnumField(enum=enums.FilePurpose, help_text='The purpose of the uploaded file.') class-attribute instance-attribute
djstripe.models.core.File.size = models.IntegerField(help_text='The size in bytes of the file upload object.') class-attribute instance-attribute
djstripe.models.core.File.stripe_class = stripe.File class-attribute instance-attribute
djstripe.models.core.File.type = StripeEnumField(enum=enums.FileType, help_text='The type of the file returned.') class-attribute instance-attribute
djstripe.models.core.File.url = models.CharField(max_length=200, help_text='A read-only URL where the uploaded file can be accessed.') class-attribute instance-attribute

Functions

djstripe.models.core.File.__str__()
Source code in djstripe/models/core.py
1737
1738
def __str__(self):
    return f"{self.filename}, {enums.FilePurpose.humanize(self.purpose)}"
djstripe.models.core.File.is_valid_object(data) classmethod
Source code in djstripe/models/core.py
1733
1734
1735
@classmethod
def is_valid_object(cls, data):
    return data and data.get("object") in ("file", "file_upload")

Bases: StripeModel

To share the contents of a File object with non-Stripe users, you can create a FileLink. FileLinks contain a URL that can be used to retrieve the contents of the file without authentication.

Stripe documentation: https://stripe.com/docs/api/file_links?lang=python

Source code in djstripe/models/core.py
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
class FileLink(StripeModel):
    """
    To share the contents of a File object with non-Stripe users,
    you can create a FileLink. FileLinks contain a URL that can be used
    to retrieve the contents of the file without authentication.

    Stripe documentation: https://stripe.com/docs/api/file_links?lang=python
    """

    stripe_class = stripe.FileLink

    expires_at = StripeDateTimeField(
        null=True, blank=True, help_text="Time at which the link expires."
    )
    file = StripeForeignKey("File", on_delete=models.CASCADE)
    url = models.URLField(help_text="The publicly accessible URL to download the file.")

    def __str__(self):
        return f"{self.file.filename}, {self.url}"
djstripe.models.core.FileLink.expires_at = StripeDateTimeField(null=True, blank=True, help_text='Time at which the link expires.') class-attribute instance-attribute
djstripe.models.core.FileLink.file = StripeForeignKey('File', on_delete=models.CASCADE) class-attribute instance-attribute
djstripe.models.core.FileLink.stripe_class = stripe.FileLink class-attribute instance-attribute
djstripe.models.core.FileLink.url = models.URLField(help_text='The publicly accessible URL to download the file.') class-attribute instance-attribute
djstripe.models.core.FileLink.__str__()
Source code in djstripe/models/core.py
1764
1765
def __str__(self):
    return f"{self.file.filename}, {self.url}"

djstripe.models.core.Mandate

Bases: 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

Source code in djstripe/models/core.py
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
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."
        ),
    )

Attributes

djstripe.models.core.Mandate.customer_acceptance = JSONField(help_text="Details about the customer's acceptance of the mandate.") class-attribute instance-attribute
djstripe.models.core.Mandate.multi_use = JSONField(null=True, blank=True, help_text='If this is a `multi_use` mandate, this hash contains details about the mandate.') class-attribute instance-attribute
djstripe.models.core.Mandate.payment_method = StripeForeignKey('paymentmethod', on_delete=models.CASCADE) class-attribute instance-attribute
djstripe.models.core.Mandate.payment_method_details = JSONField(help_text='Additional mandate information specific to the payment method type.') class-attribute instance-attribute
djstripe.models.core.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-attribute instance-attribute
djstripe.models.core.Mandate.status = StripeEnumField(enum=enums.MandateStatus, help_text='The status of the mandate, which indicates whether it can be used to initiate a payment.') class-attribute instance-attribute
djstripe.models.core.Mandate.stripe_class = stripe.Mandate class-attribute instance-attribute
djstripe.models.core.Mandate.type = StripeEnumField(enum=enums.MandateType, help_text='The status of the mandate, which indicates whether it can be used to initiate a payment.') class-attribute instance-attribute

djstripe.models.core.PaymentIntent

Bases: StripeModel

A PaymentIntent guides you through the process of collecting a payment from your customer. We recommend that you create exactly one PaymentIntent for each order or customer session in your system. You can reference the PaymentIntent later to see the history of payment attempts for a particular session.

A PaymentIntent transitions through multiple statuses throughout its lifetime as it interfaces with Stripe.js to perform authentication flows and ultimately creates at most one successful charge.

Stripe documentation: https://stripe.com/docs/api?lang=python#payment_intents

Source code in djstripe/models/core.py
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
class PaymentIntent(StripeModel):
    """
    A PaymentIntent guides you through the process of collecting a payment
    from your customer. We recommend that you create exactly one PaymentIntent for each order
    or customer session in your system. You can reference the PaymentIntent later to
    see the history of payment attempts for a particular session.

    A PaymentIntent transitions through multiple statuses throughout its lifetime as
    it interfaces with Stripe.js to perform authentication flows and ultimately
    creates at most one successful charge.

    Stripe documentation: https://stripe.com/docs/api?lang=python#payment_intents
    """

    stripe_class = stripe.PaymentIntent
    stripe_dashboard_item_name = "payments"

    amount = StripeQuantumCurrencyAmountField(
        help_text="Amount (in cents) intended to be collected by this PaymentIntent."
    )
    amount_capturable = StripeQuantumCurrencyAmountField(
        help_text="Amount (in cents) that can be captured from this PaymentIntent."
    )
    amount_received = StripeQuantumCurrencyAmountField(
        help_text="Amount (in cents) that was collected by this PaymentIntent."
    )
    # application
    # application_fee_amount
    canceled_at = StripeDateTimeField(
        null=True,
        blank=True,
        default=None,
        help_text=(
            "Populated when status is canceled, this is the time at which the "
            "PaymentIntent was canceled. Measured in seconds since the Unix epoch."
        ),
    )

    cancellation_reason = StripeEnumField(
        enum=enums.PaymentIntentCancellationReason,
        blank=True,
        help_text=(
            "Reason for cancellation of this PaymentIntent, either user-provided "
            "(duplicate, fraudulent, requested_by_customer, or abandoned) or "
            "generated by Stripe internally (failed_invoice, void_invoice, "
            "or automatic)."
        ),
    )
    capture_method = StripeEnumField(
        enum=enums.CaptureMethod,
        help_text="Capture method of this PaymentIntent, one of automatic or manual.",
    )
    client_secret = models.TextField(
        max_length=5000,
        help_text=(
            "The client secret of this PaymentIntent. "
            "Used for client-side retrieval using a publishable key."
        ),
    )
    confirmation_method = StripeEnumField(
        enum=enums.ConfirmationMethod,
        help_text=(
            "Confirmation method of this PaymentIntent, one of manual or automatic."
        ),
    )
    currency = StripeCurrencyCodeField()
    customer = StripeForeignKey(
        "Customer",
        null=True,
        on_delete=models.CASCADE,
        help_text="Customer this PaymentIntent is for if one exists.",
    )
    description = models.TextField(
        max_length=1000,
        default="",
        blank=True,
        help_text=(
            "An arbitrary string attached to the object. "
            "Often useful for displaying to users."
        ),
    )
    last_payment_error = JSONField(
        null=True,
        blank=True,
        help_text=(
            "The payment error encountered in the previous PaymentIntent confirmation."
        ),
    )
    next_action = JSONField(
        null=True,
        blank=True,
        help_text=(
            "If present, this property tells you what actions you need to take "
            "in order for your customer to fulfill a payment using the provided source."
        ),
    )
    on_behalf_of = StripeForeignKey(
        "Account",
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        help_text=(
            "The account (if any) for which the funds of the "
            "PaymentIntent are intended."
        ),
        related_name="payment_intents",
    )
    payment_method = StripeForeignKey(
        "PaymentMethod",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        help_text="Payment method used in this PaymentIntent.",
    )
    payment_method_types = JSONField(
        help_text=(
            "The list of payment method types (e.g. card) that this "
            "PaymentIntent is allowed to use."
        )
    )
    receipt_email = models.CharField(
        blank=True,
        max_length=255,
        help_text=(
            "Email address that the receipt for the resulting payment will be sent to."
        ),
    )
    # TODO: Add `review` field after we add Review model.
    setup_future_usage = StripeEnumField(
        enum=enums.IntentUsage,
        null=True,
        blank=True,
        help_text=(
            "Indicates that you intend to make future payments with this "
            "PaymentIntent's payment method. "
            "If present, the payment method used with this PaymentIntent can "
            "be attached to a Customer, even after the transaction completes. "
            "Use `on_session` if you intend to only reuse the payment method "
            "when your customer is present in your checkout flow. Use `off_session` "
            "if your customer may or may not be in your checkout flow. "
            "Stripe uses `setup_future_usage` to dynamically optimize "
            "your payment flow and comply with regional legislation and network rules. "
            "For example, if your customer is impacted by SCA, using `off_session` "
            "will ensure that they are authenticated while processing this "
            "PaymentIntent. You will then be able to make later off-session payments "
            "for this customer."
        ),
    )
    shipping = JSONField(
        null=True, blank=True, help_text="Shipping information for this PaymentIntent."
    )
    statement_descriptor = models.CharField(
        max_length=22,
        blank=True,
        help_text=(
            "For non-card charges, you can use this value as the complete description "
            "that appears on your customers' statements. Must contain at least one "
            "letter, maximum 22 characters."
        ),
    )
    status = StripeEnumField(
        enum=enums.PaymentIntentStatus,
        help_text=(
            "Status of this PaymentIntent, one of requires_payment_method, "
            "requires_confirmation, requires_action, processing, requires_capture, "
            "canceled, or succeeded. "
            "You can read more about PaymentIntent statuses here."
        ),
    )
    transfer_data = JSONField(
        null=True,
        blank=True,
        help_text=(
            "The data with which to automatically create a Transfer when the payment "
            "is finalized. "
            "See the PaymentIntents Connect usage guide for details."
        ),
    )
    transfer_group = models.CharField(
        blank=True,
        max_length=255,
        help_text=(
            "A string that identifies the resulting payment as part of a group. "
            "See the PaymentIntents Connect usage guide for details."
        ),
    )

    def __str__(self):
        account = self.on_behalf_of
        customer = self.customer
        amount = get_friendly_currency_amount(self.amount / 100, self.currency)
        status = enums.PaymentIntentStatus.humanize(self.status)

        if account and customer:
            return f"{amount} ({status}) for {account} by {customer}"
        if account:
            return f"{amount} for {account}. {status}"
        if customer:
            return f"{amount} by {customer}. {status}"

        return f"{amount} ({status})"

    def update(self, api_key=None, **kwargs):
        """
        Call the stripe API's modify operation for thi