Menu

Expand
Rate this page:

Migrating from Facebook Account Kit to Twilio Verify

Facebook announced that they are deprecating Account Kit and services will no longer be available starting in March 2020. Twilio Verify offers end to end functionality to quickly and easily replace your application's dependency on Account Kit for SMS login. This tutorial will cover implementing Twilio Verify in web applications.

Quick links:

Why Twilio Verify?

With a similar workflow to Facebook's Account Kit, you can use your existing UI/UX with minimal code changes to integrate Verify. Verify offers:

  • global coverage
  • fast performance
  • high scale
  • token management

...all out of the box.

Like Account Kit, Verify manages sending and checking verification tokens for you so there are limited backend changes required to move to this API.

With 99.999% of API uptime, you can rely on Verify to automatically handle delivery using a robust global SMS and voice network covering 200+ countries. Verify email delivery channel is expected to be in Public Beta in November 2019 and GA in early 2020. Build WhatsApp channel separately with Twilio's WhatsApp API. WhatsApp support through Verify is not currently available; if this is something that would be useful to your company please let us know. Twilio Verify does not support instant verification but does support a voice channel.

Prerequisites to adding Twilio Verify to your application

To code along with this tutorial, you’ll need:

Make note of your Service SID (starts with VA)

We don't want to store our API Keys directly in our front-end application, so we'll need a backend server that will talk to the Verify API. Account Kit handled some of this with their javascript SDK, we'll do this with Twilio Functions.

Twilio Functions provide a serverless environment to build and run Twilio applications so you can get to production faster. Your first 10,000 invocations/month are free. Learn more about our runtime products to build, deploy, and operate apps at scale.

Head over to your Twilio Function configuration and:

  1. Check the box to Enable ACCOUNT_SID and AUTH_TOKEN
  2. Add VERIFY_SERVICE_SID as an environment variable (create a service here if you haven't already)

Then create two Twilio Functions, one to start and one to check verifications. For each function:

  • Choose "Blank"
  • Replace the code with the code in the template file:
  • In properties, give your function a name and add a relevant path (start or check)

Make note of your function path, we'll need that soon.

Replace Account Kit's Login with SMS with Twilio Verify

Start with a basic HTML page like this or use your existing web application.

Import Bootstrap and jQuery by adding these lines in your <head> tag. These will be used for some basic styling and adding a modal so we can check the verification code. You can skip the Bootstrap CSS if you have your own styling.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

Set up the UI input elements for your page in your <body> tag

<div class="container">
  <p>Enter your phone number to receive a verification code:</p>
  <form class="form-inline">
    <input value="+1" id="country_code" class="form-control"/>
    <input placeholder="phone number" id="phone_number" class="form-control"/>
    <input type="button" onclick="smsLoginTwilio();" class="btn btn-primary" value="Login via SMS" />
  </form>
</div>

Add a JavaScript function to send a verification code

Add the following code to your file. Replace the URL in the fetch call with the URL to your Twilio Function and a path of /start.

<script>
  var cc = null;
  var pn = null;

  function flashStatus(alertType, message) {
    var content = $(".result-message");
    content.empty();
    content.append(`<div class="alert alert-${alertType}" role="alert">${message}</div>`);
  }

  function smsLoginTwilio() {
    var countryCode = $("#country_code").val().replace(/\W/g, ''); // strip special characters
    var phoneNumber = $("#phone_number").val().replace(/\W/g, ''); // strip special characters

    // save for checking
    cc = countryCode;
    pn = phoneNumber;

    // Twilio functions do not accept multipart/form-data
    const data = new URLSearchParams();
    data.append("country_code", countryCode);
    data.append("phone_number", phoneNumber);

    // TODO REPLACE THIS
    fetch("your-twilio-function-start-verify-url/start", {
        method: 'POST',
        body: data
      })
      .then(response => {
        return response.json()
      })
      .then((json) => {
        console.log(json);
        if (json.success) {
          console.log("Successfully sent token.")
        } else {
          console.log("Error sending token.")
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }
</script>

Open up developer tools and open your file in the browser. Input your phone number in the phone number field and hit "Login via SMS". You should receive an SMS with a 6 digit code and see the following output in the console.

console output

Check Verification Tokens with Twilio Verify

Add the following modal HTML in your body tag so we can verify the token sent to the user. In your implementation, this could also redirect to a new page.

<div class="modal" id="verification_modal">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-body">
        <div class="row">
          <div class="col-lg-12">
            <div class="result-message">
            </div>
            <div class="input-group input-group-lg">
              <input type="text" class="form-control input-lg" id="verification_code" placeholder="Enter the token sent to your device">
              <span class="input-group-btn">
                <button onclick="smsVerifyTwilio();" class="btn btn-primary btn-lg" type="submit">Verify</button>
              </span>
            </div>
          </div>
        </div>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

Then update your smsWithTwilio() function to open the modal if the json response indicates success:

if (json.success) {
  $(".modal").modal("show");
  console.log("Successfully sent token.");
}

Now if you click "Login with SMS" you should see the verification modal:

Finally, add a function to verify the token in your script tag. Replace the URL in the fetch call with the URL to your Twilio function and a path of /check.

function smsVerifyTwilio() {
  var code = $("#verification_code").val();

  // Twilio functions do not accept multipart/form-data
  const data = new URLSearchParams();
  data.append("country_code", cc);
  data.append("phone_number", pn);
  data.append("verification_code", code);

  // TODO REPLACE THIS
  fetch("your-twilio-function-start-verify-url/check", {
      method: 'POST',
      body: data
    })
    .then(response => response.json())
    .then((json) => {
      if (json.success) {
        flashStatus("success", "Success!");
        console.log("Successfully verified the token.");
      } else {
        flashStatus("danger", json.message);
        $("#verification_code").val("");
        console.log("Incorrect token.")
      }
    })
    .catch((err) => {
      var content = $(".result-message");
      console.log(err);
    });
}

Click 'Login with SMS' once more and now if you enter the token sent to your phone you'll see if it was correct!

Next Steps

With just two API calls and one web page, you’ve now validated that a user has a real phone number and access to that number, which will help prevent a lot of fraudulent accounts and ensure that your users can receive other text or voice notifications from your app.

More links that may be helpful:

If you have any questions about phone verification or account security, please leave a comment or contact me on Twitter.

Kelley Robinson Kat King Maria Bermudez Anna Mason Gisela Osorio
Rate this page:

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd by visiting Twilio's Stack Overflow Collective or browsing the Twilio tag on Stack Overflow.

Loading Code Sample...
        
        
        

        Thank you for your feedback!

        Please select the reason(s) for your feedback. The additional information you provide helps us improve our documentation:

        Sending your feedback...
        🎉 Thank you for your feedback!
        Something went wrong. Please try again.

        Thanks for your feedback!

        thanks-feedback-gif