Integrating Stripe as a payment gateway enables secure and efficient online payment processing for your application. This comprehensive guide walks you through the complete integration process, from initial setup to production deployment.
If you haven't already, sign up for a Stripe account at stripe.com. You'll need to create a business account, which involves a straightforward process of entering your business details. Don't worry about getting everything perfect initially—all details can be updated later through the dashboard.

The dashboard includes multiple configuration tabs, including Branding, which we'll explore later for customizing your checkout page appearance.
Navigate to the Developers section in your Stripe dashboard to find your API keys. You'll need both keys, though for this integration we'll primarily use the Secret Key:

In the Stripe dashboard, navigate to the "Products" section to create products and their associated prices. This step is essential for subscription-based services or any recurring billing.

You can create multiple pricing tiers for a single product, which is particularly useful for different billing cycles (monthly, yearly) or plan types. After creating your products, copy the price ID from the product details page—you'll need this for your Checkout Sessions.

Install the Stripe SDK in your backend application using your preferred package manager:
npm install stripeOnce installed, you'll need to create several API endpoints in your backend application:
This endpoint creates a Checkout Session that redirects users to Stripe's secure hosted payment page:
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
const express = require("express");
const app = express();
app.post("/create-checkout-session", async (req, res) => {
const session = await stripe.checkout.sessions.create({
// Optional: Include customer ID if you have an existing customer
// Useful for tracking customers across your system
customer: undefined, // Replace with customer ID when available
customer_email: "customer@example.com", // Optional: Pre-fill customer email
mode: "subscription", // Use "payment" for one-time payments
allow_promotion_codes: true,
saved_payment_method_options: { payment_method_save: "enabled" },
client_reference_id: "user_123", // Your internal user identifier
line_items: [
{
price: "price_1RdLFBQExBUsbrwOi5bVyWon", // Your price ID from Stripe
quantity: 1,
},
],
success_url: "https://example.com/success",
cancel_url: "https://example.com/cancel",
subscription_data: {
trial_period_days: 14, // Optional: Add trial period
trial_settings: {
end_behavior: { missing_payment_method: "cancel" },
},
},
});
res.json({ url: session.url });
});`success_url` and `cancel_url` are the URLs where users will be redirected after a successful payment or if they cancel the checkout process, respectively.
Webhooks allow your application to respond to events from Stripe, such as successful payments or subscription changes. This endpoint processes these events securely:
app.post(
"/webhook",
express.raw({ type: "application/json" }), // Required for signature verification
async (req, res) => {
const sig = req.headers["stripe-signature"];
let event;
try {
event = stripe.webhooks.constructEvent(req.body, sig, process.env.STRIPE_WEBHOOK_SECRET);
} catch (err) {
console.error(`Webhook signature verification failed: ${err.message}`);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
// Process the event
switch (event.type) {
case "checkout.session.completed":
// First payment successful, subscription created
// ✅ Grant access to your product/service
const session = event.data.object;
console.log(`Payment for session ${session.id} was successful!`);
break;
case "checkout.session.expired":
// User abandoned the checkout process
// Optional: Send reminder email to complete purchase
break;
case "customer.subscription.updated":
// Customer changed their plan or subscription settings
// Optional: Update user interface to reflect changes
break;
case "customer.subscription.deleted":
// Subscription has been cancelled
// ❌ Revoke access to your product/service
console.log(`Subscription for customer ${event.data.object.customer} was cancelled.`);
break;
case "invoice.paid":
// Recurring payment successful
// ✅ Ensure continued access to your product/service
console.log(`Invoice ${event.data.object.id} was paid successfully.`);
break;
case "invoice.payment_failed":
// Payment failed (expired card, insufficient funds, etc.)
// Stripe automatically retries failed payments
// ❌ Consider revoking access or wait for retry success
break;
default:
console.warn(`Unhandled event type: ${event.type}`);
}
res.json({ received: true });
}
);Stripe sends numerous event types to webhooks. The events above cover the most common scenarios for subscription-based applications. You can find the complete list in the Stripe Events documentation.
The webhook endpoint requires `express.raw()` instead of `express.json()` because Stripe needs the raw request body to verify the webhook signature. If you're using `express.json()` globally, exclude the webhook endpoint:
app.use((req, res, next) => {
if (req.originalUrl === "/webhook") {
next(); // Skip JSON parsing for webhook
} else {
express.json()(req, res, next);
}
});After implementing your webhook endpoint, configure it in the Stripe dashboard:

When you are creating webhooks in Stripe, you need to listen for specific events:
To copy the webhook secret, click on the endpoint in the Stripe dashboard, and you'll find the secret under the "Signing secret" section. This secret is crucial for verifying the authenticity of incoming webhook requests.

You have two options for testing webhooks during development:
Use the Stripe CLI to forward events to your local server:
stripe listen --forward-to localhost:3000/webhookThis creates a temporary webhook endpoint and provides a unique webhook secret for testing. Note that this secret differs from production webhook secrets.
For testing with a publicly accessible endpoint, you'll need HTTPS. Tools like ngrok can expose your local server:
ngrok http 3000Use the generated HTTPS URL in your Stripe webhook configuration.
Allow customers to manage their subscriptions through Stripe's hosted customer portal:
app.post("/create-portal-session", async (req, res) => {
const session = await stripe.billingPortal.sessions.create({
customer: "cus_123456789", // Customer ID from your database
return_url: "https://example.com/account",
});
res.json({ url: session.url });
});The customer portal enables users to update payment methods, download invoices, and manage subscriptions without requiring additional development on your part.
Connect your frontend to the Checkout Session endpoint:
const createCheckoutSession = async () => {
try {
const response = await fetch("/create-checkout-session", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
});
const data = await response.json();
window.location.href = data.url;
} catch (error) {
console.error("Error creating checkout session:", error);
}
};Enhance your checkout experience by customizing the Stripe interface:
These customizations ensure a consistent brand experience throughout the payment process.

This guide has covered the essential components of a Stripe Checkout integration:
With these components in place, you can provide a secure, professional payment experience that scales with your business needs. Stripe's robust infrastructure handles the complexities of payment processing, allowing you to focus on your core product development.
Remember to test thoroughly in Stripe's test mode before going live, and monitor your webhook endpoints to ensure reliable event processing in production.