Integrating Stripe in React Applications: A Complete Guide
As web development continues to evolve, integrating payment systems into applications remains a critical aspect—especially for e-commerce and subscription-based platforms. One of the leading payment gateways is Stripe, known for its developer-friendly API and robust security features. In this article, we’ll explore how to effectively integrate Stripe into a React application, providing a step-by-step guide to setting up payments securely.
What Is Stripe?
Stripe is a payment processing platform that allows you to accept online payments. By offering a comprehensive set of tools and libraries, Stripe allows businesses to focus on their core activities while managing payment complexities. Developers can customize payment workflows, streamline transactions, and ensure compliance with security standards.
Why Choose Stripe for Your React Application?
- Easy to Integrate: Stripe provides excellent documentation and SDKs that make it easy to integrate with various frameworks, including React.
- Robust Security: Stripe offers built-in compliance with PCI regulations and provides tools for secure data handling.
- Customizable: With extensive APIs, you can create custom workflows tailored to your application’s needs.
- Global Reach: Stripe supports multiple currencies and payment methods, making it ideal for businesses looking to scale.
Prerequisites
Before we begin, ensure you have the following:
- A Stripe account (Sign up at stripe.com)
- A React application set up (You can create one using
create-react-app) - Basic knowledge of React and JavaScript
Setting Up Your Project
Let’s start with a new React application setup.
npx create-react-app my-stripe-app
cd my-stripe-app
npm install @stripe/react-stripe-js @stripe/stripe-js
Here’s what each package does:
- @stripe/react-stripe-js: A React wrapper for Stripe’s JavaScript library.
- @stripe/stripe-js: The core Stripe.js library for handling payments.
Creating a Stripe Account and Getting API Keys
1. Go to the Stripe Dashboard and log into your account.
2. Navigate to the “Developers” section and then “API Keys”. Here you’ll find your Publishable key and Secret key. Keep these for later use.
Building a Payment Form
Let’s create a simple payment form in our React application to take card details.
Payment Form Component
import React from 'react';
import { CardElement } from '@stripe/react-stripe-js';
const PaymentForm = () => {
return (
{/* Stripe’s CardElement will handle card input */}
);
};
export default PaymentForm;
The CardElement component handles the card input and automatically manages the inputs for card number, expiry date, and CVC.
Setting Up Stripe Provider
Your Stripe components should be wrapped in a StripeProvider to share the API keys.
import React from 'react';
import ReactDOM from 'react-dom';
import { Elements } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
import App from './App';
const stripePromise = loadStripe('YOUR_PUBLISHABLE_KEY');
ReactDOM.render(
,
document.getElementById('root')
);
Make sure to replace YOUR_PUBLISHABLE_KEY with your actual Stripe Publishable Key.
Handling Payment Submission
Next, let’s handle the form submission and create a payment intent.
import React, { useState } from 'react';
import { CardElement, useStripe, useElements } from '@stripe/react-stripe-js';
const PaymentForm = () => {
const stripe = useStripe();
const elements = useElements();
const [error, setError] = useState(null);
const [success, setSuccess] = useState(null);
const handleSubmit = async (event) => {
event.preventDefault();
const cardElement = elements.getElement(CardElement);
const { error, paymentIntent } = await stripe.createPayment({
payment_method: {
card: cardElement,
},
});
if (error) {
setError(error.message);
setSuccess(null);
} else {
setSuccess(`Payment successful! ID: ${paymentIntent.id}`);
setError(null);
}
};
return (
{error && {error}
}
{success && {success}
}
);
};
export default PaymentForm;
Backend Setup for Payment Processing
To securely handle payments, you will need a backend server to create payment intents and manage sensitive data. Here, we’ll provide a brief example using Express.js.
Installing Necessary Packages
npm install express cors body-parser stripe
Creating the Express Server
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const stripe = require('stripe')('YOUR_SECRET_KEY');
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.post('/create-payment-intent', async (req, res) => {
const { amount } = req.body;
try {
const paymentIntent = await stripe.paymentIntents.create({
amount,
currency: 'usd',
});
res.json({ clientSecret: paymentIntent.client_secret });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(5000, () => console.log('Server running on port 5000'));
Replace YOUR_SECRET_KEY with your actual Stripe Secret Key. This endpoint will be used to create a payment intent when the user submits their payment information.
Connecting Frontend and Backend
Now, let’s connect our React application to the backend to create a payment intent:
const handleSubmit = async (event) => {
event.preventDefault();
const cardElement = elements.getElement(CardElement);
const response = await fetch('http://localhost:5000/create-payment-intent', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ amount: 1000 }) // $10.00
});
const { clientSecret } = await response.json();
const { error, paymentIntent } = await stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: cardElement,
},
});
if (error) {
setError(error.message);
setSuccess(null);
} else {
setSuccess(`Payment successful! ID: ${paymentIntent.id}`);
setError(null);
}
};
Conclusion
Integrating Stripe into your React application provides a robust solution for handling payments. Whether you’re creating a simple payment form or developing a complex e-commerce platform, Stripe offers the tools needed to ensure a smooth payment process.
With this guide, you should be able to set up Stripe integration effectively. Always remember to test everything thoroughly, handle errors gracefully, and keep your API keys secure.
Happy coding!
