Let’s change the requirement a bit this time.
- After the user signs up, send an SMS verification. If SMS verification goes well then use that phone number for future use.
- But if the user’s phone number doesn’t support the SMS feature, then call on user’s phone number for the verification.
- In the call, ask the user to press 1 from keypad to complete the verification. If that user presses the 1 key, then mark the phone number as verified.
Step 1: Make a call for phone verification
We already handled SMS verification, so let’s add call related changes in
PhoneVerificationService class we have added some major changes:
- We have defined one more attribute reader
initializemethod we have set it.
- We have created two new constants
- We have changed
processmethod and now we check which verification process should be taken place based on
- We also have added new methods
Let’s go through these newly added methods.
In this method, first we try to send an SMS verification. If SMS verification fails with error message like ‘is not a mobile number’ then in the rescue block, we make a phone verification call or we raise the error.
In this method, we create an actual phone call and pass the all required info to twilio client object.
In this method, we set the callback_url which is
required for Twilio for making a call. When we call the user for
verification, our app needs to behave like a human and should ask to the user to
press 1 to complete the verification (i.e. In the form of TwiML).
callback_url needs be to set in our app.
Step 2: Add voice action in phone verification controller
callback_url, add route for
voice action in
voice action and required code for it in
voice method, we have set up the Twilio response. When a call is made to
the user, this response will get converted into robotic human voice.
method which sets twilio response in
text form is required for Twilio APIs. Set up the response header in the
set_header method which gets called in
Step 3: Set request URL for voice phone verification in Twilio
voice action method, we have setup the request url in the
action key of Twilio
response object, that also needs to be set in your Twilio account. So when, user replies
back to the call query, Twilio will make a request to our app and adds its own some values
as parameters to the request. Using those parameters we handle the actual phone
verification in the app.
Open twilio account and under NUMBERS section/tab, click on your Twilio number. Then in Voice section, add request URL with HTTP POST method. Add URL like this.
Step 4: Add verify_from_voice action in phone verification controller
First add route for this action in
Add this method, in your
Modify private method
get_user_for_phone_verification to support voice verification
verify_from_voice method, we get parameters
from Twilio request. Using these parameters, we search for user in the database. If we get the
proper user then we mark user’s phone number as verified phone number.