Billing your customers periodically is a common use case, and it's easy to do with Stripe. Before we get started, you'll probably want to install one of our client libraries on your server, which is where we'll be adding our code. This guide will walk you through:
- Creating a plan
- Subscribing a customer to a plan
Step 1: Creating a plan
Stripe's subscription billing uses two main primitives: plans, and customers. Plans are objects representing the cost and billing cycle of your subscriptions. You're probably already familiar with SaaS websites that offer plans like personal, team, gold, etc. For example, if you have two groups of customers — one group who are using basic features of your application for $10 per month and another group who are using pro features for $30 per month — you can create a Basic plan and a Pro plan.
In order to sign up a customer for a subscription, then, first we'll need to create a plan. There are two ways to do this: the first is in our dashboard, on the plans page. Alternatively, you can use our API to create plans. Here's a brief snippet of code for how that might look:
Go ahead and create a plan one way or the other. Each plan has an unique id. This value is what you'll provide in API requests when you actually subscribe a customer to one of your plans. For the rest of this tutorial, we'll assume you've called it the gold plan, but if you called it something else you can just change the other code snippets accordingly.
Step 2: Subscribing a customer to a plan
Customers are the other main component of subscriptions. In a broad sense, a customer is just a generic way to associate your own users with your Stripe account. Typically, you'll want to associate some metadata — like an email address — with a customer. Customer objects can also store a credit card, which is how they'll be billed later on.
Creating a new customer via the API is easy. Here's a self contained example that creates a customer and associates that customer with a plan at the same time. Also notice that we're attaching the credit card we collected from our payment form at the same time too:
Once you've created a customer, you should store its
id in your own database so
you can refer to it later when communicating with stripe. We created and subscribed our
customer in one step, but you can also update a customer's subscription later on.
Behind the scenes, Stripe creates an Invoice object for every billing cycle that tracks what your users will be charged, and when and how they paid. You can even add additional items to an invoice for one off charges like setup fees.