Class: Cardflex::Http

Inherits:
Object
  • Object
show all
Defined in:
lib/cardflex/http.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Http



5
6
7
# File 'lib/cardflex/http.rb', line 5

def initialize(config)
  @config = config
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



3
4
5
# File 'lib/cardflex/http.rb', line 3

def config
  @config
end

Instance Method Details

#_add_api_key(params) ⇒ Object



59
60
61
62
# File 'lib/cardflex/http.rb', line 59

def _add_api_key(params)
  key = params.keys[0]
  { key => params[key].merge(:api_key => @config.api_key) }
end

#_current_timeObject



45
46
47
# File 'lib/cardflex/http.rb', line 45

def _current_time
  Time.now.utc.strftime("%d/%b/%Y %H:%M:%S %Z")
end

#_do_http(http_verb, body = nil) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/cardflex/http.rb', line 15

def _do_http(http_verb, body=nil)
  connection = Net::HTTP.new(@config.server, @config.port)
  connection.open_timeout = 60
  connection.read_timeout = 60
  if @config.ssl?
    connection.use_ssl = true
    connection.verify_mode = OpenSSL::SSL::VERIFY_PEER
    connection.ca_file = @config.ca_file
    connection.verify_callback = proc { |preverify_ok, ssl_context| _verify_ssl_certificate(preverify_ok, ssl_context) }
  end

  connection.start do |http|
    request = http_verb.new("#{@config.three_step_path}")
    request['Accept'] = 'text/xml'
    @config.logger.debug("[Cardflex] [#{_current_time}] #{request.method} as text/xml")
    if body
      request['Content-Type'] = 'text/xml'
      request.body = body
      @config.logger.debug _format_body_for_log(body)
    end

    response = http.request(request)
    @config.logger.info "[Cardflex] [#{_current_time}] #{request.method} #{response.code}"
    @config.logger.debug _format_body_for_log(response.body)
    response
  end
rescue OpenSSL::SSL::SSLError
  raise Cardflex::SSLCertificateError
end

#_format_body_for_log(body) ⇒ Object



64
65
66
# File 'lib/cardflex/http.rb', line 64

def _format_body_for_log(body)
  body.gsub(/^/, "[Cardflex] ")
end

#_verify_ssl_certificate(preverify_ok, ssl_context) ⇒ Object



49
50
51
52
53
54
55
56
57
# File 'lib/cardflex/http.rb', line 49

def _verify_ssl_certificate(preverify_ok, ssl_context)
  if preverify_ok != true || ssl_context.error != 0
    err_msg = "SSL Verification failed -- Preverify: #{preverify_ok}, Error: #{ssl_context.error_string} (#{ssl_context.error})"
    @config.logger.error err_msg
    false
  else
    true
  end
end

#post(params = {}) ⇒ Object



9
10
11
12
13
# File 'lib/cardflex/http.rb', line 9

def post(params={})
  params = _add_api_key(params)
  response = _do_http(Net::HTTP::Post, Xml.hash_to_xml(params))
  Xml.parse(response.body)
end