Archive for the ‘Payment Gateways’ Category

Braintree Integration In Rails Application

Braintree is one gateway that is getting a lot of traction and user love these days due to its ease of use and getting started easily. I have indicated here a few things that should get you started with braintree in rails quickly. In this Blog, we’ll securely process a credit card transaction using the official braintree gem and the Client-side encryption method, utilizing Braintree.js library. The blog covers the case where the form to accept the payments is rendered on the client side only.     Note: Before starting you’ll need to sign up for a Sandbox account. That will provide us with the required braintree API keys. There are two parts to the problem. First one is setting up the form and securing the data to be sent to the server. The next is to process the transaction the server side. Payment Form A simple payment form captures the credit card information along with amount of payment to be made. Here goes a very simple HTML form which asks for all the required info:
<h1>Braintree Credit Card Transaction Form</h1>
<div><form id="braintree- payment-form" action="/create_transaction" method="POST"><label>Card Number</label>
<input type="text" autocomplete="off" size="20" data-encrypted-name="number" />

<input type="text" autocomplete="off" size="4" data-encrypted-name="cvv" />

<label>Expiration (MM/YYYY)</label>
<input type="text" name="month" size="2" /> / <input type="text" name="year" size="4" />

<input id="submit" type="submit" /></form></div>
Next up, we need to encrypt the payment that is being sent from client side to our server for processing. Braintree provides a nice JS library to encrypt the data that is being sent from your form. The integration is as simple as including the library and calling a do it all method.
<script type="text/javascript" src=""></script><script type="text/javascript">// <![CDATA[
var braintree = Braintree.create("YourClientSideEncryptionKey"); braintree.onSubmitEncryptForm('braintree-payment-form');
// ]]></script>
As you can see, we just did couple of steps to secure the data being sent to the server.
  • We initialized the Braintree.js with client-side encryption key.
  • We then called the Braintree.js onSubmitEncryptForm method with the id of the form to encrypt the form before sending it to the server.
Thats it, your data is being securely sent to your server now for processing. Lets move on to the server side of the things. First up install the official braintree gem in your Gemfile. Setting up Rails Controller to commit a transaction with Braintree
  • Every Braintree user receives a unique set of API keys. These need to available in your application.
  • To retrieve the keys, first sign in your Sandbox account.
  • On the sandbox home page, you can get the API keys required to execute transactions with BrainTree.
  • The code will look like this(for sandbox environment)
  • 	Braintree::Configuration.environment = :sandbox
    	Braintree::Configuration.merchant_id = “use_your_merchant_id”
    	Braintree::Configuration.public_key = “use your public key”
    	Braintree::Configuration.private_key = “use your private key”
  • Next Up, lets call up the API call to make the transaction. Braintree gem comes with exhaustive set of method calls to interact with the gateway. Here we initiate a sale with Braintree.
  • 	result = => “1000.00”,
    :credit_card => {:number => params[:number], :cvv => params[:cvv], :expiration_month => params[:month], :expiration_year => params[:year]},
    :options => {:submit_for_settlement => params[:settlement]})
  • Thats it !! The result object will tell us whether initiating the payment succeeded or not. The object comes loaded with methods to test the result like result.success? and result.failed?
This is not the end to the whole payment process in Braintree. Braintree will send calls/hooks informing your application about the various payment states but that is out of scope for the purpose of this blog and will better taken up as a post for separate. I hope the blog helps you get up with Braintree Quickly. Please feel free to drop in comments if any.

Stripe Integration with Ruby on Rails

Stripe is a payment gateway that is easy to set up with your ROR app. It only charges fees on a per-transaction basis and that fee is very reasonable due to which it has been gaining foot in the market and is choice for many internet based stores as a defacto payment processor. Stripe is currently only available in the United States so you’ll need an account at a U.S. bank if you want to use it in your app. In this blog we will see how one can integrate strip in an RoR app:-
  1. First of all create your account at Stripe(
  2. You will get stripe keys(api and publishable) after creating an account, to retrieve. Go to Your Stipe Account -> Account Settings -> API Keys and note down the keys.
  3. Now add the stripe gem in your Gemfile as
  4. gem 'stripe', :git =>
  5. Place the api key in a configuration file to use them globally. For the simplicity of the blog, I assume we have an AppConfig struct which contains the application level globals
  6. Stripe.api_key = AppConfig.stripe[:api_key]
  7. Now Create a view page which will accept the card information from the user that contains the card information like name on card, card number, card id, exp_month and exp_year.
  8. <%= content_tag :tr do %>
     <%= label_tag "Name on Card:"%>
     <% end %>
     <%= content_tag :td do%>
     <%= f.text_field :name_on_card, :required => true%>
     <% end %>
     <% end %>
     <%= content_tag :tr do%>
     <%= content_tag :td do%>
     <%= label_tag "Card Number:"%>
     <% end %>
     <%= content_tag :td do%>
     <%= f.text_field :card_number, :required => true%>
     <% end %>
     <% end %>
  9. Create a stripe token to initiate a payment process
  10. card_token = Stripe::Token.create(:card => {:number => params[:card_number], :exp_month => params[:exp_month],
    :exp_year => params[:exp_year], :cvc => params[:card_id] })
  11. And then charge the card with the token obtained above. Thats it !! Isn’t it damn simple ?
  12. stripe_charge = Stripe::Charge.create(:amount => amoumt_in_cents, :currency => "usd", :card => card_token[:id],:description=> your_email_id )
  13. Stripe takes the amount in cents and your email is required to link the transaction. Now, the charge deducted from the user’s credit card will be added to your account excluding stripe charges.
  14. You can also retrieve the charge information as follows for the record purposes as:
  15. Stripe::Charge.retrieve(stripe_charge[:id])
  16. To Refund the Charge
charge = Stripe::Charge.retrieve(stripe_charge[:id])</pre>
Meanwhile, The Stripe API’s Documentation is available at Important Note: Please note that blog is just meant to illustrate the usage of Stripe in an RoR app. There are many security considerations that must be taken into account while implementing a payment processor in the application. All that is topic for another day and we will suggest to research on proper security methods before implementing any payment processor in the application.

Paypal Integration with RoR application – Securing the transaction

This post is in continuation with the Post Paypal Integration with Rails Application – Integrating IPN. It is important that we secure our paypal transactions with some sort of encryption so that evil hackers dont find it a cakewalk to hack across the various parameters being sent to the paypal server. This step is completely optional but very much neccessary for the secure payments on our website. Generating a Key Pair The first step in securing the payments is to create a key that only our app understands. For this purpose, Create a directory named as ‘certs’ to accommodate certificates. Now generate an openssl keypair and RSA certificate using the following commands:
mkdir certs
cd certs
openssl genrsa -out app_key.pem 1024
openssl req -new -key app_key.pem -x509 -days 365 -out app_cert.pem
Now you have two files in certs directory. Login Merchant’s Account -> Options -> Encrypted Payment Settings -> Add -> browse and select app_cert.pem file -> Add. After you are done, you will see a column ‘Cert ID’ ,copy and paste (in some text file) the text under this column, its your paypal certificate id. We will use if in further steps. Select the added certificate (using radio buttton) and click Download button. Move the downloaded file to our certs directory created above. Modifying the application logic Now we need to modify the application logic to encrypt the parameters and propogate the neccessary certificate information to paypal to be able to decrypt the parameters at its end. In paypal_url method of app/models/product.rb, add :
cert_id =&gt; AppConfig.cert_id, after :notify_url =&gt; notify_url, replace :business =&gt; YOUR_MERCHANT_EMAIL with :business =&gt; AppConfig.paypal_email and replace

1 1="+" 2="values.to_query" 3="[/php" language=""]
24.Add following code to encrypt the information being sent to the paypal:
PAYPAL_CERT_PEM ="#{Rails.root}/certs/paypal_cert.pem")
APP_CERT_PEM ="#{Rails.root}/certs/app_cert.pem")
APP_KEY_PEM ="#{Rails.root}/certs/app_key.pem")

# openssl encryption.
def encrypt_for_paypal(values)
signed = OpenSSL::PKCS7::sign(,                                               , ''), { |k, v|                                                                   "#{k}=#{v}" }.join("\n"), [], OpenSSL::PKCS7::BINARY)
OpenSSL::PKCS7::encrypt([],                                                        signed.to_der, OpenSSL::Cipher::Cipher::new("DES3"),                                                                                                                   OpenSSL::PKCS7::BINARY).to_s.gsub("\n", "")
Set the following values in your configuration file.
paypal_url: ""
paypal_email:  YOUR_MERCHANT_EMAIL

paypal_url: ""
paypal_email:  YOUR_MERCHANT_EMAIL
Note:PAYPAL_CERT_ID is the certificate id that is saved above. In app/views/products/index.html.erb, replace
product.paypal_url(products_url, notification_products_url)
Login to merchant account -> Profile -> Website Payment Preferences -> Select ‘ON’ radio button under heading ‘Encrypted Website Payments’ -> Save. It will block non-encrypted websites to make payments. That’s it. You are now sending encrypted parameters to paypal. Troubleshooting: uninitialized constant AppConfig : Please use whatever protocol you use to load environment specific configuration settings.

Paypal Standard integration with RoR Application – Integrating IPN

Paypal IPN(Instant Payment Notification) is a paypal feature which enables you to get the Payment notification at your application end whenever the payment is complete. This feature enables you to have infinite flexibility at your hand when you want to perform some post payment operations such as shipping etc. Since this blog is a continuation in the series of paypal integration with RoR app, I strongly suggest that you go through our previous article of Basic Paypal Integration with Rails application. Lets go step by step to integrate IPN into our rails application: Enable IPN in the Paypal merchant account: First of all we need to enable IPN in our paypal account. Login to merchant account -> Profile -> Instant Payment Notification Preferences -> Enter notification url and select radio button “Receive IPN messages” -> Save notification url is the url at which the paypal will send the messages to. Handling IPN in the rails application After getting IPN, you can make any operation according to your application’s need. For the demonstration application, I am going to update the payment status as soon as we receive IPN. For this, Generate a new model order and migrate it to database. This model references our old model product and represents an order placed by our user.
 $ rails generate model order product_id:integer quantity:integer amount:decimal status:string

$ rake db:migrate 
Define the required associations. This the order belongs_to a product and product has many orders, we say:
  • In app/models/product.rb, add
has_many : orders
  • In app/models/order.rb, add
belongs_to :product
Make route to receive IPN. Open config/route.rb, replace
 resources :products 
resources :products do

collection do

post 'notification'


Add new method in app/controllers/products_controller.rb, for handling IPN
def notification
if params[:item_number1] && !params[:item_number1].empty?
#paypal sends an IPN even when the transaction is voided.
#save the payment status along with the amount of the transaction.
if params[:payment_status] != 'Voided'
@product = Product.find(params[:item_number1].to_i) rescue nil => 1, :amount => params[:mc_gross_1], :status =>                                                           params[:payment_status]).save unless @product.nil?
render :nothing => true
In app/views/products/index.html.erb, replace product.paypal_url(products_url) with
product.paypal_url(products_url, notification_products_url)
and add a new line after :return => return_url in paypal_url method (in app/models/product.rb), for supporting notify_url:
:notify_url => notify_url,
also change signature of this method to accept notify_url parameter, it will look like:
def paypal_url(return_url, notify_url)
This will basically send the notify_url as a parameter to the paypal informing paypal to send the notification at this url instead of one defined in the paypal merchant control panel. This feature comes in very handy when you need to define the notification url on per product basis. We are now done with implementing the IPN on our RoR application side. Debugging the IPN: Paypal provides a handy tool to check the IPN history. Login to merchant account -> History -> IPN History. You can see the IPN calls being sent and HTTP results for each of them. This comes in pretty handy while debugging the IPN based logic. Enjoy your payments !! The fully implemented application is uploaded on heroku:

Basic Paypal integration with RoR application

Paypal is now a widely accepted payment gateway by the developer community due to its global acceptability and ease of integration with all types of web applications. Here in this blog, we will learn to integrate Paypal Standard with Ruby on Rails(RoR) 3 application.

Sign up for Paypal sandbox account Paypal Sandbox lets you test your Paypal integration without actually charging your credit card or your paypal account. Sandbox is very handy tool to have while your application is in development mode. You can sign up for Paypal Sandbox here. Create Sandbox accounts We will need to create a seller and a buyer account on paypal sandbox for proper testing of payments. When you login to Paypal sandbox, you will see the following options to create accounts:
  • Create a preconfigured account and
  • Create an account manually.
You can use any of above mentioned options for creating accounts. You just need to create two accounts, one for seller and another for buyer. Set the application Scaffold the model. We assume that model is called as Product.
$rails generate scaffold product name: string unit_price: decimal
Migrate the changes to database
$ rake db:migrate
Set root for the application
root :to => 'products#index'
Start rails server ($ rails server) and add some products using link “New Product”. Add a link to buy now in your views(app/views/products/index.html.erb for this example), add following code for every products record We need to define the paypal_url for each product to be sold to communicate appropriate data to paypal. The function defines the various parameters for the paypal and returns them in the form of Query String.  More details about these query string parameters can be found on the paypal developer website. In app/models/product.rb

# This defines the paypal url for a given product sale
def paypal_url(return_url)
values = {
:cmd => '_cart',
:upload => 1,
:return => return_url,
:invoice => UNIQUE_INTEGER

"amount_1" => unit_price,
"item_name_1" => name,
"item_number_1" => id,
"quantity_1" => '1'

# This is a paypal sandbox url and should be changed for production.
# Better define this url in the application configuration setting on environment
# basis.
"" + values.to_query

Some notes about the parameters to be sent to Paypal:
  • : Invoice should be unique every time you make transaction.
  • : Cmd i.e. ‘_cart’ specifies that it’s for shopping cart purchases.
  • : upload = ‘1’ allows third party carts.
For making actual payments, you have to replace last line of above method to:
 "" + values.to_query 
For actual payments you need merchant account on PayPal. 13.In app/controllers/products_controller.rb, add following code:
 flash[:notice] = "Your Transaction is #{params[:st]} for amount of $#{params[:amt]}. Thank You for shopping." if params[:st] 
That’s it!! Now start rails server and click on “Buy Now” link. It will land you to paypal’s payment page. Enter your buyer test account credentials and click login. Now you will see a page with some details, check them and click Pay Now. It will make transaction and will redirect you to return_url you sent from paypal_url method. Notes You will need to enable PAYMENT DATA TRANSFER in the merchant account. To do so, Login to merchant account -> Profile  -> Website Payment Preferences -> Find radio buttons under PAYMENT DATA TRANSFER and set it to ON. -> Click on Save. References
  1. Paypal Standard Integration Guide :
  2. HTML Variables for Paypal Standard Integration: and its Integration in Rails 3.x Application – Part 1

Authorize.Net is a payment gateway that enables merchants to accept credit card and electronic check payments via Web sites, retail stores, mail order/telephone order (MOTO) call centers and mobile devices. In other words, Authorize.Net enables the traditional credit card swipe machine you find in the physical retail world on the web.

Recently, we had an implementation where we had to integrate with a Rails 3.x application. The integration is a cake walk and is very easy for even the novice programmers to follow:

1. The first thing we need is a developer account on Sign up for test account to get API Login ID and Transaction Key. You can sign up from here. Enter you details and select “Card Not Present” as Account Type. Click submit.

2. After successful sign up, you will get a welcome email from developer center which contains some test credit cards numbers.

3. Now simply log in to the Merchant Interface and click “Account.” Then click “API Login ID and Transaction Key.” Your API Login ID will be displayed. For security reasons, you cannot view your Transaction Key. Instead, you must generate a new one. To do this you will need the Secret Answer to the system-generated Secret Question, which is “Simon”.

4. There are 3 major ways to implement in your application:

  • Server Integration Method (SIM)
  • Direct Post Method (DPM) and
  • Advanced Integration Method (AIM)

In this particular blog post, I am going to discuss Server Integration Method (SIM). There are two main features of this method:

  • Provides a customizable, secure hosted payment form.
  • Authorize.Net handles all the steps in the secure transaction process.
  1. We will use authorize-net gem for this particular case. To integrate SIM in your rails application, open the file “Gemfile” in the root directory of your new rails application and add the following line to the end of the file:
gem 'authorize-net'

   and run “bundle install” command from console.

  1. Run the following command it will scaffold everything which we need for integration.
$ rails generate authorize_net:sim payments YOUR_API_LOGIN_ID YOUR_TRANSACTION_KEY YOUR_API_LOGIN_ID
  1. Open config/routes.rb and add the route to the method to claim the payments:
root :to => 'payments#payment'
  1. Now your application is ready to run. Start the server using following command:
$ rails server

You will see a page displaying total amount to be paid and a payment button. If you are facing some errors while starting server, refer to Troubleshoot section of the blog.

  1. Terminate the server and open app/views/payments/payment.erb. It will looks like:
<%= form_for :sim_transaction, :url => AuthorizeNet::SIM::Transaction::Gateway::TEST do |f| %>
 <%= sim_fields(@sim_transaction) %>
 <%= label_tag 'x_amount', "Total: #{number_to_currency(@amount)}" %>
 <br />
 <%= f.submit 'Purchase'%>
<% end %>

  1. Add following code after the label_tag:
<%= hidden_field_tag("x_invoice_num", UNIQUE_INVOICE_NUMBER, {:id => "x_invoice_num"}) %>
<%= hidden_field_tag("x_cust_id", CUSTOMER_ID, {:id => "x_cust_id"}) %>
<%= hidden_field_tag("x_email", EMAIL_ID, {:id => "x_email"}) %>

In above code you have to replace UNIQUE_INVOICE_NUMBER , CUSTOMER_ID, EMAIL_ID with some values or variables. Invoice number should be unique for every payment transaction.

  1. Open app/views/payments/thank_you.erb and add a link to root of your application.
<%= link_to "Home", root_path %>

5. Start your rails server and open the application on browser. Click the “Purchase” button and complete the payment form that appears on the hosted payment page.

6. Select “Visa” and enter any test credit card, any expiration date (MMYY) in the future (such as “1120”), and hit “Submit”.

7. That’s it!! The payment is completed and the user will be redirected to thank you page.

Please feel free to drop a comment in case you have any queries.


  • uninitialized constant RAILS_ROOT: Open config/initializers/authorize_net.rb and replace RAILS_ROOT with Rails.root
  • uninitialized constant RAILS_ENV: Open config/initializers/authorize_net.rb and replace RAILS_ENV with Rails.env

Source Code : The source code for this blog can be found at github.