Using Checkout and Sinatra

This tutorial will help you integrate Stripe and Ruby’s Sinatra framework

We’re going to create a simple application using Sinatra and Stripe’s Checkout to accept payments in a few lines of code. Sinatra and Stripe are extremely well suited to each other, and the end result of this tutorial is elegant and compact.

You’ll need to have the following prerequisites before we go any further:

The first step is to install the Stripe and Sinatra gems:

$ gem install stripe sinatra

Let’s create a file called app.rb and setup Stripe’s configuration:

require 'sinatra'
require 'stripe'

set :publishable_key, ENV['PUBLISHABLE_KEY']
set :secret_key, ENV['SECRET_KEY']

Stripe.api_key = settings.secret_key

We’re creating two Sinatra settings, :publishable_key and :secret_key which are being pulled out of the current environmental variables. We’re not hardcoding these keys, since it’s often bad practice to put sensitive data into source control.

Next, let’s create some Sinatra methods, to first display our payment form, and then to create charges.

get '/' do
  erb :index
end

post '/charge' do
  # Amount in cents
  @amount = 500

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

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

  erb :charge
end

In our /charge method, we’re creating a Stripe::Charge object with various POST parameters. Stripe expects charges to be in cents, so we’re converting the amount parameter by multiplying it by a hundred.

Stripe Charges also take an optional :description parameter, which in this case is Sinatra Charge. 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 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, and catch any CardError exceptions.

error Stripe::CardError do
  env['sinatra.error'].message
end

Templates

Sinatra lets you inline templates into Ruby files using a neat little Ruby trick, the __END__ keyword.

First we’re going to create a Sinatra layout, which is going to wrap our templates.

__END__

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

Next, let’s create our :index template, which is going to have the credit card form, amount and description. Notice we’re using Checkout, which will display a credit card overlay which includes validation and error handling.

@@ index
  <form action="/charge" method="post" class="payment">
    <article>
      <label class="amount">
        <span>Amount: $5.00</span>
      </label>
    </article>

    <script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
            data-key="<%= settings.publishable_key %>"></script>
  </form>

Finally let’s create a :charge template that shows users a success message.

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

So that’s it, complete Stripe and Sinatra integration in about 60 lines of Ruby and HTML! You can see the full example here. 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 ruby app.rb

Now, if we navigate to http://localhost:4567, 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 Sinatra and Rack. Firstly, get a Heroku account, and install the gem:

$ gem install heroku

We also need to setup a few things, so Heroku knows what gems we’re using. Firstly, we’ll to create a Gemfile for Bundler:

source 'http://rubygems.org'
gem 'sinatra'
gem 'stripe'

Remember to run bundle install to create the Gemfile.lock. Next, let’s add a file called config.ru for Rack:

require './app'
run Sinatra::Application

That’s all the setup required. 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://.