Stripe: Get total successfully paid invoices count - stripe-payments

I'm using stripe for subscription. Where i need to fire an event after 3 successfully charges.
For this i am using invoice.payment_succeeded webhook.
But there is no key which specify the number of this recurring payment means whether it is first or second or nth charge. So how could i get the number of successfully payment made on a subscription.

You can call the https://api.stripe.com/v1/invoices API endpoint with the customer's ID, the status parameter set to paid and optionally, the subscription parameter and then count how many invoices were returned.
There are some other parameters, like limit, starting_after, etc. that you can send it too.
The invoice.payment_succeeded webhook sends the invoice object in the data.object field so you should be able to get the customer and subscription values from it.
I'd recommend doing the invoices call asynchronously to ensure that the webhook call doesn't time out.

FYI there is an expand to it, like with the current node api;
const ret = await stripe.invoices.list(
{
expand: ["total_count"],
limit: 0,
});
console.log(ret.total_count)
It can be called with ${url}?expand[]=total_count&limit=0 too, if you need to write it by hand.
I did not found this in the documentation, but some libs using it, and it is indeed works. (But be careful, if it is not documented it could stop working too.)
Here is the docs; https://stripe.com/docs/api/pagination/search#search_pagination-total_count

Yes, as it is stated in the answer by D Malan, you can use the https://api.stripe.com/v1/invoices endpoint.
Though there is one thing to keep in mind when retrieving data from Stripe.
You can only get 100 items per call. Therefore, if you had recurring payment that generates more than 100 invoices after some time, you wouldn't be able to get the total count in one call. I suggest storing invoices/payment intents to your database and then using your DB engine to count the results.
Keep in mind that you should listen to invoice.payment_succeeded event in order to keep your database in sync, if you store the invoice or payment intent beforehand, while its status is not paid or succeeded, respectively.

Related

How to use stripe checkout for first come, first served buying experience

I'm trying to use Stripe checkout in a first-come, first-served buying process. Multiple buyers may be trying to buy the same item at the same time, and only the one who completes the stripe checkout process first should get it. At the moment, the stripe checkout session duration requires me to 'book' the stock item and only release them back into stock once the session duration expires (even if they close the tab).
Is there a way to set up Stripe Checkout in a way that would detect whether the item has already been purchased by another buyer (e.g. the stock is no longer available), and for example show an error when the user tries to pay?
If not, any suggestions as to alternative ways of implementing this functionality while still using Stripe?
You can listen for checkout.session.completed events and add some event handler logic to retrieve the Session object while expanding the line_items:
https://stripe.com/docs/payments/checkout/fulfill-orders
https://stripe.com/docs/api/expanding_objects
This will allow you to inspect the price and product IDs for the completed Session. You could then have some logic to expire any other Checkout sessions so no other customers are able to go through the payment flow:
https://stripe.com/docs/payments/checkout/managing-limited-inventory
https://stripe.com/docs/api/checkout/sessions/expire
You can use the paymentIntent that allows you to confirm or reject the payment later. You can create the paymentIntent for all the customers are trying at the same time and next take the first one and confirm only this paymentIntent and reject the others
Read the Stripe documentation:
Stripe | PaymentIntent

Stripe webhook circular reference

I'm subscribed to stripe webhook charge.refund.updated event. On that event, I need to attach specific metadata to stripe refund entity (accounting needs this data in stripe exports so I need it there), but this causes same charge.refund.updated event being called again, which causes circular requests.
Only solution I'm thinking of right now is to add some kind of additional ignore field to metadata and then just ignore webhook if that value is true, but I don't really like that solution because it would persist on the refund entity, and if something actually did change on refund, my handler would ignore it.
I guess the best option would be something like stripe.refunds.update(..., { ignoreWebhook: true }), but that's not an option because API doesn't support anything like that (as far as I've investigated).
It’s recommended that you need to design your webhook endpoint to treat duplicates events. Because regardless of your circular call on Charge updates, Stripe occasionally sends the same event more than once [1]. One of the solutions: is to log the event you’ve processed and then not process already-logged events.
In your case, you can add a metadata that contains a version number of the charge. Something like this:
1 - Received an event charge.refund.updated
2- Add your logic along with another version of metadata.
3- You log the charge id, version any other field you are basing your logic while adding metadata (example: status)
4- You’ll receive another event charge.refund.updated, you check if you have already treated that charge based on what you logged already (id, version, status…)
Meanwhile, if you hit the same update charge request API [3] multiple times, only one webhook event is triggered you can test it on your own.
[1] https://stripe.com/docs/webhooks/best-practices#duplicate-events
[2] https://stripe.com/docs/webhooks/best-practices#duplicate-events:~:text=One%20way%20of%20doing%20this%20is%20logging%20the%20events%20you%E2%80%99ve%20processed%2C%20and%20then%20not%20processing%20already%2Dlogged%20events.
[3] https://stripe.com/docs/api/refunds/update

Get purchased product from PaymentIntent

in my app i want to list past purchases for a stripe customer. So I was looking at the relevant API objects like PaymentIntents, Sessions or Charges. But they all do not seem to contain any reference to Product or Price, which I would need to list the purchased products.
Subscriptions contain a list of items that are contained in that subscription, so I was expecting PaymentIntents to have something like that too.
Does anyone has an idea how to archive my list of past purchases? Thanks!
I did some digging through the Stripe API docs[1] and, out of the three objects you referrenced (PaymentIntent, Session, Charges), the only one that I can see being able to trace back to a product is the Session.
Session objects have a line_items property[2] which can be followed all the way down to line_items.data.price.product[3]. To access this you’ll need to inlcude the expand=["data.line_items"] parameter to your call to list Checkout Sessions. You can read more about expanding API responses here[4]
So for all the charges to your customers that were done using Checkout Sessions, you could list them all, use the customer property to associate earch session with a customer in your application, traverse the the returned data, and then query the API for the product details. If you have a lot of customers & products these API calls will add up fast so I would store this data in your back-end to avoid hitting rate limits[5].
Alternatively, you could just save the product ID (either Stripe or your local version) as metadata[6] for any of the above Stripe payment objects listed. That would allow you to link any payment object you wish to a product.
https://stripe.com/docs/api
https://stripe.com/docs/api/checkout/sessions/object#checkout_session_object-line_items
https://stripe.com/docs/api/checkout/sessions/object#checkout_session_object-line_items-data-price-product
https://stripe.com/docs/expand
https://stripe.com/docs/rate-limits
https://stripe.com/docs/api/metadata
I had the same question I found a way to retrieve the products related to a specific PaymentIntent.
You need to get the sessions that was linked to PaymentIntent when the Checkout process was made.
I will give you the code (in PHP) that I use to to this.
\Stripe\Stripe::setApiKey(STRIPE_API_SECRET);
// Find the Session for that PaymentIntent
$sessions = \Stripe\Checkout\Session::all([
'payment_intent' => "pi_xxxxxxxxxx",
'expand' => ['data.line_items'],
]);
You will then have an key line_items that contain the products linked.
Enjoy

Stripe Payment Intents and charge.succeeded webhook sometimes not firing

We create PaymentIntents (with capture_method=manual in case that matters) in our iOS/Android apps when the user places an order.
We send the order to the connected venue once the charge.succeeded webhook fires. If this doesn't happen within a couple of minutes, we expired the placed order on our side.
So interestingly 2 out of 10 times we don't get this webhook to fire.
Im wondering if it's actually wise to listen to this webhook in order to decide if we send the order to the connected account's venue or not or if there is a better way to determine that the payment will actually work once we try to capture it.
Webhooks are the recommended way for getting a payment intent's status, but you can also use the API to get its status.
A quote from the Stripe docs:
It is technically possible to use polling instead of webhooks to
monitor for changes caused by asynchronous operations—repeatedly
retrieving a PaymentIntent so that you can check its status—but this
is markedly less reliable and may pose challenges if used at scale.
Stripe enforces rate limiting on API requests, so exercise caution
should you decide to use polling.
In your case, I'd recommend waiting for the webhook and then after a few minutes, call either the PaymentIntents API or the Charges API if you haven't received the webhook yet.
There's likely something else going on here, so I'd suggest you reach out to Stripe - webhooks should fire all the time, and it's a really really rare occurrence that they wouldn't.

Paypal recurring payment with variable amount every month

My problem is, the amount will differ every cycle but in recurring I have to pass only one fix amount which is depend on customers how they use our service.
I read reference transaction doc but i didn't got whole point.
I don't have any problem with manage from my side and set charge to user dynamically by my side but how it will work.
Paypal is not providing metered billing concept. For that I have use STRIPE later that time.

Resources