Class: CommandTower::Identity::PhoneVerification::SmsTransport::Adapters::TwilioAdapter

Inherits:
Object
  • Object
show all
Defined in:
app/services/command_tower/identity/phone_verification/sms_transport/adapters/twilio_adapter.rb

Overview

Smallest Twilio REST adapter. Requires Twilio credentials via CredentialResolution and identity.phone_verification.sms_from (or TWILIO_FROM).

Instance Method Summary collapse

Instance Method Details

#deliver(to:, body:) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'app/services/command_tower/identity/phone_verification/sms_transport/adapters/twilio_adapter.rb', line 14

def deliver(to:, body:)
  twilio = CredentialResolution.resolve(:twilio)
   = twilio.
  auth_token = twilio.auth_token
  from = CommandTower.config.identity.phone_verification.sms_from.presence ||
    ENV["TWILIO_FROM"].to_s.presence ||
    ENV["TWILIO_FROM_NUMBER"].to_s.presence

  if .blank? || auth_token.blank? || from.blank?
    return SmsTransport::Result.new(
      success?: false,
      error_code: :configuration_unavailable,
      error_message: "SMS provider is not configured"
    )
  end

  uri = URI("https://api.twilio.com/2010-04-01/Accounts/#{}/Messages.json")
  request = Net::HTTP::Post.new(uri)
  request.basic_auth(, auth_token)
  request.set_form_data("To" => to, "From" => from, "Body" => body)

  response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
    http.request(request)
  end

  if response.is_a?(Net::HTTPSuccess)
    SmsTransport::Result.new(success?: true, error_code: nil, error_message: nil)
  else
    SmsTransport::Result.new(
      success?: false,
      error_code: :provider_unavailable,
      error_message: "SMS provider rejected the request"
    )
  end
rescue StandardError
  SmsTransport::Result.new(
    success?: false,
    error_code: :provider_unavailable,
    error_message: "SMS provider unavailable"
  )
end