Using Stripe’s Checkout and Rails

This tutorial will help you integrate Stripe and Ruby on Rails

This tutorial will get you up and running with Stripe’s Checkout and Rails in no time at all.

The first step is adding the Stripe gem to your Rails application’s Gemfile:

gem 'stripe', :git => 'https://github.com/stripe/stripe-ruby'

Run bundle install, and then lets generate a new Charges controller.

$ rails g controller charges

The controller is going to do two things. Show a credit card form, and create the actual charges. Let’s go ahead and add those two actions:

def new
end

def create
  # Amount in cents
  @amount = 500

  customer = Stripe::Customer.create(
    :email => 'example@stripe.com',
    :card  => params[:stripeToken]
  )

  charge = Stripe::Charge.create(
    :customer    => customer.id,
    :amount      => @amount,
    :description => 'Rails Stripe customer',
    :currency    => 'usd'
  )

rescue Stripe::CardError => e
  flash[:error] = e.message
  redirect_to charges_path
end

In our create method, we’re creating a Stripe::Charge object with various POST parameters. Stripe expects charges to be in cents, so since we’re charging $5, we’ll need to set the amount parameter to 500.

A Stripe Charge also take an optional :description parameter, which in this case is Rails Stripe customer. This is not something that’ll display in people’s statements, but just in Stripe’s management interface.

Finally, we’re setting the :card property to the stripeToken parameter. This is something that is automatically created for us by Stripe’s Checkout, which we’re going to cover next.

Some payments could fail, for a variety of reasons such as an invalid CVC, card number or failed charge. We can cater for this in a basic manner for the time being by catching any Stripe::CardError exceptions and setting the flash hash.

Routes

Users need to be able to access our newly created controller, so lets add a route to it in config/routes.rb:

resources :charges

Configuration

We need to setup Stripe’s API key before we can use the API. Let’s do this in an initializer. Add the following to config/initializers/stripe.rb:

Rails.configuration.stripe = {
  :publishable_key => ENV['PUBLISHABLE_KEY'],
  :secret_key      => ENV['SECRET_KEY']
}

Stripe.api_key = Rails.configuration.stripe[:secret_key]

We’re pulling these keys out of environmental variables so as not to hardcode them. It’s often bad practice to put sensitive data into source control.

Views

The next step is to create the relevant views, for our credit card form and charge response. Let’s create a charges.html.erb layout under app/views/layouts:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <%= yield %>
</body>
</html>

Now let’s create new.html.erb under app/views/charges, which is going to be our checkout page. Notice we’re using Stripe’s Checkout, which will display a credit card overlay which includes validation and error handling.

<%= form_tag charges_path do %>
  <article>
    <label class="amount">
      <span>Amount: $5.00</span>
    </label>
  </article>

  <script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
          data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
          data-description="A month's subscription"
          data-amount="500"></script>
<% end %>

Finally let’s make a create.html.erb view under app/views/charges that shows users a success message.

<h2>Thanks, you paid <strong>$5.00</strong>!</h2>

And that’s a wrap, Stripe and Rails integration in a matter of minutes.

Let’s start the server, making sure to set the environmental variables we used earlier to Stripe’s publishable and secret keys. For now, let’s use the test keys, rather than the live ones.

PUBLISHABLE_KEY=pk_foo SECRET_KEY=sk_bar rails s

Now, if we navigate to http://localhost:3000/charges/new, we should see our payment form ready to use. If you’re using Stripe’s test keys, then we can test it with some dummy data. Enter the test number 4242 4242 4242 4242, a three digit CVC and any expiry date in the future. Submitting the form should bring up our successful charge page.

Deploying to Heroku

So now we’ve created our basic payment page, let’s get it deployed somewhere so people can use it! Heroku is an awesome way to do this, and integrates seamlessly with Rails and Rack. Firstly, get a Heroku account, and install the gem:

$ gem install heroku

Now to tell Heroku to deploy our application.

heroku create
heroku config:set PUBLISHABLE_KEY=pk_test_6pRNASCoBOKtIshFeQd4XMUh SECRET_KEY=sk_test_BQokikJOvBiI2HlWgH4olfQ2
git push heroku master
heroku open

Note that we’ve placed your test API keys in the example above. You’ll need to swap it out with your live keys in production. You can see all your keys in your dashboard.

By default, Heroku includes SSL for all applications. Just change the url from http:// to https://.