How to Create customer and add new address programmatically in magento 2?

To create customer and customer addresses programmatically in Magento 2, You need to study the entire article and implement the code in your website.

Given the below code checks, the Customer exists or not using the email id. If the customer is new, Add a new customer and add the given address to the same customer otherwise display an already existing customer message.

<?php
$customerInfo =[
    'customer' =>[
        'firstname'    => 'Rakesh',
        'email'        => 'rakesh.jesadiya@aaaa.com', //customer email id
        'lastname'     => 'jesadiya',
        'password' => 'admin123',
        'prefix' => 'Mr',
        'suffix' => ''
    ],
    'address' =>[
        'firstname'    => 'Rakesh',
        'lastname'     => 'Jesadiya',
        'prefix' => 'Mr',
        'suffix' => '',
        'street' => 'Abcd street',
        'city' => 'Los Angeles',
        'country_id' => 'US',
        'region' => 'California',
        'region_id' => '12', // State region id
        'postcode' => '45454',
        'telephone' => '1234512345',
        'save_in_address_book' => 1
    ]
];

$block->createCustomer($customerInfo);

In the Block file, Pass customer-required data from the above $customerInfo array,

<?php

namespace Rbj\CreateCustomer\Block;

class CustomerAddress extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Customer\Api\Data\AddressInterfaceFactory $dataAddressFactory,
        \Magento\Customer\Api\AddressRepositoryInterface $addressRepository,
        array $data = []
    ) {
        $this->storeManager = $storeManager;
        $this->customerFactory = $customerFactory;
        $this->dataAddressFactory = $dataAddressFactory;
        $this->addressRepository = $addressRepository;
        parent::__construct($context, $data);
    }

    /** Create customer
     *  Pass customer data as array
     */
    public function createCustomer($data) {
        $store = $this->storeManager->getStore();
        $storeId = $store->getStoreId();
        $websiteId = $this->storeManager->getStore()->getWebsiteId();
        $customer = $this->customerFactory->create();
        $customer->setWebsiteId($websiteId);
        $customer->loadByEmail($data['customer']['email']);// load customer by email to check if customer is availalbe or not
        if(!$customer->getId()){
            /* create customer */
            $customer->setWebsiteId($websiteId)
                    ->setStore($store)
                    ->setFirstname($data['customer']['firstname'])
                    ->setLastname($data['customer']['lastname'])
                    ->setPrefix($data['customer']['prefix'])
                    ->setMobile($data['customer']['mobile'])
                    ->setEmail($data['customer']['email'])
                    ->setPassword($data['customer']['password']);
            $customer->save();

            /* save address as customer */
            $address = $this->dataAddressFactory->create();
            $address->setFirstname($data['address']['firstname']);
            $address->setLastname($data['address']['lastname']);
            $address->setTelephone($data['address']['telephone']);

            $street[] = $data['address']['street'];//pass street as array
            $address->setStreet($street);

            $address->setCity($data['address']['city']);
            $address->setCountryId($data['address']['country_id']);
            $address->setPostcode($data['address']['postcode']);
            $address->setRegionId($data['address']['region_id']);
            $address->setIsDefaultShipping(1);
            $address->setIsDefaultBilling(1);
            $address->setCustomerId($customer->getId());
            try
            {
                $this->addressRepository->save($address);  
            }
            catch (\Exception $e) {
                return __('Error in shipping/billing address.');
            }
        } else {
            return __('Customer is already exist!');
        }
    }
    
}

Run the indexer command to see a customer in the admin panel,

php bin/magento indexer:reindex
php bin/magento cache:flush

How to get Default billing and Shipping address by customer id in magento 2?

In Magento 2 we can get Customer’s Default billing and Shipping address by customer id using below code snippet,

Using the Block file get the customer’s default billing and shipping address,

<?php

namespace Rbj\Customer\Block;

class CustomerAddressById extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Customer\Api\AccountManagementInterface $accountManagement,
        \Magento\Customer\Model\Address\Config $addressConfig,
        \Magento\Customer\Model\Address\Mapper $addressMapper,
        \Magento\Framework\App\Http\Context $httpContext,
        array $data = []
    ) {
        $this->accountManagement = $accountManagement;
        $this->_addressConfig = $addressConfig;
        $this->addressMapper = $addressMapper;
        parent::__construct($context, $data);
    }

    /**
     * $customerId
     */
    public function getDefaultShippingAddress($customerId)
    {
        try {
            $address = $this->accountManagement->getDefaultBillingAddress($customerId);
        } catch (NoSuchEntityException $e) {
            return __('You have not set a default shipping address.');
        }
        return $address;
    }

    /**
     * $customerId
     */
    public function getDefaultBillingAddress($customerId)
    {
        try {
            $address = $this->accountManagement->getDefaultBillingAddress($customerId);
        } catch (NoSuchEntityException $e) {
            return __('You have not set a default billing address.');
        }
        return $address;
    }
    /* Html Format */
    public function getDefaultShippingAddressHtml($address) {
        if ($address) {
            return $this->_getAddressHtml($address);
        } else {
            return __('You have not set a default Shipping address.');
        }
    }
    /* Html Format */
    public function getDefaultBillingAddressHtml($address) {
        if ($address) {
            return $this->_getAddressHtml($address);
        } else {
            return __('You have not set a default billing address.');
        }
    }

    /**
     * Render an address as HTML and return the result
     *
     * @param AddressInterface $address
     * @return string
     */
    protected function _getAddressHtml($address)
    {
        /** @var \Magento\Customer\Block\Address\Renderer\RendererInterface $renderer */
        $renderer = $this->_addressConfig->getFormatByCode('html')->getRenderer();
        return $renderer->renderArray($this->addressMapper->toFlatArray($address));
    }
}

Call the required function in the template file,

<?php
$customerId = 1;

$shippingAddress = $block->getDefaultShippingAddress($customerId);
//echo "<pre>";print_r($shippingAddress->__toArray());

$billingAddress = $block->getDefaultBillingAddress($customerId);
//echo "<pre>";print_r($billingAddress->__toArray());

echo $block->getDefaultShippingAddressHtml($shippingAddress);
echo $block->getDefaultBillingAddressHtml($billingAddress);
?>

How to get Default billing and Shipping address of current customer in magento 2?

In Magento 2 we can get the Current Customer Default billing and Shipping address using the given code snippet.

If the Customer is not logged in they will display customer is not logged in.
Using Block file get logged in customer default billing and shipping address,

<?php
namespace Rbj\CustomerAddress\Block;

class Addressinfo extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Customer\Helper\Session\CurrentCustomerAddress $currentCustomerAddress,
        \Magento\Customer\Model\Address\Config $addressConfig,
        \Magento\Customer\Model\Address\Mapper $addressMapper,
        \Magento\Framework\App\Http\Context $httpContext,
        array $data = []
    ) {
        $this->currentCustomerAddress = $currentCustomerAddress;
        $this->_addressConfig = $addressConfig;
        $this->addressMapper = $addressMapper;        
        $this->httpContext = $httpContext;
        parent::__construct($context, $data);
    }

    /**
     * Array for Shipping Address
     *
     * @return \Magento\Framework\Phrase|string
     */
    public function getDefaultShippingAddress()
    {
        try {
            $address = $this->currentCustomerAddress->getDefaultShippingAddress();
        } catch (NoSuchEntityException $e) {
            return __('You have not set a default shipping address.');
        }
        return $address;
    }

    /**
     * Array for Billing Address
     *
     * @return \Magento\Framework\Phrase|string
     */
    public function getDefaultBillingAddress()
    {
        try {
            $address = $this->currentCustomerAddress->getDefaultBillingAddress();
        } catch (NoSuchEntityException $e) {
            return __('You have not set a default billing address.');
        }
        return $address;
    }
    /* Html Format */
    public function getDefaultShippingAddressHtml($address) {
        if ($address) {
            return $this->_getAddressHtml($address);
        } else {
            return __('You have not set a default Shipping address.');
        }
    }
    /* Html Format */
    public function getDefaultBillingAddressHtml($address) {
        if ($address) {
            return $this->_getAddressHtml($address);
        } else {
            return __('You have not set a default billing address.');
        }
    }

    /**
     * Render an address as HTML and return the result
     *
     * @param AddressInterface $address
     * @return string
     */
    public function _getAddressHtml($address)
    {
        /** @var \Magento\Customer\Block\Address\Renderer\RendererInterface $renderer */
        $renderer = $this->_addressConfig->getFormatByCode('html')->getRenderer();
        return $renderer->renderArray($this->addressMapper->toFlatArray($address));
    }

    /*
     * return bool
     */
    public function getLogin() {
        return $this->httpContext->isLoggedIn();
    }
}

Call a required function in the template file,

<?php
$isLoggedin = $block->getLogin(); //output for logged in customer as 'roni_cost@example.com'
if($isLoggedin) {
    $shippingAddress = $block->getDefaultShippingAddress();
    //echo "<pre>";print_r($shippingAddress->__toArray());
    $billingAddress = $block->getDefaultBillingAddress();
    //echo "<pre>";print_r($billingAddress->__toArray());
    echo $block->getDefaultShippingAddressHtml($shippingAddress);
    echo $block->getDefaultBillingAddressHtml($billingAddress);
} else {
    echo __('You have not logged in.');
}

Output for the customer has a shipping address exist,

echo "<pre>";print_r($shippingAddress->__toArray());

Array
(
    [firstname] => Rakesh
    [lastname] => Jesadiya
    [street] => Array
        (
            [0] => 61460 Honey Street Parkway
        )

    [city] => Hollywood
    [country_id] => US
    [region] => Array
        (
            [region] => Michigan
            [region_code] => MI
            [region_id] => 33
        )

    [region_id] => 33
    [postcode] => 49628-7978
    [telephone] => (555) 229-3326
    [id] => 1
    [customer_id] => 1
    [default_billing] => 1
    [default_shipping] => 1
)

Output for HTML format of the Shipping address,

Rakesh Jesadiya
61460 Honey Street Parkway
Hollywood, Michigan, 49628-7978
United States
T: (555) 229-3326