Home > Enterprise >  Accessing Twilio response header PHP
Accessing Twilio response header PHP

Time:03-21

I am trying to do a phone lookup using twilio API, everything works fine except the part where I can't access the header response statusCode

Code sample

$lookup_phone_number = $client->lookups->v1->phoneNumbers("xxxxxxxxxx")->fetch(["type" => ["carrier"]]);

a var_dump will output "statusCode" property along with other data, but I can't seem to find the method to access the header property.

I have tried

var_dump($lookup_phone_number->getHeaders());

var_dump($lookup_phone_number->getStatusCode());

var_dump($lookup_phone_number->getContent());

Twilio library version is 6.34.0

CodePudding user response:

The intention of the library is to abstract away the HTTP request, so it gives access to the properties of the response, not the status code or headers.

When using the Lookups API a successful (200) response will give you the properties of the phone number. If the phone number doesn't exist it will return a 404 response and throw an error. So handling responses should look like this:

function doValidNo($phone_number) {
try {
        $phoneNumber = $client
            ->lookups
            ->v1
            ->phoneNumbers($phone_number)
            ->fetch(
                [
                    "type" => ["caller-name"]
                ]
            );
        return True; // The phone number exists and was looked up successfully
    } catch (\Twilio\Exceptions\TwilioException $e) {
        return False; // The phone number does not exist
    }
}

CodePudding user response:

I parsed the entire response from Twilio API and perform a string manipulation to find the statusCode property and access it's value.

function doValidNo($lookup_phone_number) {
  $rr = print_r($lookup_phone_number, true);
  $findme = '[statusCode:protected] =>';
  $pos = strpos($rr, $findme);

  if ($pos === false) {
      $LookUpValid = 0;
  } 
  else {
      //echo "Valid";
      $statuscode = substr($rr, strlen($findme) $pos, 5);
      $statuscode = str_replace(' ', '', $statuscode);
      $statuscode = trim($statuscode);
      $statuscode = (int)$statuscode;
      if ($statuscode == 200) {
        $LookUpValid = 1;
      }else {
        $LookUpValid = 0;
      }
  }
  return $LookUpValid;
}

It's not a perfect solution, but it get the job done at least for now.

Note: If Twilio changes their API response it could break the solution.

  • Related