Stripe Subscription: latest_invoice.payment_intent raises AttributeError: payment_intent
I'm trying to create a subscription in Stripe using Python and the official library, with the goal of obtaining the client_secret from the initial invoice's PaymentIntent to complete payment on the frontend.
Here is the code I'm using:
import stripe
stripe.api_key = 'sk_test_...'
price_id = 'price_...' # Example
subscription = stripe.Subscription.create(
customer=customer.id,
items=[{'price': price_id}],
payment_behavior='default_incomplete',
expand=['latest_invoice.payment_intent'],
)
I want to access: subscription.latest_invoice.payment_intent.client_secret
But I get the error:
AttributeError: payment_intent
What I've checked so far
- The subscription is created successfully.
- The parameter
expand=['latest_invoice.payment_intent']is included to embed thepayment_intentobject. - I've verified that the invoice (
latest_invoice) exists. - However, the
payment_intentfield is missing from thelatest_invoiceobject.
Questions
- Why is
payment_intentmissing fromlatest_invoicewhen creating the subscription withpayment_behavior='default_incomplete'and expanding the field? - How should I obtain the
client_secretto confirm payment on the frontend using Stripe.js in these cases?
This part of the API was changed by Stripe in their latest major API version called Basil. The stripe-python SDK is pinned to the latest API version so if you are using the most recent version you have that newer API version. I recommend carefully reading their changelog here that covers all breaking changes for each API version.
In your specific case, Stripe removed the connection between the Invoice and its PaymentIntent to add support for multiple partial payments on one Invoice. You can read more about this in this specific changelog entry where they explain that instead of looking at the PaymentIntent's client_secret, you can access this directly on the Invoice in the confirmation_secret property that you also have to expand.
Your code should be
subscription = stripe.Subscription.create(
customer=customer.id,
items=[{'price': price_id}],
payment_behavior='default_incomplete',
expand=['latest_invoice.confirmation_secret'],
)