Aug 07, 2014

Integrating a Rails App With Espago

blogpost author photo
Michał Brodecki
blogpost cover image
Most projects contain features that have to be done using a payment broker. Your client can choose from lots of avaliable payments providers in Poland, i.e.: paylane, payU, przelewy24 etc. Every operator is trying to do their best to convince customers that they are the most suitable offer on the market.

Depending on margins, clients can choose a payment provider and our job is to properly intagrate application with the service. And here comes the difficult part. Each provider has their own documentation and a unique system of handling payments. As developers we need to read that documentation and worse, we need to understand it perfectly. Recently we have integrated some applications with Espago payments. Sadly there aren’t many examples of integrating it with Rails (which means: there are no examples). I decided to help anyone that uses Espago in their own Rails app. The sample application can be found on our github. Keep in mind that you’re going to need to create your own secrets.yml file.

What do I need to begin?

First of all, you need a sandbox account at Espago. After you obtain such an account (a sandbox account suits well for our playground), you can start integrating. In this post, I will show you how to process a credit card transaction. Thankfully there exists an espago gem written by one of the Espago developers that will help us wrap the API calls.

gem 'espago', :git => 'git://'

You need to obtain your espago app_id, application password, and public key. This data is neccessary to connect with our sandbox installation and test out our payments.


The second good thing to do is opening the documentation, where you can find instructions on finding these information. OK, let’s start with a little theory.

How it works.

Espago card payments are based on a provided script written in Java. Why do we need this script? Obviously, we cannot receive sensitive parameters that are sent during the form submit. We have to include the script into our app, and then write our own little piece of javascript. Seems complicated? It may appear so when you don’t know how to handle it yet. But belive me, it isn’t that complex. See how it’s done: 1. We bind espago script to our form. 2. The form is communicating with an Espago gate using it’s own API. 3. The token is created and sent to the app as a parameter named “card_token”. This token an accessor code that can identify a customer. 4. From now on, we can make API calls using that token, so we can create a client, charge him for a specific amount, delete him from espago etc.

OK – enough theory. I think we can now take a step forward.

Building the view.

First we need to create a view containing the form. Just remmember to ommit the attribute ‘name’ in order to prevent the parameters from being sent. Please forgive very ugly stylesheet, I will try to fix this in the future :( The nasty form view looks like this:

%h1 Payments
=form_tag charge_customer_path do
    %label Credit Card Number
    %input#espago_card_number{type: "text"}
    %label First Name
    %input#espago_first_name{type: "text"}
    %label Last Name
    %input#espago_last_name{type: "text"}
    %label Month expire
    %input#espago_month{type: "text"}
    %label Year expire
    %input#espago_year{type: "text"}
    %label Verification Value
    %input#espago_verification_value{type: "text"}
  =submit_tag "Charge me"

This simple form collects all the required fields for Espago. The next step will be binding the Espago js script to it.

Adding the javascripts.

First of all we need to identify our form. We assign an id to it – “espago_form”. Then we need to write and bind some javascript to it. The one used here is a pretty basic example from the Espago docs, but feel free to customize it as much as you want.

$( document ).ready(function() {
    var espago = new Espago({public_key: "#{Rails.application.secrets.espago_public_key}", custom: true, live: false});
    if (espago.validate_card_number()){
    } else {
      $("#espago_card_number_error").text("Data error!");

    if (espago.validate_first_name()){
    } else {
      $("#espago_first_name_error").text("Data error!");

    if (espago.validate_last_name()){
    } else {
      $("#espago_last_name_error").text("Data error!");

    if (espago.validate_card_date()){
    } else {
      $("#espago_year_error").text("Data error!");

    if (espago.validate_card_cvc()){
    } else {
      $("#espago_verification_value_error").text("Data error!");

Before, when we submitted the form without javascript, we received an error because Rails accessed an empty action in our controller. With this javascript we can prevent the call of the action and first validate the data, create a token and pass it to the controller action. We can test it by filling the form with correct data. Below you’ll find an example set of data:

  1. name –> string
  2. surname –> string
  3. card number –> 4242424242424242
  4. year expire –> current year and further
  5. month expire –> month from range 01 to 05 – the rest of the numbers are reserved for error messages (read more in docs)
  6. cvc –> 123

After filling in the form we can look into the parameters.

{"utf8"=>"✓", "authenticity_token"=>"gWbGUitZLyqoXg9Hebftn6lapI429iJ2YvRZUJCcyw4=", "card_token"=>"cc_9PCxD2rjeZcnpO2", "action"=>"charge_customer", "controller"=>"payments"}

Please notice the card_token parameter. Javascript returned this precious information for us :) As we log into sandbox we will notice that our API call is showing up.

Getting money!

OK, now for the most important thing. We need to start getting the money! We have it all prepared, and now we need to make some API calls to make use of it. First of all we have to create the client object in Espago’s system. The gem I mentioned before can help us with this. We just need to add the espago.rb file in our /config/initializers folder.

Espago.app_id = ESPAGO_APP_ID
Espago.app_password = ESPAGO_APP_PASSWORD
Espago.public_key = ESPAGO_PUBLIC_KEY
Espago.production = ESPAGO_PRODUCTION

Remmember to replace the values on the right side. Now after we get our espago token we can call the API action that is responsible for creating the client (it is neccessary to charge the money). Using this gem is really simple.

response = Espago.clients(:post, card: params[:card_token], description: "New client" ).body

At response we got this hash:

{"email"=>nil, "id"=>"cli_B5loNyay-z-MvH", "created_at"=>1406121738, "description"=>"New client", "card"=>{"company"=>"VI", "last4"=>"4242", "year"=>2015, "month"=>3, "first_name"=>"Test", "last_name"=>"test", "authorized"=>true, "created_at"=>1406121738}, "deleted"=>false}

We can see that Espago created our client. Great success! Let’s proceed with charging him for a little amount of money.

charge = {amount: 100.0, description: "Description", currency: 'pln', client: request["id"]}
response = Espago.charges(:post, charge)

First, let’s build a hash contaning all neccessary information that we need to pass to Espago. We need to send the amount, transaction description and client id, which can be obtained from the previous request’s response. After that, we can make a POST request and it’s done. Our client has now been charged for 100 PLN :) You may want to analyse the response to see if no errors were returned.

{"id"=>"pay_1iUiVzFQ_I7zaX", "description"=>"Description", "channel"=>"elavon", "amount"=>"100.00", "currency"=>"pln", "state"=>"executed", "client"=>"cli_gOphIJ6GmdDdS9", "created_at"=>1406121994, "card"=>{"company"=>"VI", "last4"=>"4242", "year"=>2015, "month"=>3, "first_name"=>"Test", "last_name"=>"test", "authorized"=>true, "created_at"=>1406121992}, "issuer_response_code"=>"00", "reversable"=>true, "transaction_id"=>"tn_dGUdLDMyh"}

If you want to use this code you’ll have to add error and success handling to it and design a bit nicer layout. This post was only a basic explanation on using the Espago payment provider and our beloved Rails framework. I hope you understood it well – feel free to contact me if you have any trouble. Good luck!