Class: Afterpay::Client

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/afterpay/client.rb

Overview

Client object acting as the connection Enables the Client to call get/post/patch/delete

Defined Under Namespace

Classes: NotFoundError, UnauthorizedError

Constant Summary collapse

BASE_URL =
"https://api.afterpay.com/"
SANDBOX_BASE_URL =
"https://api.us-sandbox.afterpay.com/v2/"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection = nil) ⇒ Client

Returns a new instance of Client.



35
36
37
# File 'lib/afterpay/client.rb', line 35

def initialize(connection = nil)
  @connection = connection || default_connection
end

Class Method Details

.auth_tokenObject

Auth requires format to be Base64 encoded ‘<app_id>:<secret>`



30
31
32
33
# File 'lib/afterpay/client.rb', line 30

def self.auth_token
  auth_str = "#{Afterpay.config.app_id}:#{Afterpay.config.secret}"
  Base64.strict_encode64(auth_str)
end

.server_urlObject

Decides which URL to use based on env



24
25
26
# File 'lib/afterpay/client.rb', line 24

def self.server_url
  Afterpay.env == "sandbox" ? SANDBOX_BASE_URL : BASE_URL
end

Instance Method Details

#default_connectionObject

The connection object



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/afterpay/client.rb', line 40

def default_connection
  # Use local thread to keep connection open to make use of connection reuse.
  Thread.current[:afterpay_default_connection] ||=
    Faraday.new(url: self.class.server_url) do |conn|
      conn.use ErrorMiddleware if Afterpay.config.raise_errors
      conn.authorization "Basic", self.class.auth_token
      conn.headers["User-Agent"] = "#{Afterpay.config.afterpay_plugin} (#{Afterpay.config.platform}; #{Afterpay.config.system_information}; Merchant/#{Afterpay.config.app_id}) #{Afterpay.config.merchant_website_url}"

      conn.request :json
      conn.response :json, content_type: "application/json", parser_options: { symbolize_names: true }
      conn.adapter Faraday.default_adapter
    end
end