Getting Started with Subscriptions

Learn how to set up basic recurring billing for your customers. If you need help after reading this, check out our answers to common questions or chat live with other developers in #stripe on freenode.

Billing your customers periodically is a common use case, and it’s easy to do with Stripe, requiring only three steps:

  1. Create a plan that defines how much should be billed and at what interval
  2. Associate a plan with a customer to create a subscription
  3. Sync with your site

(After creating a plan once, you simply execute the second step for every subsequent customer.)

Before getting started, you’ll want to install one of our client libraries on your server, which is where you’ll run this tutorial’s code. You’ll need to also collect your customer’s credit card info. If you haven’t set up that functionality, look at our Checkout and custom form tutorials before reading on.

Step 1: Create a plan

Stripe’s subscription billing has two main primitives: plans and customers. Plans are objects representing a set cost and billing cycle. You may define just one plan or several hundred, covering the diversity of service levels you offer. For example, if you have two groups of customers–one using the basic features of your application for $10 per month and another using the pro features for $30 per month–you can create a Basic plan and a Pro plan in Stripe.

There are two ways to create plans:

The creation of a single plan via the API uses code like:

# Set your secret key: remember to change this to your live secret key in production
# See your keys here: https://dashboard.stripe.com/account/apikeys
Stripe.api_key = "sk_test_BQokikJOvBiI2HlWgH4olfQ2"

Stripe::Plan.create(
  :amount => 2000,
  :interval => 'month',
  :name => 'Amazing Gold Plan',
  :currency => 'usd',
  :id => 'gold'
)
# Set your secret key: remember to change this to your live secret key in production
# See your keys here: https://dashboard.stripe.com/account/apikeys
stripe.api_key = "sk_test_BQokikJOvBiI2HlWgH4olfQ2"

stripe.Plan.create(
  amount=2000,
  interval="month",
  name="Amazing Gold Plan",
  currency="usd",
  id="gold"
)
// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
\Stripe\Stripe::setApiKey("sk_test_BQokikJOvBiI2HlWgH4olfQ2");

\Stripe\Plan::create(array(
  "amount" => 2000,
  "interval" => "month",
  "name" => "Amazing Gold Plan",
  "currency" => "usd",
  "id" => "gold")
);
// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
Stripe.apiKey = "sk_test_BQokikJOvBiI2HlWgH4olfQ2";

Map<String, Object> planParams = new HashMap<String, Object>();
planParams.put("amount", 2000);
planParams.put("interval", "month");
planParams.put("name", "Amazing Gold Plan");
planParams.put("currency", "usd");
planParams.put("id", "gold");

Plan.create(planParams);
// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
var stripe = require("stripe")("sk_test_BQokikJOvBiI2HlWgH4olfQ2");

stripe.plans.create({
  amount: 2000,
  interval: "month",
  name: "Amazing Gold Plan",
  currency: "usd",
  id: "gold"
}, function(err, plan) {
  // asynchronously called
});

We’ve placed a random test API key in the code. Replace it with your actual API key to test this code through your Stripe account.

Each plan requires a unique ID. You’ll provide this value in API requests when you actually subscribe a customer to one of your plans. The rest of this tutorial assumes you’ve created a gold plan using either the Dashboard or the API.

As a reminder, the plan itself only needs to be created once. It’s the association of the plan with a customer that creates a subscription.

Step 2: Subscribe a customer to a plan

Customers are the other main component of subscriptions. In a broad sense, a Customer object 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 have a stored payment method, such as a credit card, that allows for subsequent billing.

You can create customers via the Dashboard, but as you’ll likely create them as part of the workflow at your site, it makes more sense to use the API. Below is a self-contained example that creates a customer and associates that customer with a plan in a single request. Also notice that a credit card is being attached to the customer. The card is represented by a token, collected from a payment form.

# Set your secret key: remember to change this to your live secret key in production
# See your keys here: https://dashboard.stripe.com/account/apikeys
Stripe.api_key = "sk_test_BQokikJOvBiI2HlWgH4olfQ2"

# Get the credit card details submitted by the form
token = params[:stripeToken]

# Create a Customer
customer = Stripe::Customer.create(
  :source => token,
  :plan => "gold",
  :email => "payinguser@example.com"
)
# Set your secret key: remember to change this to your live secret key in production
# See your keys here: https://dashboard.stripe.com/account/apikeys
stripe.api_key = "sk_test_BQokikJOvBiI2HlWgH4olfQ2"

# Get the credit card details submitted by the form
token = request.POST['stripeToken']

# Create a Customer
customer = stripe.Customer.create(
  source=token,
  plan="gold",
  email="payinguser@example.com"
)
// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
\Stripe\Stripe::setApiKey("sk_test_BQokikJOvBiI2HlWgH4olfQ2");

// Get the credit card details submitted by the form
$token = $_POST['stripeToken'];

$customer = \Stripe\Customer::create(array(
  "source" => $token,
  "plan" => "gold",
  "email" => "payinguser@example.com")
);
// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
Stripe.apiKey = "sk_test_BQokikJOvBiI2HlWgH4olfQ2";

// Get the credit card details submitted by the form
String token = request.getParameter("stripeToken");

Map<String, Object> customerParams = new HashMap<String, Object>();
customerParams.put("source", token);
customerParams.put("plan", "gold");
customerParams.put("email", "payinguser@example.com");

Customer.create(customerParams);
// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
var stripe = require("stripe")("sk_test_BQokikJOvBiI2HlWgH4olfQ2");

// Get the credit card details submitted by the form
var token = request.body.stripeToken; // Using Express

stripe.customers.create({
  source: token,
  plan: "gold",
  email: "payinguser@example.com"
}, function(err, customer) {
  // ...
});

If the credit card is valid, Stripe will return a new Customer object with all the relevant details:

{
  "object": "customer",
  "created": 1409190039,
  "id": "cus_4fdAW5ftNQow1a",
  "livemode": false,
  "email": "payinguser@example.com",
  ...
  "subscriptions": {
    "object": "list",
    "total_count": 1,
    "has_more": false,
    "url": "/v1/customers/cus_4fdAW5ftNQow1a/subscriptions",
    "data": [
      {
        "id": "sub_4fdAS9IlSOFfiv",
        "plan": {
          "interval": "month",
          "name": "Amazing Gold Plan",
          "created": 1409178429,
          "amount": 2000,
          "currency": "usd",
          "id": "gold",
          "object": "plan",
          "livemode": false,
          "interval_count": 1,
          "trial_period_days": null,
          "metadata": {},
          "statement_descriptor": null
        },
        ...
      }
    ]
  },
  ...
}

Once you create a customer, you should store its id in your own database for later reference. This customer will be charged immediately for the first month of their subscription (often called prebilling). They will continue to be billed $20 every month–the plan’s cost and interval–until the subscription is canceled.

If the credit card had not been valid, an error would have been returned instead of a Customer object.

Behind the scenes, Stripe creates an Invoice object for every billing cycle. The invoice reflects what your customer will be charged, when, and the payment status. You can even add additional items to an invoice to factor in one-off charges like setup fees.

Since most subscription activity happens automatically from this point forward, you’ll want to setup webhooks to be notified of events as they occur.

Step 3: Sync with your site

Subscriptions require more coordination between your site and Stripe than one-time payments do. Let’s use the example of a site where a subscription provides access to site content.

On your site, you’d need to store each user’s login credentials (e.g., username and password, in an appropriately secure, encrypted format). You’d also need to store a value for how long the customer has paid for access.

If a customer was subscribed to a monthly plan, you would initially set this timestamp value (i.e., active_until) to one month from now. When the customer logs in, you’d verify the login credentials and check the active_until timestamp to confirm that it’s still in the future, and therefore an active account.

TIP: You can view all active subscriptions from the dashboard. You can even filter by which customers are subscribed to a particular plan.

When the subscription is renewed (i.e., when Stripe bills the customer and they are charged again) your site will need to be notified of the additional payment so that you can update the customer’s active_until timestamp in your database. This is where events and webhooks come into play.

Next steps

Congrats! You’ve gone through the basics of creating a subscription in Stripe. Some things you might want to read next: