In this section, we'll delve into the powerful world of Stripe subscriptions, enabling you to build robust recurring billing models directly within your Next.js application. This involves creating subscription plans, associating them with customers, and managing their lifecycle. We'll cover the essential steps to get your subscription system up and running.
The core of Stripe subscriptions lies in two main entities: Products and Prices. A Product represents the service or good you're selling (e.g., 'Pro Plan', 'Basic Access'), and a Price defines the cost and billing interval for that product (e.g., '$10/month', '$100/year'). You'll typically set these up in your Stripe dashboard, but Stripe's API allows for programmatic creation as well.
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
async function createProductAndPrice() {
try {
// Create a Product
const product = await stripe.products.create({
name: 'Premium Subscription',
description: 'Unlock all features for a premium experience.',
});
// Create a Price for the Product
const price = await stripe.prices.create({
product: product.id,
unit_amount: 2000, // $20.00 in cents
currency: 'usd',
recurring: {
interval: 'month',
},
});
console.log('Product created:', product);
console.log('Price created:', price);
return { product, price };
} catch (error) {
console.error('Error creating product and price:', error);
throw error;
}
}Once you have your products and prices defined, the next crucial step is to create a Stripe Customer. A customer object in Stripe represents your user, and it's where their subscription information will be attached. It's good practice to create a customer when a user first signs up or as part of the checkout flow.
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
async function createStripeCustomer(email, name) {
try {
const customer = await stripe.customers.create({
email: email,
name: name,
// You can add other metadata here, like your internal user ID
metadata: {
userId: 'user_123',
},
});
console.log('Stripe Customer created:', customer);
return customer;
} catch (error) {
console.error('Error creating Stripe customer:', error);
throw error;
}
}