2020-06-07 08:28:05 +00:00
|
|
|
class Api::V1::Accounts::Channels::TwilioChannelsController < Api::V1::Accounts::BaseController
|
2020-04-05 16:41:27 +00:00
|
|
|
before_action :authorize_request
|
|
|
|
|
|
|
|
def create
|
2020-04-29 20:11:13 +00:00
|
|
|
ActiveRecord::Base.transaction do
|
|
|
|
authenticate_twilio
|
|
|
|
build_inbox
|
|
|
|
setup_webhooks if @twilio_channel.sms?
|
|
|
|
rescue StandardError => e
|
|
|
|
render_could_not_create_error(e.message)
|
|
|
|
end
|
2020-04-05 16:41:27 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def authorize_request
|
|
|
|
authorize ::Inbox
|
|
|
|
end
|
|
|
|
|
|
|
|
def authenticate_twilio
|
|
|
|
client = Twilio::REST::Client.new(permitted_params[:account_sid], permitted_params[:auth_token])
|
|
|
|
client.messages.list(limit: 1)
|
|
|
|
end
|
|
|
|
|
|
|
|
def setup_webhooks
|
|
|
|
::Twilio::WebhookSetupService.new(inbox: @inbox).perform
|
|
|
|
end
|
|
|
|
|
2020-04-29 20:11:13 +00:00
|
|
|
def phone_number
|
2022-07-18 14:32:37 +00:00
|
|
|
return if permitted_params[:phone_number].blank?
|
|
|
|
|
2020-04-29 20:11:13 +00:00
|
|
|
medium == 'sms' ? permitted_params[:phone_number] : "whatsapp:#{permitted_params[:phone_number]}"
|
|
|
|
end
|
|
|
|
|
|
|
|
def medium
|
|
|
|
permitted_params[:medium]
|
|
|
|
end
|
|
|
|
|
2020-04-05 16:41:27 +00:00
|
|
|
def build_inbox
|
2020-06-07 08:28:05 +00:00
|
|
|
@twilio_channel = Current.account.twilio_sms.create!(
|
2020-04-29 20:11:13 +00:00
|
|
|
account_sid: permitted_params[:account_sid],
|
|
|
|
auth_token: permitted_params[:auth_token],
|
2022-07-18 14:32:37 +00:00
|
|
|
messaging_service_sid: permitted_params[:messaging_service_sid].presence,
|
2020-04-29 20:11:13 +00:00
|
|
|
phone_number: phone_number,
|
|
|
|
medium: medium
|
|
|
|
)
|
2020-06-07 08:28:05 +00:00
|
|
|
@inbox = Current.account.inboxes.create(
|
2020-04-29 20:11:13 +00:00
|
|
|
name: permitted_params[:name],
|
|
|
|
channel: @twilio_channel
|
|
|
|
)
|
2020-04-05 16:41:27 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def permitted_params
|
|
|
|
params.require(:twilio_channel).permit(
|
2022-07-08 12:50:07 +00:00
|
|
|
:account_id, :messaging_service_sid, :phone_number, :account_sid, :auth_token, :name, :medium
|
2020-04-05 16:41:27 +00:00
|
|
|
)
|
|
|
|
end
|
|
|
|
end
|