Twilio apllication step by step process of SMS and Call API in rails

About Twilio:- Twilio uses Amazon Web Services to host telephony infrastructure and provide connectivity between HTTP and the public switched telephone network (PSTN) through its APIs.

Twilio follows a set of architectural design principles to protect against unexpected outages, and received praise for staying online during the widespread Amazon Web Services outage in April 2011.
Twilio supports the development of open source software and regularly makes contributions to the open-source community. In June 2010 Twilio launched, an open-source product that lets business users configure phone numbers to receive and route phone calls.One month later, Twilio engineer Kyle Conroy released Stashboard, an open-source status dashboard written in the Python language that any API or software service can use to display whether their service is functioning properly or not. Twilio also sponsors Localtunnel, created by now ex-Twilio engineer Jeff Lindsay, which enables software developers to expose their local development environment to the public internet from behind a NAT.
I am describing step by step procedure how to setup twilio service for your rails application.
Step:-1 First setup the rails environment.

Step:2 Create a project in which you have to implement the method.

"rails new [Project_Name]"

Step:3 Create the model and controller for it.

Step:4 Add the Twilio gem to your Gemfile.

gem 'twilio-ruby', '~> 4.1.0'

Step:5 Install your gems.

bundle install

Step:6 Create a phone_number model to store.

(i)-the phone number itself
(ii)-a randomly generated PIN
(iii)-A flag indicating if the number has been verified

run "rails g model phone_number phone_number:string pin:string verified:boolean"
ADD THIS CODE INTO YOUR MODEL:-

def generate_pin
self.pin = rand(0000..9999).to_s.rjust(4, "0")
save
end

def twilio_client
Twilio::REST::Client.new(ENV['TWILIO_ACCOUNT_SID'], ENV['TWILIO_AUTH_TOKEN'])
end

def send_pin
twilio_client.messages.create(
to: phone_number,
from: ENV['TWILIO_PHONE_NUMBER'],
body: "Your PIN is #{pin}"
)
end

def call_me
@otp = "#{otp}".split('',4)
a = @otp
twilio_client.account.calls.create({
:from => ENV['TWILIO_PHONE_NUMBER'],
:to => phone_number,
:method => 'GET',
:application_sid => 'AP65ffa157d7df232e252453c0e1093c38',
:fallback_method => 'GET',
:status_callback_method => 'GET',
:record => 'false',
:url => "http://twimlets.com/message?Message%5B0%5D=Your%20one%20time %20password%20is%20&Message%5B1%5D=#{pin}&"
})
end

def verify(entered_pin)
update(verified: true) if self.pin == entered_pin
end



Step:7 Create the database and run the migration.
run "rake db:create db:migrate"

Step:8 Create the Controller.
As mentioned before, our verification process has three steps:

(i) The user enters a new phone number
(ii) Our app creates the phone number row and sends the user a PIN to enter back into the form
(iii) Our app verifies that the PINs match for the given phone number.

Add this code to config/routes.rb to create a route for each step:-

resources :phone_numbers, only: [:new, :create]
post 'phone_numbers/verify' => "phone_numbers#verify"

Step:9 Create the phone_numbers controller.

run "rails g controller phone_numbers"

ADD THIS CODE INTO CONTROLLER:-

def new
@phone_number = PhoneNumber.new
end

def create
@phone_number = PhoneNumber.find_or_create_by(phone_number: params[:phone_number][:phone_number])
@phone_number.generate_pin
@phone_number.send_pin
respond_to do |format|
format.js # render app/views/phone_numbers/create.js.erb
end
end

def verify
@phone_number = PhoneNumber.find_by(phone_number: params[:hidden_phone_number])
@phone_number.verify(params[:pin])
respond_to do |format|
format.js
end
end


Step:10 Inside the controller(found at app/controllers/phone_numbers_controller.rb), add a "new" method that creates a @phone_number.

Step:11 Create the View.
run "touch app/views/phone_numbers/new.html.erb"

Add this code in new.html.erb:-

<div id="send-pin">
<h3>What's your phone number?</h3>
<%= form_for @phone_number, remote: true do |f| %>
<div class="form-group">
<%= f.text_field :phone_number %>
</div>
<%= f.submit "Send PIN" , class: "btn btn-primary", id: 'send-pin-link'%>
<% end %>
</div>

<div id="verify-pin">
<h3>Enter your PIN</h3>
<%= form_tag phone_numbers_verify_path, remote: true do |f| %>
<%= hidden_field_tag 'hidden_phone_number', '' %>
<div class="form-group">
<%= text_field_tag :pin %>
</div>
<%= submit_tag "Verify PIN" , class: "btn btn-primary"%>
<% end %>
</div>
<div id="status-box" class="alert alert-success">
<p id="status-message">Status: Haven’t done anything yet</p>
</div>



Step:12 Add this CSS to app/assets/stylesheets/phone_numbers.scss

#verify-pin, #status-box
{
display: none;
}



Step:13 Create a new file.
run "touch app/views/phone_numbers/create.js.erb"
ADD this code:-

$('#hidden_phone_number').val('<%= @phone_number.phone_number %>' )
$('#send-pin').hide()
$('#verify-pin').fadeToggle()
$('#pin').focus()
JavaScript



Step:14 Create a new file.

run "touch app/views/phone_numbers/verify.js.erb"

Add this code:-

<% if @phone_number.verified %>
$('#verify-pin').hide()
$('#status-box').removeClass()
$('#status-box').addClass('alert alert-success')
$('#status-message').text('Success!!')
<% else %>
$('#status-box').removeClass()
$('#status-box').addClass('alert alert-warning')
$('#status-message').text("Sorry, that wasn't the right pin.")
<% end %>
$('#status-box').fadeToggle()


Step:15 In app/views/layouts/application.html.erb, add this line above where the application stylesheet is included.

<%= stylesheet_link_tag "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css", media: 'all', 'data-turbolinks-track' => true %>


Then replace that files current <body> with this:-

<body>
<div class="container">
<%= yield %>
</div>
</body>



Step:16 Before we can send this PIN via SMS, we need three things from Twilio.

1-Your account SID
2-Your auth Token
3-An SMS enabled phone number
So, Go to your Twilio account dashboard and find your account SID and auth token:-

Kill your server, then punch this into the same terminal window where you have created the project:-

export TWILIO_ACCOUNT_SID="REPLACEWITHACCOUNTSID"
export TWILIO_AUTH_TOKEN="REPLACEWITHAUTHTOKEN"
export TWILIO_PHONE_NUMBER="REPLACEWITHTWILIONUMBER"



Step-17 Run rails s and go to http://localhost:3000/phone_numbers/verify.


Comments

Popular posts from this blog

Exporting CSV and Excel File In ROR.

Push Notifications for IOS and Android In rails 4