0Pricing
AI Powered SaaS: Stripe + Auth + Billing + Deploy · 课时

订阅管理

使用 Stripe Subscriptions 实施周期性计费逻辑,包括创建方案和管理客户订阅周期。

订阅管理 是 CoddyKit 上的免费 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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!

常见问题解答

「订阅管理」课时是免费的吗?

是的 — 「订阅管理」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课程的其余内容,请升级到 CoddyKit PRO。 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课程共包含 4 节课。

「订阅管理」这节课中我会学到什么?

使用 Stripe Subscriptions 实施周期性计费逻辑,包括创建方案和管理客户订阅周期。 你通过在浏览器中直接运行的动手代码来练习 AI Powered SaaS: Stripe + Auth + Billing + Deploy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 AI Powered SaaS: Stripe + Auth + Billing + Deploy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「订阅管理」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课中编写并运行代码吗?

能。每节 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 订阅管理
  2. 处理 Stripe Webhook
  3. 客户门户与账单历史
  4. 计量计费与按用量定价
← 返回 AI Powered SaaS: Stripe + Auth + Billing + Deploy