Complete Guide to Stripe Checkout Integration

  • Tue Jul 01 2025
  • Jazim Abbas

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.

What we'll cover:

  • Setting up Stripe
  • Configuring the SDK
  • Creating Checkout Sessions
  • Handling webhooks
  • Testing the integration
  • Customization options
  • Conclusion

Setting Up Stripe

Create a Stripe Account

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.

Obtain API Keys

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:

  • Publishable Key: Used in frontend applications to tokenize card data (not needed for server-side Checkout Sessions)
  • Secret Key: Used in backend applications to process payments and create sessions

Create Products and Prices

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.

Configuring the SDK

Install the Stripe SDK in your backend application using your preferred package manager:

npm install stripe

Once installed, you'll need to create several API endpoints in your backend application:

  • A Checkout Session endpoint
  • A Webhook endpoint
  • A Customer Portal Session endpoint (optional)

Creating a Checkout Session

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.

Creating a Webhook Endpoint

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.

Important Note About Express Middleware

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);
  }
});

Configuring Webhooks in Stripe

After implementing your webhook endpoint, configure it in the Stripe dashboard:

  • Navigate to Developers → Webhooks
  • Add a new endpoint with your webhook URL (e.g., `https://yourdomain.com/webhook`)
  • Select the events you want to receive
  • Copy the webhook signing secret to your environment variables

When you are creating webhooks in Stripe, you need to listen for specific events:

  • `checkout.session.completed`: Indicates a successful payment and subscription creation.
  • `checkout.session.expired`: Indicates the user abandoned the checkout process.
  • `customer.subscription.updated`: Indicates a change in the customer's subscription.
  • `customer.subscription.deleted`: Indicates the customer's subscription was cancelled.
  • `invoice.paid`: Indicates a successful recurring payment.
  • `invoice.payment_failed`: Indicates a failed payment attempt.

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.

Testing Your Integration

You have two options for testing webhooks during development:

Option 1: Stripe CLI (Recommended for Local Development)

Use the Stripe CLI to forward events to your local server:

stripe listen --forward-to localhost:3000/webhook

This creates a temporary webhook endpoint and provides a unique webhook secret for testing. Note that this secret differs from production webhook secrets.

Option 2: Public HTTPS Endpoint

For testing with a publicly accessible endpoint, you'll need HTTPS. Tools like ngrok can expose your local server:

ngrok http 3000

Use the generated HTTPS URL in your Stripe webhook configuration.

Customer Portal Session (Optional)

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.

Frontend Integration

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);
  }
};

Customization

Enhance your checkout experience by customizing the Stripe interface:

  • Navigate to Settings → Branding in your Stripe dashboard
  • Upload your logo and set brand colors
  • Configure business information

These customizations ensure a consistent brand experience throughout the payment process.

Conclusion

This guide has covered the essential components of a Stripe Checkout integration:

  • Setup: Account creation, API keys, and product configuration
  • Implementation: Checkout Sessions, webhook handling, and customer portal
  • Testing: Local development and production testing strategies
  • Customization: Branding and user experience optimization

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.