22
Oct

Using Paypal with Rails

posted by vdimos No comments rails

For our latest joint venture we need to implement some kind of payment gateway.
The requirements were simple:

  • We need it secure
  • We need it simple
  • We need it now

The project was a complete overhaul of a job posting site : www.freshwebjobs.com

The talented folks over at Extendio had done a very nice job reskinning the site, and they wanted us to update the codebase, add RoR hype ,some new hooks and features.

The first thing that you think of when doing RoR and e-Commerce is Shopify.
Shopify was created by jadedPixel. They extracted their accumulated e-shopping wisdom and gave the community Active Merchant. AM does a great job in abstracting payment gateway complexity and allowing you to use and switch different payment gateways.
Our first choice for a payment gateway was AuthorizeNet.
The whole RoR community seems to be using it, and their rates were quite acceptable.

The only problem is they work only with US-based companies.
Apparently most of the payment gateways supported by AM do.

After some research we stumbled upon “PayPal Website Payments Standard” (PPWPS). It is the simplest form of payment services offered by Paypal, allowing you to accept credit card and paypal payments.

Ok here is how it works:
The customer lands on your payment page. You can set up encrypted buttons with different amounts. The customer clicks on a button and is redirected to a paypal page where he can use his credit card or paypal login to issue the payment. After doing so he is redirected to your site (or wherever you specify) while an asynchronous notification system lets you know that you have received a payment.

Getting started

In order to get started with PPWPS we need to set up an Sandbox account.
Paypal is providing developers with a virtual sandbox where you can make transactions without real money changing hands.
Before you can use the sandbox you need to create a developer account and log into it.

After you created your developer account make sure you create two test accounts for the sandbox.
One should be a business account the other a simple client account.

When done try to log in at www.sandbox.paypal.com.

Ok we now have our developer account and two accounts for the sandbox.

Paypal requires you to be logged into your developer account when trying to access the sandbox.

As a tip log with one of your browsertabs into your developer account and since the session timeouts pretty quick use autoreload, to reload the index page every 5 minutes.

Initial Setup

First thing we need to make sure is our application is playing in test mode. Test mode means that instead of using the original paypal infrastructure all request are made to the sandbox.

In your config/environment.rb file add the following lines:

# Ensure the gateway is in test mode
 ActiveMerchant::Billing::Base.gateway_mode = :test
 ActiveMerchant::Billing::Base.integration_mode = :test
 ActiveMerchant::Billing::PaypalGateway.pem_file =
                 File.read(File.dirname(__FILE__) + '/../paypal/paypal_cert.pem')

The above code will make sure AM is in test mode. Also it will include the paypal certificate.

Certificates

To get the paypal certificate and setup your own, we will need to log into the sandbox with your business test account.

The paypal sandbox can be somehow slow. Patience young jedi, patience…

When logged go to your “Profile” – “Encrypted Payment Settings”. Here download the paypal public certificate and store it in a folder in your application. I created a paypal folder in the root folder of the application. If you use something else make sure you update the references in environment.rb and crypto42.rb later on.

We will need to create some certificates ourselfes. If you are on a linux box do something like this:

 penssl genrsa -out my-prvkey.pem 1024

then

openssl req -new -key my-prvkey.pem -x509 -days 365 -out my-pubcert.pem

In Ubuntu running the above without sudo throws some errors for me about beeing unable to use the random number generator. If you are not using Linux, consider using it :) .

The above should leave you with two files. my-prvkey.pem and my-pubcert.pem. Move both files into the paypal folder with the paypal public certificate.

Now return to your sandbox account and in “Your Public Certificates” upload your public certificate.
After you added it you will see it in the listing with a Cert ID. Keep this Cert ID for later use.

Lib, controller and the view

Lets get down and write some code.

Here is a snippet I got from the internet and changed it a bit to fit my needs:

module Crypto42
  class Button
    def initialize(data)
      my_cert_file = Dir.getwd + "/paypal/my-pubcert.pem"
      my_key_file = Dir.getwd + "/paypal/my-prvkey.pem"
      paypal_cert_file = Dir.getwd + "/paypal/paypal_cert.pem"

      IO.popen("/usr/bin/openssl smime -sign -signer #{my_cert_file} -inkey #{my_key_file} -outform der -nodetach -binary | /usr/bin/openssl smime -encrypt -des3 -binary -outform pem #{paypal_cert_file}", 'r+') do |pipe|
        data.each { |x,y| pipe << "#{x}=#{y}\n" }
        pipe.close_write
        @data = pipe.read
      end
    end

    def self.from_hash(hs)
      self.new hs
    end

    def get_encrypted_text
      return @data
    end

  end #end button
end #end module

Simple save the above piece of code into a file in your applications lib directory.
It basically calls the system openssl (make sure you have it installed) function to encrypt some data we pass in as argument.

We have following scenario for our site. The customer gets at some point to a page where we want to allow him to choose and buy between N distinguish options.
These options will be buttons linking to Paypal. Upon clicking them the customer will be able to use Paypal to do the purchase.

Paypal lets you create buttons like this through their webpage, but these buttons are fixed and cannot be used to carry extra variables like maybe an invoice number.

We want to create such buttons ourselfes everytime a user comes to our payment site.

Here is how our users controller would look like:

class UsersController < ApplicationController

  include ActiveMerchant::Billing::Integrations
  require 'crypto42'
  require 'money'

... Different user functions...

#place order is for a specific job
  def place_order

    @job = Job.find(params[:job_id])
    fetch_decrypted(@job)

    if @logged_user.credits > 0
      render(:action => "confirm_order")
      return
    else
      #place order will have our paypal buttons
      render(:action => "place_order")
      return
    end

  rescue ActiveRecord::RecordNotFound
    flash[:alert] = "Buying credits for fun?"
    redirect_to :action => "profile"
  end

...

private
  def fetch_decrypted(job = nil)

    # cert_id is the certificate if we see in paypal when we upload our own certificates
    # cmd _xclick need for buttons
    # item name is what the user will see at the paypal page
    # custom and invoice are passthrough vars which we will get back with the asunchronous
    # notification
    # no_note and no_shipping means the client want see these extra fields on the paypal payment
    # page
    # return is the url the user will be redirected to by paypal when the transaction is completed.
    decrypted = {
      "cert_id" => "cert id from your paypal business account",
      "cmd" => "_xclick",
      "business" => "name@yourpaypal.com",
      "item_name" => "FWJ - 1 Credit",
      "item_number" => "1",
      "custom" =>"something to pass to IPN",
      "amount" => "75",
      "currency_code" => "USD",
      "country" => "US",
      "no_note" => "1",
      "no_shipping" => "1",
    }

    if job
      decrypted.merge!("invoice" => "Another passthrough var", "return" => "http://www.freshwebjobs.com/users/done?job_id=#{job.id}")
    else
      decrypted.merge!("return" => "http://www.freshwebjobs.com/users/done")
    end

    @encrypted_basic = Crypto42::Button.from_hash(decrypted).get_encrypted_text


     @action_url = ENV['RAILS_ENV'] == "production" ? "https://www.paypal.com/uk/cgi-bin/webscr" : "https://www.sandbox.paypal.com/uk/cgi-bin/webscr"
end

Now we have our encrypted button code so we can use it like this in the view:

<form action="<%= @action_url %>" method="post">
          <input type="hidden" name="cmd" value="_s-xclick" />
          <input type="hidden" name="encrypted" value="<%= @encrypted_basic %>" />
          <input type="image" src="/images/btn_buynow_SM.jpg" name="submit" alt="3 credits">
</form>

@action_url is set by us depending on the mode.

IPN – Instant (?) Payment Notification

With all the above done, you should have a working payment site! Actually you could stop here and track the transactions via paypal. That would be rather weird though since the application would have no kind of automated feedback about the transactions.
That is where IPN, Paypals’ automated asynchronous event notification system, comes into play.
To set it up we need to enter the sandbox business account again, and go to “Profile” → “Instant Payment Notification Preferences”. Turn it on and set the URL to a URL of you application we are going to use to handle IPNs.

Update: As Mathias mentions in the comments, the IPN URL can be passed as a separate button parameter to Paypal instead of hardcoding it as mentioned above

Here is the code fragment to handle the IPNs, pretty much as it is in the AM source code:

  def ipn
    # Create a notify object we must
    notify = Paypal::Notification.new(request.raw_post)

    #we must make sure this transaction id is not allready completed
    if !Trans.count("*", :conditions => ["paypal_transaction_id = ?", notify.transaction_id]).zero?
       # do some logging here...
    end


    if notify.acknowledge
      begin
        if notify.complete?
           #transaction complete.. add your business logic here
        else
           #Reason to be suspicious
        end

      rescue => e
        #Houston we have a bug
      ensure
        #make sure we logged everything we must
      end
    else #transaction was not acknowledged
      # another reason to be suspicious
    end

    render :nothing => true
  end

Everytime a user pays us, Paypal will issue a request to the IPN url appending a bunch of usefull information. AM is used to acknowledge the request (to make sure noone is spoofing them) and if everything is ok we can add the credits to the user.

Moving into production mode

In order to move our site into production mode we must not forget following things:

  • Change :test to :production in environment.rb
  • Download the real Paypal certificate from your real business account.
  • Upload your own certificates to our account.
  • Change the values for Cert_id, business_name, and returnURL in your button code in the controller
  • Change the IPN URL in your business account profile.
  • Additionaly you can check the allow only encrypted payments in your profile, and check the other settings as well.

To do some basic testing in the real world you can temporarily change the charged amount, make a purchase then issue a refund through paypal.

Ok I think I have covered the basics. Next post will be about testing IPN with mock objects.