How to set default shipping address of the customer Magento 2?

Set Default shipping address id of the customer in Magento 2 using Address Repository Interface.

You required Customer Id to set shipping address and address id you want to assign it.

<?php
namespace JJ\SetShippingAddress\Model;

use Magento\Customer\Api\AddressRepositoryInterface;
use Magento\Customer\Api\CustomerRepositoryInterface;

class DefaultShipping
{
     /**
     * @var CustomerRepositoryInterface
     */
    private $customerRepository;

    /**
     * @var AddressRepositoryInterface
     */
    private $addressRepository;

    /**
     * @var LoggerInterface
     */
    private $logger;

    public function __construct(
        CustomerRepositoryInterface $customerRepository,
        AddressRepositoryInterface $addressRepository,
        LoggerInterface $logger
    ) {
        $this->customerRepository = $customerRepository;
        $this->addressRepository = $addressRepository;
        $this->logger = $logger;
    }

    /**
     * assign default shipping address
     *
     * @param int $customerId
     * @param int $addressId
     * @return void
     */
    public function setShippingAddress(int $customerId, int $addressId)
    {
        try {
            $address = $this->addressRepository->getById($addressId)->setCustomerId($customerId);
            $address->setIsDefaultShipping(true);

            $this->addressRepository->save($address);
        } catch (\Exception $exception) {
            $this->logger->critical($exception);
        }
    }
}

$address->setIsDefaultShipping(true) set the current address id to default address for the given customer.

Leave a comment

Your email address will not be published. Required fields are marked *