How to get charge id after creating a subscription using Stripe?
This is exactly what Stripe's webhooks are for. After creating a customer with an initial subscription, you'll get six webhook notifications:
customer.created
, with the customer data (which you already have if you're saving what the API returns)charge.succeeded
(orcharge.failed
), which contains the initial charge data you're looking forinvoice.created
, which is the associated invoiceinvoice.payment_succeeded
(orinvoice.payment_failed
), also telling you the status of the chargecustomer.card.created
, with the details of the new cardcustomer.subscription.created
, with the details of the customer's subscription.
Stripe's API, like many APIs and many payment solutions, is built to be used with webhooks. If you're not taking advantage of webhooks, you're going to be missing functionality, and you're probably working too hard for what can be done without webhooks.
Stripe works to deliver the data to you. If you're writing code to poll Stripe, you're working way, way too hard.
Another option you can use if you need the charge id right away and can't wait for a webhook is use the latest_invoice
field on the returned subscription object.
A python example:
inv_id = subscription.latest_invoice
inv = stripe.Invoice.retrieve(inv_id)
charge_id = inv.charge
I just ran into the same issue myself. I'm using the python library but the answer is more about Stripe's API than what language the client is in.
Ultimately, since I'm creating a new customer with each subscription, I was able to look up the invoice against the customer_id and grab its charge id. Here's what the python code for that looks like:
stripe_api.Invoice.all(customer=subscribe_result['customer'])['data'][0]['charge']
Again, note that this method would not work if you re-use customers, only if creating new customers with each subscription create.
It's certainly not ideal. It would be far better if the charge id were included in the return. Even knowing the Invoice ID would at least solve the issue of re-using customers though it would still require an unnecessary API call to fetch the invoice.