Search code examples
node.jspaypalstripe-payments

What should the general backend process be when a customer places an order on the front end when working with stripe / paypal


I am currently building an ecommerce website with Next.js and have utilized Stripe's and Paypal's react library for my checkout. I am wanting to know how I should handle posting the order information to my database. I currently have a webhook endpoint setup for Stripe but I have realized that I am not able to recieve any order details in the webhook.

An approach I thought about was posting all of the order information to my orders table even though it hasn't been confirmed and also storing the paypal / stripe id. Once I recieve the webhook I can then mark the order as confirmed. With this approach I realize that anyone could post an order to the database through the API route, but it wouldn't ever get confirmed because there wouldn't be any webhook that gets triggered. Is this approach optimal or is there a better way of posting orders to a database?

I have my stripe payments set-up exactly as shown in this guide: https://stripe.com/docs/payments/quickstart where once the user clicks the checkout page, a payment intent is created on the backend and the client secret is sent to the front-end. I then have a webhook setup specifcally for successful payments where I verify that the request came from stripe.


Solution

  • For the PayPal checkout, you don't need webhooks for normal processing. Use the v2/checkout/orders API and make two routes (url paths) on your server, one for 'Create Order' and one for 'Capture Order'. You could use the (recently deprecated) @paypal/checkout-server-sdk for the routes' API calls to PayPal, or your own HTTPS implementation of first getting an access token and then doing the call. Both of these routes should return/output only JSON data (no HTML or text). Inside the 2nd route, when the capture API is successful you should verify the amount was correct and store its resulting payment details in your database (particularly purchase_units[0].payments.captures[0].id, which is the PayPal transaction ID) and perform any necessary business logic (such as reserving product or sending an email) immediately before forwarding return JSON to the frontend caller. In the event of an error forward the JSON details of it as well, since the frontend must handle such cases.

    Pair those 2 routes with this frontend approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server . (If you need to send any additional data from the client to the server, such as an items array or selected options, add a body parameter to the fetch with a value that is a JSON string or object. Your server can verify the information is correct before doing anything with it.)


    You can load the frontend JS with @paypal/paypal-js if desired , or just a normal script tag