In this tutorial, we will learn, how you can add a credit card payment system with Stripe by using React.
The implementation process is easy and at the end of this tutorial, you will be able to create a credit card payment system with Stripe in React.
Credit card payment system with Stripe in React
Setting up the environment is the most important part of any application development because, without a proper environment, you can not implement any functionality.
For the front end, we need to install some important packages. But at first, we will create a folder named stripe-react
and inside this folder, we will create two folders as client
and server
.
The client folder will be used for implementing the frontend part and the server folder will be used for implementing the backend part.
Though we will not cover the backend
portion in this tutorial, it is good to know about the folder structure of a project. Let’s see the below image of our project folders:
This is what our project folders will look like. Now let’s implement the frontend functionality inside the client folder and to do so, at first, we need to change our directory to the client folder.
For the first time, when you open the stripe-react folder in your VScode the directory will be set as the stripe-react, and to change it you need to run a command in your terminal as cd client Now, we are ready to implement frontend functionality in our client folder.
we need to write a command in the terminal that will create a demo react app for us. See the below command:
npx create-react-app .
With the help of this command, we will be able to install react and its necessary packages in our client folder.
Here, npx create-react-app
is the main command, and the “dot(.)”
represents that the app will be created in the present folder that is the client
.
It will take some time to install all the packages for you and it depends on the internet connection. Make sure that you have connected your computer to the internet.
To add a credit card payment system with Stripe, we need to install a few important packages.
We will use the npm
command in our terminal to install those packages. See the below command :
npm install --save @stripe/react-stripe-js @stripe/stripe-js axios
These packages will help us to connect our application with Stripe and the Axios will help us to connect the frontend application with the backend.
After the installation process has been finished, it will create a few files for you but all those files will not be necessary to complete the tutorial.
So, you may simply remove them.
We have already done that and also create a few important files.
After doing so, the file structure will look something like the below image:
You will find some extra files in your src
folder but to complete this project those files will not be necessary.
Now we are ready to work with React and implement the frontend functionality.
Environment setup for Stripe
We are almost ready to work on the main part of this tutorial but we need to do one more thing.
We need to set up the Stripe environment and to do so we need to visit the official Stripe site.
For the first time when you visit this website, it will ask you to log in or create a new account.
You have to create a new account with your own credentials and also need to verify the email account that you have added.
After creating an account successfully in Stripe, you can see the homepage.
You need to click on the developer button that exists on the right side of the website. See the below image:
Here, on the left side, you will notice a sidebar menu and from there you have to click on the API Keys
Then you will get two keys – one is the Publishable key
and the other one is the Secret key
The secret key must be secret and you don’t need to reveal it with others.
If you click on the reveal test key then you will get something like the publishable key and later on in the project you will use it. Now we are completely ready to implement the core functionality of our application.
Create PaymentOption Component
In the project folder image, you may notice that we have already created a components
folder and inside that folder, we have created two files, one is the PyamentOption.js
and another one is the StripeContainer.js
In this section, we will implement the Payment Option functionality. See the below code to understand it more clearly:
import { CardElement, useElements, useStripe } from "@stripe/react-stripe-js"
import axios from "axios"
import React, { useState } from 'react'
const CARD_OPTIONS = {
iconStyle: "solid",
style: {
base: {
iconColor: "#c4f0ff",
color: "#fff",
background: "black",
fontWeight: 700,
fontFamily: "Roboto, Open Sans, Segoe UI, sans-serif",
fontSize: "16px",
fontSmoothing: "antialiased",
},
invalid: {
iconColor: "red",
color: "white"
}
}
}
export default function PaymentForm() {
const [confirm, setConfirm ] = useState(false)
const stripe = useStripe()
const elements = useElements()
const handleSubmit = async (e) => {
e.preventDefault()
const {error, paymentMethod} = await stripe.createPaymentMethod({
type: "card",
card: elements.getElement(CardElement)
})
if(!error) {
try {
const {id} = paymentMethod
const response = await axios.post("http://localhost:5000/pay", {
amount: 1000,
id
})
if(response.data.success) {
setConfirm(true)
}
} catch (error) {
console.log("Error", error)
}
} else {
console.log(error.message)
}
}
return (
<>
{!confirm ?
<form onSubmit={handleSubmit}>
<fieldset className="FormGroup">
<div className="FormRow">
<CardElement options={CARD_OPTIONS}/>
</div>
</fieldset>
<button>Pay</button>
</form>
:
<div>
<h2>Thank You! Enjoy Your Ice-Cream</h2>
</div>
}
</>
)
}
Here, we simply import all the necessary stuff that we have need. We also import Axios and handle the backend request.
Your backend port number may be different from ours. It will not be a problem. All you need to do is to follow the procedure. We also use some CSS styles.
You can use styles based on your own interest.
Finally, we wrap up our code into a JavaScript ternary operator, that will execute our code based on the logic. Next step we will create another component named StripeContainer
Create StripeContainer Component
In this component, we will simply use the stripe’s prebuilt UI elements and to do so we need to import elements from the stripe package that we have installed before. It will give us a better and more responsive UI and we do not need to write a lot of code. If you are familiar with bootstrap then it will be easy to understand the implementation of this part. See the below code :
import { Elements } from "@stripe/react-stripe-js"
import { loadStripe } from "@stripe/stripe-js"
import React from "react"
import PaymentOption from "./PaymentOption"
const PUBLIC_KEY = "pk_test_51Kc8iQB6GMJd3WhhN9w1VNKhKol74KfnP3GiXpQ7YRHkL5onDGcPNJur2fao2p6oTi1uHT3KZevBHMtnhtEge8hR00QEOI9TxP"
const stripeTestPromise = loadStripe(PUBLIC_KEY)
export default function StripeContainer() {
return (
<Elements stripe={stripeTestPromise}>
<PaymentOption />
</Elements>
)
}
Here, you can see that we have imported our necessary elements and then imported another component that has already existed in the same file.
and we have also stored our public key into the constant PUBLIC_KEY
Finally, we used our PaymentOption
component inside the elements.
Implement Entry Point
Every react project needs an entry point from where all the codes will execute.
By default, it is App.js
and we will not change it and simply integrate our codes in this file. See the below code example where we have done this:
import { useState } from 'react';
import './App.css';
import IceCream from './assets/image/icecream.jpg'
import StripeContainer from './components/StripeContainer';
function App() {
const [showItem, setShowItem] = useState(false);
return (
<div className='App'>
<img src={IceCream} alt='Ice-Cream' />
<h1>The Ice-Cream Store</h1>
{showItem ? (
<StripeContainer />
) : (
<>
<h3>$5.00</h3>
<button onClick={() => setShowItem(true)}>Purchase Ice-Cream</button>
</>
)}
</div>
);
}
export default App;
Here, at first, we have imported react and CSS files and then we have imported an image that has been stored in our local directory and we have simply recognized the path where the image is located.
Later on, as before we have wrapped our code with a ternary operator that will execute our code based on the logic. Now it’s time to see the output in the next section.
Output
To check the output, we need to run our application, and to do so we simply run npm start
command in our terminal, and if everything is okay then our code will be executed and it will run on port no 3000. Let’s see the output in the below section:
Here, you can see that a beautiful image has appeared and below the store name has been shown with the price of the Ice-Cream and finally a button for buying the Ice-Cream.
Let’s click on the button and see what happens.
Here, you can see that the moment we have clicked on the Purchase Ice-Cream
button, it directly take us to the process of our payments.
That expects a Card number with other details. Finally, a Pay
exists that will process our payments if everything is okay and if there is an error with the credentials then it will show an error message instead of processing the payment.
But, now it will do nothing because we didn’t implement the backend functionality.
Conclusion
If you have come this far then you may congratulate yourself because from now you will be able to add a payment system with stripe by using React.
In this whole tutorial, we have focused on the frontend part and learned how we can work with stripe and create a beautiful element by using react-stripe.
You may also change the layout and make the payment UI based on your own need.
To do so, you need to explore the documentation that has been provided by stripe itself.
To learn more, you may visit React Stripe.js reference
and Stripe Elements
To learn and be a master of a particular thing, you need to make your hands dirty with the code.
The more you practice, the more things will be easy for you.
This tutorial will give you an overall idea and a quick kick-start to work with the payment system.
The next step for you is to try to implement the backend also and create a complete functionality of the Stripe payment process.
If you face any issue with the implementation feel free to comment, I will try to solve your problem.