Class: Braintree::Http

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

Overview

:nodoc:

Direct Known Subclasses

GraphQLClient

Constant Summary collapse

LINE_FEED =
"\r\n"

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Http

Returns a new instance of Http.


6
7
8
# File 'lib/braintree/http.rb', line 6

def initialize(config)
  @config = config
end

Instance Method Details

#_add_file_part(key, file) ⇒ Object


153
154
155
156
157
# File 'lib/braintree/http.rb', line 153

def _add_file_part(key, file)
  mime_type = _mime_type_for_file_name(file.path)
  return "Content-Disposition: form-data; name=\"#{key}\"; filename=\"#{file.path}\"#{LINE_FEED}" +
      "Content-Type: #{mime_type}#{LINE_FEED}#{LINE_FEED}#{file.read}#{LINE_FEED}"
end

#_add_form_field(key, value) ⇒ Object


149
150
151
# File 'lib/braintree/http.rb', line 149

def _add_form_field(key, value)
  return "Content-Disposition: form-data; name=\"#{key}\"#{LINE_FEED}#{LINE_FEED}#{value}#{LINE_FEED}"
end

#_body(response) ⇒ Object


172
173
174
175
176
177
178
179
180
181
# File 'lib/braintree/http.rb', line 172

def _body(response)
  content_encoding = response.header["Content-Encoding"]
  if content_encoding == "gzip"
    Zlib::GzipReader.new(StringIO.new(response.body)).read
  elsif content_encoding.nil?
    ""
  else
    raise UnexpectedError, "expected a gzipped response"
  end
end

#_build_query_string(params) ⇒ Object


59
60
61
62
63
64
65
66
67
68
# File 'lib/braintree/http.rb', line 59

def _build_query_string(params)
  if params.empty?
    ""
  else
    "?" + params.map do |x, y|
      raise(ArgumentError, "Nested hashes aren't supported in query parameters") if y.respond_to?(:to_hash)
      "#{x}=#{y}"
    end.join("&")
  end
end

#_build_xml(params) ⇒ Object


54
55
56
57
# File 'lib/braintree/http.rb', line 54

def _build_xml(params)
  return "" if params.nil?
  Braintree::Xml.hash_to_xml params
end

#_compose_headers(header_overrides = {}) ⇒ Object


85
86
87
88
89
90
91
92
93
94
# File 'lib/braintree/http.rb', line 85

def _compose_headers(header_overrides = {})
  headers = {}
  headers["Accept"] = "application/xml"
  headers["User-Agent"] = @config.user_agent
  headers["Accept-Encoding"] = "gzip"
  headers["X-ApiVersion"] = @config.api_version
  headers["Content-Type"] = "application/xml"

  headers.merge(header_overrides)
end

#_current_timeObject


183
184
185
# File 'lib/braintree/http.rb', line 183

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

#_format_and_sanitize_body_for_log(input_xml) ⇒ Object


187
188
189
190
191
192
193
# File 'lib/braintree/http.rb', line 187

def _format_and_sanitize_body_for_log(input_xml)
  formatted_xml = input_xml.gsub(/^/, "[Braintree] ")
  formatted_xml = formatted_xml.gsub(/<number>(.{6}).+?(.{4})<\/number>/m, '<number>\1******\2</number>')
  formatted_xml = formatted_xml.gsub(/<cvv>.+?<\/cvv>/m, "<cvv>***</cvv>")
  formatted_xml = formatted_xml.gsub(/<encrypted-card-data>.+?<\/encrypted-card-data>/m, "<encrypted-card-data>***</encrypted-card-data>")
  formatted_xml
end

#_http_do(http_verb, path, body = nil, file = nil, connection = nil, header_overrides = {}) ⇒ Object


96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/braintree/http.rb', line 96

def _http_do(http_verb, path, body = nil, file = nil, connection = nil, header_overrides = {})
  connection ||= _setup_connection

  connection.open_timeout = @config.http_open_timeout
  connection.read_timeout = @config.http_read_timeout
  if @config.ssl?
    connection.use_ssl = true
    connection.ssl_version = @config.ssl_version if @config.ssl_version
    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(path)
    _compose_headers(header_overrides).each { |header, value| request[header] = value }
    if @config.client_credentials?
      request.basic_auth @config.client_id, @config.client_secret
    elsif @config.access_token
      request["Authorization"] = "Bearer #{@config.access_token}"
    else
      request.basic_auth @config.public_key, @config.private_key
    end
    @config.logger.debug "[Braintree] [#{_current_time}] #{request.method} #{path}"
    if body
      if file
        boundary = DateTime.now.strftime("%Q")
        request["Content-Type"] = "multipart/form-data; boundary=#{boundary}"

        form_params = []
        body.each do |k, v|
          form_params.push(_add_form_field(k, v))
        end
        form_params.push(_add_file_part("file", file))
        request.body = form_params.collect { |p| "--" + boundary + "#{LINE_FEED}" + p }.join("") + "--" + boundary + "--"
        @config.logger.debug _format_and_sanitize_body_for_log(_build_xml(body))
      else
        request.body = body
        @config.logger.debug _format_and_sanitize_body_for_log(body)
      end
    end
    response = http.request(request)
    @config.logger.info "[Braintree] [#{_current_time}] #{request.method} #{path} #{response.code}"
    @config.logger.debug "[Braintree] [#{_current_time}] #{response.code} #{response.message}"
    if @config.logger.level == Logger::DEBUG
      @config.logger.debug _format_and_sanitize_body_for_log(_body(response))
    end
    response
  end
rescue OpenSSL::SSL::SSLError
  raise Braintree::SSLCertificateError
end

#_mime_type_for_file_name(filename) ⇒ Object


159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/braintree/http.rb', line 159

def _mime_type_for_file_name(filename)
  file_extension = File.extname(filename).strip.downcase[1..-1]
  if file_extension == "jpeg" || file_extension == "jpg"
    return "image/jpeg"
  elsif file_extension == "png"
    return "image/png"
  elsif file_extension == "pdf"
    return "application/pdf"
  else
    return "application/octet-stream"
  end
end

#_setup_connection(server = @config.server, port = @config.port) ⇒ Object


70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/braintree/http.rb', line 70

def _setup_connection(server = @config.server, port = @config.port)
  if @config.proxy_address
    connection = Net::HTTP.new(
      server,
      port,
      @config.proxy_address,
      @config.proxy_port,
      @config.proxy_user,
      @config.proxy_pass,
    )
  else
    connection = Net::HTTP.new(server, port)
  end
end

#_verify_ssl_certificate(preverify_ok, ssl_context) ⇒ Object


195
196
197
198
199
200
201
202
203
# File 'lib/braintree/http.rb', line 195

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

#delete(_path, query_params = {}) ⇒ Object


10
11
12
13
14
15
16
17
18
19
20
# File 'lib/braintree/http.rb', line 10

def delete(_path, query_params = {})
  path = _path + _build_query_string(query_params)
  response = _http_do Net::HTTP::Delete, path
  if response.code.to_i == 200 || response.code.to_i == 204
    true
  elsif response.code.to_i == 422
    Xml.hash_from_xml(_body(response))
  else
    Util.raise_exception_for_status_code(response.code)
  end
end

#get(_path, query_params = {}) ⇒ Object


22
23
24
25
26
27
28
29
30
# File 'lib/braintree/http.rb', line 22

def get(_path, query_params = {})
  path = _path + _build_query_string(query_params)
  response = _http_do Net::HTTP::Get, path
  if response.code.to_i == 200 || response.code.to_i == 422
    Xml.hash_from_xml(_body(response))
  else
    Util.raise_exception_for_status_code(response.code)
  end
end

#post(path, params = nil, file = nil) ⇒ Object


32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/braintree/http.rb', line 32

def post(path, params = nil, file = nil)
  body = params
  if !file
    body = _build_xml(params)
  end
  response = _http_do Net::HTTP::Post, path, body, file
  if response.code.to_i == 200 || response.code.to_i == 201 || response.code.to_i == 422
    Xml.hash_from_xml(_body(response))
  else
    Util.raise_exception_for_status_code(response.code)
  end
end

#put(path, params = nil) ⇒ Object


45
46
47
48
49
50
51
52
# File 'lib/braintree/http.rb', line 45

def put(path, params = nil)
  response = _http_do Net::HTTP::Put, path, _build_xml(params)
  if response.code.to_i == 200 || response.code.to_i == 201 || response.code.to_i == 422
    Xml.hash_from_xml(_body(response))
  else
    Util.raise_exception_for_status_code(response.code)
  end
end