Sample code for 30+ languages & platforms
Ruby Requires Chilkat v11.0.0+

Check an SMS verification code with Twilio Verify

See more Twilio Examples

After the user enters the SMS code, retrieve the VE verification SID saved when you started the verification. Send that SID and the entered code to the same Verify Service. Keep the code as text so a leading zero survives.

Mark the phone number on that pending attempt as verified only when Twilio returns status=approved. A pending check leaves the number unverified. Twilio can return HTTP 404 after expiration, approval, or exhaustion of check attempts. Keep a successful result in your application so it can be used after Twilio removes the verification.

Twilio Verify API reference

Chilkat Ruby Downloads

Ruby
require 'chilkat'

success = false

#  Assumes Chilkat is unlocked. See Global Unlock Sample.
#  Obtain these credentials from the application's private configuration.
http = Chilkat::CkHttp.new()
http.put_RequireSslCertVerify(true)
http.put_BasicAuth(true)
http.put_Login("YOUR_API_KEY_SID")
http.put_Password("YOUR_API_KEY_SECRET")

#  Both requests use the same Verify Service SID (VA...).
url = Chilkat::CkStringBuilder.new()
url.Append("https://verify.twilio.com/v2/Services/")
url.Append("YOUR_VERIFY_SERVICE_SID")
url.Append("/VerificationCheck")

req = Chilkat::CkHttpRequest.new()
req.put_HttpVerb("POST")
req.put_ContentType("application/x-www-form-urlencoded")
#  Load the saved SID for this user's pending attempt. Take only the code from user input.
verificationSid = "SAVED_VERIFICATION_SID"
enteredCode = "CODE_ENTERED_BY_USER"
req.AddParam("VerificationSid",verificationSid)
req.AddParam("Code",enteredCode)

resp = Chilkat::CkHttpResponse.new()
success = http.HttpReq(url.getAsString(),req,resp)
if (resp.get_StatusCode() == 0)
    print "No response from Twilio. Check connectivity and TLS settings." + "\n";
    exit
end

if (resp.get_StatusCode() == 404)
    print "No active verification found. Check the service and verification SIDs." + "\n";
    exit
end

result = Chilkat::CkJsonObject.new()
parsed = result.Load(resp.bodyStr())
if ((success != true) or (resp.get_StatusCode() < 200) or (resp.get_StatusCode() >= 300))
    print "Twilio returned HTTP " + resp.get_StatusCode().to_s() + "\n";
    if ((parsed == true) and (result.JsonTypeOf("code") == 2))
        print "Twilio error code: " + result.IntOf("code").to_s() + "\n";
    end

    exit
end

if ((parsed != true) or (result.JsonTypeOf("status") != 1))
    print "Verification status missing from the response." + "\n";
    exit
end

status = result.stringOf("status")
if (status == "approved")
    #  Record success for the user and phone number associated with verificationSid.
    print "Phone number verified." + "\n";
else
    if (status == "pending")
        print "Code not accepted. Check the digits and enter the code again." + "\n";
    else
        print "Phone number unverified. Verification status: " + status + "\n";
    end

end