Adding MercadoPago to our store in Rails

Sebastián Vidal Aedo
2 min readMay 25, 2021

--

Before everything we need our account (in this case in sandbox) and the data for the integration (key and token). You can get both in MercadoPago site.

We need the Access Token

Then, go to our proyect and add the gem to Gemfile and bundle it.

gem 'mercadopago-sdk'

Next, add our credential to .env @le. The most important is the token

ENV_MP_TOKEN = 'here-go-our-token'

To this example, i’ll made a controller and a view just to show the button and how you pass the data (items, prices, quantities, etc)

rails g controller home index

The Controller

To this example, i’ll made a controller and a view just to show the button and how you pass the data (items, prices, quantities, etc).

- currency_id (in this case CLP)
- description
- title
- quantity
- unit_price

To this example, i’ll made a controller and a view just to show the button and how you pass the data (items, prices, quantities, etc). The index method in controller should see like this

def index
require 'mercadopago.rb'
$mp = MercadoPago.new('TEST-our-token')
preference_data = {
"items": [
{
"title": "Product 1",
"unit_price": 100,
"quantity": 1
}
]
}
preference = $mp.create_preference(preference_data)
@preference_id = preference["response"]["id"]
end

The View

Just add a button in a form

<form action="/procesar-pago" method="POST">
<script src="https://www.mercadopago.cl/integrations/v1/web-
payment-checkout.js" data-preference-id="<%= @preference_id %>">
</script>
</form>

Testing

To test the implementation, open another browser or an “ninja” tab and click on the button, this open the mercadopago wizard. Here you can use the test cards available the mercadopago test cards.

test cards

If the payment is successful you will be redirected to http://localhost:3000/procesar-pago, here we have to code the things we want to happen, like update the stock, send emails notification or what ever we want.

That’s it, very easy to integrate and test :)

--

--

No responses yet