class WorldpayCnp::ApiClient

Constants

HEADERS
INVALID_RESPONSE_VALUES

Public Class Methods

new(config) click to toggle source
# File lib/worldpay_cnp/api_client.rb, line 16
def initialize(config)
  @config = config
end

Public Instance Methods

perform_post(url, data) click to toggle source
# File lib/worldpay_cnp/api_client.rb, line 20
def perform_post(url, data)
  response = http_client.post(url, body: XML.serialize(data.to_camel_case))
  process_response(response)
end

Protected Instance Methods

handle_invalid_format_error(hash, body) click to toggle source
# File lib/worldpay_cnp/api_client.rb, line 63
def handle_invalid_format_error(hash, body)
  if INVALID_RESPONSE_VALUES.include?(hash.dig(:response))
    raise Error::InvalidFormatError.new(
      hash.dig(:message),
      response_code: hash.dig(:response),
      raw_response: body
    )
  end
end
hash_from_xml(xml) click to toggle source
# File lib/worldpay_cnp/api_client.rb, line 56
def hash_from_xml(xml)
  result = XML.parse(xml)
  if root_key = result.keys.first
    result[root_key]&.to_snake_case&.deep_symbolize_keys
  end
end
http_client() click to toggle source
# File lib/worldpay_cnp/api_client.rb, line 27
def http_client
  client = with_proxy? ? HTTP.via(*proxy) : HTTP
  client.headers(HEADERS).timeout(@config.timeout || :null)
end
parse_response_body(body) click to toggle source
# File lib/worldpay_cnp/api_client.rb, line 51
def parse_response_body(body)
  return {} if body.strip.empty?
  hash_from_xml(body)
end
process_response(response) click to toggle source
# File lib/worldpay_cnp/api_client.rb, line 40
def process_response(response)
  data = parse_response_body(response.to_s)

  if response.status.success?
    handle_invalid_format_error(data, response.to_s)
    Response.new(data, response.status.code, response.to_s)
  else
    raise Error.from_http_response(response.to_s, response.status.code)
  end
end
proxy() click to toggle source
# File lib/worldpay_cnp/api_client.rb, line 36
def proxy
  @proxy ||= @config.proxy&.values_at(:host, :port, :username, :password)&.compact
end
with_proxy?() click to toggle source
# File lib/worldpay_cnp/api_client.rb, line 32
def with_proxy?
  !proxy.nil? && !proxy.empty?
end