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}],
collection_method="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()
.