Twilio
Authy service is used for 2FA (2 factor authentication), passwordless
login, verifying mobile numbers and adding extra layer of security.
1.
Setup Authy PHP library
For
this, first we need to setup Authy PHP library. Follow below commands
to setup this library, we are using composer here to install library.
cd
/var/www/html/
mkdir
Authy
cd
Authy/
php
-r "copy('https://getcomposer.org/installer',
'composer-setup.php');"
php
-r "if (hash_file('SHA384', 'composer-setup.php') ===
'544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061')
{ echo 'Installer verified'; } else { echo 'Installer corrupt';
unlink('composer-setup.php'); } echo PHP_EOL;"
php
composer-setup.php
php
-r "unlink('composer-setup.php');"
create
one file, nano composer.json and add below content in it and save
{
"require":
{
"authy/php":
"2.*"
}
}
php
composer.phar install
This
will create vendor folder inside your Authy folder, it contains
autoload.php, which we will use.
2.
Get Authy API key from your Twilio Account
First
login to your Twilio Account, once you loggedin you can see below
dashboard.
Click
on Authy as shown below
Now
you need to create one Authy application, just create that
application and set appropriate options. Then you can get API key as
shown in below image, that will be used in api requests. Keep this
key at safe place.
3.
Mobile number verification while signup, API requests code
First
we will create AuthyID for the given mobile number, this AuthyID is
unique for the mobile number. This AuthyID can be used to create sms
token and verify token. This way we can verify the user mobile number
while signup.
a)
registerUser.php API
This
API generates AuthyID for the given mobile number.
Sample
code:
<?php
include('vendor/autoload.php');
$authy_api
= new Authy\AuthyApi('your-authy-api-key');
$user
=
$authy_api->registerUser('your_email@gmail.com','your-ten-digit-phone-number',country-code);
//email, cellphone, country_code
if($user->ok()){
$authyid
= $user->id(); //store this authyid into your database against the
signup user
echo
$authyid;
}
else{
echo
"something went wrong\n";
}
?>
b)
createSMSToken.php API
This
API creates SMS token and sends to mobile number.
Sample
code:
<?php
include('vendor/autoload.php');
$sms
= $authy_api->requestSms('your-authy-id-created-above');
if($sms->ok()){
echo
"SMS sent successfully\n";
}
else{
echo
"something went wrong\n";
}
?>
c)
verifyToken.php API
This
API verifies SMS token generated above
Sample
code:
<?php
include('vendor/autoload.php');
$authy_api
= new Authy\AuthyApi('your-authy-api-key');
$verification
= $authy_api->verifyToken('authy-id','sms-token-received-on-mobile');
if($verification->ok()){
echo
"Number verified successfully";
}
else{
echo
"something went wrong\n";
}
?>