Class: AfricaTalking::Client

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

Constant Summary collapse

API_BASE_URL_SANDBOX =
'https://api.sandbox.africastalking.com/version1/'
API_BASE_URL =
'https://api.africastalking.com/version1/'

Instance Method Summary collapse

Constructor Details

#initialize(username, apiKey, sandbox_mode = false) ⇒ Client



11
12
13
14
15
# File 'lib/africa_talking/client.rb', line 11

def initialize(username, apiKey, sandbox_mode = false)
  @username = username
  @apiKey = apiKey
  @sandbox_mode = sandbox_mode
end

Instance Method Details

#client_headersObject



48
49
50
51
52
53
54
55
56
# File 'lib/africa_talking/client.rb', line 48

def client_headers
  hsh = {
      'User-Agent': "favour121/AfricaTalking-#{AfricaTalking::VERSION}",
      'Content-Type': 'application/x-www-form-urlencoded',
      'accept': 'application/json',
      'apiKey': @apiKey
  }
  hsh
end

#client_payloadObject



44
45
46
# File 'lib/africa_talking/client.rb', line 44

def client_payload
  {'username': self.username}
end

#send_request(sms_request) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/africa_talking/client.rb', line 21

def send_request(sms_request)
  if @sandbox_mode
    url = API_BASE_URL_SANDBOX + sms_request.route
  else
    url = API_BASE_URL + sms_request.route
  end
  method = sms_request.http_method
  payload = {}
  headers = client_headers.merge(sms_request.headers)

  headers = headers.merge(params: client_payload) if sms_request.http_method == :get
  payload = client_payload.merge(sms_request.payload) if method != :get

  begin
    response = RestClient::Request.execute(method: method, url: url, payload: payload, headers: headers)
  rescue RestClient::ExceptionWithResponse => err
    raise err
  end

  response_hash = JSON.parse(response.body)
  sms_request.response_class.new(response_hash)
end

#usernameObject



17
18
19
# File 'lib/africa_talking/client.rb', line 17

def username
  @sandbox_mode ? 'sandbox' : @username
end