Magento – How to add customer new Address(multiple shiiping and billing addresses) through API in magento2.1.7

addressapiattributesmagento-2.1magento2

How can I add customer multiple address through rest API in Magento2.1.? Hope currently there is no API for adding additional customer address.So, Please let me know is there any other option to add multiple shipping and billing addresses through rest API. Is there any kind of suggestion should be appreciated.

Best Answer

I created a custom module for that, here are the steps :

Create a module app/code/CustomerAddress/AddressBook

Create regisration.php:

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'CustomerAddress_AddressBook',
    __DIR__
);

Create etc/di.xml:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
  <preference for="CustomerAddress\AddressBook\Api\AddressInterface" type="CustomerAddress\AddressBook\Model\Address" />
</config>

Create module.xml :

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="CustomerAddress_AddressBook" setup_version="1.0.0" schema_version="1.0.0">
    </module>
</config>

Create etc/webapi.xml :

<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<!-- Routing define -->
<route url="/V1/cutomerAddress/create" method="GET">
 <service class="CustomerAddress\AddressBook\Api\AddressInterface" method="createAddress"/>
 <resources>
  <resource ref="self"/>
 </resources>
 <data>
  <parameter name="customerId" force="true">%customerId%</parameter>
  <parameter name="firstName" force="true">%firstName%</parameter>
  <parameter name="lastName" force="true">%lastName%</parameter>
  <parameter name="countryCode" force="true">%countryCode%</parameter>
  <parameter name="postCode" force="true">%postCode%</parameter>
  <parameter name="city" force="true">%city%</parameter>
  <parameter name="telephone" force="true">%telephone%</parameter>
  <parameter name="fax" force="true">%fax%</parameter>
  <parameter name="company" force="true">%company%</parameter>
  <parameter name="street" force="true">%street%</parameter>
  <!--parameter name="isDefaultBilling" force="true">%isDefaultBilling%</parameter>
  <parameter name="isDefaultShipping" force="true">%isDefaultShipping%</parameter-->
 </data>
</route>
</routes>

Create etc/zip_codes.xml :

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Directory:etc/zip_codes.xsd">
    <zip countryCode="SA">
        <codes>
            <code id="pattern_1" active="false" example="1234 AB">^[0-9]{4}\s?[a-zA-Z]{2}$</code>
        </codes>
    </zip>
</config>

Create etc/webapi_rest/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">
<type name="Magento\Framework\Authorization">
<plugin name="customerAuthorization" type="Magento\Customer\Model\Plugin\CustomerAuthorization" />
</type>
<type name="Magento\Authorization\Model\CompositeUserContext">
<arguments>
<argument name="userContexts" xsi:type="array">
<item name="customerSessionUserContext" xsi:type="array">
<item name="type" xsi:type="object">Magento\Customer\Model\Authorization\CustomerSessionUserContext</item>
<item name="sortOrder" xsi:type="string">20</item>
</item>
</argument>
</arguments>
</type>
</config>

Create API/AddressInterface.php

namespace CustomerAddress\AddressBook\Api;

use CustomerAddress\AddressBook\Api\Data\PointInterface;

interface AddressInterface
{

/**
     * Create Address On Your Store
     *
     * @param integer $customerId
     * @param string $firstName
     * @param string $lastName
     * @param string $countryId
     * @param integer $postCode
     * @param string $city
     * @param string $telephone
     * @param integer $fax
     * @param string $company
     * @param string $street
     * @return boolean
     * 
    */

public function createAddress($customerId, $firstName, $lastName, $countryCode, $postCode, $city, $telephone, $fax, $company, $street);
}

Create Model/Address.php :

<?php

namespace CustomerAddress\AddressBook\Model;


use CustomerAddress\AddressBook\Api\AddressInterface;

/**
 * Defines the implementaiton class of the calculator service contract.
 */
class Address implements AddressInterface
{


    /**
     * @param Magento\Framework\App\Helper\Context $context
     * @param Magento\Store\Model\StoreManagerInterface $storeManager
     * @param Magento\Customer\Model\CustomerFactory $customerFactory ,
     */
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository
    )
    {
        $this->_storeManager = $storeManager;
        $this->customerFactory = $customerFactory;
        $this->customerRepository = $customerRepository;
        //parent::__construct($context);
    }


    /**
     * Create Address On Your Store
     *
     * @param integer $customerId
     * @param string $firstName
     * @param string $lastName
     * @param string $$countryCode
     * @param integer $postCode
     * @param string $city
     * @param string $telephone
     * @param integer $fax
     * @param string $company
     * @param string $street
     * @return boolean
     *
     */
    public function createAddress($customerId, $firstName, $lastName, $countryCode, $postCode, $city, $telephone, $fax, $company, $street)
    {
        $array = array();

        if(empty($_GET['customerId'])){
            $arr['msg'] = 'customerId parameter is missing';
            array_push($array, $arr);
            return $array;
        }elseif (empty($_GET['firstName'])){
            $arr['msg'] = 'firstName parameter is missing';
            array_push($array, $arr);
            return $array;
        }elseif (empty($_GET['lastName'])){
            $arr['msg'] = 'lastName parameter is missing';
            array_push($array, $arr);
            return $array;
        }elseif (empty($_GET['countryCode'])){
            $arr['msg'] = 'countryCode parameter is missing';
            array_push($array, $arr);
            return $array;
        }elseif (empty($_GET['postCode'])){
            $arr['msg'] = 'postCode parameter is missing';
            array_push($array, $arr);
            return $array;
        }elseif (empty($_GET['city'])){
            $arr['msg'] = 'city parameter is missing';
            array_push($array, $arr);
            return $array;
        }elseif (empty($_GET['telephone'])){
            $arr['msg'] = 'telephone parameter is missing';
            array_push($array, $arr);
            return $array;
        }elseif (empty($_GET['fax'])){
            $arr['msg'] = 'fax parameter is missing';
            array_push($array, $arr);
            return $array;
        }elseif (empty($_GET['company'])){
            $arr['msg'] = 'company parameter is missing';
            array_push($array, $arr);
            return $array;
        }elseif (empty($_GET['street'])){
            $arr['msg'] = 'street parameter is missing';
            array_push($array, $arr);
            return $array;
        }else{

            $customerId = $_GET['customerId'];
            $firstName = $_GET['firstName'];
            $lastName = $_GET['lastName'];
            $countryCode = $_GET['countryCode'];
            $postCode = $_GET['postCode'];
            $city = $_GET['city'];
            $telephone = $_GET['telephone'];
            $fax = $_GET['fax'];
            $company = $_GET['company'];
            $street = $_GET['street'];
            /*$isDefaultBilling = $_GET['isDefaultBilling'];
            $isDefaultShipping = $_GET['isDefaultShipping'];*/


            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $addresss = $objectManager->get('\Magento\Customer\Model\AddressFactory');
            $address = $addresss->create();

            $address->setCustomerId($customerId)
                ->setFirstname($firstName)
                ->setLastname($lastName)
                ->setCountryId($countryCode)
                ->setPostcode($postCode)
                ->setCity($city)
                ->setTelephone($telephone)
                ->setFax($fax)
                ->setCompany($company)
                ->setStreet($street)
                ->setIsDefaultBilling('0')
                ->setIsDefaultShipping('0')
                ->setSaveInAddressBook('1');

            if($address->save()){
                return true;
            }else{
                return false;
            }

        }




        /*$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
        $connection = $resource->getConnection();

        $addressTable = $resource->getTableName('customer_address_entity');

         $sql = "INSERT INTO  " . $addressTable . " (`parent_id`, `city`, `company`, `country_id`, `fax`, `firstname`, `lastname`, `postcode`, `street`, `telephone`) VALUES
        ($id, 
         '$city',
         '$company',
         '$countryCode',
         $fax, 
         '$firstName',
         '$lastName',
         '$postCode',
         '$street',
         '$telephone')";

        $connection->query($sql);

        print($sql);*/

    }
}

So, You can add a feature in settings in you mobile app to enable customer to save multiple addresses in the database.

After that, when place an order and go to point save shipping address for the order, display all addresses for him so he can choose the preferred one through shipping Address API:

POST http://domain.com/index.php/rest/V1/carts/mine/shipping-information
Header    Authorization  Bearer {token}
Body
{
"addressInformation": {
 "shippingAddress": {
         "city": "Egypt",
         "country_id": "EG",
         "firstname": "Fname",
         "lastname": "Lname",
         "postcode": "11643",
         "street": [
            "First street",
            "Second Street"
         ],
         "telephone": "5656565454"
      },
 "billingAddress": {
         "city": "Egypt",
         "country_id": "EG",
         "firstname": "Fname",
         "lastname": "Lname",
         "postcode": "11643",
         "street": [
            "First street",
            "Second street"
         ],
         "telephone": "5656565454"
      },
"shipping_method_code": "flatrate",          
"shipping_carrier_code": "flatrate",  
"extension_attributes": {},
"custom_attributes": []
}
}

Hope that help you ...

Related Topic