Author Photo
Tholumuzi Khuboni
Last updated on January 12, 2025

Build an E-Commerce Store with Paystack and React

Integrating Paystack into your e-commerce store allows you to securely handle online payments. In this guide, we'll walk you through the process of creating an e-commerce store in React and integrating Paystack for payments.

Why I Chose Paystack

Paystack is a leading payment solution in Africa that offers secure, reliable, and easy-to-integrate payment gateways. It supports multiple payment methods such as credit cards, debit cards, and mobile money, making it versatile for e-commerce platforms. Its developer-friendly documentation and SDKs streamline the integration process, ensuring smooth payment processing.

Challenges i have once faced and How I Solved Them

While integrating Paystack, I used to encounter challenges such as understanding the callback structure and handling API errors effectively. To address these, I thoroughly reviewed the Paystack Documentation, tested various scenarios in the sandbox environment, and implemented robust error-handling mechanisms in my code.

How Paystack is Used

Paystack allows developers to seamlessly integrate payments into their platforms. By using their APIs, You're able to:

For more details, you can explore their API Documentation, which provides comprehensive guides and examples for various use cases.

Table of Contents

Prerequisites

Before you begin, make sure you have the following:

Ensure your development environment is ready by running the following commands to verify:


node -v
npm -v

If these commands output the versions of Node.js and npm, you're good to go!

Overview

In this guide, you will learn how to build a fully functional e-commerce store using React and integrate Paystack for secure payment processing. The guide covers:

By the end of this tutorial, you will have an e-commerce platform capable of handling secure payments via Paystack, and you'll be ready to deploy it live.

1. Setting Up Your React Project

First, create a new React project using create-react-app:

npx create-react-app ecommerce-store

Explanation: This command uses npx to set up a new React project called ecommerce-store. The tool scaffolds the project with a standard structure and initial files.

Navigate to the project directory and start the development server:

cd ecommerce-store
npm start

Explanation: The cd ecommerce-store command changes the directory to the project folder, and npm start launches the app locally, opening it in your default browser.

React App Folder Structure

After running create-react-app, you'll see the following structure:


ecommerce-store/
├── node_modules/
├── public/
│   ├── index.html
│   └── favicon.ico
├── src/
│   ├── components/
│   ├── App.css
│   ├── App.js
│   ├── index.js
│   └── index.css
├── .gitignore
├── package.json
└── README.md

Key directories:

You'll add reusable components inside the src/components/ folder for better organization.

2. Building the E-Commerce UI

Create a reusable component to display individual products. This will help to separate concerns and make the code more maintainable. Here's an updated version that includes product images:

First, create a new file called ProductCard.js in the src/components/ folder to define the product card component:


<!-- src/components/ProductCard.js -->
import React from 'react';

const ProductCard = ({ product, addToCart }) => {
  return (
    <div className="card" style={{ width: '18rem' }}>
      <img src={product.image} className="card-img-top" alt={product.name} />
      <div className="card-body">
        <h5 className="card-title">{product.name}</h5>
        <p className="card-text">Price: ${product.price / 100}</p>
        <button className="btn btn-primary" onClick={() => addToCart(product)}>
          Add to Cart
        </button>
      </div>
    </div>
  );
};

export default ProductCard;

Now, update your main component to use this new ProductCard component:


<!-- src/index.js -->
import React, { useState } from 'react';
import ProductCard from './components/ProductCard';

const App = () => {
  const [cart, setCart] = useState([]);

  const products = [
    { id: 1, name: 'Product A', price: 1000, image: 'https://via.placeholder.com/150' },
    { id: 2, name: 'Product B', price: 2000, image: 'https://via.placeholder.com/150' },
  ];

  const addToCart = (product) => {
    setCart([...cart, product]);
  };

  return (
    <div>
      <h1>E-Commerce Store</h1>
      <div className="row">
        {products.map(product => (
          <div key={product.id} className="col-4">
            <ProductCard product={product} addToCart={addToCart} />
          </div>
        ))}
      </div>
      <h2>Cart</h2>
      {cart.map((item, index) => (
        <p key={index}>{item.name} - ${item.price / 100}</p>
      ))}
    </div>
  );
};

export default App;

Explanation:

4. Styling and Responsiveness

It's important to style your e-commerce app to ensure it provides a great user experience on all devices. Here’s how you can improve the UI and make it responsive using Bootstrap and custom CSS.

Making the Layout Responsive

Bootstrap comes with a built-in grid system, which makes your layout responsive on various screen sizes. Use the grid classes to create responsive layouts:


// In your index.js file, use Bootstrap's grid system:
<div className="row">
  {products.map(product => (
    <div key={product.id} className="col-12 col-md-4">
      <ProductCard product={product} addToCart={addToCart} />
    </div>
  ))}
</div>

Customizing the Product Card

You can also add custom CSS to improve the look and feel of the product cards. For example, use custom styles for the card's border, hover effect, etc.:


.card {
  border: 1px solid #ddd;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.card:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

Understanding and Building the App.js File

The App.js file serves as the central component of your React application. It acts as the entry point where other components are integrated and provides the overall structure of the application. In this section, we'll cover the basic structure of the App.js file for your e-commerce store.

Basic Structure of App.js

By default, App.js contains boilerplate code. Here's how it looks after setting up a new React project:


// Default App.js after setting up React
import React from 'react';
import './App.css';

function App() {
  return (
    

Welcome to React

); } export default App;

This structure serves as a starting point. You can replace it with your custom UI and logic as your app grows.

Customized App.js for the E-Commerce Store

In your e-commerce store, the App.js file will coordinate different components like the product listing and shopping cart. Below is an updated version of the App.js file:


import React, { useState } from 'react';
import ProductCard from './components/ProductCard';
import './App.css';

function App() {
  const [cart, setCart] = useState([]);

  // Sample product data
  const products = [
    { id: 1, name: 'Product A', price: 1000, image: 'https://via.placeholder.com/150' },
    { id: 2, name: 'Product B', price: 2000, image: 'https://via.placeholder.com/150' },
  ];

  // Function to add a product to the cart
  const addToCart = (product) => {
    setCart([...cart, product]);
  };

  return (
    <div>
      <h1>E-Commerce Store</h1>
      <div className="row">
        {products.map((product) => (
          <div key={product.id} className="col-12 col-md-4">
            <ProductCard product={product} addToCart={addToCart} />
          </div>
        ))}
      </div>
      <h2>Cart</h2>
      {cart.map((item, index) => (
        <p key={index}>{item.name} - ${item.price / 100}</p>
      ))}
    </div>
  );
}

export default App;

Explanation of the Code

Integrating Components

The ProductCard component is imported and used to render each product. This ensures the UI is modular and easy to maintain. Below is an example of how ProductCard integrates with App.js:


// src/components/ProductCard.js
import React from 'react';

const ProductCard = ({ product, addToCart }) => {
  return (
    <div className="card" style={{ width: '18rem' }}>
      <img src={product.image} className="card-img-top" alt={product.name} />
      <div className="card-body">
        <h5 className="card-title">{product.name}</h5>
        <p className="card-text">Price: ${product.price / 100}</p>
        <button className="btn btn-primary" onClick={() => addToCart(product)}>
          Add to Cart
        </button>
      </div>
    </div>
  );
};

export default ProductCard;

Styling the App

To enhance the visual appeal of your app, you can use Bootstrap classes or write custom CSS in App.css. For example:


.row {
  margin: 20px 0;
}

.card {
  border: 1px solid #ddd;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.card:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

Next Steps

With the basic structure of App.js set up, the next step is to integrate the Paystack payment gateway. Continue to the next section for a detailed guide on implementing Paystack in your app.

Setting Up Paystack Account

Before you can integrate Paystack into your e-commerce store, you need to create a Paystack account and generate the necessary API keys.

Step 1: Create a Paystack Account

Visit Paystack's official website and sign up for a new account. Follow the instructions to verify your email and complete the registration process.

Step 2: Generate Public and Private API Keys

Once logged in to your Paystack dashboard:

Step 3: Test Your Setup

To test the integration, use the Test Public Key to simulate payments. Make sure to use Paystack’s test card details, which can be found in the Documentation section of your Paystack account.

For example, use the following test card:

3. Integrating Paystack

To start using Paystack, first install the Paystack React library:

npm install react-paystack

Before going live, you should set up a sandbox environment to test payments. This allows you to simulate payments without using real money. Log in to your Paystack account and retrieve your public test key.

Next, replace 'your-public-key' with your test key in the code below:


import React from 'react';
import { PaystackButton } from 'react-paystack';

const PayButton = ({ amount }) => {
  const publicKey = 'your-test-public-key'; // Use the test public key here
  const email = 'customer@example.com';

  const handleSuccess = (reference) => {
    console.log('Payment successful!', reference);
  };

  const handleClose = () => {
    console.log('Payment closed');
  };

  const componentProps = {
    email,
    amount: amount * 100, // Convert amount to kobo
    publicKey,
    text: 'Pay Now',
    onSuccess: handleSuccess,
    onClose: handleClose,
  };

  return ;
};

export default PayButton;

In production, make sure to replace the test key with your live public key. For testing purposes, you can also use the Paystack "Test Card" provided in your dashboard. See Paystack’s documentation for detailed testing scenarios.

Key Takeaways:

4. Testing & Error Handling

It's crucial to thoroughly test your Paystack integration before going live, ensuring everything works smoothly. This section will guide you through the testing process and how to handle errors effectively in your app.

Step 1: Set Up the Testing Environment

Before starting, ensure you are using the Test Public Key and Test Secret Key provided by Paystack. These keys allow you to simulate real payments without processing actual transactions.

Use the following test card details to simulate different payment scenarios:

Step 2: Simulate a Successful Payment

To test a successful payment, use the card details for a successful transaction. When the user clicks the "Pay Now" button, Paystack’s payment dialog should appear. Complete the payment process by following the instructions, and verify that:


// Handle success in your Paystack component:
const handleSuccess = (transaction) => {
  console.log('Payment successful', transaction);
  // Store order details in your database here
};

Step 3: Simulate a Failed Payment

Now, test the case where a payment fails. Use the card number for a failed payment (e.g., insufficient funds). Verify that:


// Handle failure in your Paystack component:
const handleFailure = (error) => {
  console.error('Payment failed', error);
  alert('Payment failed. Please try again.');
};

Step 4: Handle Network Issues

Network interruptions may cause payment processes to fail. To simulate a network issue, disable your internet connection or throttle it. Check that the system properly handles the error and prompts the user to retry or provide an alternative action:


const handleNetworkError = (error) => {
  console.error('Network error', error);
  alert('Network error. Please check your connection and try again.');
};

Step 5: Monitor API Responses

During testing, you should monitor the API responses to ensure that the system behaves as expected. Paystack provides the following endpoints for transaction initialization and verification:

You can use tools like Postman to test Paystack’s endpoints directly and confirm that the system responds correctly during payment attempts.

Step 6: Review the Logs

After testing, check the logs for any error messages or anomalies. Paystack provides a detailed transaction log for all attempts, which you can review from your Paystack dashboard:

Step 7: Switch to Live Mode

Once you’ve completed testing and everything is working as expected, switch to live mode. Replace the test keys with your live API keys and perform a live transaction to ensure everything works as expected with real payments. Always test with a small amount to avoid any issues.

Optional Features

After you've successfully set up your e-commerce store and integrated Paystack, here are some optional features you can add to enhance your store:

1. Adding User Authentication

For a personalized experience, you can implement user authentication using services like Firebase Authentication or Auth0. This will allow customers to log in, view order history, and store their payment details securely.

2. Integrating Product Categories or Search Functionality

To make browsing easier, you can add a search bar or product categories to filter the product list:


// Example of filtering products by category:
const filteredProducts = products.filter(product => product.category === selectedCategory);

3. Viewing Order History

You can add an "Order History" page where users can view their past orders. This can be done by storing order data in a backend database (e.g., Firebase, MongoDB) and displaying it to users once they are logged in.

Deployment Guide

Once you've completed your app, it's time to deploy it to a hosting platform. Here are a few options:

To deploy your app, run:

npm run build

This will generate a build/ folder, which contains your static files ready to be hosted.

To set up a custom domain on platforms like Vercel or Firebase, follow their documentation to point your domain to the hosted app. You'll need to update DNS records to associate your domain with your app.

Conclusion

Congratulations! You've successfully created an e-commerce store with Paystack integration. This setup provides a secure and seamless payment experience for your customers.

For more advanced features, check out the following resources: