구독 관리
요금제 생성과 고객 구독 주기를 포함하여 Stripe 구독을 사용한 반복 결제 로직을 구현합니다.
구독 관리은(는) CoddyKit의 무료 AI Powered SaaS: Stripe + Auth + Billing + Deploy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Powered SaaS: Stripe + Auth + Billing + Deploy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Powered SaaS: Stripe + Auth + Billing + Deploy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Recurring Billing?
Welcome to subscription management! For many SaaS businesses, recurring revenue is crucial. It provides predictable income and helps foster long-term customer relationships.
Stripe Subscriptions make it easy to implement recurring billing without handling complex payment logic yourself, allowing you to focus on your product.
Products & Prices Revisited
Before creating a subscription, you need to define what customers are subscribing to. Stripe uses two key concepts that work together:
- Products: These represent the service or good you offer (e.g., "Basic Plan", "Premium AI Access").
- Prices: These define how much and how often you charge for a product (e.g., "$10/month", "$100/year").
A single product can have multiple prices, offering flexibility for different billing cycles or tiers.
Define Your SaaS Product
First, let's create a Stripe Product. This object represents your core service or plan, like a "Pro AI Plan" for your SaaS. You can create products via the Stripe Dashboard or programmatically.
Here's how to create a product using the Stripe Python API:
import stripe
stripe.api_key = "sk_test_YOUR_SECRET_KEY" # Use your actual test key
try:
product = stripe.Product.create(
name="Pro AI Plan",
description="Access to advanced AI features and higher usage limits."
)
print(f"Product created: {product.id}")
print(f"Name: {product.name}")
except stripe.error.StripeError as e:
print(f"Error creating product: {e}")Set Your Recurring Price
Once you have a Product, you define its Price. For subscriptions, this price must be recurring. You specify the currency, amount (in cents), and the billing interval (e.g., month, year).
Let's create a monthly recurring price for our "Pro AI Plan" (replace PRODUCT_ID with the ID from the previous step):
import stripe
stripe.api_key = "sk_test_YOUR_SECRET_KEY" # Use your actual test key
# IMPORTANT: Replace with an actual product ID from your Stripe account
# Example: 'prod_Nq7sN8sN8sN8sN'
PRODUCT_ID = "prod_YOUR_PRODUCT_ID"
try:
price = stripe.Price.create(
unit_amount=2000, # $20.00 in cents
currency="usd",
recurring={"interval": "month"},
product=PRODUCT_ID,
)
print(f"Price created: {price.id}")
print(f"Amount: ${price.unit_amount / 100:.2f} / {price.recurring.interval}")
except stripe.error.StripeError as e:
print(f"Error creating price: {e}")Preparing Your Customer
Every subscription in Stripe is tied to a Customer object. This object holds essential details like their email, payment methods, and billing history.
When a user signs up for your SaaS, you'll typically create a Stripe Customer for them. If they already exist, you'll retrieve their existing customer ID to associate new subscriptions.
Registering a New Customer
To link a user to a subscription, we first need to create a Customer object in Stripe. This is a one-time process for each unique user in your system.
Here's how to create a new customer in Stripe:
import stripe
stripe.api_key = "sk_test_YOUR_SECRET_KEY" # Use your actual test key
try:
customer = stripe.Customer.create(
email="janedoe@example.com",
name="Jane Doe",
description="Customer for Pro AI Plan"
)
print(f"Customer created: {customer.id}")
print(f"Email: {customer.email}")
except stripe.error.StripeError as e:
print(f"Error creating customer: {e}")Activating the Subscription
Now for the main event! With a Product, a Recurring Price, and a Customer, you can create a subscription. This action links the customer to the chosen plan and initiates recurring billing.
When creating a subscription, you specify the customer ID and the price ID. Stripe handles the recurring billing and invoicing automatically.
import stripe
stripe.api_key = "sk_test_YOUR_SECRET_KEY" # Use your actual test key
# IMPORTANT: Replace with actual customer ID (e.g., 'cus_Nq7sN8sN8sN8sN')
CUSTOMER_ID = "cus_YOUR_CUSTOMER_ID"
# IMPORTANT: Replace with actual price ID (e.g., 'price_1Nq7sN8sN8sN8sN')
PRICE_ID = "price_YOUR_PRICE_ID"
try:
subscription = stripe.Subscription.create(
customer=CUSTOMER_ID,
items=[{"price": PRICE_ID}],
# 'expand' helps fetch related objects like the initial invoice
expand=["latest_invoice.payment_intent"]
)
print(f"Subscription created: {subscription.id}")
print(f"Status: {subscription.status}")
if subscription.latest_invoice and subscription.latest_invoice.payment_intent:
print(f"Initial Payment Intent Status: {subscription.latest_invoice.payment_intent.status}")
except stripe.error.StripeError as e:
print(f"Error creating subscription: {e}")Lifecycle of a Subscription
Stripe subscriptions go through various statuses indicating their current state. Monitoring these statuses is key for managing user access and support:
trialing: Customer is in a trial period.active: Subscription is active and billing successfully.past_due: A payment failed, and Stripe is attempting to recover.canceled: Subscription has been canceled.unpaid: Subscription has exhausted its dunning attempts and is unpaid.
Managing Active Subscriptions
Customers might want to upgrade, downgrade, or cancel their subscriptions. Stripe's API provides methods to handle these actions gracefully:
- Updating: Change the price, quantity, or add/remove items using
stripe.Subscription.modify(). - Cancelling: End a subscription immediately or at the end of the current billing period using
stripe.Subscription.cancel().
These actions often trigger webhooks, which are crucial for keeping your application in sync with Stripe!
Subscription Flow Quiz
Which of the following are essential steps in creating a new recurring subscription for a user in Stripe?
Recap: Your First Subscriptions
Great job! You've learned how to implement recurring billing with Stripe Subscriptions.
- We covered creating Products and Prices that form the basis of your subscription plans.
- We explored managing Customers, who are the recipients of these subscriptions.
- And we successfully created a Subscription, understanding its lifecycle and basic management.
Next, we'll dive into handling Stripe Webhooks to react to payment events and subscription changes in real-time, making your application dynamic and responsive!
자주 묻는 질문
“구독 관리” 강의는 무료인가요?
네 — “구독 관리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Powered SaaS: Stripe + Auth + Billing + Deploy 강의 전체를 잠금 해제할 수 있습니다. AI Powered SaaS: Stripe + Auth + Billing + Deploy 강의에는 총 4개의 강의가 포함되어 있습니다.
“구독 관리”에서 뭘 배우나요?
요금제 생성과 고객 구독 주기를 포함하여 Stripe 구독을 사용한 반복 결제 로직을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Powered SaaS: Stripe + Auth + Billing + Deploy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
AI Powered SaaS: Stripe + Auth + Billing + Deploy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 AI Powered SaaS: Stripe + Auth + Billing + Deploy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“구독 관리” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 AI Powered SaaS: Stripe + Auth + Billing + Deploy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 AI Powered SaaS: Stripe + Auth + Billing + Deploy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.