Magento 2 – Address verification using USPS API on checkout.

This blogpost is related with address verification using USPS on one page checkout page. Address verification is a very critical part of any E-Commerce application. We have to make sure that address is deliverable, in this post we are using USPS APIs for this.

Note: In this post we are only validating US address as USPS stands for United State Postal Services. 

You can create a different module for this, or if you already have then add below code. If you don’t know how to create module in Magento 2 Then, Follow this.

Let’s verify the address in onepage checkout before order place.

Here I am using my existing module and making some changes for the same.

I have a module /var/www/html/Project_name/app/code/W3solver/TwilioIntegration/. I am using Ubuntu so my path is like this if anyone is using Mac or window path till project name will vary. Create a di.xml file on below path and add the given code, which will override magento core checkout module payment information model:

/var/www/html/Project_name/app/code/W3solver/TwilioIntegration/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Checkout\Model\PaymentInformationManagement" type="W3solver\TwilioIntegration\Model\PaymentInformationManagement" />
</config>

Now create the overriden file (PaymentInformationManagement.php) at below path.

/var/www/html/bigmoon/app/code/WestAgile/TwilioIntegration/Model/PaymentInformationManagement.php

Add the below code to your file

<?php
namespace  W3solver\TwilioIntegration\Model;

use Magento\Framework\Exception\CouldNotSaveException;
class PaymentInformationManagement extends \Magento\Checkout\Model\PaymentInformationManagement {

    public function savePaymentInformationAndPlaceOrder(
        $cartId,
        \Magento\Quote\Api\Data\PaymentInterface $paymentMethod,
        \Magento\Quote\Api\Data\AddressInterface $billingAddress = null
    ) {

    	$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

        if(Your_condition )// if you want run this in every condition if(1)
        {
           $address_details = $billingAddress->getStreet();
           $address_detail = $address_details[0];
           $final_address = $address_detail.",".$address_details[1];
           $city = $billingAddress->getCity();
           $state = ($billingAddress->getRegionId() =='12')? 'CA' : 'navada';
           $zipcode = $billingAddress->getPostCode();

           $response =  $this->getStateName($final_address,$city,$state,$zipcode);

           if($response==0)
           {
              throw new CouldNotSaveException(__('Please re-check your shipping address'));
              return false;

           }else{
           $this->savePaymentInformation($cartId, $paymentMethod, $billingAddress);
           try {
                $orderId = $this->cartManagement->placeOrder($cartId);
           } catch (\Exception $e) {
                throw new CouldNotSaveException(
                __('An error occurred on the server. Please try to place the order again.'), $e
                );
           }
            return $orderId;
        }
            //echo $response;
        }
    }

    public function getStateName($final_address,$city,$state,$zipcode){
        $input_xml = <<<EOXML
               <AddressValidateRequest USERID="Your USPS User ID will Come here">
               <Revision>1</Revision>
               <Address ID="0">
               <Address1>$final_address</Address1>
               <Address2></Address2>
               <City>$city</City>
               <State>$state</State>
               <Zip5>$zipcode</Zip5>
               <Zip4></Zip4>
               </Address>
               </AddressValidateRequest>
        EOXML;

        $fields = array(
                'API' => 'Verify',
                'XML' => $input_xml
            );
        $url = 'http://production.shippingapis.com/ShippingAPITest.dll?' . http_build_query($fields);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
        $data = curl_exec($ch);
        curl_close($ch);

        // Convert the XML result into array
        $array_data = json_decode(json_encode(simplexml_load_string($data)), true);

        if (array_key_exists("Error",$array_data['Address'])){
            return  0;
        }else{
            return 1;
        }
  }
}

Go to your Magento 2 installation from terminal and run “php bin/magento setup:upgrade“.

Try this solution and let us know your thoughts.

Leave a Comment.