Learn step-by-step how to add secure Stripe payments into your web app, including setup, code examples, and best practices for a smooth checkout experience.
Table of content
Stripe is one of the most popular payment gateways for modern web apps due to its robust API, excellent documentation, and wide range of features. By integrating Stripe, you enable users to pay easily and securely while ensuring your web app meets industry standards.
npm install stripe
The PaymentIntent is a core Stripe concept for handling dynamic payments. Here’s how to set it up in a Node.js/Express backend:
const express = require('express');
const Stripe = require('stripe');
const stripe = Stripe('YOUR_SECRET_KEY');
const app = express();
app.use(express.json());
app.post('/create-payment-intent', async (req, res) => {
const { amount, currency } = req.body;
try {
const paymentIntent = await stripe.paymentIntents.create({
amount,
currency,
payment_method_types: ['card'],
});
res.json({ clientSecret: paymentIntent.client_secret });
} catch (error) {
res.status(400).json({ error: error.message });
}
});
Note: Replace YOUR_SECRET_KEY
with your real secret key. Always keep secret keys off the client side.
On the client side, Stripe provides Stripe.js and Elements for secure payments UI.
<script src="https://js.stripe.com/v3/"></script>
<form id="payment-form">
<div id="card-element"></div>
<button id="submit">Pay</button>
<div id="error-message"></div>
</form>
<script>
const stripe = Stripe('YOUR_PUBLISHABLE_KEY');
const elements = stripe.elements();
const card = elements.create('card');
card.mount('#card-element');
document.querySelector('#payment-form').addEventListener('submit', async (e) => {
e.preventDefault();
const {clientSecret} = await fetch('/create-payment-intent', {
method: 'POST', headers: {'Content-Type': 'application/json'},
body: JSON.stringify({amount: 1999, currency: 'usd'})
}).then(res => res.json());
const {error, paymentIntent} = await stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: card
}
});
if (error) {
document.getElementById('error-message').textContent = error.message;
} else if (paymentIntent.status === 'succeeded') {
alert('Payment successful!');
}
});
</script>
Replace YOUR_PUBLISHABLE_KEY
with your Stripe publishable key.
Integrating Stripe into your web app is straightforward if you follow best practices and leverage their robust tools. With a secure payment flow, you’ll boost user trust and keep your transactions running smoothly.