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