C++ Requires Chilkat v11.0.0+
C++
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 C++ Downloads
#include <CkHttp.h>
#include <CkStringBuilder.h>
#include <CkHttpResponse.h>
#include <CkJsonObject.h>
void ChilkatSample(void)
{
bool success = false;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Load an API key for the Twilio account from private application configuration.
CkHttp http;
http.put_RequireSslCertVerify(true);
http.put_BasicAuth(true);
http.put_Login("YOUR_API_KEY_SID");
http.put_Password("YOUR_API_KEY_SECRET");
// The phone number is one URL path segment. Percent-encode spaces and any leading +.
CkStringBuilder number;
number.Append("020 7946 0018");
bool encoded = number.Encode("url_rfc3986","utf-8");
if (encoded != true) {
std::cout << "Could not encode the phone number." << "\r\n";
return;
}
CkStringBuilder url;
url.Append("https://lookups.twilio.com/v2/PhoneNumbers/");
url.Append(number.getAsString());
url.Append("?CountryCode=GB");
CkHttpResponse resp;
CkJsonObject reply;
success = http.HttpNoBody("GET",url.getAsString(),resp);
if (resp.get_StatusCode() == 0) {
std::cout << "No HTTP response from Twilio." << "\r\n";
return;
}
bool parsed = reply.Load(resp.bodyStr());
if ((success != true) || (resp.get_StatusCode() != 200)) {
std::cout << "Twilio returned HTTP " << resp.get_StatusCode() << "\r\n";
if ((parsed == true) && (reply.JsonTypeOf("code") == 2)) {
std::cout << "Twilio error: " << reply.IntOf("code") << " " << reply.stringOf("message") << "\r\n";
}
return;
}
if (parsed != true) {
std::cout << "Expected a JSON response from Twilio." << "\r\n";
return;
}
if (reply.JsonTypeOf("valid") != 5) {
std::cout << "The lookup response is missing the validity flag." << "\r\n";
return;
}
if (reply.BoolOf("valid") != true) {
std::cout << "The number is invalid for the specified country." << "\r\n";
int i = 0;
while ((i < reply.SizeOfArray("validation_errors"))) {
reply.put_I(i);
std::cout << reply.stringOf("validation_errors[i]") << "\r\n";
i = i + 1;
}
return;
}
if (reply.JsonTypeOf("phone_number") != 1) {
std::cout << "The lookup response is missing the E.164 number." << "\r\n";
return;
}
std::cout << "E.164: " << reply.stringOf("phone_number") << "\r\n";
std::cout << "National format: " << reply.stringOf("national_format") << "\r\n";
}