Integrating a payment gateway like Stripe with Node.js and Express involves a series of steps. Below is a step-by-step guide to help you set up payment processing in your app.
Step 1: Set Up Your Project
Create a new project folder:
mkdir payment-gateway-integration cd payment-gateway-integration
Initialize a new Node.js project:
npm init -y
Install necessary dependencies:
npm install express stripe dotenv
Step 2: Create Your Folder Structure
Create the following folder structure:
payment-gateway-integration/
|-- src/
| |-- views/
| |-- index.ejs
| |-- routes/
| |-- payment.js
| |-- app.js
|-- server.js
|-- .env
|-- .gitignore
|-- package.json
Step 3: Set Up Stripe
Create a Stripe account: Stripe Signup.
Obtain your Stripe API keys from the Stripe Dashboard.
Create a
.env
file in the root of your project and store your Stripe API keys:STRIPE_PUBLIC_KEY=your_public_key STRIPE_SECRET_KEY=your_secret_key
Step 4: Set Up Express Server
In app.js
, set up an Express server:
const express = require('express');
const path = require('path');
const dotenv = require('dotenv');
const stripe = require('stripe');
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.static(path.join(__dirname, 'src/public')));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
// Stripe setup
const stripeSecretKey = process.env.STRIPE_SECRET_KEY;
const stripeClient = stripe(stripeSecretKey);
// Routes
const paymentRoutes = require('./src/routes/payment');
app.use('/payment', paymentRoutes);
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Step 5: Create Payment Routes
In routes/payment.js
, set up routes for handling payments:
const express = require('express');
const router = express.Router();
const stripe = require('stripe');
router.get('/', (req, res) => {
res.render('index', { stripePublicKey: process.env.STRIPE_PUBLIC_KEY });
});
router.post('/charge', async (req, res) => {
const { stripeToken, amount, currency } = req.body;
try {
const charge = await stripe(process.env.STRIPE_SECRET_KEY).charges.create({
source: stripeToken,
amount,
currency,
});
res.render('success', { charge });
} catch (error) {
console.error(error);
res.render('error');
}
});
module.exports = router;
Step 6: Create Views
In views/
, create the following EJS templates:
index.ejs
: Display the payment form.success.ejs
: Display a success message after a successful payment.error.ejs
: Display an error message if the payment fails.
Step 7: Create Payment Form
In views/index.ejs
, create the payment form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Payment Gateway Integration</title>
<script src="https://js.stripe.com/v3/"></script>
<style>
body {
font-family: 'Arial', sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
form {
width: 300px;
text-align: center;
}
button {
background-color: #3498db;
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<form id="payment-form">
<div id="card-element"></div>
<button type="button" id="submit-button">Pay</button>
</form>
<script>
const stripePublicKey = '<%= stripePublicKey %>';
const stripe = Stripe(stripePublicKey);
const elements = stripe.elements();
const cardElement = elements.create('card');
cardElement.mount('#card-element');
const paymentForm = document.getElementById('payment-form');
paymentForm.addEventListener('submit', async (event) => {
event.preventDefault();
const { token, error } = await stripe.createToken(cardElement);
if (error) {
console.error(error);
} else {
// Send token to server for charging
fetch('/payment/charge', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
stripeToken: token.id,
amount: 1000, // Amount in cents (e.g., $10.00)
currency: 'usd',
}),
})
.then(response => response.json())
.then(data => {
if (data.charge && data.charge.paid) {
window.location.href = '/payment/success';
} else {
window.location.href = '/payment/error';
}
});
}
});
</script>
</body>
</html>
Step 8: Create Success and Error Pages
In views/success.ejs
and views/error.ejs
, create success and error pages:
<!-- views/success.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Payment Success</title>
<style>
body {
font-family: 'Arial', sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
</style>
</head>
<body>
<h1>Payment Successful!</h1>
</body>
</html>
<!-- views/error.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Payment Error</title>
<style>
body {
font-family: 'Arial', sans-serif;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
</style>
</head>
<body>
<h1>Payment Failed. Please try again.</h1>
</body>
</html>
Step 9: Run Your Application
In `server.js
, use the exported
app` to start the application:
const app = require('./src/app');
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Start the server:
node server.js
Visit http://localhost:3000 in your browser to see and interact with your payment form.
Congratulations! You've successfully integrated a payment gateway (Stripe) for processing payments in your Node.js and Express application. Customize the form and payment logic according to your specific requirements.