DEV Community

Cover image for Add this key feature to your eCommerce application in 3 simple steps
Supriya M
Supriya M

Posted on

Add this key feature to your eCommerce application in 3 simple steps

While getting into the world of web development, we would have definitely come across the implementation of an eCommerce application. There are a lot of eCommerce web applications available to take inspiration from and implement the set of features such as product listing, filter categories, product details, cart, and wishlist.

We could take it one step further and add user authentication to this application such that few of the features such as wishlist and personal details could be exclusively accessible to only registered users.

I did the same while creating my version of an eCommerce application - SupMart. This application has data curated from various web applications specific to the theme of jumping rope.

I have developed this project using the following tech stack:

  • React with useContext + useReducer

  • Routing using react-router v6

  • Backend API structure with Express and Node.

  • Mongoose as an ORM to access and maintain data on MongoDB.

  • User authentication using JWT (JSON Web Token).

I took inspiration from Myntra in terms of the flow and structure of the application. I made sure that the wishlist, address management, and order summary pages are considered private routes. This means, only users who are registered to SupMart would be able to use these features to store persistent data.

After covering a handful of features along with the landing page, I was missing out on one huge implementation. When we talk about an eCommerce application that lets us add products into the cart, continue to add/manage address details, and finally present the order summary page, we surely would need a way to complete this transaction. We need a payment gateway integration to be implemented.

Why is this feature important?

Within any given eCommerce application, the complete workflow of placing an order is as follows:

  • Search for the desired product from the product listing page
  • View the details about this product on the product detail page
  • Add the product into the cart
  • Proceed to checkout and fill in the address information
  • View and verify the details about the order on the summary page
  • Complete the payment using the given payment gateway.
  • An acknowledgment is provided to the user regarding the order and payment status.

Including the payment gateway implementation is like completing the whole application; the end-to-end journey is achieved, otherwise it's similar to baking a beautiful cake but not adding the icing on top of it. A cake wouldn't look complete without the icing or cream at the top layer.

List of payment gateways integration

As we have understood that payment gateways are a crucial part of any given eCommerce application, there are plenty of payment gateway options available currently in the market.
Paypal, Razorpay, Stripe, Paytm, Google pay, Pay U, etc. When I searched about payment integration tutorials using react, most of the tutorials used Stripe. Thus, I decided to go with the same. My thought here was - If I was unable to learn the implementation using the official documentation, I could always use these tutorials as an alternative. The ultimate goal was to get this feature on my eCommerce application. Thanks to Stripe for providing the most beautiful documentation that is beginner-friendly. Following is the implementation approach that I have used - React(FE) and Express(BE).

Here, I would like you to take a pause, go ahead and create an account with Stripe. By this, you would gain access to the public key and secret key details.

Building the checkout feature on React

Step 1: Install stripe-js

npm install @stripe/stripe-js
or
yarn add @stripe/stripe-js
Enter fullscreen mode Exit fullscreen mode

Further, you could make use of the useStripe, useElement hooks from @stripe/react-stripe-js. Although, we will restrain from this usage.

Step 2: Make a call to the API using Stripe's public key.

import { loadStripe } from "@stripe/stripe-js";

const stripePromise = loadStripe(`[public-key-details]`);

const redirectToStripePayment = async () => {
  try {
    setShowLoader(true);
    const response = await axios.post(`[server-api-url]`);
    if (response.data.success) {
      let stripe = await stripePromise;
      await stripe.redirectToCheckout({
        sessionId: response.data.id,
      });
    }
  } catch (err) {
    console.error(err);
  } finally {
    setShowLoader(false);
  }
};
Enter fullscreen mode Exit fullscreen mode

The loadStripe function asynchronously loads the Stripe.js script and initializes a Stripe object. Pass the returned Promise to Elements.
Once this promise is fulfilled, we redirect our application from the order-summary page to the Stripe payment gateway with a predefined UI template.

Setting up Stripe redirection on server

Step 3: The API called by the react application has been developed using Express (web framework for Node.js) as follows.

const stripe = require("stripe")(`[secret-key-details]`);

const stripeTransaction = async (req, res) => {
  const { cart, user } = req;

  // fetching the cart details of the user.
  let cartItems = await getCartItems(cart);

  // creating a new session for stripe transaction
  const session = await stripe.checkout.sessions.create({
    payment_method_types: ["card"],
    line_items: cartItems,
    mode: "payment",
    success_url: "https://[app_url]/payment-transaction?status=success",
    cancel_url: "https://[app_url]/payment-transaction?status=failure",
    customer_email: user.email,
  });
  res.json({ success: true, id: session.id, url: session.url });
};
Enter fullscreen mode Exit fullscreen mode

stripeTransaction function is invoked when the API call is made from redirectToStripePayment. Using the secret-key, stipe creates a new session object. Once the transaction is completed, it redirects to success_url or cancel_url based on the result.

Tadaa, there you go! You have successfully set up the payment gateway integration on your eCommerce app. Now, this application is wholesome ❤️

You can check out this functionality on the eCommerce app that I have developed - SupMart

If this article was helpful, please give this post a like. Let me know your thoughts in the comments.

Reach out to me on Twitter if you have any queries. Happy learning! 💻

Peace ✌

Top comments (0)