Module: MercadoPago::Request

Defined in:
lib/mercadopago/request.rb

Defined Under Namespace

Classes: ClientError

Constant Summary collapse

CONTENT_HEADERS =
{
  content_type: 'application/json',
  accept: 'application/json'
}.freeze
MERCADOPAGO_URL =

This URL is the base for all API calls.

'https://api.mercadopago.com'.freeze

Class Method Summary collapse

Class Method Details

.make_request(type, path, payload = nil, headers = {}) ⇒ Object

Makes a HTTP request to a MercadoPago API.

  • type: the HTTP request type (:get, :post, :put, :delete).

  • path: the path of the API to be called.

  • payload: the data to be trasmitted to the API.

  • headers: the headers to be transmitted over the HTTP request.



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/mercadopago/request.rb', line 65

def self.make_request(type, path, payload = nil, headers = {})
  args = [type, MERCADOPAGO_URL, path, payload, headers].compact

  connection = Faraday.new(MERCADOPAGO_URL, ssl: { version: :TLSv1_2 })

  response = connection.send(type) do |req|
    req.url path
    req.headers = headers
    req.body = payload
  end

  JSON.load(response.body)
rescue Exception => e
  if e.respond_to?(:response)
    JSON.load(e.response)
  else
    raise e
  end
end

.wrap_get(path, headers = nil) ⇒ Object

Makes a GET request to a MercadoPago API.

  • path: the path of the API to be called, including any query string parameters.

  • headers: the headers to be transmitted over the HTTP request.



52
53
54
55
# File 'lib/mercadopago/request.rb', line 52

def self.wrap_get(path, headers = nil)
  headers ||= CONTENT_HEADERS
  make_request(:get, path, nil, headers)
end

.wrap_post(path, payload, headers = nil) ⇒ Object

Makes a POST request to a MercadoPago API.

  • path: the path of the API to be called.

  • payload: the data to be trasmitted to the API.

  • headers: the headers to be transmitted over the HTTP request.



28
29
30
31
32
# File 'lib/mercadopago/request.rb', line 28

def self.wrap_post(path, payload, headers = nil)
  raise ClientError('No data given') if payload.nil? or payload.empty?
  headers ||= CONTENT_HEADERS
  make_request(:post, path, payload, headers)
end

.wrap_put(path, payload, headers = {}) ⇒ Object

Makes a PUT request to a MercadoPago API.

  • path: the path of the API to be called.

  • payload: the data to be trasmitted to the API.

  • headers: the headers to be transmitted over the HTTP request.



41
42
43
44
# File 'lib/mercadopago/request.rb', line 41

def self.wrap_put(path, payload, headers = {})
  raise ClientError('No data given') if payload.nil? or payload.empty?
  make_request(:put, path, payload, headers)
end