Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

An example Rails 3.2 app with recurring billing using Stripe for a membership or subscription site.

branch: master

This branch is 0 commits ahead and 0 commits behind master

Fetching latest commit…

Cannot retrieve the latest commit at this time

README.textile

Rails Application for a Membership, Subscription, or SaaS Site Rails App for a Membership, Subscription, or SaaS Site

Rails 3.2 example application with recurring billing using Stripe. Use for a Rails membership site, subscription site, or SaaS site (software-as-a-service). Using:

  • Devise authentication and user management
  • CanCan authorization for administrator access
  • Twitter Bootstrap front-end framework for CSS styling
  • Stripe for recurring billing and subscription management

Best of all, there’s a detailed tutorial to show how it’s built.

Rails Application for a Membership, Subscription, or SaaS Site

Follow on Twitter Follow on Twitter

Follow the project on Twitter: @rails_apps. Please tweet some praise if you like what you’ve found.

Tutorial

A complete tutorial is available:

View the Tutorial

The tutorial documents each step to follow to create the application. Every step is documented concisely, so a complete beginner can create this application without any additional knowledge. However, no explanation is offered for any of the steps, so if you are a beginner, you’re advised to look for an introduction to Rails elsewhere. See a list of recommended resources for Rails.

What Is Implemented — and What Is Not

Membership sites restrict access to content such as articles, videos, or user forums. Software-as-a-service (SaaS) sites limit use of web-based software to paid subscribers. The revenue model is the same whether the site provides high-value content or software as a service: A visitor purchases a subscription and gains access to restricted areas of the site. Typically, the subscription is repurchased monthly through a service that provides recurring billing.

The example application provides a complete and fully functional membership site.

  • tiered pricing for multiple subscription plans
  • optional “free trial” subscription as well as free accounts using Stripe
  • uses Stripe for no local credit card storage
  • Stripe accepts credit card payments from customers in any country or currency
  • PCI compliance using the Stripe JavaScript library
  • Stripe handles recurring billing, retries if payment fails, and cancels subscription if retries fail
  • paid subscriptions are created only after a successful credit card transaction
  • subscribers can upgrade or downgrade subscription plans
  • subscribers can cancel subscription plans
  • configurable subscription renewal period (defaults to one month)
  • administrator can change subscription plan or delete user

What is Not Implemented

There are additional features you may want for a SaaS application, such as:

  • Basecamp-style subdomains (each user gets their own subdomain)
  • multitenancy database segmentation

These features are not included in this application. See the rails3-subdomains example application for help with subdomains. For multitenancy, try Brad Robertson’s Apartment gem.

Similar Examples and Tutorials

RailsApps

This is one in a series of Rails example apps and tutorials from the RailsApps Project. See a list of additional Rails examples, tutorials, and starter apps.

This example application is based on the rails3-bootstrap-devise-cancan starter application. This example application uses ActiveRecord and a SQLite database with RSpec and Cucumber for testing.

You might also be interested in the rails-prelaunch-signup example and tutorial from the RailsApps project.

Other Projects

Dependencies

Before generating your application, you will need:

  • The Ruby language (version 1.9.3)
  • Rails 3.2

See the article Installing Rails for advice about updating Rails and your development environment.

Getting the Application

You have several options for getting the code. You can fork, clone, or generate.

Fork

If you’d like to add features (or bug fixes) to improve the example application, you can fork the GitHub repo and make pull requests. Your code contributions are welcome!

Clone

If you want to copy and customize the app with changes that are only useful for your own project, you can clone the GitHub repo. You’ll need to search-and-replace the project name throughout the application. You probably should generate the app instead (see below). To clone:

$ git clone git://github.com/RailsApps/rails-stripe-membership-saas.git

You’ll need git on your machine. See Rails and Git.

Generate

If you want to use the project as a starter app, use the Rails Composer tool to generate a new version of the example app. You’ll be able to give it your own project name when you generate the app. Generating the application gives you many additional options.

To build the example application, run the command:

$ rails new rails-stripe-membership-saas -m https://raw.github.com/RailsApps/rails-composer/master/composer.rb -T

Use the -T flag to skip Test::Unit files.

The $ character indicates a shell prompt; don’t include it when you run the command.

This creates a new Rails app named rails-stripe-membership-saas on your computer. You can use a different name if you wish.

You’ll see a prompt:

question  Install an example application?
      1)  I want to build my own application
      2)  rails-stripe-membership-saas
      3)  rails-prelaunch-signup
      4)  rails3-bootstrap-devise-cancan
      5)  rails3-devise-rspec-cucumber
      6)  rails3-mongoid-devise
      7)  rails3-mongoid-omniauth
      8)  rails3-subdomains

Choose rails-stripe-membership-saas. The Rails Composer tool may give you other options (other choices may have been added since these notes were written).

The application generator template will ask you for additional preferences:

 question  Web server for development?
       1)  WEBrick (default)
       2)  Thin
       3)  Unicorn
       4)  Puma
 question  Web server for production?
       1)  Same as development
       2)  Thin
       3)  Unicorn
       4)  Puma
 question  Template engine?
       1)  ERB
       2)  Haml
       3)  Slim
   extras  Set a robots.txt file to ban spiders? (y/n)
   extras  Create a project-specific rvm gemset and .rvmrc? (y/n)
   extras  Create a GitHub repository? (y/n)

Web Servers

Use the default WEBrick server for convenience. If you plan to deploy to Heroku, select “thin” as your production webserver.

Template Engine

The example application uses the default “ERB” Rails template engine. Optionally, you can use another template engine, such as Haml or Slim. See instructions for Haml and Rails.

Other Choices

Set a robots.txt file to ban spiders if you want to keep your new site out of Google search results.

It is a good idea to use rvm, the Ruby Version Manager, and create a project-specific rvm gemset and .rvmrc file (not available on Windows). See Installing Rails.

If you choose to create a GitHub repository, the generator will prompt you for a GitHub username and password.

Troubleshooting

If you get an error “OpenSSL certificate verify failed” or “Gem::RemoteFetcher::FetchError: SSL_connect” see the article OpenSSL errors and Rails.

If you get an error like this:

Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.
    composer  Running 'after bundler' callbacks.
The template [...] could not be loaded.
Error: You have already activated ..., but your Gemfile requires .... 
Using bundle exec may solve this.

It’s due to conflicting gem versions. See the article Rails Error: “You have already activated (…)”.

Edit the README

If you’re storing the app in a GitHub repository, please edit the README files to add a description of the app and your contact info. If you don’t change the README, people will think I am the author of your version of the application.

Getting Started

Stripe Account

The application implements recurring billing using Stripe. Before you start, go to the Stripe website and set up an account. You don’t need a credit card merchant account or payment gateway. There’s no approval process to delay getting started.

Install the Required Gems

Check the Gemfile to see which gems are used by this application.

Run the bundle install command to install the required gems on your computer:

$ bundle install

You can check which gems are installed on your computer with:

$ gem list

Keep in mind that you have installed these gems locally. When you deploy the app to another server, the same gems (and versions) must be available.

I recommend using rvm, the Ruby Version Manager, to create a project-specific gemset for the application. See the article Installing Rails.

Configure Email

You must configure the application for your email account. See the article Send Email with Rails.

Configure Devise

You can modify the configuration file for Devise if you want to use something other than the defaults:

  • config/initializers/devise.rb

Set Up a Database Seed File

You’ll want to set up a default user so you can easily log in to test the app. You can modify the file db/seeds.rb for your own name, email and password. You can also set a list of roles that correspond to the subscription plans you will offer.

puts 'CREATING ROLES'
Role.create([
  { :name => 'admin' }, 
  { :name => 'silver' }, 
  { :name => 'gold' },
  { :name => 'platinum' }
], :without_protection => true)
puts 'SETTING UP DEFAULT USER LOGIN'
user = User.create! :name => 'First User', :email => 'user@example.com', :password => 'please', :password_confirmation => 'please'
user.add_role :admin
puts 'admin created: ' << user.name
user2 = User.create! :name => 'Silver User', :email => 'user2@example.com', :password => 'please', :password_confirmation => 'please'
user2.add_role :silver
user3 = User.create! :name => 'Gold User', :email => 'user3@example.com', :password => 'please', :password_confirmation => 'please'
user3.add_role :gold
user4 = User.create! :name => 'Platinum User', :email => 'user4@example.com', :password => 'please', :password_confirmation => 'please'
user4.add_role :platinum
puts "added users: #{user2.name}, #{user3.name}, #{user4.name}"

You can change the roles and name, email, and password as you wish.

If you include your private password in the file, be sure to add the filename to your .gitignore file so that your password doesn’t become available in your public GitHub repository.

Note that it’s not necessary to personalize the db/seeds.rb file before you deploy your app. You can deploy the app with an example user and then use the application’s “Edit Account” feature to change name, email address, and password after you log in. Use this feature to log in as an administrator and change the user name and password to your own.

The db/seeds.rb file is the only place where we create a list of possible roles. There is no other configuration of roles. Any new role can be added to the roles datatable with a statement such user.add_role :superhero.

Set the Database

Prepare the database and add the default user to the database by running the commands:

$ rake db:migrate
$ rake db:seed

Set the database for running tests:

$ rake db:test:prepare

If you’re not using rvm, the Ruby Version Manager, you should preface each rake command with bundle exec. You don’t need to use bundle exec if you are using rvm version 1.11.0 or newer.

Configure the Stripe Initializer

The Stripe gem requires an API key to operate. You also need to supply a public key when initiating a transaction. You can find both keys on the Stripe website when you visit your Stripe account page. You’ll store the API and public key in an initializer file.

Here’s the file config/initializers/stripe.rb:

Stripe.api_key = ENV["STRIPE_API_KEY"]
STRIPE_PUBLIC_KEY = ENV["STRIPE_PUBLIC_KEY"]

For security, don’t record sensitive information in your application code where it might be exposed publicly on a GitHub repo. Instead, set Unix environment variables in the file that is read when starting an interactive shell (the ~/.bashrc file for the bash shell). This will keep the password out of your repository.

Add this to your ~/.bashrc file (or the equivalent file for your preferred Unix shell):

export STRIPE_API_KEY="secret"
export STRIPE_PUBLIC_KEY="secret"

Replace “secret” with your keys. You can find both keys on your Stripe account page. Two sets of keys are available: one for testing, one for live transactions. Use the testing keys on your development machine. When you deploy, use the live keys. If you plan to use Heroku for hosting, make a note for yourself to set up the Heroku environment variables after deployment.

Here’s how to set Heroku environment variables to provide the same data your application obtains from your local shell environment:

$ heroku config:add STRIPE_API_KEY=secret STRIPE_PUBLIC_KEY=secret

You can’t set Heroku environment variables now; you’ll do that after you deploy.

Prepare Your Stripe Account

Before you can use the application, you must prepare your Stripe account to recognize the subscription plans you’ll offer.

This step is necessary if you’re going to use Stripe to automatically handle recurring billing. To match the example application, tell Stripe that you have three plans named “Silver”, “Gold”, and “Platinum” that will be billed monthly at rates of $9, $19, and $29. Once a customer is created and assigned a plan, Stripe will do all the work of notifying the user, initiating monthly billing, and contacting the user when a credit card is declined or expires.

Go to the Stripe plan management page to create a subscription plan. Stripe offers documentation about creating a plan and additional detail about plans.

Look for the toggle switch “Live/Test” and set it to “Test.” Click the button to “Create your first plan.”

Create three different plans with the following values:

ID Name Amount Interval
silver Silver 9.00 monthly
gold Gold 19.00 monthly
platinum Platinum 29.00 monthly

“ID” is a unique string of your choice that is used to identify the plan when subscribing a customer. In our application, each plan should have an ID that corresponds to the roles we’ve created to manage access. “Name” is displayed on invoices and in the Stripe web interface. “Amount” is the subscription price in US dollars. “Interval” is the billing frequency. Optionally, you can specify a trial period (in days). If you include a trial period, the customer won’t be billed for the first time until the trial period ends. If the customer cancels before the trial period is over, she’ll never be billed at all.

Stripe Webhooks

When a credit card expires or a monthly transaction is declined, Stripe will automatically retry a recurring payment after it fails. After a number of attempts (set in your Stripe account settings), Stripe will cancel the subscription. Your application needs to know to deny access for a subscriber with an expired account. Stripe provides webhooks to communicate events to you (for details, see the Stripe webhooks documentation).

A Stripe webhook is an HTTP request from Stripe’s servers to your site, containing JSON data that provides data about the event, plus an event id that can be used to retrive the data from the Stripe server. The example application responds to Stripe webhooks, using an implementation provided by Danny Whalen’s stripe_event gem. The stripe_event gem is a Rails engine that responds to webhook requests at http://localhost:3000/stripe (you can change the URL by modifying the engine mounting in the config/routes.rb file).

The example application only responds to “customer.subscription.deleted” events. You can customize the application to respond to other events (such as sending a thank you email in response to an “invoice.payment_succeeded” event).

For webhooks to work, you must visit your Stripe dashboard at https://manage.stripe.com/#account/webhooks and add the URL for your application, such as http://example.com/stripe.

Change your Application’s Secret Token

If you’ve cloned the application from GitHub, it is crucial that you change the application’s secret token before deploying your application in production mode. Otherwise, people could change their session information, and potentially access your SaaS or membership site as a premium user or administrator! Ideally, your secret token should be at least 30 characters long and completely random. Edit your config/initializers/secret_token.rb file:

RailsStripeMembershipSaas::Application.config.secret_token = '...some really long, random string...'

If you’ve used the Rails Composer tool to generate the application, the application’s secret token will already be unique, just as with any Rails application generated with the rails new command.

Test the App

You can check that your app runs properly by entering the command:

$ rails server

To see your application in action, open a browser window and navigate to http://localhost:3000/.

Sign in as the first user (the administrator) using:

  • email: user@example.com
  • password: please

You’ll see a navigation link for Admin. Clicking the link will display a page with a list of users at
http://localhost:3000/users.

To sign in as the second user, use

  • email: user2@example.com
  • password: please

The second user will not see the Admin navigation link and will not be able to access the page at
http://localhost:3000/users.

You should be able to create additional users using the fake credit card number 4242424242424242. You’ll see the new users listed when you log in as an administrator. And you’ll see the new users listed as customers when you visit your Stripe dashboard.

Stop the server with Control-C.

If you test the app by starting the web server and then leave the server running while you install new gems, you’ll have to restart the server to see any changes. The same is true for changes to configuration files in the config folder. This can be confusing to new Rails developers because you can change files in the app folders without restarting the server. Stop the server each time after testing and you will avoid this issue.

Deploy to Heroku

For your convenience, here is a Tutorial for Rails on Heroku. Heroku provides low cost, easily configured Rails application hosting.

Before you deploy to production, modify the app/models/user.rb file to remove the statement return if email.include?('example.com'). If you don’t do so, your application will allow any visitor to create a free account by using an “example.com” email address.

Be sure to set up SSL before you make your application available in production. See the Heroku documentation on SSL.

Customizing

This application provides a fully functional membership site that’s ready to take credit card payments and serve access to restricted content.

It uses Stripe for payment processing, allows users to change credit cards or subscription plans, and uses Stripe webhooks to delete users who have expired or declined credit cards.

You might consider a few enhancements. For example, you might want the application to respond to a Stripe webhook event when a credit card payment is successful by sending a “paid” invoice. Or you might respond to Stripe webhook events when credit card payments are unsuccessful by sending a friendly note encouraging the user to check for an expired credit card before the subscription is cancelled.

If you have suggestions for additional features, please create an issue on GitHub.

Testing

This is an early release of the application and does not contain a full suite of RSpec unit tests and Cucumber scenarios and step definitions.

After installing the application, run rake -T to check that rake tasks for RSpec and Cucumber are available.

Run rake spec to run all RSpec tests.

Run rake cucumber (or more simply, cucumber) to run all Cucumber scenarios.

Please send the author a message, create an issue, or submit a pull request if you can contribute improved RSpec or Cucumber files.

Troubleshooting

Problems? Check the issues.

Documentation

The tutorial provides additional documentation.

Issues

Please create a GitHub issue if you identify any problems or have suggestions for improvements.

Where to Get Help

Your best source for help with problems is Stack Overflow. Your issue may have been encountered and addressed by others.

You can also try Rails Hotline, a free telephone hotline for Rails help staffed by volunteers.

Contributing

If you make improvements to this application, please share with others.

Send the author a message, create an issue, or fork the project and submit a pull request.

If you add functionality to this application, create an alternative implementation, or build an application that is similar, please contact me and I’ll add a note to the README so that others can find your work.

Credits

Daniel Kehoe implemented the application and wrote the tutorial.

Is the app useful to you? Follow the project on Twitter: @rails_apps
and tweet some praise. I’d love to know you were helped out by what I’ve put together.

MIT License

MIT License

Copyright © 2012 Daniel Kehoe

githalytics.com alpha

Something went wrong with that request. Please try again.