Intermediate TDD in Rails : Subscription using Stripe API

Objective


To to get familiar with the Stripe API by reading the docs and experimenting.

Steps


Step 1

Add

gem 'stripe'

to Gemfile.

Step 2

Run bundle.

Step 3

Go to Stripe Ruby API docs. Search for Customer.

Step 4

Let's play in the Rails console. Since I already have customers in my test account, I can retrieve them:

require "stripe"
Stripe.api_key = "sk_test_BQokikJOvBiI2HlWgH4olfQ2"

customers = Stripe::Customer.all

returns a Stripe::ListObject

Step 5

Copy the output after JSON: in the terminal and paste it on Online JSON Editor

You can see the JSON data for each customer object. There are 10 customers. You can navigate through the data structure to view attributes and nested attributes such as subscriptions. Click on the Subscriptions in the left navigation of the API.

Subscriptions allow you to charge a customer's card on a recurring basis. A subscription ties a customer to a particular plan you've created.

We need to create plans before we can subscribe a customer. Click on the Plans, Create a Plan. Since we will only create a plan once, we can do it on the stripe dashboard. I have manually created two plans from the Stripe Dashboard called Silver and Amazing Gold Plan.

Step 6

Copy the 'Test Secret Key' and 'Test Publishable Key' from 'Your Account', 'API Keys' tab.

Test Secret Key : sk_test_watHqWl2XD88WHqhknk7sqXN
Test Publishable Key: pk_test_GxDbP7Q6f4GkaUe0I0LrbQSz

Click on Subscriptions -> Create a Subscription. We can create a subscription for an existing customer. There does not seem to be a way to create a subscription and a customer at the same time. So, let's create a customer first.

Step 7

Click on Customers, Create a customer.

require "stripe"
Stripe.api_key = "sk_test_BQokikJOvBiI2HlWgH4olfQ2"

Stripe::Customer.create(
  :description => "Customer for test@example.com",
  :source => "tok_15hByA2eZvKYlo2CILNOo2SS" # obtained with Stripe.js
)

The source is a token that is obtained when the credit card details is submitted by the form on our website to Stripe servers. The Stripe.js javascript will be used in the view that takes care of submitting the credit card details to Stripe servers. For now, we can use the Stripe::Token.create method to create a valid token like this:

token = Stripe::Token.create(
  card: {
    number: "4242424242424242",
    exp_month: 3,
    exp_year: 2016,
    cvc: "314"
  }
)

Step 8

We can now use the token.id as the source to create the customer:

customer = Stripe::Customer.create(
  description: "Customer for tutorial@example.com",
  source: token.id)

We can store the customer details in our database. If the id is not nil and there was no exceptions, it means the call succeeded. We now know:

  1. How to create a token
  2. How to create a customer using a valid token

Step 9

So, we can create a subscription for this customer as follows:

customer = Stripe::Customer.retrieve({CUSTOMER_ID})
customer.subscriptions.create({:plan => PLAN_ID})

Step 10

To retrieve our plans we can make a call:

plans = Stripe::Plan.all
 => #<Stripe::ListObject:0x3fc9c17aeca0> JSON: {
  "object": "list",
  "has_more": false,
  "url": "/v1/plans",
  "data": [
    {"id":"silver","interval":"month","name":"Silver","created":1415672471,"amount":1500,"currency":"usd","object":"plan","livemode":false,"interval_count":1,"trial_period_days":null,"metadata":{},"statement_descriptor":null},
    {"id":"gold","interval":"month","name":"Amazing Gold Plan","created":1415160352,"amount":2000,"currency":"usd","object":"plan","livemode":false,"interval_count":1,"trial_period_days":null,"metadata":{},"statement_descriptor":null}
  ]

We have plan with id silver and gold. We already have a customer object, let's create the subscription:

subscription = customer.subscriptions.create(plan: 'gold')

 => #<Stripe::Subscription:0x3fc9bc510c64 id=sub_5tEIxKfqb9fjyq> JSON: {
  "id": "sub_5tEIxKfqb9fjyq",
  "plan": {"id":"gold","interval":"month","name":"Amazing Gold Plan","created":1415160352,"amount":2000,"currency":"usd","object":"plan","livemode":false,"interval_count":1,"trial_period_days":null,"metadata":{},"statement_descriptor":null},
  "object": "subscription",
  "start": 1426626141,
  "status": "active",
  "customer": "cus_5tEGApxI5MNWqN",
  "cancel_at_period_end": false,
  "current_period_start": 1426626141,
  "current_period_end": 1429304541,
  "ended_at": null,
  "trial_start": null,
  "trial_end": null,
  "canceled_at": null,
  "quantity": 1,
  "application_fee_percent": null,
  "discount": null,
  "tax_percent": null,
  "metadata": {}
} 

If the subscription id is not nil and there are no exceptions, the subscription was successful and we can save the subscription details in our database.

Summary


In this lesson, we experimented with the Stripe API using stripe gem and we have learned:

  1. How to create a token.
  2. How to create a customer.
  3. How to subscribe a customer to one of our existing plans.

In the next lesson, we will drive the development of a library to subscribe a customer to a plan using tests.


Related Articles


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.