Class: Glabssms::Client

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Client

Returns a new instance of Client.



5
6
7
8
9
10
11
12
13
# File 'lib/glabssms/client.rb', line 5

def initialize(config)
  if config.is_a? Hash
    @config = Configuration.new config
  elsif config.is_a? Glabssms::Configuration
    @config = config
  else
    raise ArgumentError, 'config is an invalid type'
  end
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



3
4
5
# File 'lib/glabssms/client.rb', line 3

def config
  @config
end

Instance Method Details

#get_token(code:) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/glabssms/client.rb', line 15

def get_token(code:)
  uri = URI.parse("https://developer.globelabs.com.ph/oauth/access_token?app_id=#{config.app_id}&app_secret=#{config.app_secret}&code=#{code}")
  https = Net::HTTP.new(uri.host, uri.port)
  https.use_ssl = true
  req = Net::HTTP::Post.new(uri.request_uri)
  res = https.request(req)
  body = JSON.parse(res.body).with_indifferent_access

  if body[:access_token] && body[:subscriber_number]
    TokenResult._new(body)
  elsif body[:error]
    ErrorResult.new(body[:error])
  else
    raise UnexpectedError, 'expected query parameters app_id, app_secret and code'
  end
end

#send_sms(number:, message:, token:) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/glabssms/client.rb', line 32

def send_sms(number:, message:, token:)
  header = { 'Content-Type': 'application/json' }
  sender_address = config.short_code[-4..-1]
  sms_params = {
    outboundSMSMessageRequest: {
      senderAddress: sender_address,
      outboundSMSTextMessage: { message: message },
      address: number
    }
  }.to_json

  uri = URI.parse("https://devapi.globelabs.com.ph/smsmessaging/v1/outbound/#{sender_address}/requests?access_token=#{token}")
  https = Net::HTTP.new(uri.host, uri.port)
  https.use_ssl = true
  req = Net::HTTP::Post.new(uri.request_uri, header)
  req.body = sms_params
  res = https.request(req)

  body = JSON.parse(res.body).with_indifferent_access

  if body['outboundSMSMessageRequest']
    SmsResult._new(body)
  elsif body[:error]
    ErrorResult.new(body[:error])
  else
    raise UnexpectedError, 'expected query parameters access_token'
  end
end