Comprehensive Guide to Integrating Stripe Billing Customer Portal with Next.js 14

Integrating the Stripe Billing Customer Portal with Next.js 14 involves setting up Stripe, handling webhooks, and managing subscription data. This guide covers each step with detailed code snippets, best practices, and insights to ensure an efficient integration process.

Setting Up Stripe and Customer Portal
  1. Create a Stripe Account

    • Sign up for a Stripe account.

    • Navigate to the Stripe Dashboard to create necessary products and configure the customer portal.

    • Create a pricing plan for your products.

  2. Configure the Customer Portal

    • Go to Stripe Dashboard > Settings > Billing > Customer Portal.

    • Configure options like update billing information, cancel subscriptions, and switch between pricing plans.

  3. Code Example: Adding a Customer Portal Button

    import axios from 'axios';
    import { useRouter } from 'next/router';
    
    const ManageSubscriptionButton = () => {
      const router = useRouter();
    
      const handleClick = async () => {
        const { data } = await axios.get('/api/portal');
        router.push(data.url);
      };
    
      return <button onClick={handleClick}>Manage Subscription</button>;
    };
    
    export default ManageSubscriptionButton;
    
Backend Integration: API Routes and Webhooks
  1. Setup API Route for Customer Portal Session

    • Create an API route to handle customer portal session creation.

    import { NextApiRequest, NextApiResponse } from 'next';
    import Stripe from 'stripe';
    
    const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, { apiVersion: '2022-08-27' });
    
    export default async (req: NextApiRequest, res: NextApiResponse) => {
      const session = await stripe.billingPortal.sessions.create({
        customer: req.body.customerId,
        return_url: 'https://your-website.com/account',
      });
      res.send({ url: session.url });
    };
    
  2. Webhook Handling for Subscription Changes

    • Setup webhook endpoint to listen for subscription updates and cancellations.

    import { NextApiRequest, NextApiResponse } from 'next';
    import Stripe from 'stripe';
    import { buffer } from 'micro';
    
    const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, { apiVersion: '2022-08-27' });
    
    export const config = { api: { bodyParser: false } };
    
    const webhookHandler = async (req: NextApiRequest, res: NextApiResponse) => {
      const buf = await buffer(req);
      const sig = req.headers['stripe-signature'];
    
      let event;
      try {
        event = stripe.webhooks.constructEvent(buf.toString(), sig, process.env.STRIPE_WEBHOOK_SECRET);
      } catch (err) {
        return res.status(400).send(`Webhook error: ${err.message}`);
      }
    
      if (event.type === 'customer.subscription.updated' || event.type === 'customer.subscription.deleted') {
        const subscription = event.data.object;
        // Handle subscription event (update your database, etc.)
      }
    
      res.json({ received: true });
    };
    
    export default webhookHandler;
    
Frontend Integration with Next.js 14
  1. Creating a Pricing Table Component

    import React, { useState, useEffect } from 'react';
    
    const StripePricingTable = () => {
      useEffect(() => {
        const script = document.createElement('script');
        script.src = 'https://js.stripe.com/v3/pricing-table.js';
        script.async = true;
        document.body.appendChild(script);
        return () => {
          document.body.removeChild(script);
        };
      }, []);
    
      return (
        <stripe-pricing-table
          pricing-table-id={process.env.NEXT_PUBLIC_STRIPE_PRICING_TABLE_ID}
          publishable-key={process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY}
        ></stripe-pricing-table>
      );
    };
    
    export default StripePricingTable;
    
  2. Managing Subscriptions through Customer Portal

    import axios from 'axios';
    
    const handleManageSubscription = async () => {
      const { data } = await axios.get('/api/portal');
      window.location.href = data.url;
    };
    
    return <button onClick={handleManageSubscription}>Manage Subscription</button>;
    
Conclusion and Call to Action

By integrating Stripe Billing Customer Portal with Next.js 14, you can offer a seamless billing experience to your users. This guide covered detailed steps and provided code examples for both frontend and backend integration processes.

8/13/2024
Related Posts
Integration of Stripe Subscription with Next.js 14 Application

Integration of Stripe Subscription with Next.js 14 Application

Maximize your app's potential with Next.js 14 and Stripe! Build efficient, subscription-based systems with our comprehensive guide. Get started with lightning fast development!

Read Full Story
Handling Stripe Subscription Callback with Next.js 14

Handling Stripe Subscription Callback with Next.js 14

Learn to seamlessly integrate Stripe with Next.js 14 for robust subscription handling. Our step-by-step guide ensures secure, reliable webhook handling.

Read Full Story
Setting up tRPC with Next.js 14

Setting up tRPC with Next.js 14

Unlock the full potential of Next.js 14 by integrating it with tRPC! Follow this comprehensive guide to create type-safe, efficient applications—perfect for developers looking to optimize.

Read Full Story