Address validation using UPS api, cURL and PHP

January 21, 2024


$shipping_name = 'Fake Name';
$shipping_building_name = 'The Pentagon';
$shipping_address_1 = '1600 Fake St.';
$shipping_address_2 = 'Suite 66';
$shipping_address_3 = '';
$shipping_city = 'Star City';
$shipping_state = 'Montana';
$shipping_zipcode_5 = '99999';
$shipping_zipcode_4 = '9999';
$shipping_region = $shipping_city.' '.$shipping_state.' '.$shipping_zipcode_5;
$shipping_urbanization = '';
$shipping_country = 'US';

$UPS_request_option = "3";

$query = array(
  "regionalrequestindicator" => "false",
  "maximumcandidatelistsize" => "10"
);

$payload = array(
  "XAVRequest" => array(
    "AddressKeyFormat" => array(
      "ConsigneeName" => $shipping_name,
      "BuildingName" => $shipping_building_name,
      "AddressLine" => array(
        $shipping_address_1,
        $shipping_address_2,
        $shipping_address_3
      ),
      "Region" => $shipping_region,
      "PoliticalDivision2" => $shipping_city,
      "PoliticalDivision1" => $shipping_state,
      "PostcodePrimaryLow" => $shipping_zipcode_5,
      "PostcodeExtendedLow" => $shipping_zipcode_4,
      "Urbanization" => $shipping_urbanization,
      "CountryCode" => $shipping_country
    )
  )
);

$UPS_url = 'https://onlinetools.ups.com/api/addressvalidation/v1/' . $UPS_request_option . '?' . http_build_query($query);

$curlopt_postfields = json_encode($payload);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $UPS_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_POSTFIELDS, $curlopt_postfields);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $UPS_access_token",
    "Content-Type: application/json"
]);

$error = curl_error($curl);
$response = curl_exec($curl);
curl_close($curl);

if($error){
echo $error;

}else{

$data = json_decode($response, true);

if(isset($data["response"]["errors"])){

echo = $data["response"]["errors"][0]["code"];
echo = $data["response"]["errors"][0]["message"];

}else{

// good to go...
// start doing stuff here...

}
}


Comments

There are no comments.


Comment on this Article

Your email address will never be published. Comments are usually approved within an hour or two. (to prevent spam)