How to react to Stripe PaymentIntent success webhook in frontend - stripe-payments

I'm updating a webapp to Stripes SCA ready flow with PaymentIntent.
So far I have working (on my local test server):
Generate Intent on frontend and pass secret to form
Use Elements to collect card into
Use handleCardPayment to create the charge
Now here's the part where I am unsure. The handleCardPayment responses all seem to indicate a succeeded event, but the documentation warns to not use this repsonse, but instead wait for the Webhook response and only then fulfill customer orders.
Step 5: Asynchronously fulfill the customer’s order
You can use the PaymentIntent returned by Stripe.js to provide
immediate feedback to your customers when the payment completes on the
client. However, your integration should not attempt to handle order
fulfillment on the client side because it is possible for customers to
leave the page after payment is complete but before the fulfillment
process initiates. Instead, you will need to handle asynchronous
events in order to be notified and drive fulfillment when the payment
succeeds. Documentation
So far so good, I've set up test webhooks and tunneling through ngrok I can actually receive the paymentIntent from the Stripe webhook.
Now, my question comes at this point, where the Stripe documentation ends. How should I deal with the UI from the point of the "Pay" button being pressed, and how do I in the frontend detect that the webhook has been triggered?
I am wondering if I should poll my own server, which in turn retrieves a database result that indicated if the webhook for this order has been received? Or what is a reasonable way to deal with this, technically and from an UX perspective?
Any pointers?

I just implemented this, and I decided to poll my own server for the update and ask the user to wait. The webhook marks our internal representation as "paid", so we don't need to poll Stripe. If the webhook doesn't come within 30 seconds, we tell the user that it's ok to leave the page, and we'll email them the result.
Technically, these webhooks can take up to 7 days to come in, so that's why Stripe doesn't want you to have the user wait. In reality, it almost always comes in within 5 seconds, and I would rather just have the user wait and see a final confirmation in the same session.

Related

Best way to handle one-time payments with STRIPE webhooks in nodeJS

I am using STRIPE as my payment processor, in an REACT + nodeJS app. I already have something that already works, but I would like some feedback, maybe I'm doing something wrong.
So... I have this Redirect-To-Checkout functionality thats made available by STRIPE, basically I redirect the user to this STRIPE page where all card-data (sensitive information) is processes in order for the payment to full-fill.
What I do in my nodeJS server part is the following:
Once the user acces the redirect to check-out page, I already create a PendingOrder, with the products selected by client (Here I save some information based on client/stripe payment-intent, in order to check in later steps)
Once webhook gives me the 'payment_intent.succeeded' I check for the payment-intent information to see if it exists in my PendingOrder collection, then proceed to add in to ConfirmedOrders and remove it from PendingOrders.
I have to do this whole process because Stripe no longer gives me access to some information I require when the user is checking-out his order(such as observation that the user has based on the type of service he chooses).
Are there any down-sides to this approach or is there any other way to do it?
Thanks in advance!
You’re not really far from the best practices that Stripe recommends here. The only thing that I would change is listening to checkout.session.completed instead of the payment_intent.succeeded event. As of the latest API version, a PaymentIntent is no longer created upfront so a better to way to handle order fulfillment is to either store the Checkout Session ID (e.g. cs_live_xxx) or you could add some metadata when creating the Checkout Session and use that instead to identify the order.
I have to do this whole process because Stripe no longer gives me access to some information I require when the user is checking-out his order
As for this, I’m not sure what you mean, you can always use your app with the success page customization described here alongside webhooks. I wouldn’t use that to fulfill the order though since the user might close the page before the redirection completes which means that the fulfillment wouldn’t be done in that case. As such, webhooks are essential to order fulfillment.

Stripe API testing automation

Background
I am integrating stripe API into my site to take one off payments. My site will be API first on server side with a separate web and mobile front end. I am working on the API server side code. I will eventually use stripe payment pages to take credit card payments. I am trying to automate the testing of my APIs and am bamboozled by the documentation (which are thorough) as I just can't see what steps to take next.
My server side initiates a call with stripe using stripe sdk to create a stripe Session object - this contains a URL to redirect to checkout.stripe.com/pay/..., a success URL when payment is successful and a cancel URL (these I set to handle the callback).
Problem
I can automate in Postman all my API calls from Browse Products, Select Product, Place Order but the next step I am stuck. After Placing Order I get back the stripe session but how can I mimick making the payment with stripe for the session and then call my Success URL ?
When the site is complete I will redirect the UI to stripe to take payments but I am testing and completing the back end flow first.
I have copied and pasted the session URL which is returned by the stripe Session object to bring up the page in a browser and used Dev tools on Chrome to inspect Network to see which APIs are being called by stripe in an attempt to reproduce and I can see a POST to stripe.com/api/payment_methods and I can see the posted values but I can't reproduce this in Postman. Also, the documentation (https://stripe.com/docs/api/payment_methods/create) says
"Instead of creating a PaymentMethod directly, we recommend using the
PaymentsIntents API to accept a payment immediately"
Question
Which stripe APIs do I need to call to automate the flow from a stripe Session object to make a payment and then check that it was successful? Payment Methods? Make a Charge? Payments Intents? ...and how. Happy to be pointed to the documentation if you can help me understand the flow.
TIA
Checkout is a Stripe product that looks like a "box" and you can't know (and shouldn't need to know) what happens inside. It is created for the purpose that merchants won't have to think about what's being done under the hood.
Speaking from an automation perspective, you can try to reproduce the whole process but there's no guarantee it won't change in the future, and it could leave you with more problems later.
For options to reproduce:
The closest way is simulating browser filling and submission, using automated browser tools (ie Selenium). But it's not as straightforward as PostMan. Generally you would want to simulate every browser action that a human could do.
Or you can try to accomplish the same with the logs and events you receive on Stripe's Dashboard, when you test a Checkout Session by yourself. From now there are 3 requests.
And your goal is to receive the same 5 events in Webhook:
TBH I recommend to reconsider the need of this test, to see if it worth your efforts.

Can Stripe change the payment intent status between the confirm payment call, if successful, and the webhook they send me?

I have a social app where my customer is going to make single purchases (credits/tokens/likes) using a credit card (Visa, Master, Amex, Discover). When the purchase is complete, and I receive a "succeeded" in the result "status" from the Stripe result, the customer will then be given 10, 20, 50, 100, etc. tokens to their profile that can be used now for "liking" someone.
FYI - If the user has a card saved and chooses that card, that Stripe card number and customer number is used for the payment intent, otherwise I'm collecting the card details, and passing that to the "confirmpayment()".
QUESTION - Once I call Stripe "confirmpayment()" client side, and get the result back, which shows the status (succeeded, failed, incomplete, etc.) Is it possible to receive a "succeeded" status in the result and then at some later date via Stripe's webhook, receive a different status other than "succeeded"?
FYI - I've gone through almost all test card scenarios to test for this type of condition, but it doesn't seem like it will happen? It seems like the payment will either succeed or fail on the confirmpayment() call. I'm also double checking the status result on the server side by fetching the paymentIntent from Stripe. Just to make sure the user (client side) hasn't changed it in the code (JS/Typescript).
Concern - The customer finishes their purchase, the confirmpayment result shows a status of "succeeded", their "tokens" are added to their profile at that moment and then they proceed to use them to send "likes" to another user. Then later on I get the Stripe webhook back showing a different status with "failed" or "incomplete". But by this point, "tokens" will have been used and a monetary amount based on the amount of the "token" will have been moved from my Connect account where the original purchased fund will be sent to the intended receiver's connect account. If this happens I foresee it being extremely difficult to back all this out and reverse it will out a huge headache.
ALTERNATIVE WORKFLOW - I could create a "payment" entity on the server side with a pending status and wait until I receive the Stripe webhook before I add any "tokens" to the user account/profile. This will insure there is no possibility for error, but it makes the user wait until the webhook comes in before they will see a status of "success" on their payment page and won't be able to use any "tokens" from that purchase until I get the webhook. I wanted to give them a more instant experience.
Any help or advice will be much appreciated.
The result you get back after the Promise confirmCardPayment() resolves will be the same as the status you get back on the webhook event so it will never be that a succeeded PaymentIntent transitions back to requires_payment_method or requires_action, as succeeded is an end state of the lifecycle.
Keep in mind, webhook events can be out of order, so technically you could get a payment_intent.requires_action after your payment_intent.succeeded event (if they happen very quickly.
The best thing to do is to fetch the PaymentIntent from the API (after an event) to get the "true" state of the PaymentIntent.

Special workflow (state management) for the Stripe payment, can simple Stripe Checkout work?

I am building an app to sell single item product (i.e, each kind of products listed on my platform only has a single item).
(this part has been done, and won't change) I built an in-house backend having the Rest API POST -D {"buyer_email": "abc#example.com"} url/items/{itemID}, let's call it transaction_call, which will make sure once a customer succeed the POST operation, his contact info is recorded into my backend as the successful buyer; and all other customers will fail to buy that item (at API level, transaction_call return 4xx error) because my platform can only sell one item for that product;
(this is the step that my current question is about) I am trying to use Stripe as my payment system on this platform.
I really want to integrate with Stripe as simple as possible (as I understand Stripe Checkout is the most simple / out-of-box way to implement payment). However, I am not sure if Stripe Checkout can achieve the above functionality correctly. Since the problem is a two-step problem, here is the potential issue I may run into:
Let's say, two customers A, B, get to my platform at 10:00am, both of them start purchasing process for a product, Item_a
If my system interact / call the Stripe Checkout first as the first step then call the transaction_call, here could be the problem:
A's Stripe call hits the Stripe server at 10:00:01am, and A's buying call hits my backend at 10:00:02am;
B's Stripe call hits the Stripe server at 10:00:01am, and A's buying call hits my backend at 10:00:03am;
in this way, we have already charged B but he really did not get the item
If my system calls the transaction_call first, and only if transaction call succeeds then it interacts / calls the Stripe Checkout, then
A's transaction_call succeed at 10:00:01am, but he for some reason decided not to pay (not click confirm button on the Stripe Checkout UI)
In this way, my system fails to sell the item to other buyers.
My question is whether the above reasoning process is correct, and whether I could somehow use Stripe Checkout to achieve what I am doing.
Maybe I have implement the payment functionality using Stripe Intent API to build a workflow-based payment, which I assume will be much more complex, if the Stripe Checkout way (simple wayO is really not possible.
From what I understand you have a potential race problem, where the item you're selling is very limited in quantity and you want to make sure that you can correctly notify users if it's out of stock or already spoken for.
For your first scenario, the simple solution is only invoke Stripe's API on your backend when you've received the transaction_call. For instance, you'd only create the Checkout Session once your system has identified that the item is still available. You'd then "lock" the item so that when B attempts to purchase you can immediately return an error instead of creating a payment via Stripe's API. The logic on who to charge (basically who initiated the checkout process first) in the case of a tie would then be for you to implement in your transaction_call rather than on Stripe's side.
The second scenario is a little tricker, as Checkout Sessions can't be cancelled once you create them. They automatically cancel themselves after 24 hours if no payment is made, but I doubt that you'd want B to have to wait that long if A abandons the payment flow.
Instead I think you should look at implementing a PaymentIntents integration, where you can more finely control the flow.
Your flow for scenario 2 could be:
A begins the checkout process, create a PaymentIntent on the backend, "lock" the item and start a timer
The timer (which you'd ideally show to your user) times out after N minutes if A doesn't pay
Cancel the PaymentIntent on your backend and remove the lock
B can now attempt to pay for the item, upon where you restart the process

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.

Resources