class OrangeSms::Client

Orange Api Client used to send http request to the Orange Backend

Constants

SUPPORTED_COUNTRIES

Attributes

country[R]
country_code[R]
sender_phone[R]

Public Class Methods

new(country_code = nil) click to toggle source
# File lib/orange_sms/client.rb, line 23
def initialize(country_code = nil)
  @country_code = country_code.nil? ? OrangeSms.default_receiver_country_code : country_code
  @country = SUPPORTED_COUNTRIES[@country_code]
  @sender_country = SUPPORTED_COUNTRIES[OrangeSms.sender_country_code]
  @sender_phone = @sender_country[:prefix] + OrangeSms.sender_phone
end

Public Instance Methods

fetch_access_token() click to toggle source

Fetch the access token directly from your code

# File lib/orange_sms/client.rb, line 31
def fetch_access_token
  response = send_request('/oauth/v2/token',
                          'grant_type=client_credentials',
                          OrangeSms.authorization,
                          'application/x-www-form-urlencoded')
  raise OrangeSms::Error::AuthenticationError.new('Unable to fetch access token', response) if response.status != 200

  JSON.parse(response.body).fetch('access_token', nil)
end
send_sms(receiver_phone, message) click to toggle source

Ask Orange backend to send Sms to some number

# File lib/orange_sms/client.rb, line 47
def send_sms(receiver_phone, message)
  response = send_request("/smsmessaging/v1/outbound/#{sender_phone}/requests",
                          build_sms_payload(receiver_phone, message),
                          "Bearer #{OrangeSms.access_token}", 'application/json')
  raise OrangeSms::Error::ApiError.new('Unable to Send message', response) if response.status != 201
end
send_test_sms() click to toggle source

Ask Orange backend to send test message to the sender_phone defined in the /config/initializer/orange_sms.rb

# File lib/orange_sms/client.rb, line 42
def send_test_sms
  send_sms(OrangeSms.sender_phone, "Yes ! it's working")
end

Private Instance Methods

build_sms_payload(receiver_phone, message) click to toggle source

Build the payload that gonna be sended

# File lib/orange_sms/client.rb, line 64
def build_sms_payload(receiver_phone, message)
  {
    outboundSMSMessageRequest: {
      address: country[:prefix] + receiver_phone,
      senderName: OrangeSms.sender_name,
      senderAddress: sender_phone,
      outboundSMSTextMessage: {
        message: message
      }
    }
  }.to_json
end
send_request(partial_url, payload, authorization_header, content_type) click to toggle source

Send a request

# File lib/orange_sms/client.rb, line 57
def send_request(partial_url, payload, authorization_header, content_type)
  Faraday.post(OrangeSms.base_url + partial_url,
               payload,
               { 'Authorization' => authorization_header, 'Content-type' => content_type })
end