class MandarinApi::Wrapper

Wraps request sending

Public Class Methods

new(merchant_id:, secret:, logger: nil) click to toggle source
# File lib/mandarin_api/wrapper.rb, line 10
def initialize(merchant_id:, secret:, logger: nil)
  @merchant_id = merchant_id
  @secret = secret
  @logger = logger
end

Public Instance Methods

request(endpoint, params = {}) click to toggle source
# File lib/mandarin_api/wrapper.rb, line 16
def request(endpoint, params = {})
  url = URI.join(MandarinApi.config.request_url, endpoint).to_s
  perform_loging url, params, header
  curl = Curl::Easy.new(url)
  curl.headers = header
   curl.post(json(params))
  body = JSON.parse(curl.body_str)
  return body if curl.response_code == 200
  { 'status' => curl.response_code, 'error' => body }
end

Private Instance Methods

camelize(str) click to toggle source
# File lib/mandarin_api/wrapper.rb, line 64
def camelize(str)
  str.split('_').map.with_index(0) do |letter, index|
    if index.zero?
      letter
    else
      letter.capitalize
    end
  end.join
end
generate_x_auth_header(merchant_id, secret) click to toggle source
# File lib/mandarin_api/wrapper.rb, line 41
def generate_x_auth_header(merchant_id, secret)
  request_id = SecureRandom.uuid
  hash = Digest::SHA256.hexdigest "#{merchant_id}-#{request_id}-#{secret}"
  "#{merchant_id}-#{hash}-#{request_id}"
end
header() click to toggle source
# File lib/mandarin_api/wrapper.rb, line 34
def header
  {
    'Content-Type' => 'application/json',
    'X-Auth' => generate_x_auth_header(@merchant_id, @secret)
  }
end
json(params = {}) click to toggle source
# File lib/mandarin_api/wrapper.rb, line 47
def json(params = {})
  JSON.generate(key_transform(params))
end
key_transform(hash) click to toggle source
# File lib/mandarin_api/wrapper.rb, line 51
def key_transform(hash)
  new_hash = {}
  hash.each_key do |key|
    new_hash[camelize(key.to_s)] = case hash[key]
                                   when Hash then key_transform hash[key]
                                   when Array then hash[key].map { |e| key_transform e }
                                   else
                                     hash[key]
                                   end
  end
  new_hash
end
perform_loging(url, params, header) click to toggle source
# File lib/mandarin_api/wrapper.rb, line 29
def perform_loging(url, params, header)
  return if @logger.nil?
  @logger.info "Calling MandarinBank at: #{url}; body: #{params}, header: #{header}"
end