Let's Build: With Ruby on Rails - Book Library App with Stripe Subscription Payments
Tags: rails, ruby, showdev, tutorial
Published: 2019-02-15 23:44:19

Welcome to my Let's Build series featuring Ruby on Rails. This installment focuses on accepting payments using Ruby on Rails as a web application framework. We partner Ruby on Rails with Stripe to create a subscription-based SaaS model for a fictitious book library application.

### What's new in this build?

- Rails 5.2 makes an appearance 
- We use [ActiveStorage](http://edgeguides.rubyonrails.org/active_storage_overview.html) which comes new with Rails 5.2. No longer do we require third-party gems like PaperClip or Carrierwave. 
- New encrypted secrets which make managing any environment variables or keys way easier. You can commit these to version control without fear thanks to the encrypted quality
- [Stripe Billing](https://stripe.com/billing) - Stripe recently released a new model around their subscription products. Within Stripe Billing you can define overlying products which have associated plans. It's a nicer way to bundle whatever it is you sell but still be able to sell things in different manners i.e. Flat rates, Multiple Plans, Per seat, Usage-based, and Flat rate + overage.

I used a new Ruby on Rails application template (based on <a href="https://bulma.io/">Bulma CSS</a> in this series of which you can download <a href="https://github.com/justalever/kickoff">here</a>

{% github https://github.com/justalever/book_library %}

### The Book Library application

The application is a simple book application that allows a user to add and remove books from their library. These books can be downloaded for reading once a user is subscribed. Accessing a library is only possible if a user is subscribed. This app differs than previous apps where a user must pay before making an account. 

A user is presented with buttons for adding a book to their library. As you can guess, to do this action a user first needs an account. Upon clicking the "add to library" button a public facing user (someone with no account) is redirected to a signup page of which we implement using the [Devise](https://github.com/plataformatec/devise) gem. 

A nice callback function from Devise allows us to redirect a user upon successfully signing up. In this case, we redirect a user to a pricing page which features three plans to choose from. Each plan has its own parameters associated with it. Upon clicking the "subscribe" button on any of the tiers, the user is redirected to a payment page carrying over the necessary parameters to hook into Stripe with. 

What seems like a simple app carries some logic and weight to cover all our tracks. The application is far from complete but you can, however, extend this to be much more however you like. 

I ran out of time but one obvious area to extend this app is to save what plan a user has subscribed to. This can be done at the time they create a subscription. From there you can query different places in your app to show and hide specific features based on their plan type. 


#### Part 1 
{% youtube eS52517o6Ck %}


#### Part 2 
{% youtube JG1whaC_8i8 %}

#### Part 3 
{% youtube mOS-tzf7xXA %}

#### Part 4 
{% youtube 56vbxhw3S2o %}

#### Part 5 
{% youtube GUbLcffLY7I %}


#### Part 6
{% youtube cSKEFco7HdA %}



#### Models and Relationships

Our app features just three models. At all times we access books and users through a library model. This ends up being a `many-to-many` association. 

**User**
<pre class="language-bash"><code>
email
name
stripe_id
stripe_subscription_id
card_last4
card_exp_month
card_exp_year
card_type
admin
subscribed 
</code></pre>

**Book**
<pre class="language-bash"><code>
title
description
author
user_id
</code></pre>

**Library**
<pre class="language-bash"><code>
book_id
user_id
</code></pre>


The relationships end up as follows:

<pre class="language-ruby"><code>
#app/models/book.rb

class Book &lt; ApplicationRecord
  has_one_attached :thumbnail
  belongs_to :user
  has_many :libraries
  has_many :added_books, through: :libraries, source: :user
 end
</code></pre>

<pre class="language-ruby"><code>
#app/models/library

class Library &lt; ApplicationRecord
  belongs_to :book
  belongs_to :user
end
</code></pre>

<pre class="language-ruby"><code>
#app/models/user
class User &lt; ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :charges
  has_many :books, dependent: :destroy
  has_many :libraries
  has_many :library_additions, through: :libraries, source: :book

  def subscribed?
    stripe_subscription_id?
  end
end
</code></pre>


### Controllers

Our controllers are where much of the magic happens when submitting a successful payment as well as a subscribing a new user.

The easy controller to start with is our book controller. This mimics many of our previous series where a user needed to be associated with another model. Be sure your `Book` model has a `user_id` field.

#### Books Controller

<pre class="language-ruby"><code>
class BooksController &lt; ApplicationController
  before_action :set_book, only: [:show, :edit, :update, :destroy, :library]
  before_action :authenticate_user!, except: [:index, :show]

  # GET /books
  # GET /books.json
  def index
    @books = Book.all
  end

  # GET /books/1
  # GET /books/1.json
  def show
  end

  # GET /books/new
  def new
    @book = current_user.books.build
  end

  # GET /books/1/edit
  def edit
  end

  # POST /books
  # POST /books.json
  def create
    @book = current_user.books.build(book_params)

    respond_to do |format|
      if @book.save
        format.html { redirect_to @book, notice: 'Book was successfully created.' }
        format.json { render :show, status: :created, location: @book }
      else
        format.html { render :new }
        format.json { render json: @book.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /books/1
  # PATCH/PUT /books/1.json
  def update
    respond_to do |format|
      if @book.update(book_params)
        format.html { redirect_to @book, notice: 'Book was successfully updated.' }
        format.json { render :show, status: :ok, location: @book }
      else
        format.html { render :edit }
        format.json { render json: @book.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /books/1
  # DELETE /books/1.json
  def destroy
    @book.destroy
    respond_to do |format|
      format.html { redirect_to books_url, notice: 'Book was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  # Add and remove books to library
  # for current_user
  def library
    type = params[:type]

    if type == "add"
      current_user.library_additions &lt;&lt; @book
      redirect_to library_index_path, notice: "#{@book.title} was added to your library"

    elsif type == "remove"
      current_user.library_additions.delete(@book)
      redirect_to root_path, notice: "#{@book.title} was removed from your library"
    else
      # Type missing, nothing happens
      redirect_to book_path(@book), notice: "Looks like nothing happened. Try once more!"
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_book
      @book = Book.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the whitelist through.
    def book_params
      params.require(:book).permit(:title, :description, :author, :thumbnail, :user_id)
    end
end
</code></pre>

In this controller, you will see one new action in place. This action allows us to actually add a book to a given user's library. We take the parameter passed through from the view and determine if we are adding or removing the book. While we are at it we display notice messages to improve the UX.

<pre class="language-ruby"><code>
  # Add and remove books to the library
  # for current_user
  def library
    type = params[:type]

    if type == "add"
      current_user.library_additions &lt;&lt; @book
      redirect_to library_index_path, notice: "#{@book.title} was added to your library"

    elsif type == "remove"
      current_user.library_additions.delete(@book)
      redirect_to root_path, notice: "#{@book.title} was removed from your library"
    else
      # Type missing, nothing happens
      redirect_to book_path(@book), notice: "Looks like nothing happened. Try once more!"
    end
  end
</code></pre>

This action does require some changes to our routes file. The final route file looks like this:

<pre class="language-ruby"><code>
#config/routes.rb

require 'sidekiq/web'

Rails.application.routes.draw do

  resources :library, only:[:index]
  mount Sidekiq::Web =&gt; '/sidekiq'

  resources :books do
    member do
      put "add", to: "books#library"
      put "remove", to: "books#library"
    end
  end

  devise_for :users, controllers: { registrations: "registrations" }
  root to: 'books#index'
  resources :pricing, only:[:index]
  resources :subscriptions
end
</code></pre>

Notice who within `resources :books` we declare a block and add a `member` do block. 

The corresponding markup to make this all work looks like this in our `_book.html.erb` partial.

<pre class="language-markup"><code>
&lt;div class="content"&gt;
   &lt;% if subscribed? %&gt;

    &lt;% if user_added_to_library?(current_user, book) %&gt;

      &lt;%= link_to 'Remove from library', add_book_path(book, type: "remove"), method: :put, class: "button is-danger is-fullwidth" %&gt;

      &lt;% if controller.controller_name == "library" %&gt;
        &lt;%= link_to 'Download', '#', class:"button is-success is-fullwidth mt1" %&gt;
      &lt;% end %&gt;

    &lt;% else %&gt;
      &lt;%= link_to 'Add to library', add_book_path(book, type: "add"), method: :put, class: "button is-link is-fullwidth" %&gt;
    &lt;% end %&gt;

  &lt;% else %&gt;
    &lt;%= link_to 'Add to library', new_user_registration_path, class: "button is-link is-fullwidth" %&gt;
  &lt;% end %&gt;
&lt;/div&gt;
</code></pre>

We are doing multiple things here but the main focus are the `link_to` methods. These pass the `add_book_path()` along with the `book`, and the `type` of "add" or remove. You can pass any param with a link like this but since we want our route to match the naming convention this is why they do.



#### Subscriptions Controller

<pre class="language-ruby"><code>
class SubscriptionsController &lt; ApplicationController
  layout "subscribe"
  before_action :authenticate_user!, except: [:new, :create]

  def new
    if user_signed_in? &amp;&amp; current_user.subscribed?
      redirect_to root_path, notice: "You are already a subscriber!"
    end
  end

  def create
    Stripe.api_key = Rails.application.credentials.stripe_api_key

    plan_id = params[:plan_id]
    plan = Stripe::Plan.retrieve(plan_id)
    token = params[:stripeToken]

    product = Stripe::Product.retrieve(Rails.application.credentials.book_library)

    customer = if current_user.stripe_id?
                 Stripe::Customer.retrieve(current_user.stripe_id)
               else
                 Stripe::Customer.create(email: current_user.email, source: token)
               end

    subscription = customer.subscriptions.create(plan: plan.id)

    options = {
      stripe_id: customer.id,
      stripe_subscription_id: subscription.id,
      subscribed: true,
    }

    options.merge!(
      card_last4: params[:user][:card_last4],
      card_exp_month: params[:user][:card_exp_month],
      card_exp_year: params[:user][:card_exp_year],
      card_type: params[:user][:card_type]
    ) if params[:user][:card_last4]

    current_user.update(options)

    redirect_to root_path, notice: "&#x1f389; Your subscription was set up successfully!"
  end

  def destroy
    customer = Stripe::Customer.retrieve(current_user.stripe_id)
    customer.subscriptions.retrieve(current_user.stripe_subscription_id).delete
    current_user.update(stripe_subscription_id: nil)

    redirect_to root_path, notice: "Your subscription has been cancelled."
  end

end
</code></pre>

Our subscriptions controller gets all the logic we need to be associated with the Stripe gem. Combined with some markup and Javascript from the Stripe Elements library we take in parameters from the view. 

<pre class="language-ruby"><code>
 plan_id = params[:plan_id] # passed in through the view
 plan = Stripe::Plan.retrieve(plan_id) # retrives the plans on stripe.com of which we already made
 token = params[:stripeToken] # necessary to submit payment to stripe
</code></pre>



We can then either retrieve an exsting customer or create a new one with these lines:

<pre class="language-ruby"><code>
customer = if current_user.stripe_id?
                 Stripe::Customer.retrieve(current_user.stripe_id)
               else
                 Stripe::Customer.create(email: current_user.email, source: token)
               end
</code></pre>

Finally to create a new subscription we call this line:

<pre class="language-ruby"><code>
subscription = customer.subscriptions.create(plan: plan.id)
</code></pre>

While we are at it you can update a few things related to your user:

<pre class="language-ruby"><code>
 options = {
      stripe_id: customer.id, # saves customer id for later
      stripe_subscription_id: subscription.id, # allows us to modify subscription where applicable
      subscribed: true, # dictates if a user is subscribed or not
    }

    options.merge!(
      card_last4: params[:user][:card_last4],
      card_exp_month: params[:user][:card_exp_month],
      card_exp_year: params[:user][:card_exp_year],
      card_type: params[:user][:card_type]
    ) if params[:user][:card_last4]

    current_user.update(options) # updates/adds all options to user account from above

    redirect_to root_path, notice: "&#x1f389; Your subscription was set up successfully!"
</code></pre>



The view repsonisble for a lot of this data looks like this:

<pre class="language-markup"><code>
&lt;!-- app/views/subscriptions/new --&gt;
&lt;section class="section"&gt;
  &lt;div class="columns is-centered"&gt;
    &lt;div class="column is-6 border pa5"&gt;
    &lt;h1 class="title is-3"&gt;Subscribe&lt;/h1&gt;
    &lt;hr /&gt;
      &lt;p&gt;Chosen plan: &lt;strong&gt;&lt;%= params[:plan] %&gt;&lt;/strong&gt;&lt;/p&gt;
    &lt;hr /&gt;
  &lt;%= form_tag subscriptions_path, id: "payment-form" do |form| %&gt;

    &lt;div class="field"&gt;

      &lt;label class="label" for="card-element"&gt;
        Enter credit or debit card
      &lt;/label&gt;

      &lt;div id="card-element"&gt;
        &lt;!-- A Stripe Element will be inserted here. --&gt;
      &lt;/div&gt;

      &lt;!-- Used to display Element errors. --&gt;
      &lt;div id="card-errors" role="alert"&gt;&lt;/div&gt;

      &lt;%= hidden_field_tag :plan_id, params[:plan_id] %&gt;

    &lt;button class="button is-fullwidth is-link mt4"&gt;Submit&lt;/button&gt;
  &lt;/div&gt;

&lt;% end %&gt;

&lt;/div&gt;
&lt;/div&gt;
&lt;/section&gt;
</code></pre>

Ultimately, we are using Stripe Elements to render a payment form. The form input gets generated using JavaScript along with error handling. I find this to be the easiest method as opposed to rolling your own form. You might roll your own if you need to handle multiple merchants like PayPal.

Before a user lands on this page they have already come from the pricing page where they chose a plan. Each plan has an associated parameter passed through to this view which explains the `params[:plan]` as well as the hidden field tag:

<pre class="language-markup"><code>
&lt;%= hidden_field_tag :plan_id, params[:plan_id] %&gt;
</code></pre>

We need a way to know which plan to charge the user for. This is a quick way to do just that. This id gets fed through from the pricing page which I'll talk about next but before I do let's look at the JavaScript required to make this all happen:

<pre class="language-javascript"><code>
document.addEventListener("turbolinks:load", function() {
  const publishableKey = document.querySelector("meta[name='stripe-key']").content;
  const stripe = Stripe(publishableKey);

  const elements = stripe.elements({
    fonts: [{
      cssSrc: "https://rsms.me/inter/inter-ui.css"
    }],
    locale: 'auto'
  });

  // Custom styling can be passed to options when creating an Element.
  const style = {
    base: {
      color: "#32325D",
      fontWeight: 500,
      fontFamily: "Inter UI, Open Sans, Segoe UI, sans-serif",
      fontSize: "16px",
      fontSmoothing: "antialiased",

      "::placeholder": {
        color: "#CFD7DF"
      }
    },
    invalid: {
      color: "#E25950"
    }
  };

  // Create an instance of the card Element.
  const card = elements.create('card', { style });

  // Add an instance of the card Element into the `card-element` &lt;div&gt;.


    card.mount('#card-element');

    card.addEventListener('change', ({ error }) =&gt; {

      const displayError = document.getElementById('card-errors');
      if (error) {
        displayError.textContent = error.message;
      } else {
        displayError.textContent = '';
      }
    });

    // Create a token or display an error when the form is submitted.
    const form = document.getElementById('payment-form');

    form.addEventListener('submit', async(event) =&gt; {
      event.preventDefault();

      const { token, error } = await stripe.createToken(card);

      if (error) {
        // Inform the customer that there was an error.
        const errorElement = document.getElementById('card-errors');
        errorElement.textContent = error.message;
      } else {
        // Send the token to your server.
        stripeTokenHandler(token);
      }
    });

    const stripeTokenHandler = (token) =&gt; {
      // Insert the token ID into the form so it gets submitted to the server
      const form = document.getElementById('payment-form');
      const hiddenInput = document.createElement('input');
      hiddenInput.setAttribute('type', 'hidden');
      hiddenInput.setAttribute('name', 'stripeToken');
      hiddenInput.setAttribute('value', token.id);
      form.appendChild(hiddenInput);

      ["type", "last4", "exp_month", "exp_year"].forEach(function(field) {
        addCardField(form, token, field);
      });

      // Submit the form
      form.submit();
    }

    function addCardField(form, token, field) {
      let hiddenInput = document.createElement('input');
      hiddenInput.setAttribute('type', 'hidden');
      hiddenInput.setAttribute('name', "user[card_" + field + "]");
      hiddenInput.setAttribute('value', token.card[field]);
      form.appendChild(hiddenInput);
    }

});
</code></pre>

If you're following along step-by-step you may have a `subscriptions.coffee` file inside your `app/assets/javascripts` directory. If so, rename it to `subscriptions.js` and type in the code above. 

We created a new custom layout for the payment flow. This is denoted in our `subscriptions_controller.rb` at the very top using a simple line :

<pre class="language-ruby"><code>
class SubscriptionsController &lt; ApplicationController
  layout "subscribe"
  ...
 end
</code></pre>

This allows us to create a new file called `subscribe.html.erb` within `app/views/layouts/`.

You'll need to add a meta tag to your `subscribe.html.erb` layout file to get this to work. Note how I added the stripe js library as well `https://js.stripe.com/v3/`.  That code looks like this:

<pre class="language-markup"><code>
&lt;head&gt;
&lt;%= javascript_include_tag 'application', 'https://js.stripe.com/v3/', 'data-turbolinks-track': 'reload' %&gt;
  
 &lt;%= tag :meta, name: "stripe-key", content: Rails.application.credentials.stripe_publishable_key %&gt;
&lt;/head&gt;
</code></pre>

As part of Rails 5.2 we are accessing our new credentials in a different way than the previous series. Be sure to watch the videos on how to edit/update/store these.

With that outputting your `test` stipe publishable key you are now ready to implement the javascript for Stripe to do it's magic. 



### The Pricing Page

Getting all the plans and parameters we need requires some user input. The pricing page is responsible for this. 

<pre class="language-markup"><code>
&lt;section class="section"&gt;
  &lt;div class="has-text-centered box"&gt;
    &lt;h1 class="title"&gt;Pricing&lt;/h1&gt;
    &lt;h2 class="subtitle"&gt;Choose the best plan that matches your reading consistency and budget.&lt;/h2&gt;
    &lt;div class="pricing-table"&gt;
      &lt;div class="pricing-plan is-warning"&gt;
        &lt;div class="plan-header"&gt;Starter&lt;/div&gt;
        &lt;div class="plan-price"&gt;&lt;span class="plan-price-amount"&gt;&lt;span class="plan-price-currency"&gt;$&lt;/span&gt;5&lt;/span&gt;/month&lt;/div&gt;
        &lt;div class="plan-items"&gt;
          &lt;div class="plan-item"&gt;5 Downloads&lt;/div&gt;
        &lt;/div&gt;
        &lt;div class="plan-footer"&gt;
          &lt;% if user_signed_in? %&gt;
          &lt;%= link_to 'Subscribe', new_subscription_path(plan: "starter", plan_id: Rails.application.credentials.starter), class:"button is-fullwidth" %&gt;
            &lt;% else %&gt;
          &lt;%= link_to 'Subscribe', new_user_registration_path, class:"button is-fullwidth" %&gt;
          &lt;% end %&gt;
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;div class="pricing-plan is-link is-active"&gt;
        &lt;div class="plan-header"&gt;Book Worm&lt;/div&gt;
        &lt;div class="plan-price"&gt;&lt;span class="plan-price-amount"&gt;&lt;span class="plan-price-currency"&gt;$&lt;/span&gt;10&lt;/span&gt;/month&lt;/div&gt;
        &lt;div class="plan-items"&gt;
          &lt;div class="plan-item"&gt;10 Downloads&lt;/div&gt;
        &lt;/div&gt;
        &lt;div class="plan-footer"&gt;
          &lt;% if user_signed_in? %&gt;
          &lt;%= link_to 'Subscribe', new_subscription_path(plan: "book_worm", plan_id: Rails.application.credentials.book_work), class:"button is-fullwidth" %&gt;
          &lt;% else %&gt;
          &lt;%= link_to 'Subscribe', new_user_registration_path, class:"button is-fullwidth" %&gt;
          &lt;% end %&gt;
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;div class="pricing-plan is-danger"&gt;
        &lt;div class="plan-header"&gt;Scholar&lt;/div&gt;
        &lt;div class="plan-price"&gt;&lt;span class="plan-price-amount"&gt;&lt;span class="plan-price-currency"&gt;$&lt;/span&gt;30&lt;/span&gt;/month&lt;/div&gt;
        &lt;div class="plan-items"&gt;
          &lt;div class="plan-item"&gt;30 Downloads&lt;/div&gt;
        &lt;/div&gt;
        &lt;div class="plan-footer"&gt;
          &lt;% if user_signed_in? %&gt;
          &lt;%= link_to 'Subscribe', new_subscription_path(plan: "scholar", plan_id: Rails.application.credentials.scholar), class:"button is-fullwidth" %&gt;
          &lt;% else %&gt;
          &lt;%= link_to 'Subscribe', new_user_registration_path, class:"button is-fullwidth" %&gt;
          &lt;% end %&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/section&gt;
</code></pre>

Out of the box, Bulma doesn't support this markup. You can extend bulma with [this library](https://wikiki.github.io/components/pricingtable/) to add the extra CSS to do so. 

Apart from that you can see that each subscribe button features it's own set of parameters. We store the `plan_id` params as secret credentials. You can grab these from plans you create on stripe.com in your dashboard. We also pass the plan name itself just to aid the UX on the next screen where it comes time for a user to know what they are purchasing. As I said before this is a good spot to save the plan type to your user model so you can dictate what features you want available for each plan type.



### Rounding out

Overall this app seems fairly simple. We are using some exciting new features of Rails 5.2 of which I talk more in depth about in the videos. I invite you to follow along and as always feel free to ask questions. The comments below or the comments on YouTube are a great way to gain feedback. The same is true for the source code on Github. 

If you made it this far, I can't thank you enough. This experience has been a massive learning one for me. I chose to learn in public not only to share what I learned but gain feedback on if I'm doing something wrong or not up to spec. Feel free to critique and if you're new here be sure to check out all of my [previous series](https://web-crunch.com/series)!


**Related series** 

1. [Let’s Build: With Ruby on Rails – Introduction](https://web-crunch.com/lets-build-with-ruby-on-rails-introduction/)
2. [Let’s Build: With Ruby on Rails – Installation](https://web-crunch.com/lets-build-with-ruby-on-rails-installation/)
3. [Let’s Build: With Ruby on Rails – Blog with Comments](https://web-crunch.com/lets-build-with-ruby-on-rails-blog-with-comments)
4. [Let’s Build: With Ruby on Rails – A Twitter Clone](https://web-crunch.com/lets-build-with-ruby-on-rails-a-twitter-clone/)
5. [Let’s Build: With Ruby on Rails – A Dribbble Clone](https://web-crunch.com/lets-build-dribbble-clone-with-ruby-on-rails/)


### Shameless plug time

<a href="http://hellorails.io"><img src="https://web-crunch.com/wp-content/uploads/2019/01/YouTube-Promo3.jpg" alt="" width="3840" height="2160" class="aligncenter size-full wp-image-3999" /></a>

I have a new course called [Hello Rails](https://hellorails.io). Hello Rails is modern course designed to help you start using and understanding Ruby on Rails fast. If you're a novice when it comes to Ruby or Ruby on Rails I invite you to check out the site. The course will be much like these builds but a super more in-depth version with more realistic goals and deliverables. [Sign up to get notified today](https://hellorails.io/)! 

Follow [@hello_rails](https://twitter.com/hello_rails) and [myself @justalever](https://twitter.com/justalever) on Twitter.