Let’s add a Checkout Feature in Vue.js for Our Ecommerce App
Tags: ecommerce, backend, java, vue
Published: 2021-03-15 18:05:49



In this tutorial, we will learn how to integrate payment gateway in VueJs using Stripe in our demo e-commerce app

![](https://cdn-images-1.medium.com/max/2612/1*p5oqDMy_BSSA33RaMDCeAA.png)

## Introduction

We are building an e-commerce app from scratch using Vue.js in the frontend and Java with Springboot for the backend. You can check out the first front-end tutorial of this series here.
[**Let’s Create a Frontend for our eCommerce App with Vue.js**
We are building a complete E-commerce application from scratch. Today we are going to add the Products feature.javascript.plainenglish.io](https://javascript.plainenglish.io/lets-create-vue-js-frontend-for-products-in-our-e-commerce-app-14cc8c3459c8)

A payment gateway is an important feature for an e-commerce app. In the previous tutorial, we integrated a payment gateway using Spring Boot and Stripe. Now we will build the front-end part of it like accepting the cart items and card details.
>  **If you want to refer to the backend part for the payment gateway use the below link.**
{% medium https://medium.com/javarevisited/lets-add-a-checkout-feature-in-spring-boot-for-our-ecommerce-app-72b12a7f3648 %}

## Live Demo
[**Webtutsplus E-Commerce App**](http://remotedevs.org:8000/)

![checkout demo gif](https://cdn-images-1.medium.com/max/2400/1*CgkD82Bw59ykyKfNJ7Jo_A.gif)

You can find the complete code at [Github](https://github.com/webtutsplus/ecommerce-vuejs).

## Pre-requisites

 1. Knowledge of **Vuejs**

 2. [Visual Studio Code](https://code.visualstudio.com/) **—**open-source (Recommended)

 3. A good browser **—**(Chrome — recommended)

## API we will be using

![](https://cdn-images-1.medium.com/max/2000/1*ReLfho3oS8lezT4BzWJcRw.png)

### getCartItems:

This is a get method and we will use it for storing the cart items in an array so that we can pass it as a request body to our backend API using Axios.

![](https://cdn-images-1.medium.com/max/2000/1*Bhq1mRF-d5tif8DKftCKCQ.png)

### checkoutList:

This is a post method to which as a response body we will pass the array of cart items. This method is responsible for generating the session id.

![post body if the cart contains these two products](https://cdn-images-1.medium.com/max/2000/1*szYoVN4Czj7Pj4WaTrfPPQ.png)

![We get the session id as a response](https://cdn-images-1.medium.com/max/2000/1*rUJf9A0OfV3qogQg7wuzCg.png)

### placeOrder:

This is a post method and if the payment is successful we will use it to add the order in the order table in our database. So as parameters to the Axios post method we will pass the token of the logged-in user and the session id generated.

![](https://cdn-images-1.medium.com/max/2206/1*7htabX3UJZCyVymEmClfKA.png)

![We pass session id and token as parameters and if the payment is successful the order is being placed](https://cdn-images-1.medium.com/max/2000/1*RhtmxF-EsXUQMj9hFqNhSQ.png)

## Project Structure

![](https://cdn-images-1.medium.com/max/2000/1*EHVevXyRYQb2N72aNRLBCA.png)

## Stripe

Stripe is one of the best ways to handle payments online and recently they released Stripe Elements. [Stripe Elements](https://stripe.com/elements) is their pre-built library of UI components that help you easily create your own checkout flows. This now makes it easier than ever to set up a custom payment form for your app.

In this tutorial, we will be using [Stripe.js](https://stripe.com/docs/js) for creating[ a payment gateway](https://stripe.dev/stripe-java/index.html).

First of all, we need our own Stripe test API key. So go ahead and [create an account ](https://dashboard.stripe.com/register?redirect=%2Fdocs%2Fjs%2Finitializing)on stripe and then from the dashboard get the API key for testing purposes. Store that key in the environment variable. To do this:

**Create a file** in the source directory with an extension .env

![](https://cdn-images-1.medium.com/max/2000/1*w6ZLrt0lrQn4-TZ2iQxQhw.png)

In this file **create a variable** that will store the API key.

Name the variable as VUE_APP_VARIABLENAME=YOURAPIKEY .

## The flow of the tutorial
>  Declaration of required data variables
>  Installation of stripe
>  Initialization and configuration of Stripe element
>  Implement Fetching the cart items method
>  Implement Passing the cart items to the backend API method and receiving the session id as a response
>  Navigating the user to success or failure payment component according to the status of Stripe payment

## Now let’s code

Create a folder named Checkout and in that folder create a vue file named Checkout which will hold the frontend logic for payment gateway.

![Checkout component](https://cdn-images-1.medium.com/max/3784/1*T7tgub3IwDERGn8UbpeLyg.png)

## 1.Creation of data variables

stripeAPIToken : stores the API key

stripe : a stripe element

Stripe Element is a collection of components with a variety of elements you can use to create checkout forms like buttons and inputs for collecting information from the user. The one we’re going to focus on is the card element. The card element lets you collect card information all within one element. It includes a dynamically-updating card brand icon as well as inputs for email, expiry, CVV, country name, cardholder name.

token : stores token of the user

sessionId : stores the generated sessionId by the Stripe

checkoutBodyArray : the response body we will be sent to our backend API

## 2. Installation of Stripe

Stripe element is a part of Stripe.js so we need to include the script by using the includeStripe method (that we will implement further) to which we pass the script source URL and since includeStripe is a callback function we call the configureStripe method which we will implement ahead. So when do we call this includeStripe method? When the component is rendered at that time we initialize this method.
{% gist https://gist.github.com/SudhanshuGulhane/e7e937e23e935bd8379c441fff69239e.js %}
i.e. in mounted method we call this function.
>  We are binding this so we have access to the local component’s methods inside the callback and we are calling configureStripe once everything has been loaded. We have not implemented that yet, but that’s next! That’s our callback method that will set up Stripe locally within the component.

Also, this checkout page will be rendered when the user clicks confirm order from the cart page. If you want to have a look then you may refer to [this](https://github.com/webtutsplus/ecommerce-vuejs/blob/master/src/views/Cart/Cart.vue). So when the user clicks confirm the order we call the checkout method in the cart component, in which we navigate the user to Checkout component using router method. And to this router method, we pass params id as the size of the cart (number of items in cart).

    checkout(){ 
    this.$router.push({ name: ‘Checkout’,params:{id:this.len}}) 
    }
    //from the Cart.vue
>  Now why do we pass the params id ?

We pass the id in order to check if the checkout page is being called if and only if the user clicks the confirm order button. Suppose the user is on some other page like the products page and from there he navigates to the checkout page by explicitly mentioning in the URL, the user won’t be able to because then the id by default will be passed as undefined. And in the mounted method of Checkout the component we first check that if the id is of the valid data type(in this case it should be string since we pass the id as params in the router method of Cart component) then only we render the Checkout component.

If the id is undefined i.e. user tries to navigate to checkout page without confirming the order he then will be redirected to Home page. Also if the cart is empty then the confirm order button is disabled but then also if the user tries to navigate to checkout page by explicitly mentioning in the URL, the user will be still navigated to Home page, because in that case also the id passed to the Checkout component will be undefined.

So the params id (size of cart) is passed from the Cart component to just confirm that whether or not the user is navigating to the Checkout component by confirming the order.

## 3.Initialization and configuration of Stripe element
>  Include Stripe.js dynamically

### **3.1 includeStripe**:

It will create a script tag and load our Stripe javascript file and add it to the head of our application. This method accepts 2 parameters, the URL of the file we are loading dynamically which will be the Stripe JS file, and a callback function that will run when the file is loaded.
{% gist https://gist.github.com/SudhanshuGulhane/4c84e91c52a57e151102abc6e2520ec5.js %}
Now, when we have the file properly loaded, we will callback, and Stripe will be configured.
>  Configure Stripe Element

### 3.2 **configureStripe:**

Remember in the mounted method we called the includeStripe method and then as a callback function we called the configureStripe method which is responsible for creating the Stripe object for the particular payment session.

The stripe we declared earlier as data variable will house a local instance of the Stripe object that is in the Stripe JS API that we loaded.
{% gist https://gist.github.com/SudhanshuGulhane/a5eacbddd2e3f921a8b31b3e2cd05ac4.js %}
## 4.Implement Fetching the cart items method

Firstly we need to store the cart items in an array and that we have declared as a data variable named checkoutBodyArray .
>  So how do we want to store the cart items in data variable?

Since the post API, we implemented in the [previous ](https://medium.com/javarevisited/lets-add-a-checkout-feature-in-spring-boot-for-our-ecommerce-app-72b12a7f3648)tutorial requires the list of cart items as the request body we store the cart items in the checkoutBodyArray .

### Fetching the cart items

We implement the getAllItems method which calls that get API /cart which returns the items in the cart as a response. So we store this response in checkoutBodyArray and pass this array as a request body to the checkout backend API.

We call the getAllItems method in the mounted method since we want to fetch the cart items when the Checkout component is rendered. **So call this method in the mounted method we implemented earlier.**
{% gist https://gist.github.com/SudhanshuGulhane/4e98cb836a38d291ce0fe654f70b8711.js %}
## 5.Implement Passing the cart items to the backend API method

### Passing the cart items to the backend API

Now since we have cart items in checkoutBodyArray we need to pass this to the post method. So we implement the function goToCheckout which calls the Axios post. After passing the cart items array to the backend API we get the session id as a response.

So we store the session id in the local storage and then we call the redirectToCheckout method of Stripe in which we store the session id we received from the response data in our sessionId which will redirect the user to a Stripe-hosted page to securely collect payment information. When a user completes their purchase, they are redirected back to our website.

This is how Stripe Checkout Page looks like

![](https://cdn-images-1.medium.com/max/3828/1*3g-ZnkCWZgeUMFYCGOqz5g.png)

## 6. Navigating the user to success or failure payment component according to the status of Stripe payment

Here we handle the result of payment i.e. If payment is successful then we add the order to the order table and if the payment fails then we don’t add that order and navigate the user to the order history page.

So where is the result of payment handled? We didn’t define it here in the frontend so if you remember, in the [previous ](https://medium.com/javarevisited/lets-add-a-checkout-feature-in-spring-boot-for-our-ecommerce-app-72b12a7f3648)backend tutorial (more precisely in the OrderService class)we defined the had set the success URL and failure URL as below.

    SessionCreateParams params = SessionCreateParams.*builder*()
            .addPaymentMethodType(SessionCreateParams.PaymentMethodType.*CARD*)
            .setMode(SessionCreateParams.Mode.*PAYMENT*)
            .setCancelUrl(failedURL)
            .addAllLineItem(sessionItemsList)
            .setSuccessUrl(successURL)
            .build();

And the failedURL and successURL were defined as

    String successURL = baseURL + "payment/success";
    String failedURL = baseURL + "payment/failed";

and the baseURL was the [frontend Vuejs URL](http://localhost:8081/) which we are working on.
>  Navigating the user to success or failure payment component according to the status of Stripe payment

Firstly we need to create a folder in the source directory named helper and in that folder, we create another folder named payment . In this folder create two vue components Failed.vue and Success.vue .

![Folder Structure](https://cdn-images-1.medium.com/max/2000/1*rxGIKDd9cGV7a2SjlrNPcw.png)

### Payment Success Component

So in the Success component, we create **data variables** token and session-id and define a **method** to **save** the current order to our database.

So in the saveOrder method we use the backend API /order/add

which we will discuss in the **next tutorial**.

To get an idea of what the API does refer to the API description above:
{% gist https://gist.github.com/SudhanshuGulhane/3bf6a7f364a9c5efdbf3a6f4c3d770c5.js %}
On success, we redirect the user to the order history component where the current and old orders are visible.

![](https://cdn-images-1.medium.com/max/3752/1*J8DcD2Q_dWEbZ6jYRFaUwg.png)

### Payment Failure Component

In this component, we remove the session id from local storage and do not save that order in the order table. Finally, we still navigate the user to the order history page but here the current order won’t be visible but the previous orders will be available.
{% gist https://gist.github.com/SudhanshuGulhane/3121efe913b7ca475fcdbfb2585c83a8.js %}
## Congratulations!!!

You have successfully implemented the frontend part of the payment gateway using Vuejs and Stripe. You can find the complete code at [Github](https://github.com/webtutsplus/ecommerce-vuejs).