Rails 3.2 example application with recurring billing using Recurly. 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
- Recurly for recurring billing and subscription management
You can build this application in only a few minutes using the Rails Composer tool.
Follow the project on Twitter: @rails_apps. Please tweet some praise if you like what you’ve found.
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 Recurly
- uses Recurly for no local credit card storage
- Recurly accepts credit card payments from customers in any country or currency
- PCI compliance using the Recurly JavaScript library
- Recurly 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
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.
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.
This application is similar to the rails-stripe-membership-saas application which provides recurring billing using the Stripe billing service.
You might also be interested in the rails-prelaunch-signup example and tutorial from the RailsApps project.
- Recurly’s recurly-client-ruby-demo
- Recurly’s recurly-client-ruby
- Nick O’Neill’s recurly-rails
Before generating your application, you will need:
- The Ruby language (version 1.9.3 or 2.0.0)
- The Rails gem (version 3.2.13)
See the article Installing Rails for advice about updating Rails and your development environment.
You have several options for getting the code. You can fork, clone, or generate.
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!
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-recurly-subscription-saas.git
You’ll need git on your machine. See Rails and Git.
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 additional options.
To build the example application, run the command:
$ rails new rails-recurly-subscription-saas -m https://raw.github.com/RailsApps/rails-composer/master/composer-Rails3_2.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-recurly-subscription-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) membership/subscription/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 membership/subscription/saas.
Then choose Recurly:
question Billing with Stripe or Recurly? 1) Stripe 2) Recurly
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 Use or create a project-specific rvm gemset? (y/n) extras Create a GitHub repository? (y/n)
We recommend Thin in development for speed and less noise in the log files.
If you plan to deploy to Heroku, select Thin as your production webserver.
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.
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 (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.
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 (…)”.
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.
See the article Installing Rails to make sure your development environment is prepared properly.
The application implements recurring billing using Recurly. Before you start, go to the Recurly website and set up an account.
Your business will need a merchant account in order to accept credit card payments. Recurly does not include a merchant account as part of the service. If your business is established and already taking credit card payments, you will already have a merchant account. If not, you will have to obtain a merchant account. If you have a U.S.-based business, Recurly will refer you to their partner, TSYS Merchant Solutions, one of the largest credit card processors in the U.S., and a salesperson will contact you to send you an application form. It takes a few days to get approval so get the process started early.
I recommend using rvm, the Ruby Version Manager, to create a project-specific gemset for the application. If you generate the application with the Rails Composer tool, you can create a project-specific gemset.
Check the Gemfile to see which gems are used by this application.
If you generate the application with the Rails Composer tool, all gems will be installed.
Otehrwise, 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.
You must configure the application for your email account. See the article Send Email with Rails.
You can modify the configuration file for Devise if you want to use something other than the defaults:
- config/initializers/devise.rb
The application uses the figaro gem to set environment variables. Credentials for your administrator account and Recurly API and cryptographic keys are set in the config/application.yml file. The .gitignore file prevents the config/application.yml file from being saved in the git repository so your credentials are kept private. See the article Rails Environment Variables for more information.
Modify the file config/application.yml:
# Add account credentials and API keys here. # See http://railsapps.github.io/rails-environment-variables.html # This file should be listed in .gitignore to keep your settings secret! # Each entry sets a local environment variable and overrides ENV variables in the Unix shell. # For example, setting: # GMAIL_USERNAME: Your_Gmail_Username # makes 'Your_Gmail_Username' available as ENV["GMAIL_USERNAME"] # Add application configuration variables here, as shown below. # GMAIL_USERNAME: Your_Username GMAIL_PASSWORD: Your_Password ADMIN_FIRST_NAME: First ADMIN_LAST_NAME: User ADMIN_EMAIL: [email protected] ADMIN_PASSWORD: changeme ROLES: [admin, silver, gold, platinum] RECURLY_API_KEY: = recurly_api_key RECURLY_JS_PRIVATE_KEY: = recurly_js_private_key RECURLY_SUBDOMAIN: myapp
Set the user name and password needed for the application to send email.
If you wish, set your name, email address, and password for an administrator’s account. If you prefer, you can use the default to sign in to the application and edit the account after deployment. It is always a good idea to change the administrator’s password after the application is deployed.
The roles you specify in the configuration file are the subscription plans that will be available to the application’s users. You will need an “admin” role. Keep the “silver”, “gold”, and “platinum” roles while you are testing the application. You can change these roles later, after you familiarize yourself with the application and begin to customize it for your own needs.
The Recurly gem requires an API key to operate. We’ll also need to supply a private key so the Recurly gem can generate a cryptographic signature. You can find both keys on your Recurly account profile under “API Credentials”.
Set a RECURLY_SUBDOMAIN
environment variable that is used in the JavaScript code that initiates the Recurly transaction. Recurly creates a customer-facing website and API interface with a subdomain on the Recurly website. The URL will look like this: https://myapp.recurly.com/
where “myapp” is the name of your company or service. You’ll use the subdomain “myapp” to form the URL that makes requests to the Recurly API interface. The Recurly subdomain is listed on your Recurly account profile.
All configuration values in the config/application.yml file are available anywhere in the application as environment variables. For example, ENV["GMAIL_USERNAME"]
will return the string “Your_Username”.
If you prefer, you can delete the config/application.yml file and set each value as an environment variable in the Unix shell.
The db/seeds.rb file initializes the database with default values. To keep some data private, and consolidate configuration settings in a single location, we use the config/application.yml file to set environment variables and then use the environment variables in the db/seeds.rb file.
puts 'ROLES' YAML.load(ENV['ROLES']).each do |role| Role.find_or_create_by_name({ :name => role }, :without_protection => true) puts 'role: ' << role end puts 'DEFAULT USERS' user = User.find_or_create_by_email :first_name => ENV['ADMIN_FIRST_NAME'].dup, :last_name => ENV['ADMIN_LAST_NAME'].dup, :email => ENV['ADMIN_EMAIL'].dup, :password => ENV['ADMIN_PASSWORD'].dup, :password_confirmation => ENV['ADMIN_PASSWORD'].dup puts 'user: ' << user.name user.add_role :admin user2 = User.find_or_create_by_email :first_name => 'Silver', :last_name => 'User', :email => '[email protected]', :password => 'changeme', :password_confirmation => 'changeme' user2.add_role :silver user3 = User.find_or_create_by_email :first_name => 'Gold', :last_name => 'User', :email => '[email protected]', :password => 'changeme', :password_confirmation => 'changeme' user3.add_role :gold user4 = User.find_or_create_by_email :first_name => 'Platinum', :last_name => 'User', :email => '[email protected]', :password => 'changeme', :password_confirmation => 'changeme' user4.add_role :platinum puts "users: #{user2.name}, #{user3.name}, #{user4.name}"
The db/seeds.rb file reads a list of roles from the config/application.yml file and adds the roles to the database. In fact, any new role can be added to the roles datatable with a statement such user.add_role :superhero
. Setting the roles in the db/seeds.rb file simply makes sure each role is listed and available should a user wish to change roles.
We add an administrator and three sample users. Our User model has separate first and last names to accommodate Recurly’s customer schema.
Values from the config/application.yml file are used to create a user with an administrator role. You can log in with this account for access as an administrator.
You can change the administrator name, email, and password in this file but it is better to make the changes in the config/application.yml file to keep the credentials private. If you decide to include your private password in the db/seeds.rb 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.
Prepare the database and add the default user to the database by running the commands:
$ rake db:migrate $ rake db:seed
Use rake db:reset
if you want to empty and reseed the database.
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.
The file config/initializers/recurly.rb sets the Recurly API key and cryptographic private key from environment variables:
Recurly.api_key = ENV['RECURLY_API_KEY'] Recurly.js.private_key = ENV['RECURLY_JS_PRIVATE_KEY'] RECURLY_SUBDOMAIN = ENV['RECURLY_SUBDOMAIN'] # Recurly.default_currency = 'USD'
You could hardcode the Recurly API key and cryptographic private key in the config/initializers/recurly.rb file but instead, we advise to set the Recurly API key and cryptographic private key in the config/application.yml file. Recording sensitive information in the config/initializers/recurly.rb file might expose it publicly on a GitHub repo. Both the Recurly API key and cryptographic private key should be kept secret; the Recurly subdomain can be revealed without consequence.
If you’re not operating with US dollars as your currency, you can change the default in the initializer file.
Before we can submit a billing request to Recurly, we have to set up our Recurly account.
First, take a look at “Site Settings” in your Recurly account profile. Recurly offers options for “Address Requirement.” By default, Recurly expects a full address, including street, city, state and postal code. Our example application only asks for the user’s country (for enhanced fraud protection). Change the “Address Requirement” setting to “No Address.” If you don’t change the “Address Requirement” setting from the default, you’ll see an error when you test the application: “Billing info address1 can’t be empty, Billing info zip can’t be empty, Billing info city can’t be empty, Billing info state can’t be empty.”
Next we’ll set up our subscription plans. We’ll tell Recurly that we 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, Recurly 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 your Recurly account profile to create a subscription plan. Look for “Configuration/Subscription Plans.” Recurly offers documentation about creating subscriptions and additional detail about subscriptions.
Create three different plans with the following values:
Plan Name | Plan Code | Pricing | Interval |
---|---|---|---|
Silver | silver | 9.00 | monthly |
Gold | gold | 19.00 | monthly |
Platinum | platinum | 29.00 | monthly |
“Plan Name” is displayed on invoices and in the Recurly web interface. “Plan Code” is a unique string of your choice that is used to identify the plan when subscribing a customer. The “Plan Code” should correspond to a role we’ve created to manage access. “Pricing” is the subscription price. You’ll specify the billing frequency. Optionally, you can specify a free trial period. 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.
When a credit card expires or a monthly transaction is declined, Recurly will automatically retry a recurring payment after it fails. After a number of attempts (set in your Recurly “Dunning Management” settings), Recurly will cancel the subscription. Your application needs to know to deny access for a subscriber with an expired account. Recurly provides webhooks (push notifications) to communicate events to you (for details, see the Recurly Push Notifications documentation and Recurly Push Notifications API).
A Recurly push notification is an HTTP request from Recurly’s servers to your site. It is not a visit to your website from a web browser; rather it is an HTTP POST request (like a form submission) to your application from the Recurly servers. The HTTP request contains XML data that provides data about the event, including a customer account code that can be used to retrive the data from the Recurly server. It is best to ignore the event data (because it could be falsified) and query the Recurly server to obtain the subscription status.
The example application only responds to “expired_subscription_notification” events. You can customize the application to respond to other events.
For push notifications to work, you must visit your Recurly dashboard and enter the URL in your “Push Notifications” settings:
If you’ve used the Rails Composer tool to generate the application, the application’s secret token will be unique, just as with any Rails application generated with the rails new
command.
However, if you’ve cloned the application directly 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. Your secret token should be at least 30 characters long and completely random.
Get a unique secret token:
rake secret
Edit your config/initializers/secret_token.rb file to add the secret token:
RailsRecurlySubscriptionSaas::Application.config.secret_token = '...some really long, random string...'
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/.
If you are using the default values from the config/application.yml file, you can sign in as the administrator using:
- email: [email protected]
- password: changeme
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: [email protected]
- password: changeme
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 4111111111111111. 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 Recurly 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.
For your convenience, here is a Tutorial for Rails on Heroku. Heroku provides low cost, easily configured Rails application hosting.
Be sure to set up SSL before you make your application available in production. See the Heroku documentation on SSL.
Prior to deployment, change your db/seeds.rb file. Remove the “example.com” sample users.
puts 'ROLES' YAML.load(ENV['ROLES']).each do |role| Role.find_or_create_by_name({ :name => role }, :without_protection => true) puts 'role: ' << role end puts 'DEFAULT USERS' user = User.find_or_create_by_email :name => ENV['ADMIN_NAME'].dup, :email => ENV['ADMIN_EMAIL'].dup, :password => ENV['ADMIN_PASSWORD'].dup, :password_confirmation => ENV['ADMIN_PASSWORD'].dup puts 'user: ' << user.name user.add_role :admin
You’ll need to set the configuration values from the config/application.yml file as Heroku environment variables. See the article Rails Environment Variables for more information.
With the figaro gem, just run:
rake figaro:heroku
Alternatively, you can set Heroku environment variables directly with heroku config:add
.
$ heroku config:add GMAIL_USERNAME='[email protected]' GMAIL_PASSWORD='secret' $ heroku config:add 'ROLES=[admin, silver, gold, platinum]' $ heroku config:add ADMIN_FIRST_NAME='First' ADMIN_LAST_NAME='User' ADMIN_EMAIL='[email protected]' ADMIN_PASSWORD='changeme' $ heroku config:add RECURLY_API_KEY=secret RECURLY_JS_PRIVATE_KEY=secret RECURLY_SUBDOMAIN=mydomain
Prepare your application assets for Heroku.
Add this configuration parameter to the config/application.rb file:
# Heroku requires this to be false config.assets.initialize_on_precompile=false
Then precompile assets, commit to git, and push to Heroku:
$ rake assets:precompile $ git add -A $ git commit -m "assets compiled for Heroku" $ git push heroku master
Complete Heroku deployment with:
$ heroku run rake db:migrate $ heroku run rake db:seed
See the Tutorial for Rails on Heroku for details.
This application provides a fully functional membership site that is ready to take credit card payments and serve access to restricted content.
It uses Recurly for payment processing, allows users to change credit cards or subscription plans, and uses Recurly push notifications to delete users who have expired or declined credit cards.
If you have suggestions for additional features, please create an issue on GitHub.
The application provides a 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.
Problems? Check the issues.
The tutorial provides additional documentation.
Please create a GitHub issue if you identify any problems or have suggestions for improvements.
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.
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.
Daniel Kehoe implemented the application and wrote the tutorial.
Taylor Mock contributed tests and feature improvements.
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.
Copyright © 2012 Daniel Kehoe