E-Commerce using Rack::Payment

To view this screencast, add it to your cart and checkout. You can buy this screencast for any price, including FREE!

Rack::Payment lets you add 5 lines of code to your Rails (or any Rack-based) application and you can start accepting single payments!

Let’s say you have an online store and you want to accept credit card payments. You can require rack-payment in your application:

 1 # config/environment.rb
 2 
 3 Rails::Initializer.run do |config|
 4   config.gem 'rack-payment'
 5 
 6   config.after_initialize do
 7     config.middleware.use Rack::Payment, :gateway   => 'Paypal',
 8                                          :login     => 'bob',
 9                                          :password  => 'secret',
10                                          :signature => '...'
11   end
12 end

Then you can add a bit more code to display a credit card page to your users to charge them:

 1 class ProductsController < ApplicationController
 2 
 3   # this gives you the 'payment' method
 4   include Rack::Payment::Methods
 5 
 6   def purchase
 7     @product = Product.find params[:id]
 8 
 9     # let Rack::Payment know how much to charge your user
10     payment.amount = @product.cost
11 
12     # this will return a 402 'Payment Required'
13     # which Rack::Payment will see and show the user 
14     # a credit card entry page
15     head :payment_required
16   end
17 
18 end

That’s it :)

If the user fills out the credit card information, they will be charges and see a confirmation page.

That gets you up and running with Rack::Payment’s built-in form, but there is a lot you can do to customize what the form looks like and customize how you handle success/failutre. Rack::Payment also supports Paypal’s express gateway out of the box!

You can use Rack::Payment for recurring payments but it’s not currently built for that. Rack::Payment is currently best used for single transactions.