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 takes an optional :description parameter, which in this case is Rails Stripe customer.

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:

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.

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: