module Paidy

Constants

VERSION

Attributes

secret_key[RW]

Public Class Methods

api_uri(path: '') click to toggle source
# File lib/paidy.rb, line 22
def self.api_uri(path: '')
  URI.parse([@api_base, path].join('/'))
end
request(method, path, params = {}, headers = {}) click to toggle source
# File lib/paidy.rb, line 26
def self.request(method, path, params = {}, headers = {})
  if secret_key.nil?
    raise Paidy::AuthenticationError.new('API key does not set.' \
      'You should set `Paidy.secret_key = YOUR_PAIDY_SECRET_KEY`.'
    )
  end

  uri = api_uri(path: path)

  case method.to_s.downcase.to_sym
  when :get
    uri += (uri.query.present? ? '&' : '?') + query_parameter(params) if params.present?
    req = Net::HTTP::Get.new(uri)
  when :post
    req = Net::HTTP::Post.new(uri)
    req.body = params.to_json
  end

  req['Content-Type'] = 'application/json'
  req['Paidy-Version'] = @api_version
  req['Authorization'] = "Bearer #{secret_key}"

  req_options = {
    use_ssl: @use_ssl,
  }

  response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
    http.request(req)
  end

  body = JSON.parse(response.body)
  case response.code.to_i
  when 200
    body
  else
    raise Paidy::ApiError.new "code: #{body['code']}, title: #{body['title']}, description: #{body['description']}"
  end
end

Private Class Methods

query_parameter(params) click to toggle source
# File lib/paidy.rb, line 67
def self.query_parameter(params)
  params.map do |k, v|
    if v.is_a?(Array)
      v.map{ |vv| "#{k}[]=#{CGI.escape(vv)}" }.join('&')
    else
      "#{k}=#{CGI.escape(v)}"
    end
  end.join('&')
end