简体   繁体   中英

Creating sms verification system using twilio

I am trying to create a sms verification system just for the sake of learning. So the file structure would be following

Index.php Form.php Sendcode.php Verify.php

What i am trying to achieve here is to try to learn, how can i force logged in users to be redirected to form.php and if they verify their number get redirected back to index.php otherwise prompted to verify their number back at form.php with an error. So if the status in DB is set as 1 the user can access index.php otherwise the status stays set at 0 and is required to verify number at form.php

Can someone help me with this? Perhaps write a sample index.php code
Here are the file contents
Form.php

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
   $(document).ready(function(){
      $("#phone").submit(function() 
      {
          var phone_no = $('#phone_no').val();

          if(phone_no != '')
          {

              $.post("sendcode.php", { phone_no: phone_no },
                    function(data) 
                    {
                       $(".result").html(data);
                    }, 
                    "html"
              );

          }

          return false;
      });
   });
</script>

<div class = "result"></div>
<p>Enter your phone number below, and we will send you a verification code to that phone number.</p>
<form id = "phone" method  = "POST" action = "">
<label for = "phone">Phone number</label>
<input name = "phone" type = "text" id = "phone_no" />
<input name = "submit" type = "submit" value = "Send Verification Code" />
</form>

<p>Enter Verification Code received to the phone number specified above in the form below.</p>

<form id = "verification" method  = "POST" action = "verify.php">
<label for = "code">Verification Code</label>
<input name = "code" type = "text" id = "code" />
<input name = "submit" type = "submit" value = "Verify" />
</form>

Sendcode.php

<?php
// configuration 
/*** mysql hostname ***/
$hostname = 'localhost';
// database name
$dbname = '';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
// enter SID here
$twilioSid = '';
// enter twilio token here
$twilioToken = '';
if(isset($_POST['phone_no']))
{
    try 
    {
        $verifyCode = rand(1000, 9999);

        $phone = $_POST['phone_no'];

        $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);

        /*** add verification code and phone number to db **/
        $sth = "INSERT INTO user (phone, code) VALUES(:phone, :code)";
        $command = $dbh->prepare($sth);
        $command->bindParam(':phone', $phone, PDO::PARAM_STR);
        $command->bindParam(':code', $verifyCode, PDO::PARAM_INT);
        $command->execute();

        // twilio library
        require ('Services/Twilio.php');

        $client = new Services_Twilio($twilioSid, $twilioToken);

        // send sms with verifcation code 
        $response = $client->account->sms_messages->create('555-555-555', $phone, 'Verification code ' . $verifyCode);

        echo '<p>A verification code was sent to your phone number. Please enter it below.</p>';

        /*** close the database connection ***/
        $dbh = null;
    }
    catch(PDOException $e)
    {
        echo $e->getMessage();
    }
}
?>  

Verify.php

<?php
if(isset($_POST['code']))
{
    $verifyCode = $_POST['code'];

    /*** mysql hostname ***/
    $hostname = 'localhost';

    /*** database name ***/
    $dbname = '';
    /*** mysql username ***/
    $username = 'username';
    /*** mysql password ***/
    $password = 'password';

    try {

        $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);

        // USER_ID is the login ID of the user
        $sql = "SELECT code FROM user WHERE id = {$user_id}";
        $sth = $dbh->query($sql);

        $code = $sth->fetchColumn();

        if($code == $verifyCode)
        {
            echo "Your account has been validated.";

            // verify user in db
            $todo = "UPDATE user SET status = 1 WHERE user_id = {$user_id}";
            $dbh->execute($todo);

        }
        else
        {
            echo "Your account has not been validated.";
        }

        $dbh = null;
    }
    catch(PDOException $e)
    {
        echo $e->getMessage();
    }
}
?>

Ricky from Twilio here.

We put together a sample application showing SMS account verification that may be helpful here:

https://www.twilio.com/docs/tutorials/walkthrough/account-verification/php/laravel

We used Authy, which is a Twilio product build specifically for this kind of use case. Breaking down a few parts to compare to your current code. Here's the section where we're sending an SMS:

$authyUser = $authyApi->registerUser($newUser->email, $newUser->phone_number, $newUser->country_code);
if($authyUser->ok())
{
    $newUser->authy_id = $authyUser->id();
    $newUser->save();
    $request->session()->flash(
        'status',
        "User created successfully"
    );

    $sms = $authyApi->requestSms($newUser->authy_id);
    DB::commit();
    return redirect()->route('user-show-verify');
}

And here's where we verify the code the user entered:

public function verify(Request $request, Authenticatable $user, AuthyApi $authyApi, TwilioRestClient $client)
{
    $token = $request->input('token');
    $verification = $authyApi->verifyToken($user->authy_id, $token);

    if ($verification->ok())
    {
        $user->verified = true;
        $user->save();
        $this->sendSmsNotification($client, $user);

        return redirect()->route('user-index');
    }
    else
    {
        $errors = $this->getAuthyErrors($verification->errors());
        return view('verifyUser',['errors' => new MessageBag($errors)]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM