In Part 1 of this series, you learned how the Browser Post API can be used for accepting payments with multiple payment options like credit cards or Apple Pay, and how to integrate it into your React application to create a payment request. The React app you created in that tutorial allows customers to purchase one item at a time. In this article, you'll learn how to modify your custom payment processing app to include a shopping cart so customers can purchase multiple items in one transaction.
A shopping cart makes your customers' shopping experience more convenient. They can add items to their cart as they browse, as well as pause and resume their selection process later. They can also organize and manage the products they want to purchase in one place so that they can make changes to their order before they complete their purchase.
For merchants, shopping carts offer the opportunity to upsell and cross-sell related or complementary products, and provide suggestions to customers. This can help increase sales and it also improves the customer's shopping experience.
In this tutorial, you'll implement a shopping cart in the React app you created in Part 1 of this series. You'll also learn how you can persist the cart to local storage to make sure users can access their cart if they leave and return to the page. Finally, you'll learn how to make it easy for the customer to edit their cart before making an online payment on the checkout page using their preferred payment method.
You can follow along with this Node.js GitHub repo for the back-end web service and this React repo for the front-end ecommerce storefront.


Setting Up the Development Environment
Creating the Cart Context
React Context API is a feature that allows you to share data between various components in your application. This helps to avoid the problem of prop drilling, which is when data is passed through multiple levels of components that don't need it, in order to get to a nested component.
To create the cart context, create a folder named context inside the src folder. In the context folder, create a new file named CartContext.jsx and paste the code below into it:
The CartProvider function contains a few variables and functions. The variables include the following:
- cartItems is an array that stores the details of the items in a cart. The initial value of this variable is read from local storage. If it does not exist in local storage, the initial value is set to an empty array.
- loading is a boolean value that is used to display a loading message during a post request for the terminal authorization code (TAC) token to the EPX servers.
The code also contains a useEffect function that persists the cart to local storage when the value of the cartItems array changes.
The CartProvider function also includes the following functions:
- getCartItemQuantity() is a helper function used to get the number of items of the specified id in the cart. If the specified item does not exist in the cart, the function returns zero. If the specified item exists in the cart, the function returns the value of the quantity key of the item object.
- addOneItemToCart() is used to add a single item to the cart. It uses the getCartItemQuantity() function to check if an item exists in the cart. If the item does not exist in the cart, it uses the spread operator to expand the array and add an object containing the values received as parameters and an initial quantity of one. Otherwise, the function loops through the objects in the cartItems array and increases the quantity of the specified item by one.
- removeOneItemFromCart() uses the getCartItemQuantity() method to check the quantity of the specified item. If the quantity is equal to one, the function calls the deleteItemFromCart() method to remove the item from the cart. Otherwise, it loops through the cartItems array and decreases the value of the quantity of the specified item by one.
- getTotalCost() loops through all the items in the cartItems array and returns the total cost of the items.
- getNumberOfCartItems() loops through all the items in the cartItems array and returns the total number of items.
Modifying the Product Page
In Part 1 of this series, you created the file src/pages/ProductPage.jsx, which contains a Purchase Now button that sends a post request for a TAC token when it's clicked. In this section, you will modify this button to add an item to the cart.
Open src/pages/ProductPage.jsx and replace the existing code with the following:
The code above uses the useContext() hook to load the loading and addOneItemToCart() context values from the CartContext. When the loading value is set to true, the page displays a modal showing the loading message. When the 'Add to Cart' button is clicked, the addOneItemToCart() function is called and the product ID, price, title, and image are passed as arguments.
Modifying the Payment Results Page
Next, you'll modify the src/pages/PaymentResults.jsx file to reset the cartItems array and remove the values saved in local storage once a payment is successfully processed.
Open the file and replace the existing code with the following:
Be sure to replace with the actual link of the Node API that you created and deployed in Part 1 of this series.
Creating the Cart Modal
In this section, you'll create the modal in which your shopping cart will be displayed.
Start by opening the src/components/NavBar.jsx file and replacing the existing code with the following:
The code above contains a show variable that is used to track the status of the modal. It also contains the handleClose() and handleShow() functions, which are used to control whether the modal should be displayed or not.
The code also displays a CartModal component, which you will create next. Create a file named CartModal.jsx inside the src/components folder and paste the following code into it:
The code above uses the useContext() hook to load getNumberOfCartItems(), getTotalCost(), setLoading(), and items from CartContext. The getNumberOfCartItems() function is used to display the total number of items in the cart next to the button used to control the modal status.
Modal.Footer contains the Continue Shopping button, which is used to close the modal and navigate to the home page, as well as the Checkout button, which is used to close the modal and call the getTAC() function.
As discussed in Part 1, the getTAC() function makes a POST request to the /getTAC route on the server and passes the total cart amount in the request body. It then receives a response, converts it to JSON, and checks whether the response contains the TAC. If the response contains a TAC value, it saves the TAC value and the total cart amount to local storage and navigates the user to the payment page. Otherwise, it informs the user that an error occurred.
Modal.Body informs the reader that there are no items in the cart if the length of the items array is less than one. Otherwise, it renders the MyCart component, which you will create next.
Be sure to replace in the code above with the actual link of the Node API link that you created and deployed in Part 1 of this series.
In the code above, localStorage.setItem('totalCost', totalCost) saves the total amount of the items in the cart to local storage. This means that you must modify the src/pages/Payment.jsx file to read this value. Open the src/pages/Payment.jsx and replace const AMOUNT = JSON.parse(localStorage.getItem('productPrice')).toFixed(2) with const AMOUNT = JSON.parse(localStorage.getItem('totalCost')).toFixed(2).
Finally, create a file named MyCart.jsx inside the src/components folder and paste the following code into it:
The code above uses the useContext() hook to load items, addOneItemToCart, removeOneItemFromCart, deleteItemFromCart, and getTotalCost from CartContext. The code loops through the items array and renders a table row for each item in the array. It also contains buttons to allow the user to edit the cart.
Providing the Cart Context to the React App
To ensure that your app can access the variables and functions in the CartContext.jsx file, open the App.jsx file and wrap your entire application with the CartProvider, as in the code below:
Deploying the React Application to Netlify
Your app is now ready to deploy!
Upload the React app code to GitHub and deploy it to Netlify.
As in Part 1, set the following environment variables in Netlify:
- VITE_CUST_NBR: this is provided by the North Integration team.
- VITE_DBA_NBR: this is provided by the North Integration team.
- VITE_INDUSTRY_TYPE: use E to specify that this transaction belongs to the ecommerce industry. You can learn more about the various values that you can use in this field in the EPX Data Dictionary, located in the Supplemental Resource Files folder.
- VITE_MERCH_NBR: this is provided by the North Integration team.
- VITE_TERMINAL_NBR: this is provided by the North Integration team.
- VITE_TRAN_CODE: use SALE.
Once your site is deployed, copy the app link and set it as the value for the PAYMENT_RESULT_PAGE_LINK environment variable in the deployed Node Express app. Remember to append /payment/result to the app link, and that changing an environment variable may automatically trigger a new deployment, depending on your deployment settings.
Demonstrating the Final App
When the deployment finishes, open your deployed app to test it. Click View Details on any product to open the product details page.
Click on 'Add to Cart' to add the item to the cart. Open another product and click on 'Add to Cart'. Then, click on 'My Cart' to view the items in the cart.
You can click +, -, and x to add, remove, and delete items from the cart.
To add more items to the cart, you can click on 'Continue Shopping'. Otherwise, click on 'Checkout' to navigate to the payment page. A loading message will display while the TAC token is being generated.
After the TAC token is successfully generated, the payment form will load. The form will be prefilled with the test card test details, as you saw in Part 1.
Click 'Submit' to make a payment request. This will post the payment details to EPX's servers and redirect you to the payment results page.
Conclusion
In Part 1 of this series, you used North's Browser Post API to set up embedded payments in a React ecommerce application. In this article, you learned how to add a shopping cart to your app.
Both embedded payments and a shopping cart make for a more convenient customer experience, which is great for increasing conversions and revenue. As mentioned in Part 1, using the Browser Post API for embedded payments also has the benefit of not storing sensitive payment data, such as credit card details, in the merchant's system. This reduces the risk of data breaches and makes Payment Card Industry (PCI) compliance much easier for merchants.
How To Get Started
Contact North's Sales Engineering team to learn more about how the Browser Post API and other tools can meet your business needs.