Twilio API - getting the child call SID after Status Callback - twilio

I am using a TwiML App to establish a phone call via the browser.
I have a Status Callback URL in the APp that post the details of the child call.
The problem is, in the POST I only have the Parent Call ID, not the actual child call ID. How can I get it?
The post looks something like:
post: ApiVersion=2010-04-01&Called=&CallStatus=completed&Duration=1&From=client%3Akaren_calls&CallDuration=20&Timestamp=Mon%2C%2025%20May%202015%2020%3A48%3A22%20%2B0000&Direction=inbound&CallbackSource=call-progress-events&AccountSid=ACfxxxxxxxxxxxxxxxxxxx&ApplicationSid=xxxxxxxxxxxx&Caller=client%3Akaren_calls&SequenceNumber=0&To=&CallSid=CAxxxxxxxxxxxxxxxxxx
The "CallSid" above is for the parent call, not the child.

Twilio developer evangelist here.
You can get the child calls of a call by retrieving a list of calls from the REST API and filtering it by the parent call SID. You can see how you can filter calls in the documentation.
If you were doing this with the Ruby library, you would do the following:
require 'twilio-ruby'
# Fill in your account SID and auth token below
client = Twilio::REST::Client.new "ACxxxx", "XYzzzzz"
# Fill in the call SID below
child_calls = client.calls.list parent_call_sid: "CAxxxxx"
Let me know if this helps.

Related

Create external customer from Devise user via HTTP request

What I need is, immediately after a new user was created with Devise, my app to send an HTTP request (POST) with the ID of this user to an external API (which will create a Customer on that platform). The request will return a Customer_ID that needs to be stored in the database for the user.
What is the best way to do this?
after_create callback can come handy here.
In your User model,
after_create :set_customer_id
private
def set_customer_id
response = API_REQUEST
update_attribute(:customer_id, response.body[:customer_id])
end
Assuming, response body is json and required key is customer_id.
You can read about before_create and other callbacks here as pointed out in comments.

Twilio: Multiple outbound conferences at once using one Twilio phone number.

Just wondering if any Twilio experts can shed some light onto how I might handle having multiple conferences attached to the same Twilio number happening at once.
In the simplest case I would be looking to handle 2 person conferences (so basically just a regular call).
E.g. lets say I have two 2-person conferences scheduled for 1:00 and those two calls are waiting in a queue to be set up. At 1:00 Twilio would pull the first call from the queue and send out outbound calls to connect User A and User B in the first conference, then it would pull the second call from the queue and send out outbound calls to User C and User D to connect them in a second separate conference. Apart from Twilio’s 1-second per call limit is there anything stopping me from using the same Twilio number to connect both separate conferences?
Is it simply the fact that when my app pulls the second call from the queue it is making separate HTTP requests that keeps the two conferences separate even though they're attached to the same number? I’m working in Rails but I’d appreciate input from anyone as to how I might need to handle that in my code.
Twilio developer evangelist here.
As Akhil says, there's no limit on making multiple conferences from the same caller id.
What you might do to accomplish this is set a URL parameter in the URL you pass to the create call method that indicates which conference your users will join. For example:
client = Twilio::REST::Client.new(ACCOUNT_SID, AUTH_TOKEN)
client.calls.create(
:from => YOUR_TWILIO_NUMBER,
:to => user.phone_number,
:url => "/conference?conference_room=#{user.current_conference}"
)
Then, in your route you can look up the conference name and add the user to it.
def conference
conf_room = params[:conference_room]
twiml = Twilio::TwiML::Response.new do |r|
r.Dial do
r.Conference conf_room
end
end
render :xml => twiml.to_xml
end
Let me know if that helps at all!
There is no limitation in making multiple conferences at once from the same caller ID. You can have any number of simultaneous calls from the same number at a time (Respecting twilio's 1 call per second limit).
The key here is to have a unique name for a conference and join users to the correct conference.

Tracking Which Twilio Users Make Which Calls

Problem: I'm unable to determine which of my Rails app's users are making which browser-to-browser calls using Twilio.
I am able to make browser to browser calls with Twilio and I am able to store the #call object in the Calls table like this:
def start_conference
#call = Call.create_from_twilio_params(params)
#call.user_id = current_user.id #current_user doesn't work in this Twilio request even when the user is signed into the Rails app
#call.save
end
Here are the parameters that Twilo app returns in the log when it processes a user's call:
TwilioController#start_conference as HTML
Parameters: {"AccountSid"=>"AC123", "ApplicationSid"=>"AP234", "Caller"=>"client:test", "CallStatus"=>"ringing", "Called"=>"", "To"=>"", "CallSid"=>"CAxyz", "From"=>"client:test", "Direction"=>"inbound", "ApiVersion"=>"2010-04-01"}
Is it possible to add my own parameters such as user_id? Or maybe there is another way for me to connect the call to the user?
From this StackOverflow question, it seems possible to attach parameters to the callback URL, but where is the Twilio documentation about specifying a custom callback URL?
Thank you!
Twilio developer evangelist here.
You can indeed pass more parameters around when making a call with Twilio Client.
When you call Twilio.Device.connect() to make the call you can pass an object with parameters in that will get POSTed to your controller. For example:
// In your front end code
Twilio.Device.connect({ userId: '<%= current_user.id %>' });
And then, in your controller code, you will receive that userId in the params and you could use it like this:
def start_conference
user_id = params.delete('userId')
#call = Call.create_from_twilio_params(params)
#call.user_id = user_id
#call.save
end
Let me know if this helps!

Using Webhooks with Rails

I am unfamiliar with Webhooks but I feel like they are the right thing for my app.
I have the following documentation for FluidSurveys webhook
I understand how I can make the webhook through a POST request to their API, but I don't know how can I tell where the webhook is actually going to send the response.
Can I pass any subscription url I want? e.g. https://www.myapp.com/test and is that where webhook will send the data? Also, after the webhook is created I'm not sure how to ensure my Rails app will receive the response that is initiated.
I assume a controller method that corresponds with the url I provide to the webhook.
If I'm correct on the controller handling the webhook, what would that look like?
Any guidance is appreciated.
Webhooks hook into your app via a callback URL you provide. This is just an action in one of your controllers that responds to POST requests and handles the webhook request. Every time something changes to the remote service, the remote service makes a request to the callback URL you provided, hence triggering the action code.
I'll exemplify with the survey created event. You start by defining a callback action for this event, where you handle the request coming from the webhook. As stated here the webhook responds with the following body:
survey_creator_name=&survey_name=MADE+A+NEW+SURVEY&survey_creator_email=timothy#example.com&survey_url=http%3A%2F%2Fexample.com%2Fsurveys%2Fbob%2Fmade-a-new-survey%2F``
Let's leave the headers for now, they don't contain important information. The available body parameters (survey_creator_name, survey_name etc.) will reflect all details regarding the new survey available on the remote service. So let's write a callback action that handles this request:
class HooksController
def survey_created_callback
# If the body contains the survey_name parameter...
if params[:survery_name].present?
# Create a new Survey object based on the received parameters...
survey = Survey.new(:name => params[:survey_name]
survey.url = params[:survey_url]
survey.creator_email = params[:survey_creator_email]
survey.save!
end
# The webhook doesn't require a response but let's make sure
# we don't send anything
render :nothing => true
end
end
Let's add the route for this (in config/routes.rb):
scope '/hooks', :controller => :hooks do
post :survey_created_callback
end
This will enable the POST /hooks/survey_created_callback route.
Now you'll need to subscribe this callback URL to the Webhooks API. First you'll want to know which hooks are available to you. You do this by placing a GET request at /api/v2/webhooks/. In the response you'll find the event name, survey and collector parameters.
Finally, you subscribe to one of the previously listed hooks by placing a request to the POST /api/v2/webhooks/subscribe/ URL with the following contents:
{
"subscription_url": "http://your-absolute-url.com/hooks/survey_created_callback",
"event": "[EVENT NAME FROM THE HOOKS LIST]",
"survey": "[SURVEY FROM THE HOOKS LIST]",
"collector": "[COLLECTOR FROM THE HOOKS LIST]"
}
The response to this will be a code 201 if the hook was created successfully, or code 409, if a webhook for the same callback URL already exists. Or something else, if this went bad :)
You can now test the hook, by creating a survey on the remote service and then watch it getting replicated in your Rails app.
Hope this helps...

Rails 3 and Twilio to do phone verification

I am building an app in Rails 3, using twilio to verify a businesses existance. Basically, when you create a new buisiness I randomly generate a 6 digit number and then call the business phone number with this verification code and the user needs to enter it back in the system to finish the signup process. I am having trouble finding any relevant examples as to how to get this set up. I've found this, but it seems horribly outdated and doesn't work with Rails 3 seemingly. The documentation for the twilio-rb gem is confusing as well.
Does anyone know of any examples or have any code samples that could point me in the right direction?
As I said in the comment on your question itself, I am the author of the twilio-rb gem you mention. Off the top of my head, I would implement a verifications resource that you post a telephone number to.
POST /verifications.voice { telephone_number: '+12125551234' }
In the create action use Twilio::Call.create to create a new call with Twilio
def create
#verification = Verification.new params[:verification]
if #verification.save
Twilio::Call.create to: #verification.telephone_number,
from: YOUR_CALLER_ID, url: verification_url(#verification, format: :voice)
# 201 created and return verification code etc
else
# Handle errors
end
end
You will also want to rescue any API errors that twilio-rb might raise. The url refers to the show action of the verification resource instance. Twilio will then dial the supplied telephone number, and when the call is connected will request the url, e.g. GET /verifications/1.voice so you'll need a show view that asks for the verification code and collects the digits with the <Gather> verb:
res.gather num_digits: 4, action: twilio_hack_verification_url(#verification, :format => :voice), method: 'POST' do |form|
form.say 'Please enter the your 4 digit verification code'
end
Since Twilio currently does not implement the PUT verb, you'll to add a member to your resource
resources :verifications do
member { post 'twilio_hack' }
end
Then in your controller update the object with the user input:
def twilio_hack
#verification = Verification.find(params[:id]).tap do |v|
v.user_input params['Digits']
v.save
end
if #verification.confirmed?
# handle success
else
# handle failure
end
end
Finally in your model you'll need code that generates the verification code, and verifies if it is confirmed
class Verification < ActiveRecord::Base
before_save -> { self[:confirmed] = true if user_input == verification_code }, if: user_input
before_create -> { self[:verification_code] = rand.to_s[2..5] }
end
This is all untested and off the top of my head with about 2 minutes thought, but it should get you started.
When you wish to verify a Business:
Generate a verification code.
Use the Twilio REST API to initiate an outbound call, passing a URL for a callback to a controller which will handle the verification logic. Docs at Twilio are here and an example is here.
This means that you need to pass the verification code into your controller via the callback URL. Use a non-resourceful route with a bound parameter. See here.
Write a controller that handles the call and processes the verification:
Emit TwiML that challenges the user to enter the verification code. I have found using Nokogiri to build the TwiML myself to be the most straightforward approach. (See the method phone_greeting in this simple app I wrote: here.)
If it's correct, flag the Business as verified, congratulate the user, and hang up.
If not, loop.
Hopefully that's enough information to point you in the right direction.
Have you considered using Twilio's Outgoing Caller IDs to help solve this problem?
When calling Twilio over REST to add a new caller id to your account, Twilio will return a 6 digit verification code (property ValidationCode) for you to display in your UI, and then Twilio will automatically call the number and prompt for the code. When the user verifies the number over the phone, their number will be added to your account's caller ids. You can then query Twilio for their phone number over REST (parameter PhoneNumber) to ensure the verification was successful.
See here for documentation:
Add a caller id: http://www.twilio.com/docs/api/rest/outgoing-caller-ids#list-post
Find a caller id: http://www.twilio.com/docs/api/rest/outgoing-caller-ids#list

Resources