With just a few lines of code, your Go application can verify phone numbers and add another layer of security with Twilio Verify.
This Verify Quickstart will teach you how to do this using our Verify REST API and the Twilio Go helper library.
In this Quickstart, you will learn how to:
Short on time? Spin up a low-code, fully editable verification demo in less than 2 minutes using Twilio's Code Exchange and Quick Deploy here.
If you already have a Twilio account, you're all set here! Feel free to jump to the next step.
Before you can send an SMS with Go, you'll need to sign up for a Twilio account or sign into your existing account.
You can sign up for a free Twilio trial account here.
If you've sent SMS with Twilio in the past, you might remember needing to buy a phone number. With Twilio Verify, we take care of that for you! The Verify API selects the best routes for quickly and reliably delivering verification codes globally.
Verify uses Services for configuration. To send a Verify API request you will need both your Twilio Credentials and a Service SID. You can create and update a Service in two ways:
Services can be used to edit the name (which shows up in the message template), set the code length (4-10 characters), enable settings like the "do not share warning" and more.
Now that you have a Twilio account and a verification service, you can start writing some code!
To make things even easier, we'll next install Twilio's official helper library for Go applications.
If you've gone through one of our other Go Quickstarts already and have Go and the Twilio Go helper library installed, you can skip this step and get to the rest of the tutorial.
Before you can follow the rest of this tutorial, you'll need to have Go and the Twilio Go module installed.
You can check if you already have Go installed on your machine by opening up a terminal and running the following command:
go version
You should see something like:
1$ go version2go version go1.19 darwin/amd64
If you don't have Go installed, head over to go.dev and download the appropriate installer for your system. Once you've installed Go, return to your terminal, and run the command above once again. If you don't see the installed Go version, you may need to relaunch your terminal.
Create a new Go project from your terminal using:
go mod init twilio-example
Once your project has been initialized, navigate into the newly created twilio-example
directory and install the Twilio Go helper library module.
go get github.com/twilio/twilio-go
This will install the twilio-go
module so that your Go code in the current directory can make use of it.
Now that you have Go and the Twilio Go library installed, you can send an SMS verification code from the Twilio Verify Service that you just created to your phone with a single API request.
Create and open a new file called sendverification.go
and type or paste in this code sample.
1// Download the helper library from https://www.twilio.com/docs/go/install2package main34import (5"fmt"6"github.com/twilio/twilio-go"7verify "github.com/twilio/twilio-go/rest/verify/v2"8"os"9)1011func main() {12// Find your Account SID and Auth Token at twilio.com/console13// and set the environment variables. See http://twil.io/secure14// Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment15client := twilio.NewRestClient()1617params := &verify.CreateVerificationParams{}18params.SetChannel("sms")19params.SetTo("+15017122661")2021resp, err := client.VerifyV2.CreateVerification("VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",22params)23if err != nil {24fmt.Println(err.Error())25os.Exit(1)26} else {27if resp.Status != nil {28fmt.Println(*resp.Status)29} else {30fmt.Println(resp.Status)31}32}33}
1{2"sid": "VEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",3"service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",4"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",5"to": "+15017122661",6"channel": "sms",7"status": "pending",8"valid": false,9"date_created": "2015-07-30T20:00:00Z",10"date_updated": "2015-07-30T20:00:00Z",11"lookup": {},12"amount": null,13"payee": null,14"send_code_attempts": [15{16"time": "2015-07-30T20:00:00Z",17"channel": "SMS",18"attempt_sid": "VLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"19}20],21"sna": null,22"url": "https://verify.twilio.com/v2/Services/VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Verifications/VEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"23}
Save your changes and run this script from your terminal:
1go run sendverification.go2
That's it! In a few moments, your phone will receive a verification code.
Sending verification codes is only half of the equation. You also need to be able to check the codes to verify your users!
Create and open a new file called checkcode.go
and type or paste in this code sample.
1// Download the helper library from https://www.twilio.com/docs/go/install2package main34import (5"fmt"6"github.com/twilio/twilio-go"7verify "github.com/twilio/twilio-go/rest/verify/v2"8"os"9)1011func main() {12// Find your Account SID and Auth Token at twilio.com/console13// and set the environment variables. See http://twil.io/secure14// Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment15client := twilio.NewRestClient()1617params := &verify.CreateVerificationCheckParams{}18params.SetTo("+15017122661")19params.SetCode("123456")2021resp, err := client.VerifyV2.CreateVerificationCheck("VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",22params)23if err != nil {24fmt.Println(err.Error())25os.Exit(1)26} else {27if resp.Status != nil {28fmt.Println(*resp.Status)29} else {30fmt.Println(resp.Status)31}32}33}
1{2"sid": "VEaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",3"service_sid": "VAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",4"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",5"to": "+15017122661",6"channel": "sms",7"status": "approved",8"valid": true,9"amount": null,10"payee": null,11"sna_attempts_error_codes": [],12"date_created": "2015-07-30T20:00:00Z",13"date_updated": "2015-07-30T20:00:00Z"14}
Replace to
with the phone number that you sent the code to, and code
with the verification code that you received.
Save your changes and run this script from your terminal:
1go run checkcode.go2
After the briefest delay, you will see "approved"
appear in your terminal, signaling that this combination of phone number and code are considered verified!
Let's combine these two processes into a single program that accepts terminal input.
In production, you would build an OTP input modal or page in your site interface to accept the input.
There will be a main.go
file in your directory from when you first bootstrapped this Go project. Go ahead and open that file, replace the boilerplate contents with the following code sample, replace the placeholder strings for Account SID, Auth Token, Verify Service SID, and your phone number in E.164 format, and save your changes.
1package main23import (4"fmt"56"github.com/twilio/twilio-go"7openapi "github.com/twilio/twilio-go/rest/verify/v2"8)910accountSid := "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"11authToken := "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY"12verifyServiceSid := "VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"1314client := twilio.NewRestClientWithParams(twilio.ClientParams{15Username: accountSid,16Password: authToken,17})1819// This function sends an OTP to your phone number20func sendOtp(to string) {21params := &openapi.CreateVerificationParams{}22params.SetTo(to)23params.SetChannel("sms")2425resp, err := client.VerifyV2.CreateVerification(verifyServiceSid, params)26if err != nil {27fmt.Println(err.Error())28} else {29fmt.Printf("Sent verification '%s'\n", *resp.Sid)30}31}3233// This function waits for you to input the OTP sent to your phone,34// and validates that the code is approved35func checkOtp(to string) {36var code string37fmt.Println("Please check your phone and enter the code:")38fmt.Scanln(&code)3940params := &openapi.CreateVerificationCheckParams{}41params.SetTo(to)42params.SetCode(code)4344resp, err := client.VerifyV2.CreateVerificationCheck(verifyServiceSid, params)45if err != nil {46fmt.Println(err.Error())47} else if *resp.Status == "approved" {48fmt.Println("Correct!")49} else {50fmt.Println("Incorrect!")51}52}5354func main() {55to := "<your phone number here>"5657sendOtp(to)58checkOtp(to)59}
1$ go run .2Sent verification 'VEd123455403fa12345c4812345c812345'3Please check your phone and enter the code:40771005Correct!
This code sends an SMS OTP to your phone, and uses Go's fmt.Scanln
to accept your input through the terminal.
The code then checks to make sure that the status is approved
. If you provide an incorrect code, the status will remain "pending" and you'll see "Incorrect!" print to the terminal instead of "Correct!".
For this example, the verification channel is hard coded as "sms", but you could make this dynamic to accept other channel options such as "call" or "whatsapp".
Now that you've seen how to leverage Verify for SMS verification, check out adding additional verification channels supported by the Verify API like:
Lastly, to protect your service against fraud, view our guidance on Preventing Toll Fraud when using Verify.