Class: CheckHim::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/checkhim/client.rb

Overview

Client for interacting with the CheckHim Verification API.

Constant Summary collapse

DEFAULT_ENDPOINT =
'https://api.checkhim.tech/api/v1'.freeze
VERIFY_PATH =
'/verify'.freeze
DEFAULT_OPEN_TIMEOUT =
5
DEFAULT_READ_TIMEOUT =
10

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key, endpoint: DEFAULT_ENDPOINT, open_timeout: DEFAULT_OPEN_TIMEOUT, read_timeout: DEFAULT_READ_TIMEOUT, user_agent: nil) ⇒ Client

Returns a new instance of Client.

Raises:

  • (ArgumentError)


16
17
18
19
20
21
22
23
24
# File 'lib/checkhim/client.rb', line 16

def initialize(api_key, endpoint: DEFAULT_ENDPOINT, open_timeout: DEFAULT_OPEN_TIMEOUT, read_timeout: DEFAULT_READ_TIMEOUT, user_agent: nil)
  raise ArgumentError, 'api_key must be provided' if api_key.nil? || api_key.strip.empty?

  @api_key = api_key
  @endpoint = endpoint.chomp('/')
  @open_timeout = open_timeout
  @read_timeout = read_timeout
  @user_agent = user_agent || default_user_agent
end

Instance Attribute Details

#api_keyObject (readonly)

Returns the value of attribute api_key.



14
15
16
# File 'lib/checkhim/client.rb', line 14

def api_key
  @api_key
end

#endpointObject (readonly)

Returns the value of attribute endpoint.



14
15
16
# File 'lib/checkhim/client.rb', line 14

def endpoint
  @endpoint
end

#open_timeoutObject (readonly)

Returns the value of attribute open_timeout.



14
15
16
# File 'lib/checkhim/client.rb', line 14

def open_timeout
  @open_timeout
end

#read_timeoutObject (readonly)

Returns the value of attribute read_timeout.



14
15
16
# File 'lib/checkhim/client.rb', line 14

def read_timeout
  @read_timeout
end

#user_agentObject (readonly)

Returns the value of attribute user_agent.



14
15
16
# File 'lib/checkhim/client.rb', line 14

def user_agent
  @user_agent
end

Instance Method Details

#verify(number) ⇒ Object

Verifies a phone number. Returns a VerificationResult on success. Raises CheckHim::Error subclasses on failure.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/checkhim/client.rb', line 28

def verify(number)
  payload = { number: number, type: 'frontend' }
  uri = URI.parse(@endpoint + VERIFY_PATH)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = uri.scheme == 'https'
  http.open_timeout = @open_timeout
  http.read_timeout = @read_timeout

  request = Net::HTTP::Post.new(uri.request_uri)
  request['Authorization'] = "Bearer #{@api_key}"
  request['Content-Type'] = 'application/json'
  request['Accept'] = 'application/json'
  request['User-Agent'] = @user_agent
  request.body = JSON.generate(payload)

  response = http.request(request)
  handle_response(response)
rescue Timeout::Error, Errno::ECONNREFUSED, SocketError => e
  raise NetworkError.new("Network error: #{e.message}")
end