Django + Stripe Made Easy

  • Subscription management
  • Designed for easy implementation of post-registration subscription forms
  • Single-unit purchases
  • Works with Django >= 2.1
  • Works with Python >= 3.5
  • Built-in migrations
  • Dead-Easy installation
  • Leverages the best of the 3rd party Django package ecosystem
  • djstripe namespace so you can have more than one payments related app
  • Documented
  • 100% Tested

Contents

Installation

Get the distribution

Install dj-stripe:

pip install dj-stripe

Configuration

Add djstripe to your INSTALLED_APPS:

INSTALLED_APPS =(
    ...
    "djstripe",
    ...
)

Add to urls.py:

path("stripe/", include("djstripe.urls", namespace="djstripe")),

Tell Stripe about the webhook (Stripe webhook docs can be found here) using the full URL of your endpoint from the urls.py step above (e.g. https://example.com/stripe/webhook).

Add your Stripe keys and set the operating mode:

STRIPE_LIVE_PUBLIC_KEY = os.environ.get("STRIPE_LIVE_PUBLIC_KEY", "<your publishable key>")
STRIPE_LIVE_SECRET_KEY = os.environ.get("STRIPE_LIVE_SECRET_KEY", "<your secret key>")
STRIPE_TEST_PUBLIC_KEY = os.environ.get("STRIPE_TEST_PUBLIC_KEY", "<your publishable key>")
STRIPE_TEST_SECRET_KEY = os.environ.get("STRIPE_TEST_SECRET_KEY", "<your secret key>")
STRIPE_LIVE_MODE = False  # Change to True in production
DJSTRIPE_WEBHOOK_SECRET = "whsec_xxx"  # Get it from the section in the Stripe dashboard where you added the webhook endpoint

Add some payment plans via the Stripe.com dashboard.

Run the commands:

python manage.py migrate

python manage.py djstripe_init_customers

python manage.py djstripe_sync_plans_from_stripe

See https://dj-stripe.readthedocs.io/en/latest/stripe_elements_js.html for notes about usage of the Stripe Elements frontend JS library.

Running Tests

Assuming the tests are run against PostgreSQL:

createdb djstripe
pip install tox
tox

A note on Stripe API versions

A point that can cause confusion to new users of dj-stripe is that there are several different Stripe API versions in play at once.

In brief: Don’t touch the STRIPE_API_VERSION setting, but don’t worry, it doesn’t need to match your Stripe account api version.

See also https://stripe.com/docs/api/versioning

Your Stripe account’s API version

You can find this on your Stripe dashboard labelled “default” here: https://dashboard.stripe.com/developers

For new accounts this will be the latest Stripe version. When upgrading version Stripe only allows you to upgrade to the latest version. See https://stripe.com/docs/upgrades#how-can-i-upgrade-my-api

This is the version used by Stripe when sending webhook data to you (though during webhook processing, dj-stripe re-fetches the data with its preferred version). It’s also the default version used by the Stripe API, but dj-stripe overrides the API version when talking to stripe (this override is triggered on import of djstripe.models).

As a result your Stripe account API version is mostly irrelevant, though from time to time we will increase the minimum supported API version, and it’s good practise to regularly upgrade to the latest version with appropriate testing.

Stripe’s current latest API version

You can find this on your Stripe dashboard labelled “latest” or in Stripe’s API documentation, eg https://stripe.com/docs/upgrades#api-changelog

This is the version used by new accounts and it’s also “true” internal version of Stripe’s API - see https://stripe.com/blog/api-versioning

dj-stripe’s API version

This is the Stripe API version used by dj-stripe in all communication with Stripe, including when processing webhooks (though webhook data is sent to you by Stripe with your API version, we re-fetch the data with dj-stripe’s API version), this is because the API schema needs to match dj-stripe’s Django model schema.

This is defined by djstripe.settings.DEFAULT_STRIPE_API_VERSION and can be overridden, though see the warning about doing this.

dj-stripe’s tested version (as mentioned in README)

This is the most recent Stripe account API version used by the maintainers during testing, more recent versions account versions are probably fine though.

A note on Stripe Elements JS methods

Note

TLDR: If you haven’t yet migrated to PaymentIntents, prefer stripe.createSource() over stripe.createToken() for better compatibility with PaymentMethods.

A point that can cause confusion when integrating Stripe on the web is that there are multiple generations of frontend JS APIs that use Stripe Elements with stripe js v3.

In descending order of preference these are:

Payment Intents (SCA compliant)

The newest and preferred way of handling payments, which supports SCA compliance (3D secure etc).

See https://stripe.com/docs/payments/payment-intents/web

Charges using stripe.createSource()

This creates Source objects within Stripe, and can be used for various different methods of payment (including, but not limited to cards), but isn’t SCA compliant.

See https://stripe.com/docs/stripe-js/reference#stripe-create-source

The Card Elements Quickstart JS example can be used, except use stripe.createSource instead of stripe.createToken and the result.source instead of result.token.

See https://github.com/dj-stripe/dj-stripe/blob/master/tests/apps/example/templates/purchase_subscription.html in for a working example of this.

Charges using stripe.createToken()

This predates stripe.createSource, and creates legacy Card objects within Stripe, which have some compatibility issues with Payment Methods.

If you’re using stripe.createToken, see if you can upgrade to stripe.createSource or ideally to Payment Intents .

See Card Elements Quickstart JS

Checking if a customer has a subscription

No content… yet

Subscribing a customer to a plan

For your convenience, dj-stripe provides a djstripe.models.Customer.subscribe() method that will try to charge the customer immediately unless you specify charge_immediately=False

plan = Plan.objects.get(nickname="one_plan")
customer = Customer.objects.first()
customer.subscribe(plan)

However in some cases djstripe.models.Customer.subscribe() might not support all the arguments you need for your implementation. When this happens you can just call the official stripe.Customer.subscribe().

See this example from tests.apps.example.views.PurchaseSubscriptionView.form_valid


      # Create the stripe Customer, by default subscriber Model is User,
      # this can be overridden with settings.DJSTRIPE_SUBSCRIBER_MODEL
      customer, created = djstripe.models.Customer.get_or_create(subscriber=user)

      # Add the source as the customer's default card
      customer.add_card(stripe_source)

      # Using the Stripe API, create a subscription for this customer,
      # using the customer's default payment source
      stripe_subscription = stripe.Subscription.create(
          customer=customer.id,
          items=[{"plan": plan.id}],
          billing="charge_automatically",
          # tax_percent=15,
          api_key=djstripe.settings.STRIPE_SECRET_KEY,
      )

      # Sync the Stripe API return data to the database,
      # this way we don't need to wait for a webhook-triggered sync
      subscription = djstripe.models.Subscription.sync_from_stripe_data(
          stripe_subscription
      )

Note that PaymentMethods can be used instead of Cards/Source by substituting

# Add the payment method customer's default
customer.add_payment_method(payment_method)

instead of

# Add the source as the customer's default card
customer.add_card(stripe_source)

in the above example. See djstripe.models.Customer.add_payment_method().

Creating a one-off charge for a customer

No content… yet

Restricting access to only active subscribers

dj-stripe provides three methods to support constraining views to be only accessible to users with active subscriptions:

  • Middleware approach to constrain entire projects easily.
  • Class-Based View mixin to constrain individual views.
  • View decoration to constrain Function-based views.

Warning

anonymous users always raise a ImproperlyConfigured exception.

When anonymous users encounter these components they will raise a django.core.exceptions.ImproperlyConfigured exception. This is done because dj-stripe is not an authentication system, so it does a hard error to make it easier for you to catch where content may not be behind authentication systems.

Any project can use one or more of these methods to control access.

Constraining Entire Sites

If you want to quickly constrain an entire site, the djstripe.middleware.SubscriptionPaymentMiddleware middleware does the following to user requests:

  • authenticated users are redirected to djstripe.views.SubscribeFormView unless they:

    • have a valid subscription –or–
    • are superusers (user.is_superuser==True) –or–
    • are staff members (user.is_staff==True).
  • anonymous users always raise a django.core.exceptions.ImproperlyConfigured exception when they encounter these systems. This is done because dj-stripe is not an authentication system.


Example:

Step 1: Add the middleware:

MIDDLEWARE_CLASSES = (
    ...
    'djstripe.middleware.SubscriptionPaymentMiddleware',
    ...
    )

Step 2: Specify exempt URLS:

# sample only - customize to your own needs!
# djstripe pages are automatically exempt!
DJSTRIPE_SUBSCRIPTION_REQUIRED_EXCEPTION_URLS = (
    'home',
    'about',
    "[spam]",  # Anything in the dj-spam namespace
)

Using this example any request on this site that isn’t on the homepage, about, spam, or djstripe pages is redirected to djstripe.views.SubscribeFormView.

Note

The extensive list of rules for this feature can be found at https://github.com/dj-stripe/dj-stripe/blob/master/djstripe/middleware.py.

See also

Constraining Class-Based Views

If you want to quickly constrain a single Class-Based View, the djstripe.decorators.subscription_payment_required decorator does the following to user requests:

  • authenticated users are redirected to djstripe.views.SubscribeFormView unless they:

    • have a valid subscription –or–
    • are superusers (user.is_superuser==True) –or–
    • are staff members (user.is_staff==True).
  • anonymous users always raise a django.core.exceptions.ImproperlyConfigured exception when they encounter these systems. This is done because dj-stripe is not an authentication system.


Example:

# import necessary Django stuff
from django.http import HttpResponse
from django.views.generic import View
from django.contrib.auth.decorators import login_required

# import the wonderful decorator
from djstripe.decorators import subscription_payment_required

# import method_decorator which allows us to use function
# decorators on Class-Based View dispatch function.
from django.utils.decorators import method_decorator


class MyConstrainedView(View):

    def get(self, request, *args, **kwargs):
        return HttpResponse("I like cheese")

    @method_decorator(login_required)
    @method_decorator(subscription_payment_required)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)

If you are unfamiliar with this technique please read the following documentation here.

Constraining Function-Based Views

If you want to quickly constrain a single Function-Based View, the djstripe.decorators.subscription_payment_required decorator does the following to user requests:

  • authenticated users are redirected to djstripe.views.SubscribeFormView unless they:

    • have a valid subscription –or–
    • are superusers (user.is_superuser==True) –or–
    • are staff members (user.is_staff==True).
  • anonymous users always raise a django.core.exceptions.ImproperlyConfigured exception when they encounter these systems. This is done because dj-stripe is not an authentication system.


Example:

# import necessary Django stuff
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse

# import the wonderful decorator
from djstripe.decorators import subscription_payment_required

@login_required
@subscription_payment_required
def my_constrained_view(request):
    return HttpResponse("I like cheese")

Don’t do this!

Described is an anti-pattern. View logic belongs in views.py, not urls.py.

# DON'T DO THIS!!!
from django.conf.urls import patterns, url
from django.contrib.auth.decorators import login_required
from djstripe.decorators import subscription_payment_required

from contents import views

urlpatterns = patterns("",

    # Class-Based View anti-pattern
    url(
        r"^content/$",

        # Not using decorators as decorators
        # Harder to see what's going on
        login_required(
            subscription_payment_required(
                views.ContentDetailView.as_view()
            )
        ),
        name="content_detail"
    ),
    # Function-Based View anti-pattern
    url(
        r"^content/$",

        # Example with function view
        login_required(
            subscription_payment_required(
                views.content_list_view
            )
        ),
        name="content_detail"
    ),
)

Managing subscriptions and payment sources

Extending subscriptions

Subscription.extend(*delta*)

Subscriptions can be extended by using the Subscription.extend method, which takes a positive timedelta as its only property. This method is useful if you want to offer time-cards, gift-cards, or some other external way of subscribing users or extending subscriptions, while keeping the billing handling within Stripe.

Warning

Subscription extensions are achieved by manipulating the trial_end of the subscription instance, which means that Stripe will change the status to trialing.

Creating invoices

No content… yet

Adding line items to invoices

No content… yet

Running reports

No content… yet

Webhooks

Using webhooks in dj-stripe

dj-stripe comes with native support for webhooks as event listeners.

Events allow you to do things like sending an email to a customer when his payment has failed or trial period is ending.

This is how you use them:

from djstripe import webhooks

@webhooks.handler("customer.subscription.trial_will_end")
def my_handler(event, **kwargs):
    print("We should probably notify the user at this point")

You can handle all events related to customers like this:

from djstripe import webhooks

@webhooks.handler("customer")
def my_handler(event, **kwargs):
    print("We should probably notify the user at this point")

You can also handle different events in the same handler:

from djstripe import webhooks

@webhooks.handler("plan", "product")
def my_handler(event, **kwargs):
    print("Triggered webhook " + event.type)

Warning

In order to get registrations picked up, you need to put them in a module is imported like models.py or make sure you import it manually.

Webhook event creation and processing is now wrapped in a transaction.atomic() block to better handle webhook errors. This will prevent any additional database modifications you may perform in your custom handler from being committed should something in the webhook processing chain fail. You can also take advantage of Django’s transaction.on_commit() function to only perform an action if the transaction successfully commits (meaning the Event processing worked):

from django.db import transaction
from djstripe import webhooks

def do_something():
    pass  # send a mail, invalidate a cache, fire off a Celery task, etc.

@webhooks.handler("plan", "product")
def my_handler(event, **kwargs):
    transaction.on_commit(do_something)

Official documentation

Stripe docs for types of Events: https://stripe.com/docs/api/events/types

Stripe docs for Webhooks: https://stripe.com/docs/webhooks

Django docs for transactions: https://docs.djangoproject.com/en/dev/topics/db/transactions/#performing-actions-after-commit

Manually syncing data with Stripe

If you’re using dj-stripe’s webhook handlers then data will be automatically synced from Stripe to the Django database, but in some circumstances you may want to manually sync Stripe API data as well.

Command line

You can sync your database with stripe using the manage command djstripe_sync_models, e.g. to populate an empty database from an existing Stripe account.

With no arguments this will sync all supported models, or a list of models to sync can be provided.

Note that this may be redundant since we recursively sync related objects.

You can manually reprocess events using the management commands djstripe_process_events. By default this processes all events, but options can be passed to limit the events processed. Note the Stripe API documents a limitation where events are only guaranteed to be available for 30 days.

In Code

To sync in code, for example if you write to the Stripe API and want to work with the resulting dj-stripe object without having to wait for the webhook trigger.

This can be done using the classmethod sync_from_stripe_data that exists on all dj-stripe model classes.

E.g. creating a product using the Stripe API, and then syncing the API return data to Django using dj-stripe:

   import djstripe.models
   import djstripe.settings
   import stripe

   # stripe API return value is a dict-like object
   stripe_data = stripe.Product.create(
       api_key=djstripe.settings.STRIPE_SECRET_KEY,
       name="Monthly membership base fee",
       type="service",
   )

   # sync_from_stripe_data to save it to the database,
   # and recursively update any referenced objects
   djstripe_obj = djstripe.models.Product.sync_from_stripe_data(stripe_data)

   return djstripe_obj

Cookbook

This is a list of handy recipes that fall outside the domain of normal usage.

Customer User Model has_active_subscription property

Very useful for working inside of templates or other places where you need to check the subscription status repeatedly. The cached_property decorator caches the result of has_active_subscription for a object instance, optimizing it for reuse.

# -*- coding: utf-8 -*-

from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.functional import cached_property

from djstripe.utils import subscriber_has_active_subscription


class User(AbstractUser):

    """ Custom fields go here """

    def __str__(self):
        return self.username

    def __unicode__(self):
        return self.username

    @cached_property
    def has_active_subscription(self):
        """Checks if a user has an active subscription."""
        return subscriber_has_active_subscription(self)

Usage:

<ul class="actions">
<h2>{{ object }}</h2>
<!-- first use of request.user.has_active_subscription -->
{% if request.user.has_active_subscription %}
    <p>
        <small>
            <a href="{% url 'things:update' %}">edit</a>
        </small>
    </p>
{% endif %}
<p>{{ object.description }}</p>

<!-- second use of request.user.has_active_subscription -->
{% if request.user.has_active_subscription %}
    <li>
        <a href="{% url 'places:create' %}">Add Place</a>
        <a href="{% url 'places:list' %}">View Places</a>
    </li>
{% endif %}
</ul>

Making individual purchases

On the subscriber’s customer object, use the charge method to generate a Stripe charge. In this example, we’re using the user with ID=1 as the subscriber.

from decimal import Decimal

from django.contrib.auth import get_user_model

from djstripe.models import Customer


user = get_user_model().objects.get(id=1)

customer, created = Customer.get_or_create(subscriber=user)

amount = Decimal(10.00)
customer.charge(amount)

Source code for the Customer.charge method is at https://github.com/dj-stripe/dj-stripe/blob/master/djstripe/models.py

REST API

The subscriptions can be accessed through a REST API. Make sure you have Django Rest Framework installed (https://github.com/tomchristie/django-rest-framework).

The REST API endpoints require an authenticated user. GET will provide the current subscription of the user. POST will create a new current subscription. DELETE will cancel the current subscription, based on the settings.

  • /subscription/ (GET)
    • input
      • None
    • output (200)

      • id (int)
      • created (date)
      • modified (date)
      • plan (string)
      • quantity (int)
      • start (date)
      • status (string)
      • cancel_at_period_end (boolean)
      • canceled_at (date)
      • current_period_end (date)
      • current_period_start (date)
      • ended_at (date)
      • trial_end (date)
      • trial_start (date)
      • amount (float)
      • customer (int)
  • /subscription/ (POST)
    • input
      • stripe_token (string)
      • plan (string)
      • charge_immediately (boolean, optional) - Does not send an invoice to the Customer immediately
    • output (201)
      • stripe_token (string)
      • plan (string)
  • /subscription/ (DELETE)
    • input
      • None
    • Output (204)
      • None

Context Managers

Last Updated 2018-05-24

Temporary API Version

context_managers.stripe_temporary_api_version(validate=True)
Temporarily replace the global api_version used in stripe API calls with
the given value.

The original value is restored as soon as context exits.

Decorators

Last Updated 2018-05-24

Standard Decorators

Payment Required

This couldn’t be autodoc’d for some reason. See djstripe.decorators.subscription_payment_required

Event Handling Decorators

More documentation coming on these soon. For now, see our implementations in djstripe.event_handlers

Specific Event(s) Handler

webhooks.handler()

Decorator that registers a function as a webhook handler.

Functions can be registered for event types (e.g. ‘customer’) or fully qualified event sub-types (e.g. ‘customer.subscription.deleted’).

If an event type is specified, the handler will receive callbacks for ALL webhook events of that type. For example, if ‘customer’ is specified, the handler will receive events for ‘customer.subscription.created’, ‘customer.subscription.updated’, etc.

Parameters:event_types (str.) – The event type(s) that should be handled.

All Events Handler

webhooks.handler_all()

Decorator that registers a function as a webhook handler for ALL webhook events.

Handles all webhooks regardless of event type or sub-type.

Enumerations

Last Updated 2019-09-17

ApiErrorCode

class djstripe.enums.ApiErrorCode[source]

Charge failure error codes.

https://stripe.com/docs/error-codes

account_already_exists = 'account_already_exists'
account_country_invalid_address = 'account_country_invalid_address'
account_invalid = 'account_invalid'
account_number_invalid = 'account_number_invalid'
alipay_upgrade_required = 'alipay_upgrade_required'
amount_too_large = 'amount_too_large'
amount_too_small = 'amount_too_small'
api_key_expired = 'api_key_expired'
balance_insufficient = 'balance_insufficient'
bank_account_exists = 'bank_account_exists'
bank_account_unusable = 'bank_account_unusable'
bank_account_unverified = 'bank_account_unverified'
bitcoin_upgrade_required = 'bitcoin_upgrade_required'
card_declined = 'card_declined'
charge_already_captured = 'charge_already_captured'
charge_already_refunded = 'charge_already_refunded'
charge_disputed = 'charge_disputed'
charge_exceeds_source_limit = 'charge_exceeds_source_limit'
charge_expired_for_capture = 'charge_expired_for_capture'
choices = (('account_already_exists', 'Account already exists'), ('account_country_invalid_address', 'Account country invalid address'), ('account_invalid', 'Account invalid'), ('account_number_invalid', 'Account number invalid'), ('alipay_upgrade_required', 'Alipay upgrade required'), ('amount_too_large', 'Amount too large'), ('amount_too_small', 'Amount too small'), ('api_key_expired', 'Api key expired'), ('balance_insufficient', 'Balance insufficient'), ('bank_account_exists', 'Bank account exists'), ('bank_account_unusable', 'Bank account unusable'), ('bank_account_unverified', 'Bank account unverified'), ('bitcoin_upgrade_required', 'Bitcoin upgrade required'), ('card_declined', 'Card was declined'), ('charge_already_captured', 'Charge already captured'), ('charge_already_refunded', 'Charge already refunded'), ('charge_disputed', 'Charge disputed'), ('charge_exceeds_source_limit', 'Charge exceeds source limit'), ('charge_expired_for_capture', 'Charge expired for capture'), ('country_unsupported', 'Country unsupported'), ('coupon_expired', 'Coupon expired'), ('customer_max_subscriptions', 'Customer max subscriptions'), ('email_invalid', 'Email invalid'), ('expired_card', 'Expired card'), ('idempotency_key_in_use', 'Idempotency key in use'), ('incorrect_address', 'Incorrect address'), ('incorrect_cvc', 'Incorrect security code'), ('incorrect_number', 'Incorrect number'), ('incorrect_zip', 'ZIP code failed validation'), ('instant_payouts_unsupported', 'Instant payouts unsupported'), ('invalid_card_type', 'Invalid card type'), ('invalid_charge_amount', 'Invalid charge amount'), ('invalid_cvc', 'Invalid security code'), ('invalid_expiry_month', 'Invalid expiration month'), ('invalid_expiry_year', 'Invalid expiration year'), ('invalid_number', 'Invalid number'), ('invalid_source_usage', 'Invalid source usage'), ('invalid_swipe_data', 'Invalid swipe data'), ('invoice_no_customer_line_items', 'Invoice no customer line items'), ('invoice_no_subscription_line_items', 'Invoice no subscription line items'), ('invoice_not_editable', 'Invoice not editable'), ('invoice_upcoming_none', 'Invoice upcoming none'), ('livemode_mismatch', 'Livemode mismatch'), ('missing', 'No card being charged'), ('not_allowed_on_standard_account', 'Not allowed on standard account'), ('order_creation_failed', 'Order creation failed'), ('order_required_settings', 'Order required settings'), ('order_status_invalid', 'Order status invalid'), ('order_upstream_timeout', 'Order upstream timeout'), ('out_of_inventory', 'Out of inventory'), ('parameter_invalid_empty', 'Parameter invalid empty'), ('parameter_invalid_integer', 'Parameter invalid integer'), ('parameter_invalid_string_blank', 'Parameter invalid string blank'), ('parameter_invalid_string_empty', 'Parameter invalid string empty'), ('parameter_missing', 'Parameter missing'), ('parameter_unknown', 'Parameter unknown'), ('parameters_exclusive', 'Parameters exclusive'), ('payment_intent_authentication_failure', 'Payment intent authentication failure'), ('payment_intent_incompatible_payment_method', 'Payment intent incompatible payment method'), ('payment_intent_invalid_parameter', 'Payment intent invalid parameter'), ('payment_intent_payment_attempt_failed', 'Payment intent payment attempt failed'), ('payment_intent_unexpected_state', 'Payment intent unexpected state'), ('payment_method_unactivated', 'Payment method unactivated'), ('payment_method_unexpected_state', 'Payment method unexpected state'), ('payouts_not_allowed', 'Payouts not allowed'), ('platform_api_key_expired', 'Platform api key expired'), ('postal_code_invalid', 'Postal code invalid'), ('processing_error', 'Processing error'), ('product_inactive', 'Product inactive'), ('rate_limit', 'Rate limit'), ('resource_already_exists', 'Resource already exists'), ('resource_missing', 'Resource missing'), ('routing_number_invalid', 'Routing number invalid'), ('secret_key_required', 'Secret key required'), ('sepa_unsupported_account', 'SEPA unsupported account'), ('shipping_calculation_failed', 'Shipping calculation failed'), ('sku_inactive', 'SKU inactive'), ('state_unsupported', 'State unsupported'), ('tax_id_invalid', 'Tax id invalid'), ('taxes_calculation_failed', 'Taxes calculation failed'), ('testmode_charges_only', 'Testmode charges only'), ('tls_version_unsupported', 'TLS version unsupported'), ('token_already_used', 'Token already used'), ('token_in_use', 'Token in use'), ('transfers_not_allowed', 'Transfers not allowed'), ('upstream_order_creation_failed', 'Upstream order creation failed'), ('url_invalid', 'URL invalid'))
country_unsupported = 'country_unsupported'
coupon_expired = 'coupon_expired'
customer_max_subscriptions = 'customer_max_subscriptions'
email_invalid = 'email_invalid'
expired_card = 'expired_card'
idempotency_key_in_use = 'idempotency_key_in_use'
incorrect_address = 'incorrect_address'
incorrect_cvc = 'incorrect_cvc'
incorrect_number = 'incorrect_number'
incorrect_zip = 'incorrect_zip'
instant_payouts_unsupported = 'instant_payouts_unsupported'
invalid_card_type = 'invalid_card_type'
invalid_charge_amount = 'invalid_charge_amount'
invalid_cvc = 'invalid_cvc'
invalid_expiry_month = 'invalid_expiry_month'
invalid_expiry_year = 'invalid_expiry_year'
invalid_number = 'invalid_number'
invalid_source_usage = 'invalid_source_usage'
invalid_swipe_data = 'invalid_swipe_data'
invoice_no_customer_line_items = 'invoice_no_customer_line_items'
invoice_no_subscription_line_items = 'invoice_no_subscription_line_items'
invoice_not_editable = 'invoice_not_editable'
invoice_upcoming_none = 'invoice_upcoming_none'
livemode_mismatch = 'livemode_mismatch'
missing = 'missing'
not_allowed_on_standard_account = 'not_allowed_on_standard_account'
order_creation_failed = 'order_creation_failed'
order_required_settings = 'order_required_settings'
order_status_invalid = 'order_status_invalid'
order_upstream_timeout = 'order_upstream_timeout'
out_of_inventory = 'out_of_inventory'
parameter_invalid_empty = 'parameter_invalid_empty'
parameter_invalid_integer = 'parameter_invalid_integer'
parameter_invalid_string_blank = 'parameter_invalid_string_blank'
parameter_invalid_string_empty = 'parameter_invalid_string_empty'
parameter_missing = 'parameter_missing'
parameter_unknown = 'parameter_unknown'
parameters_exclusive = 'parameters_exclusive'
payment_intent_authentication_failure = 'payment_intent_authentication_failure'
payment_intent_incompatible_payment_method = 'payment_intent_incompatible_payment_method'
payment_intent_invalid_parameter = 'payment_intent_invalid_parameter'
payment_intent_payment_attempt_failed = 'payment_intent_payment_attempt_failed'
payment_intent_unexpected_state = 'payment_intent_unexpected_state'
payment_method_unactivated = 'payment_method_unactivated'
payment_method_unexpected_state = 'payment_method_unexpected_state'
payouts_not_allowed = 'payouts_not_allowed'
platform_api_key_expired = 'platform_api_key_expired'
postal_code_invalid = 'postal_code_invalid'
processing_error = 'processing_error'
product_inactive = 'product_inactive'
rate_limit = 'rate_limit'
resource_already_exists = 'resource_already_exists'
resource_missing = 'resource_missing'
routing_number_invalid = 'routing_number_invalid'
secret_key_required = 'secret_key_required'
sepa_unsupported_account = 'sepa_unsupported_account'
shipping_calculation_failed = 'shipping_calculation_failed'
sku_inactive = 'sku_inactive'
state_unsupported = 'state_unsupported'
tax_id_invalid = 'tax_id_invalid'
taxes_calculation_failed = 'taxes_calculation_failed'
testmode_charges_only = 'testmode_charges_only'
tls_version_unsupported = 'tls_version_unsupported'
token_already_used = 'token_already_used'
token_in_use = 'token_in_use'
transfers_not_allowed = 'transfers_not_allowed'
upstream_order_creation_failed = 'upstream_order_creation_failed'
url_invalid = 'url_invalid'

AccountType

class djstripe.enums.AccountType[source]
choices = (('custom', 'Custom'), ('express', 'Express'), ('standard', 'Standard'))
custom = 'custom'
express = 'express'
standard = 'standard'

BalanceTransactionStatus

class djstripe.enums.BalanceTransactionStatus[source]
available = 'available'
choices = (('available', 'Available'), ('pending', 'Pending'))
pending = 'pending'

BalanceTransactionType

class djstripe.enums.BalanceTransactionType[source]
adjustment = 'adjustment'
advance = 'advance'
advance_funding = 'advance_funding'
application_fee = 'application_fee'
application_fee_refund = 'application_fee_refund'
charge = 'charge'
choices = (('adjustment', 'Adjustment'), ('advance', 'Advance'), ('advance_funding', 'Advance funding'), ('application_fee', 'Application fee'), ('application_fee_refund', 'Application fee refund'), ('charge', 'Charge'), ('connect_collection_transfer', 'Connect collection transfer'), ('issuing_authorization_hold', 'Issuing authorization hold'), ('issuing_authorization_release', 'Issuing authorization release'), ('issuing_transaction', 'Issuing transaction'), ('network_cost', 'Network cost'), ('payment', 'Payment'), ('payment_failure_refund', 'Payment failure refund'), ('payment_refund', 'Payment refund'), ('payout', 'Payout'), ('payout_cancel', 'Payout cancellation'), ('payout_failure', 'Payout failure'), ('refund', 'Refund'), ('refund_failure', 'Refund failure'), ('reserve_transaction', 'Reserve transaction'), ('reserved_funds', 'Reserved funds'), ('stripe_fee', 'Stripe fee'), ('stripe_fx_fee', 'Stripe fx fee'), ('tax_fee', 'Tax fee'), ('topup', 'Topup'), ('topup_reversal', 'Topup reversal'), ('transfer', 'Transfer'), ('transfer_cancel', 'Transfer cancel'), ('transfer_refund', 'Transfer refund'), ('validation', 'Validation'))
connect_collection_transfer = 'connect_collection_transfer'
issuing_authorization_hold = 'issuing_authorization_hold'
issuing_authorization_release = 'issuing_authorization_release'
issuing_transaction = 'issuing_transaction'
network_cost = 'network_cost'
payment = 'payment'
payment_failure_refund = 'payment_failure_refund'
payment_refund = 'payment_refund'
payout = 'payout'
payout_cancel = 'payout_cancel'
payout_failure = 'payout_failure'
refund = 'refund'
refund_failure = 'refund_failure'
reserve_transaction = 'reserve_transaction'
reserved_funds = 'reserved_funds'
stripe_fee = 'stripe_fee'
stripe_fx_fee = 'stripe_fx_fee'
tax_fee = 'tax_fee'
topup = 'topup'
topup_reversal = 'topup_reversal'
transfer = 'transfer'
transfer_cancel = 'transfer_cancel'
transfer_refund = 'transfer_refund'
validation = 'validation'

BankAccountHolderType

class djstripe.enums.BankAccountHolderType[source]
choices = (('company', 'Company'), ('individual', 'Individual'))
company = 'company'
individual = 'individual'

BankAccountStatus

class djstripe.enums.BankAccountStatus[source]
choices = (('errored', 'Errored'), ('new', 'New'), ('validated', 'Validated'), ('verification_failed', 'Verification failed'), ('verified', 'Verified'))
errored = 'errored'
new = 'new'
validated = 'validated'
verification_failed = 'verification_failed'
verified = 'verified'

BusinessType

class djstripe.enums.BusinessType[source]
choices = (('company', 'Company'), ('individual', 'Individual'))
company = 'company'
individual = 'individual'

CaptureMethod

class djstripe.enums.CaptureMethod[source]
automatic = 'automatic'
choices = (('automatic', 'Automatic'), ('manual', 'Manual'))
manual = 'manual'

CardCheckResult

class djstripe.enums.CardCheckResult[source]
choices = (('fail', 'Fail'), ('pass', 'Pass'), ('unavailable', 'Unavailable'), ('unchecked', 'Unchecked'))
fail = 'fail'
pass_ = 'pass'
unavailable = 'unavailable'
unchecked = 'unchecked'

CardBrand

class djstripe.enums.CardBrand[source]
AmericanExpress = 'American Express'
DinersClub = 'Diners Club'
Discover = 'Discover'
JCB = 'JCB'
MasterCard = 'MasterCard'
UnionPay = 'UnionPay'
Unknown = 'Unknown'
Visa = 'Visa'
choices = (('American Express', 'American Express'), ('Diners Club', 'Diners Club'), ('Discover', 'Discover'), ('JCB', 'JCB'), ('MasterCard', 'MasterCard'), ('UnionPay', 'UnionPay'), ('Unknown', 'Unknown'), ('Visa', 'Visa'))

CardFundingType

class djstripe.enums.CardFundingType[source]
choices = (('credit', 'Credit'), ('debit', 'Debit'), ('prepaid', 'Prepaid'), ('unknown', 'Unknown'))
credit = 'credit'
debit = 'debit'
prepaid = 'prepaid'
unknown = 'unknown'

CardTokenizationMethod

class djstripe.enums.CardTokenizationMethod[source]
android_pay = 'android_pay'
apple_pay = 'apple_pay'
choices = (('android_pay', 'Android Pay'), ('apple_pay', 'Apple Pay'))

ChargeStatus

class djstripe.enums.ChargeStatus[source]
choices = (('failed', 'Failed'), ('pending', 'Pending'), ('succeeded', 'Succeeded'))
failed = 'failed'
pending = 'pending'
succeeded = 'succeeded'

ConfirmationMethod

class djstripe.enums.ConfirmationMethod[source]
automatic = 'automatic'
choices = (('automatic', 'Automatic'), ('manual', 'Manual'))
manual = 'manual'

CouponDuration

class djstripe.enums.CouponDuration[source]
choices = (('forever', 'Forever'), ('once', 'Once'), ('repeating', 'Multi-month'))
forever = 'forever'
once = 'once'
repeating = 'repeating'

CustomerTaxExempt

class djstripe.enums.CustomerTaxExempt[source]
choices = (('exempt', 'Exempt'), ('none', 'None'), ('reverse', 'Reverse'))
exempt = 'exempt'
none = 'none'
reverse = 'reverse'

DisputeReason

class djstripe.enums.DisputeReason[source]
bank_cannot_process = 'bank_cannot_process'
choices = (('bank_cannot_process', 'Bank cannot process'), ('credit_not_processed', 'Credit not processed'), ('customer_initiated', 'Customer-initiated'), ('debit_not_authorized', 'Debit not authorized'), ('duplicate', 'Duplicate'), ('fraudulent', 'Fraudulent'), ('general', 'General'), ('incorrect_account_details', 'Incorrect account details'), ('insufficient_funds', 'Insufficient funds'), ('product_not_received', 'Product not received'), ('product_unacceptable', 'Product unacceptable'), ('subscription_canceled', 'Subscription canceled'), ('unrecognized', 'Unrecognized'))
credit_not_processed = 'credit_not_processed'
customer_initiated = 'customer_initiated'
debit_not_authorized = 'debit_not_authorized'
duplicate = 'duplicate'
fraudulent = 'fraudulent'
general = 'general'
incorrect_account_details = 'incorrect_account_details'
insufficient_funds = 'insufficient_funds'
product_not_received = 'product_not_received'
product_unacceptable = 'product_unacceptable'
subscription_canceled = 'subscription_canceled'
unrecognized = 'unrecognized'

DisputeStatus

class djstripe.enums.DisputeStatus[source]
charge_refunded = 'charge_refunded'
choices = (('charge_refunded', 'Charge refunded'), ('lost', 'Lost'), ('needs_response', 'Needs response'), ('under_review', 'Under review'), ('warning_closed', 'Warning closed'), ('warning_needs_response', 'Warning needs response'), ('warning_under_review', 'Warning under review'), ('won', 'Won'))
lost = 'lost'
needs_response = 'needs_response'
under_review = 'under_review'
warning_closed = 'warning_closed'
warning_needs_response = 'warning_needs_response'
warning_under_review = 'warning_under_review'
won = 'won'

FileUploadPurpose

class djstripe.enums.FileUploadPurpose[source]
choices = (('dispute_evidence', 'Dispute evidence'), ('identity_document', 'Identity document'), ('tax_document_user_upload', 'Tax document user upload'))
dispute_evidence = 'dispute_evidence'
identity_document = 'identity_document'
tax_document_user_upload = 'tax_document_user_upload'

FileUploadType

class djstripe.enums.FileUploadType[source]
choices = (('csv', 'CSV'), ('docx', 'DOCX'), ('jpg', 'JPG'), ('pdf', 'PDF'), ('png', 'PNG'), ('xls', 'XLS'), ('xlsx', 'XLSX'))
csv = 'csv'
docx = 'docx'
jpg = 'jpg'
pdf = 'pdf'
png = 'png'
xls = 'xls'
xlsx = 'xlsx'

InvoiceBilling

djstripe.enums.InvoiceBilling

alias of djstripe.enums.InvoiceCollectionMethod

IntentUsage

class djstripe.enums.IntentUsage[source]
choices = (('off_session', 'Off session'), ('on_session', 'On session'))
off_session = 'off_session'
on_session = 'on_session'

IntentStatus

class djstripe.enums.IntentStatus[source]

Status of Intents which apply both to PaymentIntents and SetupIntents.

canceled = 'canceled'
choices = (('canceled', 'Cancellation invalidates the intent for future confirmation and cannot be undone.'), ('processing', 'Required actions have been handled.'), ('requires_action', 'Payment Method require additional action, such as 3D secure.'), ('requires_confirmation', 'Intent is ready to be confirmed.'), ('requires_payment_method', 'Intent created and requires a Payment Method to be attached.'))
processing = 'processing'
requires_action = 'requires_action'
requires_confirmation = 'requires_confirmation'
requires_payment_method = 'requires_payment_method'

PaymentIntentStatus

class djstripe.enums.PaymentIntentStatus[source]
canceled = 'canceled'
choices = (('canceled', 'Cancellation invalidates the intent for future confirmation and cannot be undone.'), ('processing', 'Required actions have been handled.'), ('requires_action', 'Payment Method require additional action, such as 3D secure.'), ('requires_capture', 'Capture the funds on the cards which have been put on holds.'), ('requires_confirmation', 'Intent is ready to be confirmed.'), ('requires_payment_method', 'Intent created and requires a Payment Method to be attached.'), ('succeeded', 'The funds are in your account.'))
processing = 'processing'
requires_action = 'requires_action'
requires_capture = 'requires_capture'
requires_confirmation = 'requires_confirmation'
requires_payment_method = 'requires_payment_method'
succeeded = 'succeeded'

SetupIntentStatus

class djstripe.enums.SetupIntentStatus[source]
canceled = 'canceled'
choices = (('canceled', 'Cancellation invalidates the intent for future confirmation and cannot be undone.'), ('processing', 'Required actions have been handled.'), ('requires_action', 'Payment Method require additional action, such as 3D secure.'), ('requires_confirmation', 'Intent is ready to be confirmed.'), ('requires_payment_method', 'Intent created and requires a Payment Method to be attached.'), ('succeeded', 'Setup was successful and the payment method is optimized for future payments.'))
processing = 'processing'
requires_action = 'requires_action'
requires_confirmation = 'requires_confirmation'
requires_payment_method = 'requires_payment_method'
succeeded = 'succeeded'

PayoutFailureCode

class djstripe.enums.PayoutFailureCode[source]

Payout failure error codes.

https://stripe.com/docs/api#payout_failures

account_closed = 'account_closed'
account_frozen = 'account_frozen'
bank_account_restricted = 'bank_account_restricted'
bank_ownership_changed = 'bank_ownership_changed'
choices = (('account_closed', 'Bank account has been closed.'), ('account_frozen', 'Bank account has been frozen.'), ('bank_account_restricted', 'Bank account has restrictions on payouts allowed.'), ('bank_ownership_changed', 'Destination bank account has changed ownership.'), ('could_not_process', 'Bank could not process payout.'), ('debit_not_authorized', 'Debit transactions not approved on the bank account.'), ('insufficient_funds', 'Stripe account has insufficient funds.'), ('invalid_account_number', 'Invalid account number'), ('invalid_currency', 'Bank account does not support currency.'), ('no_account', 'Bank account could not be located.'), ('unsupported_card', 'Card no longer supported.'))
could_not_process = 'could_not_process'
debit_not_authorized = 'debit_not_authorized'
insufficient_funds = 'insufficient_funds'
invalid_account_number = 'invalid_account_number'
invalid_currency = 'invalid_currency'
no_account = 'no_account'
unsupported_card = 'unsupported_card'

PayoutMethod

class djstripe.enums.PayoutMethod[source]
choices = (('instant', 'Instant'), ('standard', 'Standard'))
instant = 'instant'
standard = 'standard'

PayoutStatus

class djstripe.enums.PayoutStatus[source]
canceled = 'canceled'
choices = (('canceled', 'Canceled'), ('failed', 'Failed'), ('in_transit', 'In transit'), ('paid', 'Paid'), ('pending', 'Pending'))
failed = 'failed'
in_transit = 'in_transit'
paid = 'paid'
pending = 'pending'

PayoutType

class djstripe.enums.PayoutType[source]
bank_account = 'bank_account'
card = 'card'
choices = (('bank_account', 'Bank account'), ('card', 'Card'))

PlanAggregateUsage

class djstripe.enums.PlanAggregateUsage[source]
choices = (('last_during_period', 'Last during period'), ('last_ever', 'Last ever'), ('max', 'Max'), ('sum', 'Sum'))
last_during_period = 'last_during_period'
last_ever = 'last_ever'
max = 'max'
sum = 'sum'

PlanBillingScheme

class djstripe.enums.PlanBillingScheme[source]
choices = (('per_unit', 'Per unit'), ('tiered', 'Tiered'))
per_unit = 'per_unit'
tiered = 'tiered'

PlanInterval

class djstripe.enums.PlanInterval[source]
choices = (('day', 'Day'), ('month', 'Month'), ('week', 'Week'), ('year', 'Year'))
day = 'day'
month = 'month'
week = 'week'
year = 'year'

PlanUsageType

class djstripe.enums.PlanUsageType[source]
choices = (('licensed', 'Licensed'), ('metered', 'Metered'))
licensed = 'licensed'
metered = 'metered'

PlanTiersMode

class djstripe.enums.PlanTiersMode[source]
choices = (('graduated', 'Graduated'), ('volume', 'Volume-based'))
graduated = 'graduated'
volume = 'volume'

ProductType

class djstripe.enums.ProductType[source]
choices = (('good', 'Good'), ('service', 'Service'))
good = 'good'
service = 'service'

ScheduledQueryRunStatus

class djstripe.enums.ScheduledQueryRunStatus[source]
canceled = 'canceled'
choices = (('canceled', 'Canceled'), ('failed', 'Failed'), ('timed_out', 'Timed out'))
failed = 'failed'
timed_out = 'timed_out'

SourceFlow

class djstripe.enums.SourceFlow[source]
choices = (('code_verification', 'Code verification'), ('none', 'None'), ('receiver', 'Receiver'), ('redirect', 'Redirect'))
code_verification = 'code_verification'
none = 'none'
receiver = 'receiver'
redirect = 'redirect'

SourceStatus

class djstripe.enums.SourceStatus[source]
canceled = 'canceled'
chargeable = 'chargeable'
choices = (('canceled', 'Canceled'), ('chargeable', 'Chargeable'), ('consumed', 'Consumed'), ('failed', 'Failed'), ('pending', 'Pending'))
consumed = 'consumed'
failed = 'failed'
pending = 'pending'

SourceType

class djstripe.enums.SourceType[source]
ach_credit_transfer = 'ach_credit_transfer'
ach_debit = 'ach_debit'
alipay = 'alipay'
bancontact = 'bancontact'
bitcoin = 'bitcoin'
card = 'card'
card_present = 'card_present'
choices = (('ach_credit_transfer', 'ACH Credit Transfer'), ('ach_debit', 'ACH Debit'), ('alipay', 'Alipay'), ('bancontact', 'Bancontact'), ('bitcoin', 'Bitcoin'), ('card', 'Card'), ('card_present', 'Card present'), ('eps', 'EPS'), ('giropay', 'Giropay'), ('ideal', 'iDEAL'), ('p24', 'P24'), ('paper_check', 'Paper check'), ('sepa_credit_transfer', 'SEPA credit transfer'), ('sepa_debit', 'SEPA Direct Debit'), ('sofort', 'SOFORT'), ('three_d_secure', '3D Secure'))
eps = 'eps'
giropay = 'giropay'
ideal = 'ideal'
p24 = 'p24'
paper_check = 'paper_check'
sepa_credit_transfer = 'sepa_credit_transfer'
sepa_debit = 'sepa_debit'
sofort = 'sofort'
three_d_secure = 'three_d_secure'

LegacySourceType

class djstripe.enums.LegacySourceType[source]
alipay_account = 'alipay_account'
bank_account = 'bank_account'
bitcoin_receiver = 'bitcoin_receiver'
card = 'card'
choices = (('alipay_account', 'Alipay account'), ('bank_account', 'Bank account'), ('bitcoin_receiver', 'Bitcoin receiver'), ('card', 'Card'))

RefundFailureReason

class djstripe.enums.RefundFailureReason[source]
choices = (('expired_or_canceled_card', 'Expired or canceled card'), ('lost_or_stolen_card', 'Lost or stolen card'), ('unknown', 'Unknown'))
expired_or_canceled_card = 'expired_or_canceled_card'
lost_or_stolen_card = 'lost_or_stolen_card'
unknown = 'unknown'

RefundReason

class djstripe.enums.RefundReason[source]
choices = (('duplicate', 'Duplicate charge'), ('expired_uncaptured_charge', 'Expired uncaptured charge'), ('fraudulent', 'Fraudulent'), ('requested_by_customer', 'Requested by customer'))
duplicate = 'duplicate'
expired_uncaptured_charge = 'expired_uncaptured_charge'
fraudulent = 'fraudulent'
requested_by_customer = 'requested_by_customer'

RefundStatus

class djstripe.enums.RefundStatus[source]
canceled = 'canceled'
choices = (('canceled', 'Canceled'), ('failed', 'Failed'), ('pending', 'Pending'), ('succeeded', 'Succeeded'))
failed = 'failed'
pending = 'pending'
succeeded = 'succeeded'

SourceUsage

class djstripe.enums.SourceUsage[source]
choices = (('reusable', 'Reusable'), ('single_use', 'Single-use'))
reusable = 'reusable'
single_use = 'single_use'

SourceCodeVerificationStatus

class djstripe.enums.SourceCodeVerificationStatus[source]
choices = (('failed', 'Failed'), ('pending', 'Pending'), ('succeeded', 'Succeeded'))
failed = 'failed'
pending = 'pending'
succeeded = 'succeeded'

SourceRedirectFailureReason

class djstripe.enums.SourceRedirectFailureReason[source]
choices = (('declined', 'Declined'), ('processing_error', 'Processing error'), ('user_abort', 'User-aborted'))
declined = 'declined'
processing_error = 'processing_error'
user_abort = 'user_abort'

SourceRedirectStatus

class djstripe.enums.SourceRedirectStatus[source]
choices = (('failed', 'Failed'), ('not_required', 'Not required'), ('pending', 'Pending'), ('succeeded', 'Succeeded'))
failed = 'failed'
not_required = 'not_required'
pending = 'pending'
succeeded = 'succeeded'

SubmitTypeStatus

class djstripe.enums.SubmitTypeStatus[source]
auto = 'auto'
book = 'book'
choices = (('auto', 'Auto'), ('book', 'Book'), ('donate', 'donate'), ('pay', 'pay'))
donate = 'donate'
pay = 'pay'

SubscriptionStatus

class djstripe.enums.SubscriptionStatus[source]
active = 'active'
canceled = 'canceled'
choices = (('active', 'Active'), ('canceled', 'Canceled'), ('incomplete', 'Incomplete'), ('incomplete_expired', 'Incomplete Expired'), ('past_due', 'Past due'), ('trialing', 'Trialing'), ('unpaid', 'Unpaid'))
incomplete = 'incomplete'
incomplete_expired = 'incomplete_expired'
past_due = 'past_due'
trialing = 'trialing'
unpaid = 'unpaid'

Managers

Last Updated 2018-05-24

SubscriptionManager

class djstripe.managers.SubscriptionManager[source]

Manager used in models.Subscription.

started_during(year, month)[source]

Return Subscriptions not in trial status between a certain time range.

active()[source]

Return active Subscriptions.

canceled()[source]

Return canceled Subscriptions.

canceled_during(year, month)[source]

Return Subscriptions canceled during a certain time range.

started_plan_summary_for(year, month)[source]

Return started_during Subscriptions with plan counts annotated.

active_plan_summary()[source]

Return active Subscriptions with plan counts annotated.

canceled_plan_summary_for(year, month)[source]

Return Subscriptions canceled within a time range with plan counts annotated.

churn()[source]

Return number of canceled Subscriptions divided by active Subscriptions.

TransferManager

class djstripe.managers.TransferManager[source]

Manager used by models.Transfer.

during(year, month)[source]

Return Transfers between a certain time range.

paid_totals_for(year, month)[source]

Return paid Transfers during a certain year, month with total amounts annotated.

ChargeManager

class djstripe.managers.ChargeManager[source]

Manager used by models.Charge.

during(year, month)[source]

Return Charges between a certain time range based on created.

paid_totals_for(year, month)[source]

Return paid Charges during a certain year, month with total amount, fee and refunded annotated.

Middleware

Last Updated 2018-05-24

SubscriptionPaymentMiddleware

class djstripe.middleware.SubscriptionPaymentMiddleware(get_response=None)[source]

Used to redirect users from subcription-locked request destinations.

Rules:

  • “(app_name)” means everything from this app is exempt
  • “[namespace]” means everything with this name is exempt
  • “namespace:name” means this namespaced URL is exempt
  • “name” means this URL is exempt
  • The entire djstripe namespace is exempt
  • If settings.DEBUG is True, then django-debug-toolbar is exempt
  • A ‘fn:’ prefix means the rest of the URL is fnmatch’d.

Example:

DJSTRIPE_SUBSCRIPTION_REQUIRED_EXCEPTION_URLS = (
    "[blogs]",  # Anything in the blogs namespace
    "products:detail",  # A ProductDetail view you want shown to non-payers
    "home",  # Site homepage
    "fn:/accounts*",  # anything in the accounts/ URL path
)

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.

Last Updated 2019-12-21

Core Resources

Balance Transaction

class djstripe.models.BalanceTransaction(*args, **kwargs)[source]

A single transaction that updates the Stripe balance.

Stripe documentation: https://stripe.com/docs/api#balance_transaction_object

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • amount (StripeQuantumCurrencyAmountField) – Amount. Gross amount of the transaction, in cents.
  • available_on (StripeDateTimeField) – Available on. The date the transaction’s net funds will become available in the Stripe balance.
  • currency (StripeCurrencyCodeField) – Currency. Three-letter ISO currency code
  • exchange_rate (DecimalField) – Exchange rate
  • fee (StripeQuantumCurrencyAmountField) – Fee. Fee (in cents) paid for this transaction.
  • fee_details (JSONField) – Fee details
  • net (StripeQuantumCurrencyAmountField) – Net. Net amount of the transaction, in cents.
  • status (StripeEnumField) – Status
  • type (StripeEnumField) – Type
classmethod BalanceTransaction.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
BalanceTransaction.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
BalanceTransaction.get_stripe_dashboard_url()

Get the stripe dashboard url for this object.

classmethod BalanceTransaction.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

Charge

class djstripe.models.Charge(*args, **kwargs)[source]

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/python#charges

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • amount (StripeDecimalCurrencyAmountField) – Amount. Amount charged (as decimal).
  • amount_refunded (StripeDecimalCurrencyAmountField) – Amount refunded. Amount (as decimal) refunded (can be less than the amount attribute on the charge if a partial refund was issued).
  • balance_transaction (ForeignKey to BalanceTransaction) – Balance transaction. The balance transaction that describes the impact of this charge on your account balance (not including refunds or disputes).
  • captured (BooleanField) – Captured. If the charge was created without capturing, this boolean represents whether or not it is still uncaptured or has since been captured.
  • currency (StripeCurrencyCodeField) – Currency. The currency in which the charge was made.
  • customer (ForeignKey to Customer) – Customer. The customer associated with this charge.
  • account (ForeignKey to Account) – Account. The account the charge was made on behalf of. Null here indicates that this value was never set.
  • dispute (ForeignKey to Dispute) – Dispute. Details about the dispute if the charge has been disputed.
  • failure_code (StripeEnumField) – Failure code. Error code explaining reason for charge failure if available.
  • failure_message (TextField) – Failure message. Message to user further explaining reason for charge failure if available.
  • fraud_details (JSONField) – Fraud details. Hash with information on fraud assessments for the charge.
  • invoice (ForeignKey to Invoice) – Invoice. The invoice this charge is for if one exists.
  • outcome (JSONField) – Outcome. Details about whether or not the payment was accepted, and why.
  • paid (BooleanField) – Paid. True if the charge succeeded, or was successfully authorized for later capture, False otherwise.
  • payment_intent (ForeignKey to PaymentIntent) – Payment intent. PaymentIntent associated with this charge, if one exists.
  • payment_method (ForeignKey to PaymentMethod) – Payment method. PaymentMethod used in this charge.
  • payment_method_details (JSONField) – Payment method details. Details about the payment method at the time of the transaction.
  • receipt_email (TextField) – Receipt email. The email address that the receipt for this charge was sent to.
  • receipt_number (CharField) – Receipt number. The transaction number that appears on email receipts sent for this charge.
  • receipt_url (TextField) – Receipt url. 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 (BooleanField) – Refunded. Whether or not the charge has been fully refunded. If the charge is only partially refunded, this attribute will still be false.
  • shipping (JSONField) – Shipping. Shipping information for the charge
  • source (PaymentMethodForeignKey to DjstripePaymentMethod) – Source. The source used for this charge.
  • statement_descriptor (CharField) – Statement descriptor. An arbitrary string to be displayed on your customer’s credit card statement. The statement description may not include <>”’ characters, and will appear on your customer’s statement in capital letters. Non-ASCII characters are automatically stripped. While most banks display this information consistently, some may display it incorrectly or not at all.
  • status (StripeEnumField) – Status. The status of the payment.
  • transfer (ForeignKey to Transfer) – Transfer. The transfer to the destination account (only applicable if the charge was created using the destination parameter).
  • transfer_group (CharField) – Transfer group. A string that identifies this transaction as part of a group.
classmethod Charge.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
Charge.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
Charge.get_stripe_dashboard_url()

Get the stripe dashboard url for this object.

Charge.disputed
Charge.refund(amount=None, reason=None)[source]

Initiate a refund. If amount is not provided, then this will be a full refund.

Parameters:
  • amount (Decimal) – A positive decimal amount representing how much of this charge to refund. Can only refund up to the unrefunded amount remaining of the charge.
  • 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.
  • reason – str
Returns:

Charge object

Return type:

Charge

Charge.capture()[source]

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

Charge.str_parts()

Extend this to add information to the string representation of the object

Return type:list of str
classmethod Charge.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

Customer

class djstripe.models.Customer(*args, **kwargs)[source]

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/python#customers

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • address (JSONField) – Address. The customer’s address.
  • balance (StripeQuantumCurrencyAmountField) – Balance. 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).
  • business_vat_id (CharField) – Business vat id. The customer’s VAT identification number.
  • currency (StripeCurrencyCodeField) – Currency. The currency the customer can be charged in for recurring billing purposes
  • default_source (PaymentMethodForeignKey to DjstripePaymentMethod) – Default source
  • delinquent (BooleanField) – Delinquent. Whether or not the latest charge for the customer’s latest invoice has failed.
  • coupon (ForeignKey to Coupon) – Coupon
  • coupon_start (StripeDateTimeField) – Coupon start. If a coupon is present, the date at which it was applied.
  • coupon_end (StripeDateTimeField) – Coupon end. If a coupon is present and has a limited duration, the date that the discount will end.
  • email (TextField) – Email
  • invoice_prefix (CharField) – Invoice prefix. The prefix for the customer used to generate unique invoice numbers.
  • invoice_settings (JSONField) – Invoice settings. The customer’s default invoice settings.
  • default_payment_method (ForeignKey to PaymentMethod) – Default payment method. default payment method used for subscriptions and invoices for the customer.
  • name (TextField) – Name. The customer’s full name or business name.
  • phone (TextField) – Phone. The customer’s phone number.
  • preferred_locales (JSONField) – Preferred locales. The customer’s preferred locales (languages), ordered by preference.
  • shipping (JSONField) – Shipping. Shipping information associated with the customer.
  • tax_exempt (StripeEnumField) – Tax exempt. Describes the customer’s tax exemption status. When set to reverse, invoice and receipt PDFs include the text “Reverse charge”.
  • subscriber (ForeignKey to User) – Subscriber
  • date_purged (DateTimeField) – Date purged
classmethod Customer.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
Customer.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
Customer.get_stripe_dashboard_url()

Get the stripe dashboard url for this object.

classmethod Customer.get_or_create(subscriber, livemode=False, stripe_account=None)[source]

Get or create a dj-stripe customer.

Parameters:
  • subscriber (User) – The subscriber model instance for which to get or create a customer.
  • livemode (bool) – Whether to get the subscriber in live or test mode.
Customer.legacy_cards

Model field: customer, accesses the M2M Card model.

Customer.credits

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

Customer.customer_payment_methods

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

Customer.pending_charges

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

Customer.subscribe(plan, charge_immediately=True, application_fee_percent=None, coupon=None, quantity=None, metadata=None, tax_percent=None, billing_cycle_anchor=None, trial_end=None, trial_from_plan=None, trial_period_days=None)[source]

Subscribes this customer to a plan.

Parameters:
  • plan (Plan or string (plan ID)) – The plan to which to subscribe the customer.
  • application_fee_percent (Decimal. Precision is 2; anything more will be ignored. A positive decimal between 1 and 100.) – This represents the percentage of the subscription invoice subtotal that will be transferred to the application owner’s Stripe account. The request must be made with an OAuth key in order to set an application fee percentage.
  • coupon (string) – The code of the coupon to apply to this subscription. A coupon applied to a subscription will only affect invoices created for that particular subscription.
  • quantity (integer) – The quantity applied to this subscription. Default is 1.
  • metadata (dict) – A set of key/value pairs useful for storing additional information.
  • tax_percent (Decimal. Precision is 2; anything more will be ignored. A positive decimal between 1 and 100.) – This represents the percentage of the subscription invoice subtotal that will be calculated and added as tax to the final amount each billing period.
  • billing_cycle_anchor (datetime) – A future timestamp to anchor the subscription’s billing cycle. This is used to determine the date of the first full invoice, and, for plans with month or year intervals, the day of the month for subsequent invoices.
  • trial_end (datetime) – The end datetime of the trial period the customer will get before being charged for the first time. If set, this will override the default trial period of the plan the customer is being subscribed to. The special value now can be provided to end the customer’s trial immediately.
  • charge_immediately (boolean) – Whether or not to charge for the subscription upon creation. If False, an invoice will be created at the end of this period.
  • trial_from_plan (boolean) – Indicates if a plan’s trial_period_days should be applied to the subscription. Setting trial_end per subscription is preferred, and this defaults to false. Setting this flag to true together with trial_end is not allowed.
  • trial_period_days (integer) – Integer representing the number of trial period days before the customer is charged for the first time. This will always overwrite any trials that might apply via a subscribed plan.
Customer.charge(amount, currency=None, application_fee=None, capture=None, description=None, destination=None, metadata=None, shipping=None, source=None, statement_descriptor=None, idempotency_key=None)[source]

Creates a charge for this customer.

Parameters not implemented:

  • receipt_email - Since this is a charge on a customer, the customer’s email address is used.
Parameters:
  • amount (Decimal. Precision is 2; anything more will be ignored.) – The amount to charge.
  • currency (string) – 3-letter ISO code for currency
  • application_fee (Decimal. Precision is 2; anything more will be ignored.) – A fee that will be applied to the charge and transfered to the platform owner’s account.
  • capture (bool) – Whether or not to immediately capture the charge. When false, the charge issues an authorization (or pre-authorization), and will need to be captured later. Uncaptured charges expire in 7 days. Default is True
  • description (string) – An arbitrary string.
  • destination (Account) – An account to make the charge on behalf of.
  • metadata (dict) – A set of key/value pairs useful for storing additional information.
  • shipping (dict) – Shipping information for the charge.
  • source (string, 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.
  • statement_descriptor (string) – An arbitrary string to be displayed on the customer’s credit card statement.
Customer.add_invoice_item(amount, currency, description=None, discountable=None, invoice=None, metadata=None, subscription=None)[source]

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.

Parameters:
  • amount (Decimal. Precision is 2; anything more will be ignored.) – The amount to charge.
  • currency (string) – 3-letter ISO code for currency
  • description (string) – An arbitrary string.
  • discountable (boolean) – Controls whether discounts apply to this invoice item. Defaults to False for prorations or negative invoice items, and True for all other invoice items.
  • invoice (Invoice or string (invoice ID)) – 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.
  • metadata (dict) – A set of key/value pairs useful for storing additional information.
  • subscription (Subscription or string (subscription ID)) – 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.
Customer.add_card(source, set_default=True)[source]

Adds a card to this customer’s account.

Parameters:
  • source (string, dict) – 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.
  • set_default (boolean) – Whether or not to set the source as the customer’s default source
Customer.add_payment_method(payment_method, set_default=True)[source]

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

Parameters:
  • payment_method (str, PaymentMethod) – PaymentMethod to be attached to the customer
  • set_default (bool) – If true, this will be set as the default_payment_method
Return type:

PaymentMethod

Customer.purge()[source]
Customer.has_active_subscription(plan=None)[source]

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

Parameters:plan (Plan or string (plan ID)) – The plan for which to check for an active subscription. If plan is None and there exists only one active subscription, this method will check if that subscription is valid. Calling this method with no plan and multiple valid subscriptions for this customer will throw an exception.
Returns:True if there exists an active subscription, False otherwise.
Throws:TypeError if plan is None and more than one active subscription exists for this customer.
Customer.has_any_active_subscription()[source]

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

Returns:True if there exists an active subscription, False otherwise.
Customer.active_subscriptions

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

Customer.valid_subscriptions

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

Customer.subscription

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.
Customer.can_charge()[source]

Determines if this customer is able to be charged.

Customer.send_invoice()[source]

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).
Customer.retry_unpaid_invoices()[source]

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

Customer.has_valid_source()[source]

Check whether the customer has a valid payment source.

Customer.add_coupon(coupon, idempotency_key=None)[source]

Add a coupon to a Customer.

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

Customer.upcoming_invoice(**kwargs)[source]

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

See Invoice.upcoming().

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

Extend this to add information to the string representation of the object

Return type:list of str
classmethod Customer.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

Dispute

class djstripe.models.Dispute(*args, **kwargs)[source]

Stripe documentation: https://stripe.com/docs/api#disputes

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • amount (StripeQuantumCurrencyAmountField) – Amount. 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).
  • currency (StripeCurrencyCodeField) – Currency. Three-letter ISO currency code
  • evidence (JSONField) – Evidence. Evidence provided to respond to a dispute.
  • evidence_details (JSONField) – Evidence details. Information about the evidence submission.
  • is_charge_refundable (BooleanField) – Is charge refundable. 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.
  • reason (StripeEnumField) – Reason
  • status (StripeEnumField) – Status
classmethod Dispute.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
Dispute.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
Dispute.get_stripe_dashboard_url()

Get the stripe dashboard url for this object.

Dispute.str_parts()

Extend this to add information to the string representation of the object

Return type:list of str
classmethod Dispute.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

Event

class djstripe.models.Event(*args, **kwargs)[source]

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

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • api_version (CharField) – Api version. the API version at which the event data was rendered. Blank for old entries only, all new entries will have this value
  • data (JSONField) – Data. data received at webhook. data should be considered to be garbage until validity check is run and valid flag is set
  • request_id (CharField) – Request id. 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.
  • idempotency_key (TextField) – Idempotency key
  • type (CharField) – Type. Stripe’s event description code
classmethod Event.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
Event.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
classmethod Event.process(data)[source]
Event.invoke_webhook_handlers()[source]

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).

Event.parts

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

Event.category

Gets the event category string (e.g. ‘customer’).

Event.verb

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

Event.customer
Event.str_parts()[source]

Extend this to add information to the string representation of the object

Return type:list of str
classmethod Event.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

File Upload

class djstripe.models.FileUpload(*args, **kwargs)[source]

Stripe documentation: https://stripe.com/docs/api#file_uploads

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • filename (CharField) – Filename. A filename for the file, suitable for saving to a filesystem.
  • purpose (StripeEnumField) – Purpose. The purpose of the uploaded file.
  • size (IntegerField) – Size. The size in bytes of the file upload object.
  • type (StripeEnumField) – Type. The type of the file returned.
  • url (CharField) – Url. A read-only URL where the uploaded file can be accessed.
classmethod FileUpload.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
FileUpload.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
classmethod FileUpload.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

Payout

class djstripe.models.Payout(*args, **kwargs)[source]

A Payout object is created when you receive funds from Stripe, or when you initiate a payout to either a bank account or debit card of a connected Stripe account.

Stripe documentation: https://stripe.com/docs/api#payouts

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • amount (StripeDecimalCurrencyAmountField) – Amount. Amount (as decimal) to be transferred to your bank account or debit card.
  • arrival_date (StripeDateTimeField) – Arrival date. Date the payout is expected to arrive in the bank. This factors in delays like weekends or bank holidays.
  • balance_transaction (ForeignKey to BalanceTransaction) – Balance transaction. Balance transaction that describes the impact on your account balance.
  • currency (StripeCurrencyCodeField) – Currency. Three-letter ISO currency code
  • destination (ForeignKey to BankAccount) – Destination. Bank account or card the payout was sent to.
  • failure_balance_transaction (ForeignKey to BalanceTransaction) – Failure balance transaction. If the payout failed or was canceled, this will be the balance transaction that reversed the initial balance transaction, and puts the funds from the failed payout back in your balance.
  • failure_code (StripeEnumField) – Failure code. Error code explaining reason for transfer failure if available. See https://stripe.com/docs/api/python#transfer_failures.
  • failure_message (TextField) – Failure message. Message to user further explaining reason for payout failure if available.
  • method (StripeEnumField) – Method. The method used to send this payout. instant is only supported for payouts to debit cards.
  • statement_descriptor (CharField) – Statement descriptor. Extra information about a payout to be displayed on the user’s bank statement.
  • status (StripeEnumField) – Status. Current status of the payout. A payout will be pending until it is submitted to the bank, at which point it becomes in_transit. It will then change to paid if the transaction goes through. If it does not go through successfully, its status will change to failed or canceled.
  • type (StripeEnumField) – Type
classmethod Payout.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
Payout.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
Payout.get_stripe_dashboard_url()

Get the stripe dashboard url for this object.

Payout.str_parts()

Extend this to add information to the string representation of the object

Return type:list of str
classmethod Payout.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

PaymentIntent

class djstripe.models.PaymentIntent(*args, **kwargs)[source]

Stripe documentation: https://stripe.com/docs/api#payment_intents

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • amount (StripeQuantumCurrencyAmountField) – Amount. Amount (in cents) intended to be collected by this PaymentIntent.
  • amount_capturable (StripeQuantumCurrencyAmountField) – Amount capturable. Amount (in cents) that can be captured from this PaymentIntent.
  • amount_received (StripeQuantumCurrencyAmountField) – Amount received. Amount (in cents) that was collected by this PaymentIntent.
  • canceled_at (StripeDateTimeField) – Canceled at. 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) – Cancellation reason. 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) – Capture method. Capture method of this PaymentIntent, one of automatic or manual.
  • client_secret (TextField) – Client secret. The client secret of this PaymentIntent. Used for client-side retrieval using a publishable key.
  • confirmation_method (StripeEnumField) – Confirmation method. Confirmation method of this PaymentIntent, one of manual or automatic.
  • currency (StripeCurrencyCodeField) – Currency. Three-letter ISO currency code
  • customer (ForeignKey to Customer) – Customer. Customer this PaymentIntent is for if one exists.
  • description (TextField) – Description. An arbitrary string attached to the object. Often useful for displaying to users.
  • last_payment_error (JSONField) – Last payment error. The payment error encountered in the previous PaymentIntent confirmation.
  • next_action (JSONField) – Next action. 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 (ForeignKey to Account) – On behalf of. The account (if any) for which the funds of the PaymentIntent are intended.
  • payment_method (ForeignKey to PaymentMethod) – Payment method. Payment method used in this PaymentIntent.
  • payment_method_types (JSONField) – Payment method types. The list of payment method types (e.g. card) that this PaymentIntent is allowed to use.
  • receipt_email (CharField) – Receipt email. Email address that the receipt for the resulting payment will be sent to.
  • setup_future_usage (StripeEnumField) – Setup future usage. 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) – Shipping. Shipping information for this PaymentIntent.
  • statement_descriptor (CharField) – Statement descriptor. 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) – Status. 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) – Transfer data. The data with which to automatically create a Transfer when the payment is finalized. See the PaymentIntents Connect usage guide for details.
  • transfer_group (CharField) – Transfer group. A string that identifies the resulting payment as part of a group. See the PaymentIntents Connect usage guide for details.
classmethod PaymentIntent.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
PaymentIntent.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
PaymentIntent.get_stripe_dashboard_url()

Get the stripe dashboard url for this object.

PaymentIntent.str_parts()

Extend this to add information to the string representation of the object

Return type:list of str
classmethod PaymentIntent.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

Product

class djstripe.models.Product(*args, **kwargs)[source]

Stripe documentation: - https://stripe.com/docs/api#products - https://stripe.com/docs/api#service_products

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • name (TextField) – Name. The product’s name, meant to be displayable to the customer. Applicable to both service and good types.
  • type (StripeEnumField) – Type. The type of the product. The product is either of type good, which is eligible for use with Orders and SKUs, or service, which is eligible for use with Subscriptions and Plans.
  • active (NullBooleanField) – Active. Whether the product is currently available for purchase. Only applicable to products of type=good.
  • attributes (JSONField) – Attributes. A list of up to 5 attributes that each SKU can provide values for (e.g., [“color”, “size”]). Only applicable to products of type=good.
  • caption (TextField) – Caption. A short one-line description of the product, meant to be displayableto the customer. Only applicable to products of type=good.
  • deactivate_on (JSONField) – Deactivate on. An array of connect application identifiers that cannot purchase this product. Only applicable to products of type=good.
  • images (JSONField) – Images. A list of up to 8 URLs of images for this product, meant to be displayable to the customer. Only applicable to products of type=good.
  • package_dimensions (JSONField) – Package dimensions. The dimensions of this product for shipping purposes. A SKU associated with this product can override this value by having its own package_dimensions. Only applicable to products of type=good.
  • shippable (NullBooleanField) – Shippable. Whether this product is a shipped good. Only applicable to products of type=good.
  • url (CharField) – Url. A URL of a publicly-accessible webpage for this product. Only applicable to products of type=good.
  • statement_descriptor (CharField) – Statement descriptor. Extra information about a product which will appear on your customer’s credit card statement. In the case that multiple products are billed at once, the first statement descriptor will be used. Only available on products of type=`service`.
  • unit_label (CharField) – Unit label
classmethod Product.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
Product.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
Product.get_stripe_dashboard_url()

Get the stripe dashboard url for this object.

classmethod Product.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

Refund

class djstripe.models.Refund(*args, **kwargs)[source]

Stripe documentation: https://stripe.com/docs/api#refund_object

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • amount (StripeQuantumCurrencyAmountField) – Amount. Amount, in cents.
  • balance_transaction (ForeignKey to BalanceTransaction) – Balance transaction. Balance transaction that describes the impact on your account balance.
  • charge (ForeignKey to Charge) – Charge. The charge that was refunded
  • currency (StripeCurrencyCodeField) – Currency. Three-letter ISO currency code
  • failure_balance_transaction (ForeignKey to BalanceTransaction) – Failure balance transaction. If the refund failed, this balance transaction describes the adjustment made on your account balance that reverses the initial balance transaction.
  • failure_reason (StripeEnumField) – Failure reason. If the refund failed, the reason for refund failure if known.
  • reason (StripeEnumField) – Reason. Reason for the refund.
  • receipt_number (CharField) – Receipt number. The transaction number that appears on email receipts sent for this charge.
  • status (StripeEnumField) – Status. Status of the refund.
classmethod Refund.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
Refund.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
Refund.get_stripe_dashboard_url()[source]

Get the stripe dashboard url for this object.

classmethod Refund.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

Payment Methods

BankAccount

class djstripe.models.BankAccount(djstripe_id, id, livemode, created, metadata, description, djstripe_created, djstripe_updated, account, account_holder_name, account_holder_type, bank_name, country, currency, customer, default_for_currency, fingerprint, last4, routing_number, status)[source]
Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • account (ForeignKey to Account) – Account. The account the charge was made on behalf of. Null here indicates that this value was never set.
  • account_holder_name (TextField) – Account holder name. The name of the person or business that owns the bank account.
  • account_holder_type (StripeEnumField) – Account holder type. The type of entity that holds the account.
  • bank_name (CharField) – Bank name. Name of the bank associated with the routing number (e.g., WELLS FARGO).
  • country (CharField) – Country. Two-letter ISO code representing the country the bank account is located in.
  • currency (StripeCurrencyCodeField) – Currency. Three-letter ISO currency code
  • customer (ForeignKey to Customer) – Customer
  • default_for_currency (NullBooleanField) – Default for currency. Whether this external account is the default account for its currency.
  • fingerprint (CharField) – Fingerprint. Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same.
  • last4 (CharField) – Last4
  • routing_number (CharField) – Routing number. The routing transit number for the bank account.
  • status (StripeEnumField) – Status
classmethod BankAccount.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
BankAccount.api_retrieve(api_key=None, stripe_account=None)
BankAccount.get_stripe_dashboard_url()
BankAccount.str_parts()

Extend this to add information to the string representation of the object

Return type:list of str
classmethod BankAccount.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

Card

class djstripe.models.Card(*args, **kwargs)[source]

You can store multiple cards on a customer in order to charge the customer later.

This is a legacy model which only applies to the “v2” Stripe API (eg. Checkout.js). You should strive to use the Stripe “v3” API (eg. Stripe Elements). Also see: https://stripe.com/docs/stripe-js/elements/migrating When using Elements, you will not be using Card objects. Instead, you will use Source objects. A Source object of type “card” is equivalent to a Card object. However, Card objects cannot be converted into Source objects by Stripe at this time.

Stripe documentation: https://stripe.com/docs/api/python#cards

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • address_city (TextField) – Address city. City/District/Suburb/Town/Village.
  • address_country (TextField) – Address country. Billing address country.
  • address_line1 (TextField) – Address line1. Street address/PO Box/Company name.
  • address_line1_check (StripeEnumField) – Address line1 check. If address_line1 was provided, results of the check.
  • address_line2 (TextField) – Address line2. Apartment/Suite/Unit/Building.
  • address_state (TextField) – Address state. State/County/Province/Region.
  • address_zip (TextField) – Address zip. ZIP or postal code.
  • address_zip_check (StripeEnumField) – Address zip check. If address_zip was provided, results of the check.
  • brand (StripeEnumField) – Brand. Card brand.
  • country (CharField) – Country. Two-letter ISO code representing the country of the card.
  • customer (ForeignKey to Customer) – Customer
  • cvc_check (StripeEnumField) – Cvc check. If a CVC was provided, results of the check.
  • dynamic_last4 (CharField) – Dynamic last4. (For tokenized numbers only.) The last four digits of the device account number.
  • exp_month (IntegerField) – Exp month. Card expiration month.
  • exp_year (IntegerField) – Exp year. Card expiration year.
  • fingerprint (CharField) – Fingerprint. Uniquely identifies this particular card number.
  • funding (StripeEnumField) – Funding. Card funding type.
  • last4 (CharField) – Last4. Last four digits of Card number.
  • name (TextField) – Name. Cardholder name.
  • tokenization_method (StripeEnumField) – Tokenization method. If the card number is tokenized, this is the method that was used.
classmethod Card.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
Card.api_retrieve(api_key=None, stripe_account=None)
Card.get_stripe_dashboard_url()
Card.remove()

Removes a legacy source from this customer’s account.

classmethod Card.create_token(number, exp_month, exp_year, cvc, api_key='', **kwargs)[source]

Creates a single use token that wraps the details of a credit card. This token can be used in place of a credit card dictionary with any API method. These tokens can only be used once: by creating a new charge object, or attaching them to a customer. (Source: https://stripe.com/docs/api/python#create_card_token)

Parameters:
  • number (str) – The card number without any separators (no spaces)
  • exp_month (int) – The card’s expiration month. (two digits)
  • exp_year (int) – The card’s expiration year. (four digits)
  • cvc (str) – Card security code.
  • api_key (str) –
Return type:

stripe.Token

Card.str_parts()[source]

Extend this to add information to the string representation of the object

Return type:list of str
classmethod Card.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

PaymentMethod

class djstripe.models.PaymentMethod(*args, **kwargs)[source]

Stripe documentation: https://stripe.com/docs/api#payment_methods

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • billing_details (JSONField) – Billing details. Billing information associated with the PaymentMethod that may be used or required by particular types of payment methods.
  • card (JSONField) – Card. If this is a card PaymentMethod, this hash contains details about the card.
  • card_present (JSONField) – Card present. If this is an card_present PaymentMethod, this hash contains details about the Card Present payment method.
  • customer (ForeignKey to Customer) – Customer. Customer to which this PaymentMethod is saved.This will not be set when the PaymentMethod has not been saved to a Customer.
  • type (CharField) – Type. The type of the PaymentMethod. An additional hash is included on the PaymentMethod with a name matching this value. It contains additional information specific to the PaymentMethod type.
classmethod PaymentMethod.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
PaymentMethod.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
PaymentMethod.get_stripe_dashboard_url()

Get the stripe dashboard url for this object.

classmethod PaymentMethod.attach(payment_method, customer, api_key='')[source]

Attach a payment method to a customer :param payment_method: :type payment_method: str, PaymentMethod :param customer: :type customer: Union[str, Customer] :param api_key: :type api_key: str :return: :rtype: PaymentMethod

PaymentMethod.detach()[source]

Detach the payment method from its customer.

Returns:Returns true if the payment method was newly detached, false if it was already detached
Return type:bool
PaymentMethod.str_parts()

Extend this to add information to the string representation of the object

Return type:list of str
classmethod PaymentMethod.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

Source

class djstripe.models.Source(*args, **kwargs)[source]

Stripe documentation: https://stripe.com/docs/api#sources

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • amount (StripeDecimalCurrencyAmountField) – Amount. Amount (as decimal) associated with the source. This is the amount for which the source will be chargeable once ready. Required for single_use sources.
  • client_secret (CharField) – Client secret. The client secret of the source. Used for client-side retrieval using a publishable key.
  • currency (StripeCurrencyCodeField) – Currency. Three-letter ISO currency code
  • flow (StripeEnumField) – Flow. The authentication flow of the source.
  • owner (JSONField) – Owner. Information about the owner of the payment instrument that may be used or required by particular source types.
  • statement_descriptor (CharField) – Statement descriptor. Extra information about a source. This will appear on your customer’s statement every time you charge the source.
  • status (StripeEnumField) – Status. The status of the source. Only chargeable sources can be used to create a charge.
  • type (StripeEnumField) – Type. The type of the source.
  • usage (StripeEnumField) – Usage. Whether this source should be reusable or not. Some source types may or may not be reusable by construction, while other may leave the option at creation.
  • code_verification (JSONField) – Code verification. Information related to the code verification flow. Present if the source is authenticated by a verification code (flow is code_verification).
  • receiver (JSONField) – Receiver. Information related to the receiver flow. Present if the source is a receiver (flow is receiver).
  • redirect (JSONField) – Redirect. Information related to the redirect flow. Present if the source is authenticated by a redirect (flow is redirect).
  • source_data (JSONField) – Source data. The data corresponding to the source type.
  • customer (ForeignKey to Customer) – Customer
classmethod Source.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
Source.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
Source.get_stripe_dashboard_url()

Get the stripe dashboard url for this object.

Source.detach()[source]

Detach the source from its customer.

Returns:
Return type:bool
Source.str_parts()

Extend this to add information to the string representation of the object

Return type:list of str
classmethod Source.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

Billing

Coupon

class djstripe.models.Coupon(djstripe_id, livemode, created, metadata, description, djstripe_created, djstripe_updated, id, amount_off, currency, duration, duration_in_months, max_redemptions, name, percent_off, redeem_by, times_redeemed)[source]
Parameters:
  • djstripe_id (BigAutoField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • id (StripeIdField) – Id
  • amount_off (StripeDecimalCurrencyAmountField) – Amount off. Amount (as decimal) that will be taken off the subtotal of any invoices for this customer.
  • currency (StripeCurrencyCodeField) – Currency. Three-letter ISO currency code
  • duration (StripeEnumField) – Duration. Describes how long a customer who applies this coupon will get the discount.
  • duration_in_months (PositiveIntegerField) – Duration in months. If duration is repeating, the number of months the coupon applies.
  • max_redemptions (PositiveIntegerField) – Max redemptions. Maximum number of times this coupon can be redeemed, in total, before it is no longer valid.
  • name (TextField) – Name. Name of the coupon displayed to customers on for instance invoices or receipts.
  • percent_off (StripePercentField) – Percent off. Percent that will be taken off the subtotal of any invoices for this customer for the duration of the coupon. For example, a coupon with percent_off of 50 will make a $100 invoice $50 instead.
  • redeem_by (StripeDateTimeField) – Redeem by. Date after which the coupon can no longer be redeemed. Max 5 years in the future.
  • times_redeemed (PositiveIntegerField) – Times redeemed. Number of times this coupon has been applied to a customer.
classmethod Coupon.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
Coupon.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
Coupon.get_stripe_dashboard_url()

Get the stripe dashboard url for this object.

Coupon.human_readable_amount
Coupon.human_readable
Coupon.str_parts()

Extend this to add information to the string representation of the object

Return type:list of str
classmethod Coupon.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

Invoice

class djstripe.models.Invoice(*args, **kwargs)[source]

Invoices are statements of what a customer owes for a particular billing period, including subscriptions, invoice items, and any automatic proration adjustments if necessary.

Once an invoice is created, payment is automatically attempted. Note that the payment, while automatic, does not happen exactly at the time of invoice creation. If you have configured webhooks, the invoice will wait until one hour after the last webhook is successfully sent (or the last webhook times out after failing).

Any customer credit on the account is applied before determining how much is due for that invoice (the amount that will be actually charged). If the amount due for the invoice is less than 50 cents (the minimum for a charge), we add the amount to the customer’s running account balance to be added to the next invoice. If this amount is negative, it will act as a credit to offset the next invoice. Note that the customer account balance does not include unpaid invoices; it only includes balances that need to be taken into account when calculating the amount due for the next invoice.

Stripe documentation: https://stripe.com/docs/api/python#invoices

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • account_country (CharField) – Account country. The country of the business associated with this invoice, most often the business creating the invoice.
  • account_name (TextField) – Account name. The public name of the business associated with this invoice, most often the business creating the invoice.
  • amount_due (StripeDecimalCurrencyAmountField) – Amount due. Final amount due (as decimal) at this time for this invoice. If the invoice’s total is smaller than the minimum charge amount, for example, or if there is account credit that can be applied to the invoice, the amount_due may be 0. If there is a positive starting_balance for the invoice (the customer owes money), the amount_due will also take that into account. The charge that gets generated for the invoice will be for the amount specified in amount_due.
  • amount_paid (StripeDecimalCurrencyAmountField) – Amount paid. The amount, (as decimal), that was paid.
  • amount_remaining (StripeDecimalCurrencyAmountField) – Amount remaining. The amount remaining, (as decimal), that is due.
  • application_fee_amount (StripeDecimalCurrencyAmountField) – Application fee amount. The fee (as decimal) that will be applied to the invoice and transferred to the application owner’s Stripe account when the invoice is paid.
  • attempt_count (IntegerField) – Attempt count. Number of payment attempts made for this invoice, from the perspective of the payment retry schedule. Any payment attempt counts as the first attempt, and subsequently only automatic retries increment the attempt count. In other words, manual payment attempts after the first attempt do not affect the retry schedule.
  • attempted (BooleanField) – Attempted. Whether or not an attempt has been made to pay the invoice. An invoice is not attempted until 1 hour after the invoice.created webhook, for example, so you might not want to display that invoice as unpaid to your users.
  • auto_advance (NullBooleanField) – Auto advance. Controls whether Stripe will perform automatic collection of the invoice. When false, the invoice’s state will not automatically advance without an explicit action.
  • billing_reason (StripeEnumField) – Billing reason. Indicates the reason why the invoice was created. subscription_cycle indicates an invoice created by a subscription advancing into a new period. subscription_create indicates an invoice created due to creating a subscription. subscription_update indicates an invoice created due to updating a subscription. subscription is set for all old invoices to indicate either a change to a subscription or a period advancement. manual is set for all invoices unrelated to a subscription (for example: created via the invoice editor). The upcoming value is reserved for simulated invoices per the upcoming invoice endpoint. subscription_threshold indicates an invoice created due to a billing threshold being reached.
  • charge (OneToOneField to Charge) – Charge. The latest charge generated for this invoice, if any.
  • closed (NullBooleanField) – Closed. Whether or not the invoice is still trying to collect payment. An invoice is closed if it’s either paid or it has been marked closed. A closed invoice will no longer attempt to collect payment.
  • collection_method (StripeEnumField) – Collection method. When charging automatically, Stripe will attempt to pay this invoice using the default source attached to the customer. When sending an invoice, Stripe will email this invoice to the customer with payment instructions.
  • currency (StripeCurrencyCodeField) – Currency. Three-letter ISO currency code
  • customer (ForeignKey to Customer) – Customer. The customer associated with this invoice.
  • customer_address (JSONField) – Customer address. The customer’s address. Until the invoice is finalized, this field will equal customer.address. Once the invoice is finalized, this field will no longer be updated.
  • customer_email (TextField) – Customer email. The customer’s email. Until the invoice is finalized, this field will equal customer.email. Once the invoice is finalized, this field will no longer be updated.
  • customer_name (TextField) – Customer name. The customer’s name. Until the invoice is finalized, this field will equal customer.name. Once the invoice is finalized, this field will no longer be updated.
  • customer_phone (TextField) – Customer phone. The customer’s phone number. Until the invoice is finalized, this field will equal customer.phone_. Once the invoice is finalized, this field will no longer be updated.
  • customer_shipping (JSONField) – Customer shipping. The customer’s shipping information. Until the invoice is finalized, this field will equal customer.shipping. Once the invoice is finalized, this field will no longer be updated.
  • customer_tax_exempt (StripeEnumField) – Customer tax exempt. The customer’s tax exempt status. Until the invoice is finalized, this field will equal customer.tax_exempt. Once the invoice is finalized, this field will no longer be updated.
  • default_payment_method (ForeignKey to PaymentMethod) – Default payment method. Default payment method for the invoice. It must belong to the customer associated with the invoice. If not set, defaults to the subscription’s default payment method, if any, or to the default payment method in the customer’s invoice settings.
  • due_date (StripeDateTimeField) – Due date. The date on which payment for this invoice is due. This value will be null for invoices where billing=charge_automatically.
  • ending_balance (StripeQuantumCurrencyAmountField) – Ending balance. Ending customer balance (in cents) after attempting to pay invoice. If the invoice has not been attempted yet, this will be null.
  • footer (TextField) – Footer. Footer displayed on the invoice.
  • forgiven (NullBooleanField) – Forgiven. Whether or not the invoice has been forgiven. Forgiving an invoice instructs us to update the subscription status as if the invoice were successfully paid. Once an invoice has been forgiven, it cannot be unforgiven or reopened.
  • hosted_invoice_url (TextField) – Hosted invoice url. The URL for the hosted invoice page, which allows customers to view and pay an invoice. If the invoice has not been frozen yet, this will be null.
  • invoice_pdf (TextField) – Invoice pdf. The link to download the PDF for the invoice. If the invoice has not been frozen yet, this will be null.
  • next_payment_attempt (StripeDateTimeField) – Next payment attempt. The time at which payment will next be attempted.
  • number (CharField) – Number. A unique, identifying string that appears on emails sent to the customer for this invoice. This starts with the customer’s unique invoice_prefix if it is specified.
  • paid (BooleanField) – Paid. The time at which payment will next be attempted.
  • payment_intent (OneToOneField to PaymentIntent) – Payment intent. The PaymentIntent associated with this invoice. The PaymentIntent is generated when the invoice is finalized, and can then be used to pay the invoice.Note that voiding an invoice will cancel the PaymentIntent
  • period_end (StripeDateTimeField) – Period end. End of the usage period during which invoice items were added to this invoice.
  • period_start (StripeDateTimeField) – Period start. Start of the usage period during which invoice items were added to this invoice.
  • post_payment_credit_notes_amount (StripeQuantumCurrencyAmountField) – Post payment credit notes amount. Total amount (in cents) of all post-payment credit notes issued for this invoice.
  • pre_payment_credit_notes_amount (StripeQuantumCurrencyAmountField) – Pre payment credit notes amount. Total amount (in cents) of all pre-payment credit notes issued for this invoice.
  • receipt_number (CharField) – Receipt number. This is the transaction number that appears on email receipts sent for this invoice.
  • starting_balance (StripeQuantumCurrencyAmountField) – Starting balance. Starting customer balance (in cents) before attempting to pay invoice. If the invoice has not been attempted yet, this will be the current customer balance.
  • statement_descriptor (CharField) – Statement descriptor. An arbitrary string to be displayed on your customer’s credit card statement. The statement description may not include <>”’ characters, and will appear on your customer’s statement in capital letters. Non-ASCII characters are automatically stripped. While most banks display this information consistently, some may display it incorrectly or not at all.
  • status_transitions (JSONField) – Status transitions
  • subscription (ForeignKey to Subscription) – Subscription. The subscription that this invoice was prepared for, if any.
  • subscription_proration_date (StripeDateTimeField) – Subscription proration date. Only set for upcoming invoices that preview prorations. The time used to calculate prorations.
  • subtotal (StripeDecimalCurrencyAmountField) – Subtotal. Total (as decimal) of all subscriptions, invoice items, and prorations on the invoice before any discount or tax is applied.
  • tax (StripeDecimalCurrencyAmountField) – Tax. The amount (as decimal) of tax included in the total, calculated from tax_percent and the subtotal. If no tax_percent is defined, this value will be null.
  • tax_percent (StripePercentField) – Tax percent. This percentage of the subtotal has been added to the total amount of the invoice, including invoice line items and discounts. This field is inherited from the subscription’s tax_percent field, but can be changed before the invoice is paid. This field defaults to null.
  • threshold_reason (JSONField) – Threshold reason. If billing_reason is set to subscription_threshold this returns more information on which threshold rules triggered the invoice.
  • total (StripeDecimalCurrencyAmountField) – Total (as decimal) after discount.
  • webhooks_delivered_at (StripeDateTimeField) – Webhooks delivered at. The time at which webhooks for this invoice were successfully delivered (if the invoice had no webhooks to deliver, this will match date). Invoice payment is delayed until webhooks are delivered, or until all webhook delivery attempts have been exhausted.
  • default_tax_rates (ManyToManyField) – Default tax rates. The tax rates applied to this invoice, if any.
classmethod Invoice.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
Invoice.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
Invoice.get_stripe_dashboard_url()

Get the stripe dashboard url for this object.

classmethod Invoice.upcoming(api_key='', customer=None, coupon=None, subscription=None, subscription_plan=None, subscription_prorate=None, subscription_proration_date=None, subscription_quantity=None, subscription_trial_end=None, **kwargs)

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

At any time, you can preview the upcoming invoice for a customer. This will show you all the charges that are pending, including subscription renewal charges, invoice item charges, etc. It will also show you any discount that is applicable to the customer. (Source: https://stripe.com/docs/api#upcoming_invoice)

Important

Note that when you are viewing an upcoming invoice, you are simply viewing a preview.

Parameters:
  • customer (Customer or string (customer ID)) – The identifier of the customer whose upcoming invoice you’d like to retrieve.
  • coupon (str) – The code of the coupon to apply.
  • subscription (Subscription or string (subscription ID)) – The identifier of the subscription to retrieve an invoice for.
  • subscription_plan (Plan or string (plan ID)) – If set, the invoice returned will preview updating the subscription given to this plan, or creating a new subscription to this plan if no subscription is given.
  • subscription_prorate (bool) – If previewing an update to a subscription, this decides whether the preview will show the result of applying prorations or not.
  • subscription_proration_date (datetime) – If previewing an update to a subscription, and doing proration, subscription_proration_date forces the proration to be calculated as though the update was done at the specified time.
  • subscription_quantity (int) – If provided, the invoice returned will preview updating or creating a subscription with that quantity.
  • subscription_trial_end (datetime) – If provided, the invoice returned will preview updating or creating a subscription with that trial end.
Returns:

The upcoming preview invoice.

Return type:

UpcomingInvoice

Invoice.retry()

Retry payment on this invoice if it isn’t paid, closed, or forgiven.

Invoice.status
Invoice.plan

Gets the associated plan for this invoice.

In order to provide a consistent view of invoices, the plan object should be taken from the first invoice item that has one, rather than using the plan associated with the subscription.

Subscriptions (and their associated plan) are updated by the customer and represent what is current, but invoice items are immutable within the invoice and stay static/unchanged.

In other words, a plan retrieved from an invoice item will represent the plan as it was at the time an invoice was issued. The plan retrieved from the subscription will be the currently active plan.

Returns:The associated plan for the invoice.
Return type:djstripe.Plan
Invoice.str_parts()

Extend this to add information to the string representation of the object

Return type:list of str
classmethod Invoice.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

InvoiceItem

class djstripe.models.InvoiceItem(*args, **kwargs)[source]

Sometimes you want to add a charge or credit to a customer but only actually charge the customer’s card at the end of a regular billing cycle. This is useful for combining several charges to minimize per-transaction fees or having Stripe tabulate your usage-based billing totals.

Stripe documentation: https://stripe.com/docs/api/python#invoiceitems

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • amount (StripeDecimalCurrencyAmountField) – Amount. Amount invoiced (as decimal).
  • currency (StripeCurrencyCodeField) – Currency. Three-letter ISO currency code
  • customer (ForeignKey to Customer) – Customer. The customer associated with this invoiceitem.
  • date (StripeDateTimeField) – Date. The date on the invoiceitem.
  • discountable (BooleanField) – Discountable. If True, discounts will apply to this invoice item. Always False for prorations.
  • invoice (ForeignKey to Invoice) – Invoice. The invoice to which this invoiceitem is attached.
  • period (JSONField) – Period
  • period_end (StripeDateTimeField) – Period end. Might be the date when this invoiceitem’s invoice was sent.
  • period_start (StripeDateTimeField) – Period start. Might be the date when this invoiceitem was added to the invoice
  • plan (ForeignKey to Plan) – Plan. If the invoice item is a proration, the plan of the subscription for which the proration was computed.
  • proration (BooleanField) – Proration. Whether or not the invoice item was created automatically as a proration adjustment when the customer switched plans.
  • quantity (IntegerField) – Quantity. If the invoice item is a proration, the quantity of the subscription for which the proration was computed.
  • subscription (ForeignKey to Subscription) – Subscription. The subscription that this invoice item has been created for, if any.
  • tax_rates (ManyToManyField) – Tax rates. The tax rates which apply to this invoice item. When set, the default_tax_rates on the invoice do not apply to this invoice item.
classmethod InvoiceItem.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
InvoiceItem.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
InvoiceItem.get_stripe_dashboard_url()[source]

Get the stripe dashboard url for this object.

classmethod InvoiceItem.sync_from_stripe_data(data)[source]

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

InvoiceItem

class djstripe.models.InvoiceItem(*args, **kwargs)[source]

Sometimes you want to add a charge or credit to a customer but only actually charge the customer’s card at the end of a regular billing cycle. This is useful for combining several charges to minimize per-transaction fees or having Stripe tabulate your usage-based billing totals.

Stripe documentation: https://stripe.com/docs/api/python#invoiceitems

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • amount (StripeDecimalCurrencyAmountField) – Amount. Amount invoiced (as decimal).
  • currency (StripeCurrencyCodeField) – Currency. Three-letter ISO currency code
  • customer (ForeignKey to Customer) – Customer. The customer associated with this invoiceitem.
  • date (StripeDateTimeField) – Date. The date on the invoiceitem.
  • discountable (BooleanField) – Discountable. If True, discounts will apply to this invoice item. Always False for prorations.
  • invoice (ForeignKey to Invoice) – Invoice. The invoice to which this invoiceitem is attached.
  • period (JSONField) – Period
  • period_end (StripeDateTimeField) – Period end. Might be the date when this invoiceitem’s invoice was sent.
  • period_start (StripeDateTimeField) – Period start. Might be the date when this invoiceitem was added to the invoice
  • plan (ForeignKey to Plan) – Plan. If the invoice item is a proration, the plan of the subscription for which the proration was computed.
  • proration (BooleanField) – Proration. Whether or not the invoice item was created automatically as a proration adjustment when the customer switched plans.
  • quantity (IntegerField) – Quantity. If the invoice item is a proration, the quantity of the subscription for which the proration was computed.
  • subscription (ForeignKey to Subscription) – Subscription. The subscription that this invoice item has been created for, if any.
  • tax_rates (ManyToManyField) – Tax rates. The tax rates which apply to this invoice item. When set, the default_tax_rates on the invoice do not apply to this invoice item.
classmethod InvoiceItem.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
InvoiceItem.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
InvoiceItem.get_stripe_dashboard_url()[source]

Get the stripe dashboard url for this object.

InvoiceItem.str_parts()[source]

Extend this to add information to the string representation of the object

Return type:list of str
classmethod InvoiceItem.sync_from_stripe_data(data)[source]

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

Plan

class djstripe.models.Plan(*args, **kwargs)[source]

A subscription plan contains the pricing information for different products and feature levels on your site.

Stripe documentation: https://stripe.com/docs/api/python#plans)

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • active (BooleanField) – Active. Whether the plan is currently available for new subscriptions.
  • aggregate_usage (StripeEnumField) – Aggregate usage. Specifies a usage aggregation strategy for plans of usage_type=metered. Allowed values are sum for summing up all usage during a period, last_during_period for picking the last usage record reported within a period, last_ever for picking the last usage record ever (across period bounds) or max which picks the usage record with the maximum reported usage during a period. Defaults to sum.
  • amount (StripeDecimalCurrencyAmountField) – Amount. Amount (as decimal) to be charged on the interval specified.
  • billing_scheme (StripeEnumField) – Billing scheme. Describes how to compute the price per period. Either per_unit or tiered. per_unit indicates that the fixed amount (specified in amount) will be charged per unit in quantity (for plans with usage_type=licensed), or per unit of total usage (for plans with usage_type=metered). tiered indicates that the unit pricing will be computed using a tiering strategy as defined using the tiers and tiers_mode attributes.
  • currency (StripeCurrencyCodeField) – Currency. Three-letter ISO currency code
  • interval (StripeEnumField) – Interval. The frequency with which a subscription should be billed.
  • interval_count (IntegerField) – Interval count. The number of intervals (specified in the interval property) between each subscription billing.
  • nickname (TextField) – Nickname. A brief description of the plan, hidden from customers.
  • product (ForeignKey to Product) – Product. The product whose pricing this plan determines.
  • tiers (JSONField) – Tiers. Each element represents a pricing tier. This parameter requires billing_scheme to be set to tiered.
  • tiers_mode (StripeEnumField) – Tiers mode. Defines if the tiering price should be graduated or volume based. In volume-based tiering, the maximum quantity within a period determines the per unit price, in graduated tiering pricing can successively change as the quantity grows.
  • transform_usage (JSONField) – Transform usage. Apply a transformation to the reported usage or set quantity before computing the billed price. Cannot be combined with tiers.
  • trial_period_days (IntegerField) – Trial period days. Number of trial period days granted when subscribing a customer to this plan. Null if the plan has no trial period.
  • usage_type (StripeEnumField) – Usage type. Configures how the quantity per period should be determined, can be either metered or licensed. licensed will automatically bill the quantity set for a plan when adding it to a subscription, metered will aggregate the total usage based on usage records. Defaults to licensed.
  • name (TextField) – Name. Name of the plan, to be displayed on invoices and in the web interface.
  • statement_descriptor (CharField) – Statement descriptor. An arbitrary string to be displayed on your customer’s credit card statement. The statement description may not include <>”’ characters, and will appear on your customer’s statement in capital letters. Non-ASCII characters are automatically stripped. While most banks display this information consistently, some may display it incorrectly or not at all.
classmethod Plan.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
Plan.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
Plan.get_stripe_dashboard_url()

Get the stripe dashboard url for this object.

classmethod Plan.get_or_create(**kwargs)[source]

Get or create a Plan.

Plan.amount_in_cents
Plan.human_readable_price
Plan.str_parts()

Extend this to add information to the string representation of the object

Return type:list of str
classmethod Plan.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

Subscription

class djstripe.models.Subscription(*args, **kwargs)[source]

Subscriptions allow you to charge a customer’s card on a recurring basis. A subscription ties a customer to a particular plan you’ve created.

A subscription still in its trial period is trialing and moves to active when the trial period is over.

When payment to renew the subscription fails, the subscription becomes past_due. After Stripe has exhausted all payment retry attempts, the subscription ends up with a status of either canceled or unpaid depending on your retry settings.

Note that when a subscription has a status of unpaid, no subsequent invoices will be attempted (invoices will be created, but then immediately automatically closed.

Additionally, updating customer card details will not lead to Stripe retrying the latest invoice.). After receiving updated card details from a customer, you may choose to reopen and pay their closed invoices.

Stripe documentation: https://stripe.com/docs/api/python#subscriptions

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • application_fee_percent (StripePercentField) – Application fee percent. A positive decimal that represents the fee percentage of the subscription invoice amount that will be transferred to the application owner’s Stripe account each billing period.
  • billing (StripeEnumField) – Billing. Either charge_automatically, or send_invoice. When charging automatically, Stripe will attempt to pay this subscription at the end of the cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions.
  • billing_cycle_anchor (StripeDateTimeField) – Billing cycle anchor. Determines the date of the first full invoice, and, for plans with month or year intervals, the day of the month for subsequent invoices.
  • cancel_at_period_end (BooleanField) – Cancel at period end. If the subscription has been canceled with the at_period_end flag set to true, cancel_at_period_end on the subscription will be true. You can use this attribute to determine whether a subscription that has a status of active is scheduled to be canceled at the end of the current period.
  • canceled_at (StripeDateTimeField) – Canceled at. If the subscription has been canceled, the date of that cancellation. If the subscription was canceled with cancel_at_period_end, canceled_at will still reflect the date of the initial cancellation request, not the end of the subscription period when the subscription is automatically moved to a canceled state.
  • current_period_end (StripeDateTimeField) – Current period end. End of the current period for which the subscription has been invoiced. At the end of this period, a new invoice will be created.
  • current_period_start (StripeDateTimeField) – Current period start. Start of the current period for which the subscription has been invoiced.
  • customer (ForeignKey to Customer) – Customer. The customer associated with this subscription.
  • days_until_due (IntegerField) – Days until due. Number of days a customer has to pay invoices generated by this subscription. This value will be null for subscriptions where billing=charge_automatically.
  • ended_at (StripeDateTimeField) – Ended at. If the subscription has ended (either because it was canceled or because the customer was switched to a subscription to a new plan), the date the subscription ended.
  • pending_setup_intent (ForeignKey to SetupIntent) – Pending setup intent. We can use this SetupIntent to collect user authentication when creating a subscription without immediate payment or updating a subscription’s payment method, allowing you to optimize for off-session payments.
  • plan (ForeignKey to Plan) – Plan. The plan associated with this subscription. This value will be null for multi-plan subscriptions
  • quantity (IntegerField) – Quantity. The quantity applied to this subscription. This value will be null for multi-plan subscriptions
  • start (StripeDateTimeField) – Start. Date of the last substantial change to this subscription. For example, a change to the items array, or a change of status, will reset this timestamp.
  • status (StripeEnumField) – Status. The status of this subscription.
  • tax_percent (StripePercentField) – Tax percent. A positive decimal (with at most two decimal places) between 1 and 100. This represents the percentage of the subscription invoice subtotal that will be calculated and added as tax to the final amount each billing period.
  • trial_end (StripeDateTimeField) – Trial end. If the subscription has a trial, the end of that trial.
  • trial_start (StripeDateTimeField) – Trial start. If the subscription has a trial, the beginning of that trial.
  • default_tax_rates (ManyToManyField) – Default tax rates. The tax rates that will apply to any subscription item that does not have tax_rates set. Invoices created will have their default_tax_rates populated from the subscription.
classmethod Subscription.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
Subscription.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
Subscription.get_stripe_dashboard_url()

Get the stripe dashboard url for this object.

Subscription.update(plan=None, application_fee_percent=None, billing_cycle_anchor=None, coupon=None, prorate=False, proration_date=None, metadata=None, quantity=None, tax_percent=None, trial_end=None)[source]

See Customer.subscribe()

Parameters:
  • plan (Plan or string (plan ID)) – The plan to which to subscribe the customer.
  • application_fee_percent
  • billing_cycle_anchor
  • coupon
  • prorate (boolean) – Whether or not to prorate when switching plans. Default is True.
  • proration_date (datetime) – If set, the proration will be calculated as though the subscription was updated at the given time. This can be used to apply exactly the same proration that was previewed with upcoming invoice endpoint. It can also be used to implement custom proration logic, such as prorating by day instead of by second, by providing the time that you wish to use for proration calculations.
  • metadata
  • quantity
  • tax_percent
  • trial_end

Note

The default value for prorate is the DJSTRIPE_PRORATION_POLICY setting.

Important

Updating a subscription by changing the plan or quantity creates a new Subscription in Stripe (and dj-stripe).

Subscription.extend(delta)[source]

Extends this subscription by the provided delta.

Parameters:delta (timedelta) – The timedelta by which to extend this subscription.
Subscription.cancel(at_period_end=True)[source]

Cancels this subscription. If you set the at_period_end parameter to true, the subscription will remain active until the end of the period, at which point it will be canceled and not renewed. By default, the subscription is terminated immediately. In either case, the customer will not be charged again for the subscription. Note, however, that any pending invoice items that you’ve created will still be charged for at the end of the period unless manually deleted. If you’ve set the subscription to cancel at period end, any pending prorations will also be left in place and collected at the end of the period, but if the subscription is set to cancel immediately, pending prorations will be removed.

By default, all unpaid invoices for the customer will be closed upon subscription cancellation. We do this in order to prevent unexpected payment retries once the customer has canceled a subscription. However, you can reopen the invoices manually after subscription cancellation to have us proceed with automatic retries, or you could even re-attempt payment yourself on all unpaid invoices before allowing the customer to cancel the subscription at all.

Parameters:at_period_end (boolean) – A flag that if set to true will delay the cancellation of the subscription until the end of the current period. Default is False.

Important

If a subscription is canceled during a trial period, the at_period_end flag will be overridden to False so that the trial ends immediately and the customer’s card isn’t charged.

Subscription.reactivate()[source]

Reactivates this subscription.

If a customer’s subscription is canceled with at_period_end set to True and it has not yet reached the end of the billing period, it can be reactivated. Subscriptions canceled immediately cannot be reactivated. (Source: https://stripe.com/docs/subscriptions/canceling-pausing)

Warning

Reactivating a fully canceled Subscription will fail silently. Be sure to check the returned Subscription’s status.

Subscription.is_period_current()[source]

Returns True if this subscription’s period is current, false otherwise.

Subscription.is_status_current()[source]

Returns True if this subscription’s status is current (active or trialing), false otherwise.

Subscription.is_status_temporarily_current()[source]

A status is temporarily current when the subscription is canceled with the at_period_end flag. The subscription is still active, but is technically canceled and we’re just waiting for it to run out.

You could use this method to give customers limited service after they’ve canceled. For example, a video on demand service could only allow customers to download their libraries and do nothing else when their subscription is temporarily current.

Subscription.is_valid()[source]

Returns True if this subscription’s status and period are current, false otherwise.

Subscription.str_parts()

Extend this to add information to the string representation of the object

Return type:list of str
classmethod Subscription.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

SubscriptionItem

class djstripe.models.SubscriptionItem(*args, **kwargs)[source]

Subscription items allow you to create customer subscriptions with more than one plan, making it easy to represent complex billing relationships.

Stripe documentation: https://stripe.com/docs/api#subscription_items

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • plan (ForeignKey to Plan) – Plan. The plan the customer is subscribed to.
  • quantity (PositiveIntegerField) – Quantity. The quantity of the plan to which the customer should be subscribed.
  • subscription (ForeignKey to Subscription) – Subscription. The subscription this subscription item belongs to.
  • tax_rates (ManyToManyField) – Tax rates. The tax rates which apply to this subscription_item. When set, the default_tax_rates on the subscription do not apply to this subscription_item.
classmethod SubscriptionItem.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
SubscriptionItem.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
SubscriptionItem.get_stripe_dashboard_url()

Get the stripe dashboard url for this object.

classmethod SubscriptionItem.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

TaxRate

class djstripe.models.TaxRate(*args, **kwargs)[source]

Tax rates can be applied to invoices and subscriptions to collect tax.

Stripe documentation: https://stripe.com/docs/api/tax_rates

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • active (BooleanField) – Active. Defaults to true. When set to false, this tax rate cannot be applied to objects in the API, but will still be applied to subscriptions and invoices that already have it set.
  • display_name (CharField) – Display name. The display name of the tax rates as it will appear to your customer on their receipt email, PDF, and the hosted invoice page.
  • inclusive (BooleanField) – Inclusive. This specifies if the tax rate is inclusive or exclusive.
  • jurisdiction (CharField) – Jurisdiction. The jurisdiction for the tax rate.
  • percentage (StripePercentField) – Percentage. This represents the tax rate percent out of 100.
classmethod TaxRate.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
TaxRate.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
TaxRate.get_stripe_dashboard_url()

Get the stripe dashboard url for this object.

classmethod TaxRate.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

UpcomingInvoice

class djstripe.models.UpcomingInvoice(*args, **kwargs)[source]

The preview of an upcoming invoice - does not exist in the Django database.

See BaseInvoice.upcoming()

Logically it should be set abstract, but that doesn’t quite work since we do actually want to instantiate the model and use relations.

Parameters:
  • djstripe_id (BigAutoField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • account_country (CharField) – Account country. The country of the business associated with this invoice, most often the business creating the invoice.
  • account_name (TextField) – Account name. The public name of the business associated with this invoice, most often the business creating the invoice.
  • amount_due (StripeDecimalCurrencyAmountField) – Amount due. Final amount due (as decimal) at this time for this invoice. If the invoice’s total is smaller than the minimum charge amount, for example, or if there is account credit that can be applied to the invoice, the amount_due may be 0. If there is a positive starting_balance for the invoice (the customer owes money), the amount_due will also take that into account. The charge that gets generated for the invoice will be for the amount specified in amount_due.
  • amount_paid (StripeDecimalCurrencyAmountField) – Amount paid. The amount, (as decimal), that was paid.
  • amount_remaining (StripeDecimalCurrencyAmountField) – Amount remaining. The amount remaining, (as decimal), that is due.
  • application_fee_amount (StripeDecimalCurrencyAmountField) – Application fee amount. The fee (as decimal) that will be applied to the invoice and transferred to the application owner’s Stripe account when the invoice is paid.
  • attempt_count (IntegerField) – Attempt count. Number of payment attempts made for this invoice, from the perspective of the payment retry schedule. Any payment attempt counts as the first attempt, and subsequently only automatic retries increment the attempt count. In other words, manual payment attempts after the first attempt do not affect the retry schedule.
  • attempted (BooleanField) – Attempted. Whether or not an attempt has been made to pay the invoice. An invoice is not attempted until 1 hour after the invoice.created webhook, for example, so you might not want to display that invoice as unpaid to your users.
  • auto_advance (NullBooleanField) – Auto advance. Controls whether Stripe will perform automatic collection of the invoice. When false, the invoice’s state will not automatically advance without an explicit action.
  • billing_reason (StripeEnumField) – Billing reason. Indicates the reason why the invoice was created. subscription_cycle indicates an invoice created by a subscription advancing into a new period. subscription_create indicates an invoice created due to creating a subscription. subscription_update indicates an invoice created due to updating a subscription. subscription is set for all old invoices to indicate either a change to a subscription or a period advancement. manual is set for all invoices unrelated to a subscription (for example: created via the invoice editor). The upcoming value is reserved for simulated invoices per the upcoming invoice endpoint. subscription_threshold indicates an invoice created due to a billing threshold being reached.
  • charge (OneToOneField to Charge) – Charge. The latest charge generated for this invoice, if any.
  • closed (NullBooleanField) – Closed. Whether or not the invoice is still trying to collect payment. An invoice is closed if it’s either paid or it has been marked closed. A closed invoice will no longer attempt to collect payment.
  • collection_method (StripeEnumField) – Collection method. When charging automatically, Stripe will attempt to pay this invoice using the default source attached to the customer. When sending an invoice, Stripe will email this invoice to the customer with payment instructions.
  • currency (StripeCurrencyCodeField) – Currency. Three-letter ISO currency code
  • customer (ForeignKey to Customer) – Customer. The customer associated with this invoice.
  • customer_address (JSONField) – Customer address. The customer’s address. Until the invoice is finalized, this field will equal customer.address. Once the invoice is finalized, this field will no longer be updated.
  • customer_email (TextField) – Customer email. The customer’s email. Until the invoice is finalized, this field will equal customer.email. Once the invoice is finalized, this field will no longer be updated.
  • customer_name (TextField) – Customer name. The customer’s name. Until the invoice is finalized, this field will equal customer.name. Once the invoice is finalized, this field will no longer be updated.
  • customer_phone (TextField) – Customer phone. The customer’s phone number. Until the invoice is finalized, this field will equal customer.phone_. Once the invoice is finalized, this field will no longer be updated.
  • customer_shipping (JSONField) – Customer shipping. The customer’s shipping information. Until the invoice is finalized, this field will equal customer.shipping. Once the invoice is finalized, this field will no longer be updated.
  • customer_tax_exempt (StripeEnumField) – Customer tax exempt. The customer’s tax exempt status. Until the invoice is finalized, this field will equal customer.tax_exempt. Once the invoice is finalized, this field will no longer be updated.
  • default_payment_method (ForeignKey to PaymentMethod) – Default payment method. Default payment method for the invoice. It must belong to the customer associated with the invoice. If not set, defaults to the subscription’s default payment method, if any, or to the default payment method in the customer’s invoice settings.
  • due_date (StripeDateTimeField) – Due date. The date on which payment for this invoice is due. This value will be null for invoices where billing=charge_automatically.
  • ending_balance (StripeQuantumCurrencyAmountField) – Ending balance. Ending customer balance (in cents) after attempting to pay invoice. If the invoice has not been attempted yet, this will be null.
  • footer (TextField) – Footer. Footer displayed on the invoice.
  • forgiven (NullBooleanField) – Forgiven. Whether or not the invoice has been forgiven. Forgiving an invoice instructs us to update the subscription status as if the invoice were successfully paid. Once an invoice has been forgiven, it cannot be unforgiven or reopened.
  • hosted_invoice_url (TextField) – Hosted invoice url. The URL for the hosted invoice page, which allows customers to view and pay an invoice. If the invoice has not been frozen yet, this will be null.
  • invoice_pdf (TextField) – Invoice pdf. The link to download the PDF for the invoice. If the invoice has not been frozen yet, this will be null.
  • next_payment_attempt (StripeDateTimeField) – Next payment attempt. The time at which payment will next be attempted.
  • number (CharField) – Number. A unique, identifying string that appears on emails sent to the customer for this invoice. This starts with the customer’s unique invoice_prefix if it is specified.
  • paid (BooleanField) – Paid. The time at which payment will next be attempted.
  • payment_intent (OneToOneField to PaymentIntent) – Payment intent. The PaymentIntent associated with this invoice. The PaymentIntent is generated when the invoice is finalized, and can then be used to pay the invoice.Note that voiding an invoice will cancel the PaymentIntent
  • period_end (StripeDateTimeField) – Period end. End of the usage period during which invoice items were added to this invoice.
  • period_start (StripeDateTimeField) – Period start. Start of the usage period during which invoice items were added to this invoice.
  • post_payment_credit_notes_amount (StripeQuantumCurrencyAmountField) – Post payment credit notes amount. Total amount (in cents) of all post-payment credit notes issued for this invoice.
  • pre_payment_credit_notes_amount (StripeQuantumCurrencyAmountField) – Pre payment credit notes amount. Total amount (in cents) of all pre-payment credit notes issued for this invoice.
  • receipt_number (CharField) – Receipt number. This is the transaction number that appears on email receipts sent for this invoice.
  • starting_balance (StripeQuantumCurrencyAmountField) – Starting balance. Starting customer balance (in cents) before attempting to pay invoice. If the invoice has not been attempted yet, this will be the current customer balance.
  • statement_descriptor (CharField) – Statement descriptor. An arbitrary string to be displayed on your customer’s credit card statement. The statement description may not include <>”’ characters, and will appear on your customer’s statement in capital letters. Non-ASCII characters are automatically stripped. While most banks display this information consistently, some may display it incorrectly or not at all.
  • status_transitions (JSONField) – Status transitions
  • subscription (ForeignKey to Subscription) – Subscription. The subscription that this invoice was prepared for, if any.
  • subscription_proration_date (StripeDateTimeField) – Subscription proration date. Only set for upcoming invoices that preview prorations. The time used to calculate prorations.
  • subtotal (StripeDecimalCurrencyAmountField) – Subtotal. Total (as decimal) of all subscriptions, invoice items, and prorations on the invoice before any discount or tax is applied.
  • tax (StripeDecimalCurrencyAmountField) – Tax. The amount (as decimal) of tax included in the total, calculated from tax_percent and the subtotal. If no tax_percent is defined, this value will be null.
  • tax_percent (StripePercentField) – Tax percent. This percentage of the subtotal has been added to the total amount of the invoice, including invoice line items and discounts. This field is inherited from the subscription’s tax_percent field, but can be changed before the invoice is paid. This field defaults to null.
  • threshold_reason (JSONField) – Threshold reason. If billing_reason is set to subscription_threshold this returns more information on which threshold rules triggered the invoice.
  • total (StripeDecimalCurrencyAmountField) – Total (as decimal) after discount.
  • webhooks_delivered_at (StripeDateTimeField) – Webhooks delivered at. The time at which webhooks for this invoice were successfully delivered (if the invoice had no webhooks to deliver, this will match date). Invoice payment is delayed until webhooks are delivered, or until all webhook delivery attempts have been exhausted.
classmethod UpcomingInvoice.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
UpcomingInvoice.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
UpcomingInvoice.get_stripe_dashboard_url()[source]

Get the stripe dashboard url for this object.

UpcomingInvoice.invoiceitems

Gets the invoice items associated with this upcoming invoice.

This differs from normal (non-upcoming) invoices, in that upcoming invoices are in-memory and do not persist to the database. Therefore, all of the data comes from the Stripe API itself.

Instead of returning a normal queryset for the invoiceitems, this will return a mock of a queryset, but with the data fetched from Stripe - It will act like a normal queryset, but mutation will silently fail.

UpcomingInvoice.str_parts()

Extend this to add information to the string representation of the object

Return type:list of str
classmethod UpcomingInvoice.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

UsageRecord

class djstripe.models.UsageRecord(*args, **kwargs)[source]

Usage records allow you to continually report usage and metrics to Stripe for metered billing of plans.

Stripe documentation: https://stripe.com/docs/api#usage_records

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • quantity (PositiveIntegerField) – Quantity. The quantity of the plan to which the customer should be subscribed.
  • subscription_item (ForeignKey to SubscriptionItem) – Subscription item. The subscription item this usage record contains data for.
classmethod UsageRecord.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
UsageRecord.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
UsageRecord.get_stripe_dashboard_url()

Get the stripe dashboard url for this object.

classmethod UsageRecord.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

Connect

Account

class djstripe.models.Account(*args, **kwargs)[source]

Stripe documentation: https://stripe.com/docs/api#account

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • branding_icon (ForeignKey to FileUpload) – Branding icon. An icon for the account. Must be square and at least 128px x 128px.
  • branding_logo (ForeignKey to FileUpload) – Branding logo. A logo for the account that will be used in Checkout instead of the icon and without the account’s name next to it if provided. Must be at least 128px x 128px.
  • business_profile (JSONField) – Business profile. Optional information related to the business.
  • business_type (StripeEnumField) – Business type. The business type.
  • charges_enabled (BooleanField) – Charges enabled. Whether the account can create live charges
  • country (CharField) – Country. The country of the account
  • company (JSONField) – Company. Information about the company or business. This field is null unless business_type is set to company.
  • default_currency (StripeCurrencyCodeField) – Default currency. The currency this account has chosen to use as the default
  • details_submitted (BooleanField) – Details submitted. Whether account details have been submitted. Standard accounts cannot receive payouts before this is true.
  • email (CharField) – Email. The primary user’s email address.
  • individual (JSONField) – Individual. Information about the person represented by the account. This field is null unless business_type is set to individual.
  • payouts_enabled (BooleanField) – Payouts enabled. Whether Stripe can send payouts to this account
  • product_description (CharField) – Product description. Internal-only description of the product sold or service provided by the business. It’s used by Stripe for risk and underwriting purposes.
  • requirements (JSONField) – Requirements. Information about the requirements for the account, including what information needs to be collected, and by when.
  • settings (JSONField) – Settings. Account options for customizing how the account functions within Stripe.
  • type (StripeEnumField) – Type. The Stripe account type.
  • tos_acceptance (JSONField) – Tos acceptance. Details on the acceptance of the Stripe Services Agreement
classmethod Account.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
Account.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
Account.get_stripe_dashboard_url()

Get the stripe dashboard url for this object.

classmethod Account.get_connected_account_from_token(access_token)[source]
classmethod Account.get_default_account()[source]
Account.str_parts()

Extend this to add information to the string representation of the object

Return type:list of str
classmethod Account.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

Application Fee

class djstripe.models.ApplicationFee(*args, **kwargs)[source]

When you collect a transaction fee on top of a charge made for your user (using Connect), an ApplicationFee is created in your account.

Stripe documentation: https://stripe.com/docs/api#application_fees

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • amount (StripeQuantumCurrencyAmountField) – Amount. Amount earned, in cents.
  • amount_refunded (StripeQuantumCurrencyAmountField) – Amount refunded. Amount in cents refunded (can be less than the amount attribute on the fee if a partial refund was issued)
  • balance_transaction (ForeignKey to BalanceTransaction) – Balance transaction. Balance transaction that describes the impact on your account balance.
  • charge (ForeignKey to Charge) – Charge. The charge that the application fee was taken from.
  • currency (StripeCurrencyCodeField) – Currency. Three-letter ISO currency code
  • refunded (BooleanField) – Refunded. Whether the fee has been fully refunded. If the fee is only partially refunded, this attribute will still be false.
classmethod ApplicationFee.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
ApplicationFee.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
ApplicationFee.get_stripe_dashboard_url()

Get the stripe dashboard url for this object.

classmethod ApplicationFee.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

Country Spec

class djstripe.models.CountrySpec(*args, **kwargs)[source]

Stripe documentation: https://stripe.com/docs/api#country_specs

Parameters:
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • id (CharField) – Id
  • default_currency (StripeCurrencyCodeField) – Default currency. The default currency for this country. This applies to both payment methods and bank accounts.
  • supported_bank_account_currencies (JSONField) – Supported bank account currencies. Currencies that can be accepted in the specific country (for transfers).
  • supported_payment_currencies (JSONField) – Supported payment currencies. Currencies that can be accepted in the specified country (for payments).
  • supported_payment_methods (JSONField) – Supported payment methods. Payment methods available in the specified country.
  • supported_transfer_countries (JSONField) – Supported transfer countries. Countries that can accept transfers from the specified country.
  • verification_fields (JSONField) – Verification fields. Lists the types of verification data needed to keep an account open.
classmethod CountrySpec.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
CountrySpec.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
CountrySpec.get_stripe_dashboard_url()

Get the stripe dashboard url for this object.

classmethod CountrySpec.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

Transfer

class djstripe.models.Transfer(*args, **kwargs)[source]

When Stripe sends you money or you initiate a transfer to a bank account, debit card, or connected Stripe account, a transfer object will be created.

Stripe documentation: https://stripe.com/docs/api/python#transfers

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • amount (StripeDecimalCurrencyAmountField) – Amount. The amount transferred
  • amount_reversed (StripeDecimalCurrencyAmountField) – Amount reversed. The amount (as decimal) reversed (can be less than the amount attribute on the transfer if a partial reversal was issued).
  • balance_transaction (ForeignKey to BalanceTransaction) – Balance transaction. Balance transaction that describes the impact on your account balance.
  • currency (StripeCurrencyCodeField) – Currency. Three-letter ISO currency code
  • destination (StripeIdField) – Destination. ID of the bank account, card, or Stripe account the transfer was sent to.
  • destination_payment (StripeIdField) – Destination payment. If the destination is a Stripe account, this will be the ID of the payment that the destination account received for the transfer.
  • reversed (BooleanField) – Reversed. Whether or not the transfer has been fully reversed. If the transfer is only partially reversed, this attribute will still be false.
  • source_transaction (StripeIdField) – Source transaction. ID of the charge (or other transaction) that was used to fund the transfer. If null, the transfer was funded from the available balance.
  • source_type (StripeEnumField) – Source type. The source balance from which this transfer came.
  • transfer_group (CharField) – Transfer group. A string that identifies this transaction as part of a group.
classmethod Transfer.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
Transfer.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
Transfer.get_stripe_dashboard_url()

Get the stripe dashboard url for this object.

Transfer.str_parts()[source]

Extend this to add information to the string representation of the object

Return type:list of str
classmethod Transfer.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

Transfer Reversal

class djstripe.models.TransferReversal(*args, **kwargs)[source]

Stripe documentation: https://stripe.com/docs/api#transfer_reversals

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • amount (StripeQuantumCurrencyAmountField) – Amount. Amount, in cents.
  • balance_transaction (ForeignKey to BalanceTransaction) – Balance transaction. Balance transaction that describes the impact on your account balance.
  • currency (StripeCurrencyCodeField) – Currency. Three-letter ISO currency code
  • transfer (ForeignKey to Transfer) – Transfer. The transfer that was reversed.
classmethod TransferReversal.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
TransferReversal.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
TransferReversal.get_stripe_dashboard_url()

Get the stripe dashboard url for this object.

classmethod TransferReversal.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

Fraud

TODO

Orders

TODO

Sigma

ScheduledQueryRun

class djstripe.models.ScheduledQueryRun(*args, **kwargs)[source]

Stripe documentation: https://stripe.com/docs/api#scheduled_queries

Parameters:
  • djstripe_id (BigAutoField) – Id
  • id (StripeIdField) – Id
  • livemode (NullBooleanField) – Livemode. Null here indicates that the livemode status is unknown or was previously unrecorded. Otherwise, this field indicates whether this record comes from Stripe test mode or live mode operation.
  • created (StripeDateTimeField) – Created. The datetime this object was created in stripe.
  • metadata (JSONField) – Metadata. A set of key/value pairs that you can attach to an object. It can be useful for storing additional information about an object in a structured format.
  • description (TextField) – Description. A description of this object.
  • djstripe_created (DateTimeField) – Djstripe created
  • djstripe_updated (DateTimeField) – Djstripe updated
  • data_load_time (StripeDateTimeField) – Data load time. When the query was run, Sigma contained a snapshot of your Stripe data at this time.
  • error (JSONField) – Error. If the query run was not succeesful, contains information about the failure.
  • file (ForeignKey to FileUpload) – File. The file object representing the results of the query.
  • result_available_until (StripeDateTimeField) – Result available until. Time at which the result expires and is no longer available for download.
  • sql (TextField) – Sql. SQL for the query.
  • status (StripeEnumField) – Status. The query’s execution status.
  • title (TextField) – Title. Title of the query.
classmethod ScheduledQueryRun.api_list(api_key='', **kwargs)

Call the stripe API’s list operation for this model.

Parameters:api_key (string) – The api key to use for this request. Defaults to djstripe_settings.STRIPE_SECRET_KEY.

See Stripe documentation for accepted kwargs for each object.

Returns:an iterator over all items in the query
ScheduledQueryRun.api_retrieve(api_key=None, stripe_account=None)

Call the stripe API’s retrieve operation for this model.

Parameters:
  • api_key (string) – The api key to use for this request. Defaults to settings.STRIPE_SECRET_KEY.
  • stripe_account (string) – The optional connected account for which this request is being made.
classmethod ScheduledQueryRun.sync_from_stripe_data(data)

Syncs this object from the stripe data provided.

Foreign keys will also be retrieved and synced recursively.

Parameters:data (dict) – stripe object
Return type:cls

Webhooks

WebhookEventTrigger

class djstripe.models.WebhookEventTrigger(*args, **kwargs)[source]

An instance of a request that reached the server endpoint for Stripe webhooks.

Webhook Events are initially UNTRUSTED, as it is possible for any web entity to post any data to our webhook url. Data posted may be valid Stripe information, garbage, or even malicious. The ‘valid’ flag in this model monitors this.

Parameters:
  • id (BigAutoField) – Id
  • remote_ip (GenericIPAddressField) – Remote ip. IP address of the request client.
  • headers (JSONField) – Headers
  • body (TextField) – Body
  • valid (BooleanField) – Valid. Whether or not the webhook event has passed validation
  • processed (BooleanField) – Processed. Whether or not the webhook event has been successfully processed
  • exception (CharField) – Exception
  • traceback (TextField) – Traceback. Traceback if an exception was thrown during processing
  • event (ForeignKey to Event) – Event. Event object contained in the (valid) Webhook
  • djstripe_version (CharField) – Djstripe version. The version of dj-stripe when the webhook was received
  • created (DateTimeField) – Created
  • updated (DateTimeField) – Updated
WebhookEventTrigger.json_body
WebhookEventTrigger.is_test_event
classmethod WebhookEventTrigger.from_request(request)[source]

Create, validate and process a WebhookEventTrigger given a Django request object.

The process is three-fold: 1. Create a WebhookEventTrigger object from a Django request. 2. Validate the WebhookEventTrigger as a Stripe event using the API. 3. If valid, process it into an Event object (and child resource).

Settings

STRIPE_API_VERSION (=‘2019-05-16’)

The API version used to communicate with the Stripe API is configurable, and defaults to the latest version that has been tested as working. Using a value other than the default is allowed, as a string in the format of YYYY-MM-DD.

For example, you can specify ‘2017-01-27’ to use that API version:

STRIPE_API_VERSION = '2017-01-27'

However you do so at your own risk, as using a value other than the default might result in incompatibilities between Stripe and this library, especially if Stripe has labelled the differences between API versions as “Major”. Even small differences such as a new enumeration value might cause issues.

For this reason it is best to assume that only the default version is supported.

For more information on API versioning, see the stripe documentation.

See also A note on Stripe API versions.

DJSTRIPE_IDEMPOTENCY_KEY_CALLBACK (=djstripe.settings._get_idempotency_key)

A function which will return an idempotency key for a particular object_type and action pair. By default, this is set to a function which will create a djstripe.IdempotencyKey object and return its uuid. You may want to customize this if you want to give your idempotency keys a different lifecycle than they normally would get.

The function takes the following signature:

def get_idempotency_key(object_type: str, action: str, livemode: bool):
    return "<idempotency key>"

The function MUST return a string suitably random for the object_type/action pair, and usable in the Stripe Idempotency-Key HTTP header. For more information, see the stripe documentation.

DJSTRIPE_PRORATION_POLICY (=False)

By default, plans are not prorated in dj-stripe. Concretely, this is how this translates:

  1. If a customer cancels their plan during a trial, the cancellation is effective right away.
  2. If a customer cancels their plan outside of a trial, their subscription remains active until the subscription’s period end, and they do not receive a refund.
  3. If a customer switches from one plan to another, the new plan becomes effective right away, and the customer is billed for the new plan’s amount.

Assigning True to DJSTRIPE_PRORATION_POLICY reverses the functioning of item 2 (plan cancellation) by making a cancellation effective right away and refunding the unused balance to the customer, and affects the functioning of item 3 (plan change) by prorating the previous customer’s plan towards their new plan’s amount.

DJSTRIPE_SUBSCRIPTION_REQUIRED_EXCEPTION_URLS (=())

Used by djstripe.middleware.SubscriptionPaymentMiddleware

Rules:

  • “(app_name)” means everything from this app is exempt
  • “[namespace]” means everything with this name is exempt
  • “namespace:name” means this namespaced URL is exempt
  • “name” means this URL is exempt
  • The entire djstripe namespace is exempt
  • If settings.DEBUG is True, then django-debug-toolbar is exempt

Example:

DJSTRIPE_SUBSCRIPTION_REQUIRED_EXCEPTION_URLS = (
    "(allauth)",  # anything in the django-allauth URLConf
    "[blogs]",  # Anything in the blogs namespace
    "products:detail",  # A ProductDetail view you want shown to non-payers
    "home",  # Site homepage
)

Note

Adding app_names to applications.

To make the (allauth) work, you may need to define an app_name in the include() function in the URLConf. For example:

# in urls.py
url(r'^accounts/', include('allauth.urls',  app_name="allauth")),

DJSTRIPE_SUBSCRIBER_CUSTOMER_KEY (=”djstripe_subscriber”)

Every Customer object created in Stripe is tagged with metadata This setting controls what the name of the key in Stripe should be. The key name must be a string no more than 40 characters long.

You may set this to None or "" to disable that behaviour altogether. This is probably not something you want to do, though.

DJSTRIPE_SUBSCRIBER_MODEL (=settings.AUTH_USER_MODEL)

If the AUTH_USER_MODEL doesn’t represent the object your application’s subscription holder, you may define a subscriber model to use here. It should be a string in the form of ‘app.model’.

Rules:

  • DJSTRIPE_SUBSCRIBER_MODEL must have an email field. If your existing model has no email field, add an email property that defines an email address to use.
  • You must also implement DJSTRIPE_SUBSCRIBER_MODEL_REQUEST_CALLBACK.

Example Model:

class Organization(models.Model):
    name = CharField(max_length=200, unique=True)
    subdomain = CharField(max_length=63, unique=True, verbose_name="Organization Subdomain")
    owner = ForeignKey(settings.AUTH_USER_MODEL, related_name="organization_owner", verbose_name="Organization Owner")

    @property
    def email(self):
        return self.owner.email

DJSTRIPE_SUBSCRIBER_MODEL_MIGRATION_DEPENDENCY (=”__first__”)

If the model referenced in DJSTRIPE_SUBSCRIBER_MODEL is not created in the __first__ migration of an app you can specify the migration name to depend on here. For example: “0003_here_the_subscriber_model_was_added”

DJSTRIPE_SUBSCRIBER_MODEL_REQUEST_CALLBACK (=None)

If you choose to use a custom subscriber model, you’ll need a way to pull it from request. That’s where this callback comes in. It must be a callable or importable string to a callable that takes a request object and returns an instance of DJSTRIPE_SUBSCRIBER_MODEL

Examples:

middleware.py

class DynamicOrganizationIDMiddleware(object):
    """ Adds the current organization's ID based on the subdomain."""

    def process_request(self, request):
        subdomain = parse_subdomain(request.get_host())

        try:
            organization = Organization.objects.get(subdomain=subdomain)
        except Organization.DoesNotExist:
            return TemplateResponse(request=request, template='404.html', status=404)
        else:
            organization_id = organization.id

        request.organization_id = organization_id

settings.py

def organization_request_callback(request):
    """ Gets an organization instance from the id passed through ``request``"""

    from <models_path> import Organization  # Import models here to avoid an ``AppRegistryNotReady`` exception
    return Organization.objects.get(id=request.organization_id)

Note

This callback only becomes active when DJSTRIPE_SUBSCRIBER_MODEL is set.

DJSTRIPE_USE_NATIVE_JSONFIELD (=False)

Setting this to True will make the various dj-stripe JSON fields use django.contrib.postgres.fields.JSONField instead of the jsonfield library (which internally uses text fields).

The native Django JSONField uses the postgres jsonb column type, which efficiently stores JSON and can be queried far more conveniently. Django also supports querying JSONField with the ORM.

Note

This is only supported on Postgres databases.

Note

Migrating between native and non-native must be done manually.

DJSTRIPE_WEBHOOK_URL (=r”^webhook/$”)

This is where you can set Stripe.com to send webhook response. You can set this to what you want to prevent unnecessary hijinks from unfriendly people.

As this is embedded in the URLConf, this must be a resolvable regular expression.

DJSTRIPE_WEBHOOK_SECRET (=”“)

If this is set to a non-empty value, webhook signatures will be verified.

Learn more about webhook signature verification.

DJSTRIPE_WEBHOOK_VALIDATION= (=”verify_signature”)

This setting controls which type of validation is done on webhooks. Value can be "verify_signature" for signature verification (recommended default), "retrieve_event" for event retrieval (makes an extra HTTP request), or None for no validation at all.

DJSTRIPE_WEBHOOK_TOLERANCE (=300)

Controls the milliseconds tolerance which wards against replay attacks. Leave this to its default value unless you know what you’re doing.

DJSTRIPE_WEBHOOK_EVENT_CALLBACK (=None)

Webhook event callbacks allow an application to take control of what happens when an event from Stripe is received. It must be a callable or importable string to a callable that takes an event object.

One suggestion is to put the event onto a task queue (such as celery) for asynchronous processing.

Examples:

callbacks.py

def webhook_event_callback(event):
    """ Dispatches the event to celery for processing. """
    from . import tasks
    # Ansychronous hand-off to celery so that we can continue immediately
    tasks.process_webhook_event.s(event).apply_async()

tasks.py

from stripe.error import StripeError

@shared_task(bind=True)
def process_webhook_event(self, event):
    """ Processes events from Stripe asynchronously. """
    logger.info("Processing Stripe event: %s", str(event))
    try:
        event.process(raise_exception=True)
    except StripeError as exc:
        logger.error("Failed to process Stripe event: %s", str(event))
        raise self.retry(exc=exc, countdown=60)  # retry after 60 seconds

settings.py

DJSTRIPE_WEBHOOK_EVENT_CALLBACK = 'callbacks.webhook_event_callback'

STRIPE_API_HOST (= unset)

If set, this sets the base API host for Stripe. You may want to set this to, for example, "http://localhost:12111" if you are running stripe-mock.

If this is set in production (DEBUG=False), a warning will be raised on manage.py check.

Utilities

Last Updated 2018-05-24

Subscriber Has Active Subscription Check

utils.subscriber_has_active_subscription(plan=None)

Helper function to check if a subscriber has an active subscription.

Throws improperlyConfigured if the subscriber is an instance of AUTH_USER_MODEL and get_user_model().is_anonymous == True.

Activate subscription rules (or):
  • customer has active subscription
If the subscriber is an instance of AUTH_USER_MODEL, active subscription rules (or):
  • customer has active subscription
  • user.is_superuser
  • user.is_staff
Parameters:
  • subscriber (dj-stripe subscriber) – The subscriber for which to check for an active subscription.
  • plan (Plan or string (plan ID)) – The plan for which to check for an active subscription. If plan is None and there exists only one subscription, this method will check if that subscription is active. Calling this method with no plan and multiple subscriptions will throw an exception.

Supported Currency Choice Generator

utils.get_supported_currency_choices()

Pull a stripe account’s supported currencies and returns a choices tuple of those supported currencies.

Parameters:api_key (str) – The api key associated with the account from which to pull data.

Clear Expired Idempotency Keys

utils.clear_expired_idempotency_keys()

Convert Stripe Timestamp to Datetime

utils.convert_tstamp()

Convert a Stripe API timestamp response (unix epoch) to a native datetime.

Return type:datetime

Friendly Currency Amount String

utils.get_friendly_currency_amount(currency)

Contributing

Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given.

You can contribute in many ways:

Types of Contributions

Report Bugs

Report bugs at https://github.com/dj-stripe/dj-stripe/issues.

If you are reporting a bug, please include:

  • The version of python and Django you’re running
  • Detailed steps to reproduce the bug.

Fix Bugs

Look through the GitHub issues for bugs. Anything tagged with “bug” is open to whoever wants to implement it.

Implement Features

Look through the GitHub issues for features. Anything tagged with “feature” is open to whoever wants to implement it.

Write Documentation

dj-stripe could always use more documentation, whether as part of the official dj-stripe docs, in docstrings, or even on the web in blog posts, articles, and such.

If you are adding to dj-stripe’s documentation, you can see your changes by running tox -e docs. The documentation will be generated in the docs/ directory, and you can open docs/_build/html/index.html in a web browser.

Submit Feedback

The best way to send feedback is to file an issue at https://github.com/dj-stripe/dj-stripe/issues.

If you are proposing a feature:

  • Explain in detail how it would work.
  • Keep the scope as narrow as possible, to make it easier to implement.
  • Remember that this is a volunteer-driven project, and that contributions are welcome :)

Contributor Discussion

For questions regarding contributions to dj-stripe, another avenue is our Discord channel at https://discord.gg/UJY8fcc.

Get Started!

Ready to contribute? Here’s how to set up dj-stripe for local development.

  1. Fork the dj-stripe repo on GitHub.

  2. Clone your fork locally:

    $ git clone git@github.com:your_name_here/dj-stripe.git
    
  3. Set up your test database. If you’re running tests using PostgreSQL:

    $ createdb djstripe
    

    or if you want to test vs sqlite (for convenience) or MySQL, they can be selected by setting this environment variable:

    $ export DJSTRIPE_TEST_DB_VENDOR=sqlite
    

    or

    $ export DJSTRIPE_TEST_DB_VENDOR=mysql
    

    For postgres and mysql, the database host,port,username and password can be set with environment variables, see tests/settings.py

  4. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:

    $ mkvirtualenv dj-stripe
    $ cd dj-stripe/
    $ python setup.py develop
    
  5. Create a branch for local development:

    $ git checkout -b name-of-your-bugfix-or-feature
    

    Now you can make your changes locally.

  6. When you’re done making changes, check that your changes pass the tests. A quick test run can be done as follows:

    $ DJSTRIPE_TEST_DB_VENDOR=sqlite pytest --reuse-db
    

    You should also check that the tests pass with other python and Django versions with tox. pytest will output both command line and html coverage statistics and will warn you if your changes caused code coverage to drop.:

    $ pip install tox
    $ tox
    
  7. If your changes altered the models you may need to generate Django migrations:

    $ DJSTRIPE_TEST_DB_VENDOR=sqlite ./manage.py makemigrations
    
  8. Commit your changes and push your branch to GitHub:

    $ git add .
    $ git commit -m "Your detailed description of your changes."
    $ git push origin name-of-your-bugfix-or-feature
    
  9. Submit a pull request through the GitHub website.

  10. Congratulations, you’re now a dj-stripe contributor! Have some <3 from us.

Preferred Django Model Field Types

When mapping from Stripe API field types to Django model fields, we try to follow Django best practises where practical.

The following types should be preferred for fields that map to the Stripe API (which is almost all fields in our models).

Strings

Therefore the default type for string fields that don’t have a maxLength specified in the Stripe OpenAPI schema should usually be:

str_field = TextField(max_length=5000, default=", blank=True, help_text="...")

Enumerations

Fields that have a defined set of values can be implemented using StripeEnumField.

Hash (dictionaries)

Use the JSONField in djstripe.fields, see also the DJSTRIPE_USE_NATIVE_JSONFIELD setting.

Currency amounts

Stripe handles all currency amounts as integer cents, we currently have a mixture of fields as integer cents and decimal (eg dollar, euro etc) values, but we are aiming to standardise on cents (see https://github.com/dj-stripe/dj-stripe/issues/955).

All new currency amount fields should use StripeQuantumCurrencyAmountField.

Dates and Datetimes

The Stripe API uses an integer timestamp (seconds since the Unix epoch) for dates and datetimes. We store this as a datetime field, using StripeDateTimeField.

Django Migration Policy

Migrations are considered a breaking change, so it’s not usually not acceptable to add a migration to a stable branch, it will be a new MAJOR.MINOR.0 release.

A workaround to this in the case that the Stripe API data isn’t compatible with out model (eg Stripe is sending null to a non-null field) is to implement the _manipulate_stripe_object_hook classmethod on the model.

Avoid new migrations with non-schema changes

If a code change produces a migration that doesn’t alter the database schema (eg changing help_text) then instead of adding a new migration you can edit the most recent migration that affects the field in question.

e.g.: https://github.com/dj-stripe/dj-stripe/commit/e2762c38918a90f00c42ecf21187a920bd3a2087

Squash of unreleased migrations on master

We aim to keep the number of migration files per release to a minimum per MINOR release.

In the case where there are several unreleased migrations on master between releases, we squash migrations immediately before release.

So if you’re using the master branch with unreleased migrations, ensure you migrate with the squashed migration before upgrading to the next major release.

For more details see the Squash migrations section of the Release process.

Pull Request Guidelines

Before you submit a pull request, check that it meets these guidelines:

  1. The pull request should include tests.
  2. The pull request must not drop code coverage below the current level.
  3. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring.
  4. If the pull request makes changes to a model, include Django migrations.
  5. The pull request should work for Python 3.6+. Check https://travis-ci.org/dj-stripe/dj-stripe/pull_requests and make sure that the tests pass for all supported Python versions.
  6. Code formatting: Make sure to install black and isort with pip install black isort and run black .; isort -y at the dj-stripe root to keep a consistent style.

Test Fixtures

dj-stripe’s unit tests rely on fixtures to represent Stripe API and webhook data.

Rationale

These fixtures are partly hand-coded and partly generated by creating objects in Stripe and then retrieved via the API.

Each approach has pros and cons:

Hand-coding the fixtures allows them to be crafted specifically for a test case. They can also be terse, and nested objects can be done by reference to avoid duplication. But maintaining or upgrading them is a painstaking manual process.

Generating the fixtures via Stripe gives the big advantage that Stripe schema changes are automatically represented in the fixtures, which should allow us to upgrade dj-stripe’s schema to match Stripe much more easily. This would be done by updating dj-stripe’s targeted API version (DEFAULT_STRIPE_API_VERSION), regenerating the fixtures, and updating the model to match the fixture changes. The down side is it’s tricky to regenerate fixture files without introducing big changes (eg to object ids) - the script does this by mapping a dummy id to various objects.

Regenerating the test fixtures

To regenerate the test fixtures (e.g. to populate the fixtures with new API fields from Stripe), do the following:

  1. (one time only) Create a new Stripe account called “dj-stripe scratch”, with country set to United States. (we use US so the currency matches the existing fixtures matches, in the future it would be good to test for other countries).

  2. If you already had this account ready and want to start again from scratch, you can delete all of the test data via the button in Settings > Data https://dashboard.stripe.com/account/data

  3. Activate a virtualenv with the dj-stripe project (see Getting Started)

  4. Set the dj-stripe secret key environment variable to the secret key for this account (export STRIPE_SECRET_KEY=sk_test_...)

  5. Run the manage command to create the test objects in your stripe account if they don’t already exist, and regenerate the local fixture files from them:

    $ ./manage.py regenerate_test_fixtures
    

The command tries to avoid inconsequential changes to the fixtures (e.g the created timestamp) by restoring a whitelist of values from the existing fixtures.

This functionality can be disabled by passing the parameter –update-sideeffect-fields.

Credits

Development Lead

  • Alexander Kavanaugh (@kavdev)
  • Daniel Greenfeld <pydanny@gmail.com>
  • Jerome Leclanche (@jleclanche)
  • Lee Skillen (@lskillen)
  • John Carter (@therefromhere)

Contributors

  • Audrey Roy Greenfeld (@audreyr)
  • Buddy Lindsley (@buddylindsey)
  • Yasmine Charif (@dollydagr)
  • Mahdi Yusuf (@myusuf3)
  • Luis Montiel <luismmontielg@gmail.com>
  • Kulbir Singh (@kulbir)
  • Dustin Farris (@dustinfarris)
  • Liwen S (@sunliwen)
  • centrove
  • Chris Halpert (@cphalpert)
  • Thomas Parslow (@almost)
  • Leonid Shvechikov (@shvechikov)
  • sromero84
  • Peter Baumgartner (@ipmb)
  • Vikas (@vikasgulati)
  • Colton Allen (@cmanallen)
  • Filip Wasilewski (@nigma)
  • Martin Hill (@martinhill)
  • Michael Thornhill <michael.thornhill@gmail.com>
  • Tobias Lorenz (@Tyrdall)
  • Ben Whalley
  • nanvel
  • jRobb (@jamesbrobb)
  • Areski Belaid (@areski)
  • José Padilla (@jpadilla)
  • Ben Murden (@benmurden)
  • Philippe Luickx (@philippeluickx)
  • Chriss Mejía (@chrissmejia)
  • Bill Huneke (@wahuneke)
  • Matt Shaw (@unformatt)
  • Chris Trengove (@ctrengove)
  • Caleb Hattingh (@cjrh)
  • Nicolas Delaby (@ticosax)
  • Michaël Krens (@michi88)
  • Yuri Prezument (@yprez)
  • Raphael Deem (@r0fls)
  • Irfan Ahmad (@erfaan)
  • Slava Kyrachevsky (@scream4ik)
  • Alec Brunelle (@aleccool213)
  • James Hiew (@jameshiew)
  • Dan Koch (@dmkoch)
  • Denis Orehovsky (@apirobot)

History

2.2.3 (2020-02-25)

Warning about safe uninstall of jsonfield2 on upgrade

Warning

Both jsonfield and jsonfield2 use the same import path, so if upgrading from dj-stripe~=2.2.0 in an existing virtualenv, be sure to uninstall jsonfield2 first. eg:

# ensure jsonfield is uninstalled before we install jsonfield2
pip uninstall jsonfield2 -y && pip install "dj-stripe>=2.3.0dev"

Otherwise, pip uninstall jsonfield2 will remove jsonfield’s jsonfield module from site-packages, which would cause errors like ImportError: cannot import name 'JSONField' from 'jsonfield' (unknown location)

If you have hit this ImportError already after upgrading, running this should resolve it:

# remove both jsonfield packages before reinstall to fix ImportError:
pip uninstall jsonfield jsonfield2 -y && pip install "dj-stripe>=2.3.0dev"

Note that this is only necessary if upgrading from dj-stripe 2.2.x, which temporarily depended on jsonfield2. This process is not necessary if upgrading from an earlier version of dj-stripe.

2.2.2 (2020-01-20)

This is a bugfix-only version:

  • Fixed handling of TaxRate events (#1094).

2.2.1 (2020-01-14)

This is a bugfix-only version:

  • Fixed bad package build.

2.2.0 (2020-01-13)

  • Changed JSONField dependency package from jsonfield to jsonfield2, for Django 3 compatibility (see Warning about safe uninstall of jsonfield on upgrade). Note that Django 2.1 requires jsonfield<3.1.
  • Added support for Django 3.0 (requires jsonfield2>=3.0.3).
  • Added support for python 3.8.
  • Refactored UpcomingInvoice, so it’s no longer a subclass of Invoice (to allow Invoice to use ManyToManyFields).
  • Dropped previously-deprecated Account fields (see https://stripe.com/docs/upgrades#2019-02-19 ):
    • .business_name
    • .business_primary_color
    • .business_url (changed to a property)
    • .debit_negative_balances
    • .decline_charge_on
    • .display_name
    • .legal_entity
    • .payout_schedule
    • .payout_statement_descriptor
    • .statement_descriptor
    • .support_email
    • .support_phone
    • .support_url
    • .timezone
    • .verification
  • Dropped previously-deprecated Account.business_logo property (renamed to .branding_icon)
  • Dropped previously-deprecated Customer.account_balance property (renamed to .balance)
  • Dropped previously-deprecated properties Invoice.application_fee, Invoice.date
  • Dropped previously-deprecated enum PaymentMethodType (use DjstripePaymentMethodType instead)
  • Renamed Invoice.billing to .collection_method (added deprecated property for the old name).
  • Updated Invoice model to add missing fields.
  • Added TaxRate model, and Invoice.default_tax_rates, InvoiceItem.tax_rates, Invoice.total_tax_amounts, Subscription.default_tax_rates, SubscriptionItem.tax_rates (#1027).
  • Change urls.py to use the new style urls.
  • Update forward relation fields in the admin to be raw id fields.
  • Updated StripeQuantumCurrencyAmountField and StripeDecimalCurrencyAmountField to support Stripe Large Charges (#1045).
  • Update event handling so customer.subscription.deleted updates subscriptions to status="canceled" instead of deleting it from our database, to match Stripe’s behaviour (#599).
  • Added missing Refund.reason value, increases field width (#1075).
  • Fixed Refund.status definition, reduces field width (#1076).
  • Deprecated non-standard Invoice.status (renamed to Invoice.legacy_status) to make way for the Stripe field (preparation for #1020).

Warning about safe uninstall of jsonfield on upgrade

Warning

Both jsonfield and jsonfield2 use the same import path, so if upgrading to dj-stripe>=2.2 in an existing virtualenv, be sure to uninstall jsonfield first. eg:

# ensure jsonfield is uninstalled before we install jsonfield2
pip uninstall jsonfield -y && pip install "dj-stripe>=2.2.0dev"

Otherwise, pip uninstall jsonfield will remove jsonfield2’s jsonfield module from site-packages, which would cause errors like ImportError: cannot import name 'JSONField' from 'jsonfield' (unknown location)

If you have hit this ImportError already after upgrading, running this should resolve it:

# remove both jsonfield packages before reinstall to fix ImportError:
pip uninstall jsonfield jsonfield2 -y && pip install "dj-stripe>=2.2.0dev"

Note on usage of Stripe Elements JS

See https://dj-stripe.readthedocs.io/en/latest/stripe_elements_js.html for notes about usage of the Stripe Elements frontend JS library.

TLDR: if you haven’t yet migrated to PaymentIntents, prefer stripe.createSource() to stripe.createToken().

2.1.1 (2019-10-01)

This is a bugfix-only version:

  • Updated webhook signals list (#1000).
  • Fixed issue syncing PaymentIntent with destination charge (#960).
  • Fixed Customer.subscription & .valid_subscriptions() to ignore status=incomplete_expired (#1006).
  • Fixed error on paymentmethod.detached event with card_xxx payment methods (#967).
  • Added PaymentMethod.detach() (#943).
  • Updated help_text on all currency fields to make it clear if they’re holding integer cents (StripeQuantumCurrencyAmountField) or decimal dollar (or euro, pound etc) (StripeDecimalCurrencyAmountField) (#999)
  • Documented our preferred Django model field types (#986)

Upcoming migration of currency fields (storage as cents instead of dollars)

Please be aware that we’re looking at standardising our currency storage fields as integer quanta (cents) instead of Decimal (dollar) values, to match stripe.

This is intended to be part of the 3.0 release, since it will involve some breaking changes. See #955 for details and discussion.

2.1.0 (2019-09-12)

  • Dropped Django 2.0 support
  • The Python stripe library minimum version is now 2.32.0, also 2.36.0 is excluded due to a regression (#991).
  • Dropped previously-deprecated Charge.fee_details property.
  • Dropped previously-deprecated Transfer.fee_details property.
  • Dropped previously-deprecated field_name parameter to sync_from_stripe_data
  • Dropped previously-deprecated alias StripeObject of StripeModel
  • Dropped previously-deprecated alias PaymentMethod of DjstripePaymentMethod
  • Dropped previously-deprecated properties Charge.source_type and Charge.source_stripe_id
  • enums.PaymentMethodType has been deprecated, use enums.DjstripePaymentMethodType
  • Made SubscriptionItem.quantity nullable as per Plans with usage_type="metered" (follow-up to #865)
  • Added manage commands djstripe_sync_models and djstripe_process_events (#727, #89)
  • Fixed issue with re-creating a customer after Customer.purge() (#916)
  • Fixed sync of Customer Bank Accounts (#829)
  • Fixed Subscription.is_status_temporarily_current() (#852)
  • New models
    • Payment Intent
    • Setup Intent
    • Payment Method
    • Session
  • Added fields to Customer model: address, invoice_prefix, invoice_settings, phone, preferred_locales, tax_exempt

Changes from API 2018-11-08:

Changes from API 2019-02-19:

  • Major changes to Account fields, see https://stripe.com/docs/upgrades#2019-02-19 , updated Account fields to match API 2019-02-19:

  • Added Account.business_profile, .business_type, .company, .individual, .requirements, .settings

  • Deprecated the existing fields, to be removed in 2.2

  • Special handling of the icon and logo fields:

    • Renamed Account.business_logo to Account.branding_icon (note that in Stripe’s API Account.business_logo was renamed to Account.settings.branding_icon, and Account.business_logo_large (which we didn’t have a field for) was renamed to Account.settings.branding_logo)
    • Added deprecated property for Account.business_logo
    • Added Account.branding_logo as a ForeignKey
    • Populate Account.branding_icon and .branding_logo from the new Account.settings.branding.icon and .logo

Changes from API 2019-03-14:

  • Renamed Invoice.application_fee to Invoice.application_fee_amount (added deprecated property for the old name)
  • Removed Invoice.date, in place of Invoice.created (added deprecated property for the old name)
  • Added Invoice.status_transitions
  • Renamed Customer.account_balance to Customer.balance (added deprecated property for the old name)
  • Renamed Customer.payment_methods to Customer.customer_payment_methods
  • Added new SubscriptionStatus.incomplete and SubscriptionStatus.incomplete_expired statuses (#974)
  • Added new BalanceTransactionType values (#983)

Squashed dev migrations

As per our migration policy unreleased migrations on the master branch (migration numbers >=0004) have been squashed.

If you have been using the 2.1.0dev branch from master, you’ll need to run the squashed migrations migrations before upgrading to >=2.1.0.

The simplest way to do this is to pip install dj-stripe==2.1.0rc0 and migrate, alternatively check out the 2.1.0rc0 git tag.

2.0.5 (2019-09-12)

This is a bugfix-only version:

  • Avoid stripe==2.36.0 due to regression (#991)

2.0.4 (2019-09-09)

This is a bugfix-only version:

  • Fixed irreversible migration (#909)

2.0.3 (2019-06-11)

This is a bugfix-only version:

  • In _get_or_create_from_stripe_object, wrap create _create_from_stripe_object in transaction, fixes TransactionManagementError on race condition in webhook processing (#877/#903).

2.0.2 (2019-06-09)

This is a bugfix-only version:

  • Don’t save event objects if the webhook processing fails (#832).
  • Fixed IntegrityError when REMOTE_ADDR is an empty string.
  • Deprecated field_name parameter to sync_from_stripe_data

2.0.1 (2019-04-29)

This is a bugfix-only version:

  • Fixed an error on invoiceitem.updated (#848).
  • Handle test webhook properly in recent versions of Stripe API (#779). At some point 2018 Stripe silently changed the ID used for test events and evt_00000000000000 is not used anymore.
  • Fixed OperationalError seen in migration 0003 on postgres (#850).
  • Fixed issue with migration 0003 not being unapplied correctly (#882).
  • Fixup missing SubscriptionItem.quantity on Plans with usage_type="metered" (#865).
  • Fixed Plan.create() (#870).

2.0.0 (2019-03-01)

  • The Python stripe library minimum version is now 2.3.0.
  • PaymentMethod has been renamed to DjstripePaymentMethod (#841). An alias remains but will be removed in the next version.
  • Dropped support for Django < 2.0, Python < 3.4.
  • Dropped previously-deprecated stripe_objects module.
  • Dropped previously-deprecated stripe_timestamp field.
  • Dropped previously-deprecated Charge.receipt_number field.
  • Dropped previously-deprecated StripeSource alias for Card
  • Dropped previously-deprecated SubscriptionView, CancelSubscriptionView and CancelSubscriptionForm.
  • Removed the default value from DJSTRIPE_SUBSCRIPTION_REDIRECT.
  • All stripe_id fields have been renamed id.
  • Charge.source_type has been deprecated. Use Charge.source.type.
  • Charge.source_stripe_id has been deprecated. Use Charge.source.id.
  • All deprecated Transfer fields (Stripe API < 2017-04-06), have been dropped. This includes date, destination_type (type), failure_code, failure_message, statement_descriptor and status.
  • Fixed IntegrityError when REMOTE_ADDR is missing (#640).
  • New models: - ApplicationFee - ApplicationFeeRefund - BalanceTransaction - CountrySpec - ScheduledQuery - SubscriptionItem - TransferReversal - UsageRecord
  • The fee and fee_details attributes of both the Charge and Transfer objects are no longer stored in the database. Instead, they access their respective new balance_transaction foreign key. Note that fee_details has been deprecated on both models.
  • The fraudulent attribute on Charge is now a property that checks the fraud_details field.
  • Object key validity is now always enforced (#503).
  • Customer.sources no longer refers to a Card queryset, but to a Source queryset. In order to correctly transition, you should change all your references to customer.sources to customer.legacy_cards instead. The legacy_cards attribute already exists in 1.2.0.
  • Customer.sources_v3 is now named Customer.sources.
  • A new property Customer.payment_methods is now available, which allows you to iterate over all of a customer’s payment methods (sources then cards).
  • Card.customer is now nullable and cards are no longer deleted when their corresponding customer is deleted (#654).
  • Webhook signature verification is now available and is preferred. Set the DJSTRIPE_WEBHOOK_SECRET setting to your secret to start using it.
  • StripeObject has been renamed StripeModel. An alias remains but will be removed in the next version.
  • The metadata key used in the Customer object can now be configured by changing the DJSTRIPE_SUBSCRIBER_CUSTOMER_KEY setting. Setting this to None or an empty string now also disables the behaviour altogether.
  • Text-type fields in dj-stripe will no longer ever be None. Instead, any falsy text field will return an empty string.
  • Switched test runner to pytest-django
  • StripeModel.sync_from_stripe_data() will now automatically retrieve related objects and populate foreign keys (#681)
  • Added Coupon.name
  • Added Transfer.balance_transaction
  • Exceptions in webhooks are now re-raised as well as saved in the database (#833)

1.2.4 (2019-02-27)

This is a bugfix-only version:

  • Allow billing_cycle_anchor argument when creating a subscription (#814)
  • Fixup plan amount null with tier plans (#781)
  • Update Cancel subscription view tests to match backport in f64af57
  • Implement Invoice._manipulate_stripe_object_hook for compatability with API 2018-11-08 (#771)
  • Fix product webhook for type=”good” (#724)
  • Add trial_from_plan, trial_period_days args to Customer.subscribe() (#709)

1.2.3 (2018-10-13)

This is a bugfix-only version:

  • Updated Subscription.cancel() for compatibility with Stripe 2018-08-23 (#723)

1.2.2 (2018-08-11)

This is a bugfix-only version:

  • Fixed an error with request.urlconf in some setups (#562)
  • Always save text-type fields as empty strings in db instead of null (#713)
  • Fix support for DJSTRIPE_SUBSCRIBER_MODEL_MIGRATION_DEPENDENCY (#707)
  • Fix reactivate() with Stripe API 2018-02-28 and above

1.2.1 (2018-07-18)

This is a bugfix-only version:

  • Fixed various Python 2.7 compatibility issues
  • Fixed issues with max_length of receipt_number
  • Fixed various fields incorrectly marked as required
  • Handle product webhook calls
  • Fix compatibility with stripe-python 2.0.0

1.2.0 (2018-06-11)

The dj-stripe 1.2.0 release resets all migrations.

Do not upgrade to 1.2.0 directly from 1.0.1 or below. You must upgrade to 1.1.0 first.

Please read the 1.1.0 release notes below for more information.

1.1.0 (2018-06-11)

In dj-stripe 1.1.0, we made a lot of changes to models in order to bring the dj-stripe model state much closer to the upstream API objects. If you are a current user of dj-stripe, you will most likely have to make changes in order to upgrade. Please read the full changelog below. If you are having trouble upgrading, you may ask for help by filing an issue on GitHub.

Migration reset

The next version of dj-stripe, 1.2.0, will reset all the migrations to 0001_initial. Migrations are currently in an unmaintainable state.

What this means is you will not be able to upgrade directly to dj-stripe 1.2.0. You must go through 1.1.0 first, run ``manage.py migrate djstripe``, then upgrade to 1.2.0.

Python 2.7 end-of-life

dj-stripe 1.1.0 drops support for Django 1.10 and adds support for Django 2.0. Django 1.11+ and Python 2.7+ or 3.4+ are required.

Support for Python versions older than 3.5, and Django versions older than 2.0, will be dropped in dj-stripe 2.0.0.

Backwards-incompatible changes and deprecations

Removal of polymorphic models

The model architecture of dj-stripe has been simplified. Polymorphic models have been dropped and the old base StripeCustomer, StripeCharge, StripeInvoice, etc models have all been merged into the top-level Customer, Charge, Invoice, etc models.

Importing those legacy models from djstripe.stripe_objects will yield the new ones. This is deprecated and support for this will be dropped in dj-stripe 2.0.0.

Full support for Stripe Sources (Support for v3 stripe.js)

Stripe sources (src_XXXX) are objects that can arbitrarily reference any of the payment method types that Stripe supports. However, the legacy Card object (with object IDs like card_XXXX or cc_XXXX) is not a Source object, and cannot be turned into a Source object at this time.

In order to support both Card and Source objects in ForeignKeys, a new model PaymentMethod has been devised (renamed to DjstripePaymentMethod in 2.0). That model can resolve into a Card, a Source, or a BankAccount object.

  • The ``default_source`` attribute on ``Customer`` now refers to a ``PaymentMethod`` object. You will need to call .resolve() on it to get the Card or Source in question.
  • References to Customer.sources expecting a queryset of Card objects should be updated to Customer.legacy_cards.
  • The legacy StripeSource name refers to the Card model. This will be removed in dj-stripe 2.0.0. Update your references to either Card or Source.
  • enums.SourceType has been renamed to enums.LegacySourceType. enums.SourceType now refers to the actual Stripe Source types enum.
Core fields renamed
  • The numeric id field has been renamed to djstripe_id. This avoids a clash with the upstream stripe id. Accessing .id is deprecated and **will reference the upstream stripe_id in dj-stripe 2.0.0

1.0.0 (2017-08-12)

It’s finally here! We’ve made significant changes to the codebase and are now compliant with stripe API version 2017-06-05.

I want to give a huge thanks to all of our contributors for their help in making this happen, especially Bill Huneke (@wahuneke) for his impressive design work and @jleclanche for really pushing this release along.

I also want to welcome onboard two more maintainers, @jleclanche and @lskillen. They’ve stepped up and have graciously dedicated their resources to making dj-stripe such an amazing package.

Almost all methods now mimic the parameters of those same methods in the stripe API. Note that some methods do not have some parameters implemented. This is intentional. That being said, expect all method signatures to be different than those in previous versions of dj-stripe.

Finally, please note that there is still a bit of work ahead of us. Not everything in the Stripe API is currently supported by dj-stripe – we’re working on it. That said, v1.0.0 has been thoroughly tested and is verified stable in production applications.

A few things to get excited for

  • Multiple subscription support (finally)
  • Multiple sources support (currently limited to Cards)
  • Idempotency support (See #455, #460 for discussion – big thanks to @jleclanche)
  • Full model documentation
  • Objects that come through webhooks are now tied to the API version set in dj-stripe. No more errors if dj-stripe falls behind the newest stripe API version.
  • Any create/update action on an object automatically syncs the object.
  • Concurrent LIVE and TEST mode support (Thanks to @jleclanche). Note that you’ll run into issues if livemode isn’t set on your existing customer objects.
  • All choices are now enum-based (Thanks @jleclanche, See #520). Access them from the new djstripe.enums module. The ability to check against model property based choices will be deprecated in 1.1
  • Support for the Coupon model, and coupons on Customer objects.
  • Support for the Payout/Transfer split from api version 2017-04-06.

What still needs to be done (in v1.1.0)

  • Documentation. Our original documentation was not very helpful, but it covered the important bits. It will be very out of date after this update and will need to be rewritten. If you feel like helping, we could use all the help we can get to get this pushed out asap.

  • Master sync re-write. This sounds scary, but really isn’t. The current management methods run sync methods on Customer that aren’t very helpful and are due for removal. My plan is to write something that first updates local data (via api_retrieve and sync_from_stripe_data) and then pulls all objects from Stripe and populates the local database with any records that don’t already exist there.

    You might be wondering, “Why are they releasing this if there are only a few things left?” Well, that thinking turned this into a two year release… Trust me, this is a good thing.

Significant changes (mostly backwards-incompatible)

  • Idempotency. #460 introduces idempotency keys and implements idempotency for Customer.get_or_create(). Idempotency will be enabled for all calls that need it.
  • Improved Admin Interface. This is almost complete. See #451 and #452.
  • Drop non-trivial endpoint views. We’re dropping everything except the webhook endpoint and the subscription cancel endpoint. See #428.
  • Drop support for sending receipts. Stripe now handles this for you. See #478.
  • Drop support for plans as settings, including custom plan hierarchy (if you want this, write something custom) and the dynamic trial callback. We’ve decided to gut having plans as settings. Stripe should be your source of truth; create your plans there and sync them down manually. If you need to create plans locally for testing, etc., simply use the ORM to create Plan models. The sync rewrite will make this drop less annoying.
  • Orphan Customer Sync. We will now sync Customer objects from Stripe even if they aren’t linked to local subscriber objects. You can link up subscribers to those Customers manually.
  • Concurrent Live and Test Mode. dj-stripe now supports test-mode and live-mode Customer objects concurrently. As a result, the User.customer One-to-One reverse-relationship is now the User.djstripe_customers RelatedManager. (Thanks @jleclanche) #440. You’ll run into some dj-stripe check issues if you don’t update your KEY settings accordingly. Check our GitHub issue tracker for help on this.

SETTINGS

  • The PLAN_CHOICES, PLAN_LIST, and PAYMENT_PLANS objects are removed. Use Plan.objects.all() instead.
  • The plan_from_stripe_id function is removed. Use Plan.objects.get(stripe_id=)

SYNCING

  • sync_plans no longer takes an api_key
  • sync methods no longer take a cu parameter
  • All sync methods are now private. We’re in the process of building a better syncing mechanism.

UTILITIES

  • dj-stripe decorators now take a plan argument. If you’re passing in a custom test function to subscriber_passes_pay_test, be sure to account for this new argument.

MIXINS

  • The context provided by dj-stripe’s mixins has changed. PaymentsContextMixin now provides STRIPE_PUBLIC_KEY and plans (changed to Plan.objects.all()). SubscriptionMixin now provides customer and is_plans_plural.
  • We’ve removed the SubscriptionPaymentRequiredMixin. Use @method_decorator("dispatch",subscription_payment_required) instead.

MIDDLEWARE

  • dj-stripe middleware doesn’t support multiple subscriptions.

SIGNALS

  • Local custom signals are deprecated in favor of Stripe webhooks:
  • cancelled -> WEBHOOK_SIGNALS[“customer.subscription.deleted”]
  • card_changed -> WEBHOOK_SIGNALS[“customer.source.updated”]
  • subscription_made -> WEBHOOK_SIGNALS[“customer.subscription.created”]

WEBHOOK EVENTS

  • The Event Handlers designed by @wahuneke are the new way to handle events that come through webhooks. Definitely take a look at event_handlers.py and webhooks.py.

EXCEPTIONS

  • SubscriptionUpdateFailure and SubscriptionCancellationFailure exceptions are removed. There should no longer be a case where they would have been useful. Catch native stripe errors in their place instead.

MODELS

CHARGE

  • Charge.charge_created -> Charge.stripe_timestamp

  • Charge.card_last_4 and Charge.card_kind are removed. Use Charge.source.last4 and Charge.source.brand (if the source is a Card)

  • Charge.invoice is no longer a foreign key to the Invoice model. Invoice now has a OneToOne relationship with Charge. (Charge.invoice will still work, but will no longer be represented in the database).

    CUSTOMER

  • dj-stripe now supports test mode and live mode Customer objects concurrently (See #440). As a result, the <subscriber_model>.customer OneToOne reverse relationship is no longer a thing. You should now instead add a customer property to your subscriber model that checks whether you’re in live or test mode (see djstripe.settings.STRIPE_LIVE_MODE as an example) and grabs the customer from <subscriber_model>.djstripe_customers with a simple livemode= filter.

  • Customer no longer has a current_subscription property. We’ve added a subscription property that should suit your needs.

  • With the advent of multiple subscriptions, the behavior of Customer.subscribe() has changed. Before, calling subscribe() when a customer was already subscribed to a plan would switch the customer to the new plan with an option to prorate. Now calling subscribe() simply subscribes that customer to a new plan in addition to it’s current subsription. Use Subscription.update() to change a subscription’s plan instead.

  • Customer.cancel_subscription() is removed. Use Subscription.cancel() instead.

  • The Customer.update_plan_quantity() method is removed. Use Subscription.update() instead.

  • CustomerManager is now SubscriptionManager and works on the Subscription model instead of the Customer model.

  • Customer.has_valid_card() is now Customer.has_valid_source().

  • Customer.update_card() now takes an id. If the id is not supplied, the default source is updated.

  • Customer.stripe_customer property is removed. Use Customer.api_retrieve() instead.

  • The at_period_end parameter of Customer.cancel_subscription() now actually follows the DJSTRIPE_PRORATION_POLICY setting.

  • Customer.card_fingerprint, Customer.card_last_4, Customer.card_kind, Customer.card_exp_month, Customer.card_exp_year are all removed. Check Customer.default_source (if it’s a Card) or one of the sources in Customer.sources (again, if it’s a Card) instead.

  • The invoice_id parameter of Customer.add_invoice_item is now named invoice and can be either an Invoice object or the stripe_id of an Invoice.

    EVENT

  • Event.kind -> Event.type

  • Removed Event.validated_message. Just check if the event is valid - no need to double check (we do that for you)

    TRANSFER

  • Removed Transfer.update_status()

  • Removed Transfer.event

  • TransferChargeFee is removed. It hasn’t been used in a while due to a broken API version. Use Transfer.fee_details instead.

  • Any fields that were in Transfer.summary no longer exist and are therefore deprecated (unused but not removed from the database). Because of this, TransferManager now only aggregates total_sum

    INVOICE

  • Invoice.attempts -> Invoice.attempt_count

  • InvoiceItems are no longer created when Invoices are synced. You must now sync InvoiceItems directly.

    INVOICEITEM

  • Removed InvoiceItem.line_type

    PLAN

  • Plan no longer has a stripe_plan property. Use api_retrieve() instead.

  • Plan.currency no longer uses choices. Use the get_supported_currency_choices() utility and create your own custom choices list instead.

  • Plan interval choices are now in Plan.INTERVAL_TYPE_CHOICES

    SUBSCRIPTION

  • Subscription.is_period_current() now checks for a current trial end if the current period has ended. This change means subscriptions extended with Subscription.extend() will now be seen as valid.

MIGRATIONS

We’ll sync your current records with Stripe in a migration. It will take a while, but it’s the only way we can ensure data integrity. There were some fields for which we needed to temporarily add placeholder defaults, so just make sure you have a customer with ID 1 and a plan with ID 1 and you shouldn’t run into any issues (create dummy values for these if need be and delete them after the migration).

BIG HUGE NOTE - DON’T OVERLOOK THIS

Warning

Subscription and InvoiceItem migration is not possible because old records don’t have Stripe IDs (so we can’t sync them). Our approach is to delete all local subscription and invoiceitem objects and re-sync them from Stripe.

We 100% recommend you create a backup of your database before performing this upgrade.

Other changes

  • Postgres users now have access to the DJSTRIPE_USE_NATIVE_JSONFIELD setting. (Thanks @jleclanche) #517, #523
  • Charge receipts now take DJSTRIPE_SEND_INVOICE_RECEIPT_EMAILS into account (Thanks @r0fls)
  • Clarified/modified installation documentation (Thanks @pydanny)
  • Corrected and revised ANONYMOUS_USER_ERROR_MSG (Thanks @pydanny)
  • Added fnmatching to SubscriptionPaymentMiddleware (Thanks @pydanny)
  • SubscriptionPaymentMiddleware.process_request() functionality broken up into multiple methods, making local customizations easier (Thanks @pydanny)
  • Fully qualified events are now supported by event handlers as strings e.g. ‘customer.subscription.deleted’ (Thanks @lskillen) #316
  • runtests now accepts positional arguments for declaring which tests to run (Thanks @lskillen) #317
  • It is now possible to reprocess events in both code and the admin interface (Thanks @lskillen) #318
  • The confirm page now checks that a valid card exists. (Thanks @scream4ik) #325
  • Added support for viewing upcoming invoices (Thanks @lskillen) #320
  • Event handler improvements and bugfixes (Thanks @lskillen) #321
  • API list() method bugfixes (Thanks @lskillen) #322
  • Added support for a custom webhook event handler (Thanks @lskillen) #323
  • Django REST Framework contrib package improvements (Thanks @aleccool213) #334
  • Added tax_percent to CreateSubscriptionSerializer (Thanks @aleccool213) #349
  • Fixed incorrectly assigned application_fee in Charge calls (Thanks @kronok) #382
  • Fixed bug caused by API change (Thanks @jessamynsmith) #353
  • Added inline documentation to pretty much everything and enforced docsytle via flake8 (Thanks @aleccool213)
  • Fixed outdated method call in template (Thanks @kandoio) #391
  • Customer is correctly purged when subscriber is deleted, regardless of how the deletion happened (Thanks @lskillen) #396
  • Test webhooks are now properly captured and logged. No more bounced requests to Stripe! (Thanks @jameshiew) #408
  • CancelSubscriptionView redirect is now more flexible (Thanks @jleclanche) #418
  • Customer.sync_cards() (Thanks @jleclanche) #438
  • Many stability fixes, bugfixes, and code cleanup (Thanks @jleclanche)
  • Support syncing canceled subscriptions (Thanks @jleclanche) #443
  • Improved admin interface (Thanks @jleclanche with @jameshiew) #451
  • Support concurrent TEST + LIVE API keys (Fix webhook event processing for both modes) (Thanks @jleclanche) #461
  • Added Stripe Dashboard link to admin change panel (Thanks @jleclanche) #465
  • Implemented Plan.amount_in_cents (Thanks @jleclanche) #466
  • Implemented Subscription.reactivate() (Thanks @jleclanche) #470
  • Added Plan.human_readable_price (Thanks @jleclanche) #498
  • (Re)attach the Subscriber when we find it’s id attached to a customer on Customer sync (Thanks @jleclanche) #500
  • Made API version configurable (with dj-stripe recommended default) (Thanks @lskillen) #504

0.8.0 (2015-12-30)

  • better plan ordering documentation (Thanks @cjrh)
  • added a confirmation page when choosing a subscription (Thanks @chrissmejia, @areski)
  • setup.py reverse dependency fix (#258/#268) (Thanks @ticosax)
  • Dropped official support for Django 1.7 (no code changes were made)
  • Python 3.5 support, Django 1.9.1 support
  • Migration improvements (Thanks @michi88)
  • Fixed “Invoice matching query does not exist” bug (#263) (Thanks @mthornhill)
  • Fixed duplicate content in account view (Thanks @areski)

0.7.0 (2015-09-22)

  • dj-stripe now responds to the invoice.created event (Thanks @wahuneke)
  • dj-stripe now cancels subscriptions and purges customers during sync if they were deleted from the stripe dashboard (Thanks @unformatt)
  • dj-stripe now checks for an active stripe subscription in the update_plan_quantity call (Thanks @ctrengove)
  • Event processing is now handled by “event handlers” - functions outside of models that respond to various event types and subtypes. Documentation on how to tie into the event handler system coming soon. (Thanks @wahuneke)
  • Experimental Python 3.5 support
  • Support for Django 1.6 and lower is now officially gone.
  • Much, much more!

0.6.0 (2015-07-12)

  • Support for Django 1.6 and lower is now deprecated.
  • Improved test harness now tests coverage and pep8
  • SubscribeFormView and ChangePlanView no longer populate self.error with form errors
  • InvoiceItems.plan can now be null (as it is with individual charges), resolving #140 (Thanks @awechsler and @MichelleGlauser for help troubleshooting)
  • Email templates are now packaged during distribution.
  • sync_plans now takes an optional api_key
  • 100% test coverage
  • Stripe ID is now returned as part of each model’s str method (Thanks @areski)
  • Customer model now stores card expiration month and year (Thanks @jpadilla)
  • Ability to extend subscriptions (Thanks @TigerDX)
  • Support for plan heirarchies (Thanks @chrissmejia)
  • Rest API endpoints for Subscriptions [contrib] (Thanks @philippeluickx)
  • Admin interface search by email funtionality is removed (#221) (Thanks @jpadilla)

0.5.0 (2015-05-25)

  • Began deprecation of support for Django 1.6 and lower.
  • Added formal support for Django 1.8.
  • Removed the StripeSubscriptionSignupForm
  • Removed djstripe.safe_settings. Settings are now all located in djstripe.settings
  • DJSTRIPE_TRIAL_PERIOD_FOR_SUBSCRIBER_CALLBACK can no longer be a module string
  • The sync_subscriber argument has been renamed from subscriber_model to subscriber
  • Moved available currencies to the DJSTRIPE_CURRENCIES setting (Thanks @martinhill)
  • Allow passing of extra parameters to stripe Charge API (Thanks @mthornhill)
  • Support for all available arguments when syncing plans (Thanks @jamesbrobb)
  • charge.refund() now returns the refunded charge object (Thanks @mthornhill)
  • Charge model now has captured field and a capture method (Thanks @mthornhill)
  • Subscription deleted webhook bugfix
  • South migrations are now up to date (Thanks @Tyrdall)

0.4.0 (2015-04-05)

  • Formal Python 3.3+/Django 1.7 Support (including migrations)
  • Removed Python 2.6 from Travis CI build. (Thanks @audreyr)
  • Dropped Django 1.4 support. (Thanks @audreyr)
  • Deprecated the djstripe.forms.StripeSubscriptionSignupForm. Making this form work easily with both dj-stripe and django-allauth required too much abstraction. It will be removed in the 0.5.0 release.
  • Add the ability to add invoice items for a customer (Thanks @kavdev)
  • Add the ability to use a custom customer model (Thanks @kavdev)
  • Added setting to disable Invoice receipt emails (Thanks Chris Halpert)
  • Enable proration when customer upgrades plan, and pass proration policy and cancellation at period end for upgrades in settings. (Thanks Yasmine Charif)
  • Removed the redundant context processor. (Thanks @kavdev)
  • Fixed create a token call in change_card.html (Thanks @dollydagr)
  • Fix charge.dispute.closed typo. (Thanks @ipmb)
  • Fix contributing docs formatting. (Thanks @audreyr)
  • Fix subscription canceled_at_period_end field sync on plan upgrade (Thanks @nigma)
  • Remove “account” bug in Middleware (Thanks @sromero84)
  • Fix correct plan selection on subscription in subscribe_form template. (Thanks Yasmine Charif)
  • Fix subscription status in account, _subscription_status, and cancel_subscription templates. (Thanks Yasmine Charif)
  • Now using user.get_username() instead of user.username, to support custom User models. (Thanks @shvechikov)
  • Update remaining DOM Ids for Bootstrap 3. (Thanks Yasmine Charif)
  • Update publish command in setup.py. (Thanks @pydanny)
  • Explicitly specify tox’s virtual environment names. (Thanks @audreyr)
  • Manually call django.setup() to populate apps registry. (Thanks @audreyr)

0.3.5 (2014-05-01)

  • Fixed djstripe_init_customers management command so it works with custom user models.

0.3.4 (2014-05-01)

  • Clarify documentation for redirects on app_name.
  • If settings.DEBUG is True, then django-debug-toolbar is exempt from redirect to subscription form.
  • Use collections.OrderedDict to ensure that plans are listed in order of price.
  • Add ordereddict library to support Python 2.6 users.
  • Switch from __unicode__ to __str__ methods on models to better support Python 3.
  • Add python_2_unicode_compatible decorator to Models.
  • Check for PY3 so the unicode(self.user) in models.Customer doesn’t blow up in Python 3.

0.3.3 (2014-04-24)

  • Increased the extendability of the views by removing as many hard-coded URLs as possible and replacing them with success_url and other attributes/methods.
  • Added single unit purchasing to the cookbook

0.3.2 (2014-01-16)

  • Made Yasmine Charif a core committer
  • Take into account trial days in a subscription plan (Thanks Yasmine Charif)
  • Correct invoice period end value (Thanks Yasmine Charif)
  • Make plan cancellation and plan change consistently not prorating (Thanks Yasmine Charif)
  • Fix circular import when ACCOUNT_SIGNUP_FORM_CLASS is defined (Thanks Dustin Farris)
  • Add send e-mail receipt action in charges admin panel (Thanks Buddy Lindsay)
  • Add created field to all ModelAdmins to help with internal auditing (Thanks Kulbir Singh)

0.3.1 (2013-11-14)

  • Cancellation fix (Thanks Yasmine Charif)
  • Add setup.cfg for wheel generation (Thanks Charlie Denton)

0.3.0 (2013-11-12)

  • Fully tested against Django 1.6, 1.5, and 1.4
  • Fix boolean default issue in models (from now on they are all default to False).
  • Replace duplicated code with djstripe.utils.user_has_active_subscription.

0.2.9 (2013-09-06)

  • Cancellation added to views.
  • Support for kwargs on charge and invoice fetching.
  • def charge() now supports send_receipt flag, default to True.
  • Fixed templates to work with Bootstrap 3.0.0 column design.

0.2.8 (2013-09-02)

  • Improved usage documentation.
  • Corrected order of fields in StripeSubscriptionSignupForm.
  • Corrected transaction history template layout.
  • Updated models to take into account when settings.USE_TZ is disabled.

0.2.7 (2013-08-24)

  • Add handy rest_framework permission class.
  • Fixing attribution for django-stripe-payments.
  • Add new status to Invoice model.

0.2.6 (2013-08-20)

  • Changed name of division tag to djdiv.
  • Added safe_setting.py module to handle edge cases when working with custom user models.
  • Added cookbook page in the documentation.

0.2.5 (2013-08-18)

  • Fixed bug in initial checkout
  • You can’t purchase the same plan that you currently have.

0.2.4 (2013-08-18)

  • Recursive package finding.

0.2.3 (2013-08-16)

  • Fix packaging so all submodules are loaded

0.2.2 (2013-08-15)

  • Added Registration + Subscription form

0.2.1 (2013-08-12)

  • Fixed a bug on CurrentSubscription tests
  • Improved usage documentation
  • Added to migration from other tools documentation

0.2.0 (2013-08-12)

  • Cancellation of plans now works.
  • Upgrades and downgrades of plans now work.
  • Changing of cards now works.
  • Added breadcrumbs to improve navigation.
  • Improved installation instructions.
  • Consolidation of test instructions.
  • Minor improvement to django-stripe-payments documentation
  • Added coverage.py to test process.
  • Added south migrations.
  • Fixed the subscription_payment_required function-based view decorator.
  • Removed unnecessary django-crispy-forms

0.1.7 (2013-08-08)

  • Middleware excepts all of the djstripe namespaced URLs. This way people can pay.

0.1.6 (2013-08-08)

  • Fixed a couple template paths
  • Fixed the manifest so we include html, images.

0.1.5 (2013-08-08)

  • Fixed the manifest so we include html, css, js, images.

0.1.4 (2013-08-08)

  • Change PaymentRequiredMixin to SubscriptionPaymentRequiredMixin
  • Add subscription_payment_required function-based view decorator
  • Added SubscriptionPaymentRedirectMiddleware
  • Much nicer accounts view display
  • Much improved subscription form display
  • Payment plans can have decimals
  • Payment plans can have custom images

0.1.3 (2013-08-7)

  • Added account view
  • Added Customer.get_or_create method
  • Added djstripe_sync_customers management command
  • sync file for all code that keeps things in sync with stripe
  • Use client-side JavaScript to get history data asynchronously
  • More user friendly action views

0.1.2 (2013-08-6)

  • Admin working
  • Better publish statement
  • Fix dependencies

0.1.1 (2013-08-6)

  • Ported internals from django-stripe-payments
  • Began writing the views
  • Travis-CI
  • All tests passing on Python 2.7 and 3.3
  • All tests passing on Django 1.4 and 1.5
  • Began model cleanup
  • Better form
  • Provide better response from management commands

0.1.0 (2013-08-5)

  • First release on PyPI.

Support

No content… yet

Release Process

Attention

Before MAJOR or MINOR releases:

  • Review deprecation notes (eg search for “deprecated”) and remove deprecated features as appropriate
  • Squash migrations (ONLY on unreleased migrations) - see below

Squash migrations

If there’s more than one unreleased migration on master consider squashing them with squashmigrations, immediately before tagging the new release:

  • Create a new squashed migration with ./manage.py squashmigrations (only squash migrations that have never been in a tagged release)
  • Commit the squashed migration on master with a commit message like “Squash x.y.0dev migrations” (this will allow users who running master to safely upgrade, see note below about rc package)
  • Then transition the squashed migration to a normal migration as per Django:
    • Delete all the migration files it replaces
    • Update all migrations that depend on the deleted migrations to depend on the squashed migration instead
    • Remove the replaces attribute in the Migration class of the squashed migration (this is how Django tells that it is a squashed migration)
  • Commit these changes to master with a message like “Transition squashed migration to normal migration”
  • Then do the normal release process - bump version as another commit and tag the release

See https://docs.djangoproject.com/en/dev/topics/migrations/#migration-squashing

Tag + package squashed migrations as rc package (optional)

As a convenience to users who are running master, an rc version can be created to package the squashed migration.

To do this, immediately after the “Squash x.y.0dev migrations” commit, follow the steps below but with a x.y.0rc0 version to tag and package a rc version.

Users who have been using the x.y.0dev code from master can then run the squashed migrations migrations before upgrading to >=x.y.0.

The simplest way to do this is to pip install dj-stripe==x.y.0rc0 and migrate, or alternatively check out the x.y.0rc0 git tag and migrate.

Prepare changes for the release commit

  • Choose your version number (using https://semver.org/ )
    • if there’s a new migration, it should be a MAJOR.0.0 or MAJOR.MINOR.0 version.
  • Review and update HISTORY.rst
    • Add a section for this release version
    • Set date on this release version
    • Check that summary of feature/fixes is since the last release is up to date
  • Update package version number in setup.cfg
  • Review and update supported API version in README.rst
    (this is the most recent Stripe account version tested against, not DEFAULT_STRIPE_API_VERSION)
  • git add to stage these changes

Create signed release commit tag

Note

Before doing this you should have a GPG key set up on github

If you don’t have a GPG key already, one method is via https://keybase.io/ , and then add it to your github profile.

  • Create a release tag with the above staged changes (where $VERSION is the version number to be released:

    $ git commit -m "Release $VERSION"
    $ git tag -fsm "Release $VERSION" $VERSION
    

This can be expressed as a bash function as follows:

git_release() { git commit -m "Release $1" && git tag -fsm "Release $1" $1; }
  • Push the commit and tag:

    $ git push --follow-tags
    

Update/create stable branch

Push these changes to the appropriate stable/MAJOR.MINOR version branch (eg stable/2.0) if they’re not already - note that this will trigger the readthedocs build

Configure readthedocs

If this is this is a new stable branch then do the following on https://readthedocs.org/dashboard/dj-stripe/versions/

  • Find the new stable/MAJOR.MINOR branch name and mark it as active (and then save).

Constraints

  1. For stripe.com only
  2. Only use or support well-maintained third-party libraries
  3. For modern Python and Django