Lua Requires Chilkat v11.0.0+
Lua
Validate and format a phone number with Twilio Lookup
See more Twilio Examples
Use Basic Lookup v2 to check a national-format number and obtain its E.164 and national display formats. Supply the two-letter country code for a national number. The example requests only the basic fields.
Read the boolean valid field even when the HTTP request succeeds. When it is false, display any validation_errors that Twilio supplies. Numbering-plan validation does not establish reachability or control of a phone. To confirm control, send an SMS verification code.
Chilkat Lua Downloads
local chilkat = require("chilkat")
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
-- Load an API key for the Twilio account from private application configuration.
local http = chilkat.Http.new()
http.require_ssl_cert_verify = true
http.basic_auth = true
http.login = "YOUR_API_KEY_SID"
http.password = "YOUR_API_KEY_SECRET"
-- The phone number is one URL path segment. Percent-encode spaces and any leading +.
local number = chilkat.StringBuilder.new()
number:append("020 7946 0018")
local encoded = number:encode("url_rfc3986", "utf-8")
if not encoded then
print("Could not encode the phone number.")
return
end
local url = chilkat.StringBuilder.new()
url:append("https://lookups.twilio.com/v2/PhoneNumbers/")
url:append(number:get_as_string())
url:append("?CountryCode=GB")
local resp = chilkat.HttpResponse.new()
local reply = chilkat.JsonObject.new()
local success = http:http_no_body("GET", url:get_as_string(), resp)
if resp.status_code == 0 then
print("No HTTP response from Twilio.")
return
end
local parsed = reply:load(resp.body_str)
if (not success) or (resp.status_code ~= 200) then
print("Twilio returned HTTP " .. resp.status_code)
if (parsed) and (reply:json_type_of("code") == 2) then
print("Twilio error: " .. reply:int_of("code") .. " " .. reply:string_of("message"))
end
return
end
if not parsed then
print("Expected a JSON response from Twilio.")
return
end
if reply:json_type_of("valid") ~= 5 then
print("The lookup response is missing the validity flag.")
return
end
if not reply:bool_of("valid") then
print("The number is invalid for the specified country.")
local i = 0
while i < reply:size_of_array("validation_errors") do
reply.i = i
print(reply:string_of("validation_errors[i]"))
i = i + 1
end
return
end
if reply:json_type_of("phone_number") ~= 1 then
print("The lookup response is missing the E.164 number.")
return
end
print("E.164: " .. reply:string_of("phone_number"))
print("National format: " .. reply:string_of("national_format"))