Building a Secure Online Payment System with React and Stripe
In today’s digital age, online payment systems have become an essential part of e-commerce. With the rise of online shopping, businesses need a secure and efficient way to process payments. In this tutorial, we’ll explore how to build a basic online payment system using React and Stripe.
Getting Started with Stripe
Before we dive into the tutorial, let’s get started with Stripe. Stripe is a popular online payment processing system that provides a suite of APIs for building custom payment solutions. To use Stripe, you’ll need to create a developer account and obtain your publishable and secret keys.
Setting Up the Payment Server
To process payments, we’ll need to set up a payment server using Express.js. Create a new project folder and install the required dependencies:
npm init -y
npm install express dotenv body-parser stripe
Create a new file called server.js
and add the following code:
“`
const express = require(‘express’);
const app = express();
const router = express.Router();
const port = process.env.PORT || 7000;
app.use(express.json());
app.use(router);
router.post(‘/stripe/charge’, postCharge);
app.listen(port, () => {
console.log(Server started on port ${port}
);
});
“
/stripe/charge` endpoint.
This code sets up an Express server that listens for payment requests on the
Creating the PostCharge Handler
Next, we’ll create the postCharge
handler function that processes payment requests. Create a new file called stripe.js
and add the following code:
“`
const stripe = require(‘stripe’)(process.env.STRIPESECRETKEY);
async function postCharge(req, res) {
try {
const { amount, source, receiptemail } = req.body;
const charge = await stripe.charges.create({
amount,
currency: ‘usd’,
source,
receiptemail,
});
res.status(200).json({ message: ‘Payment successful’, charge });
} catch (err) {
res.status(500).json({ message: ‘Payment failed’, error: err.message });
}
}
module.exports = postCharge;
“
postCharge` function that processes payment requests.
This code creates a new Stripe instance using the secret key and defines the
Building the Frontend
Now that we have the payment server set up, let’s build the frontend using React. Create a new file called App.jsx
and add the following code:
“`
import React, { useState, useEffect } from ‘eact’;
import { BrowserRouter, Route, Switch } from ‘eact-router-dom’;
import Products from ‘./Products’;
import Checkout from ‘./Checkout’;
function App() {
const [selectedProduct, setSelectedProduct] = useState(null);
const [history, setHistory] = useState(null);
useEffect(() => {
setHistory(createBrowserHistory());
}, []);
return (
);
}
export default App;
“
/
This code sets up a basic React app with two routes:and
/checkout. The
/route renders a list of products, while the
/checkout` route renders a checkout form.
Creating the Products Component
Create a new file called Products.jsx
and add the following code:
“`
import React from ‘eact’;
function Products({ onSelectProduct }) {
const products = [
{ id: 1, name: ‘Rubber Duck’, price: 9.99 },
{ id: 2, name: ‘Toy Car’, price: 19.99 },
];
return (
Products
-
{products.map((product) => (
- {product.name}
${product.price}
))}
);
}
export default Products;
“
onSelectProduct` function when clicked.
This code renders a list of products with a "Purchase" button that calls the
Creating the Checkout Component
Create a new file called Checkout.jsx
and add the following code:
“`
import React, { useState } from ‘eact’;
import { StripeProvider, Elements } from ‘eact-stripe-elements’;
import axios from ‘axios’;
function Checkout({ selectedProduct, history }) {
const [receiptUrl, setReceiptUrl] = useState(null);
async function handleSubmit(event) {
event.preventDefault();
const { token } = await stripe.createToken({
type: ‘card’,
card: {
number: ‘4242 4242 4242 4242’,
expmonth: 12,
expyear: 2025,
cvc: ‘123’,
},
});
const response = await axios.post('http://localhost:7000/api/stripe/charge', {
amount: selectedProduct.price * 100,
source: token.id,
receipt_email: '[email protected]',
});
setReceiptUrl(response.data.charge.receipt_url);
}
return (
{receiptUrl && (
)}
);
}
export default Checkout;
“`
This code renders a checkout form that captures payment information and submits it to the payment server using Axios. When the payment is successful, it displays a success message with a link to view the receipt.
Testing the App
To test the app, start the payment server by running node server.js
and then start the React app by running npm start
. Open a web browser and navigate to http://localhost:1234
to see the app in action.
That’s it! You’ve now built a basic online payment system using React and Stripe. Of course, this is just a starting point, and you’ll need to add more features and security measures to make it production-ready.