I have the following python code to create a charge in stripe.
a_charge = stripe.Charge.create(
amount=cents,
currency="usd",
source=token,
description="my_description",
application_fee=application_fee,
stripe_account=teacher_stripe_id
)
This succeeds (I think), because it shows up in my dashboard with a charge_id. But then, immediately after in the code, the following fails:
stripe.Charge.retrieve(a_charge.id)
With error: No such charge: somelongstringhere
However, somelongstringhere is indeed the ID under charge details on my stripe dashboard. So how come Stripe can't retrieve this charge? Is this not the correct id?
The reason the charge retrieval call fails is because the charge was created on a different account.
When you create the charge:
a_charge = stripe.Charge.create(
amount=cents,
currency="usd",
source=token,
description="my_description",
application_fee=application_fee,
stripe_account=teacher_stripe_id
)
you use the stripe_account
parameter, which instructs the library to use the Stripe-Account
in the request. This is used to tell Stripe's API that the request is issued by your platform on behalf of one of its connected accounts.
So in order to retrieve the charge, you need to use the same stripe_account
parameter:
the_same_charge = stripe.Charge.retrieve(a_charge.id, stripe_account= teacher_stripe_id)
That said, there is little use to do this in practice. You already have the charge object in a_charge
. If you execute the code above, you'd find that a_charge == the_same_charge
.
More generally, when you already have an instance of a Stripe object and want to get the latest state from the API, you can use the refresh()
method:
a_charge.refresh()
This will query the API (without you having to worry about the stripe_account
parameter -- the instance "remembers" about it and will use it in the background) and refresh the instance's attributes with the values retrieved from the API.
Why do you need to do stripe.Charge.retrieve(a.charge.id)
immediately after creating the charge while you already have the data within a_charge
?
It is possible that data are cached and/or broadcasted to multiple servers/databases. Newly created data may then take a few seconds to be available for reading.
The code you're using here is creating a charge directly on a connected Stripe account. This is covered in Stripe's documentation here.
Since the charge is on a connected account, it doesn't exist on your own Stripe account and it's expected you can't retrieve it directly. To do this, you need to pass the Stripe-Account
header again as documented here.
Your code should instead be
the_charge = stripe.Charge.retrieve(
id=a_charge.id,
stripe_account=teacher_stripe_id)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With