shipment_magento_2 shipment_magento_2

How to Create Shipment With Tracking Information Programmatically in Magento 2

Shipment is the essential part of Magento 2 E-commerce. Once an order invoice is successfully created, You can create shipment For Particular order by navigating through Magento 2 Admin > Sales > Order grid. You can also add a tracking information while creating shipment in Magento 2.

Sometimes you need to create shipment programmatically, for example, create shipment by fetching tracking information from external APIs, create shipment on successful invoice creation. In this code snippet, we will see how to create shipment with tracking information programmatically in Magento 2. You can add multiple tracking information with shipment by using this code snippet.
 

Create Shipment With Tracking Information Programmatically

<?php
namespace CodextblogAutoshipmentCron;

class GenerateAutoShipment
{

protected $orderFactory;
protected $shipmentFactory;
protected $orderModel;
protected $trackFactory;
protected $logger;

public function __construct(
    MagentoSalesApiDataOrderInterface $orderFactory,
    MagentoSalesModelConvertOrder $orderModel,
    MagentoSalesModelOrderShipmentTrackFactory $trackFactory,
    MagentoShippingModelShipmentNotifier $shipmentFactory,
    PsrLogLoggerInterface $logger

)
{
    $this->orderFactory = $orderFactory;
    $this->orderModel = $orderModel;
    $this->trackFactory = $trackFactory;
    $this->shipmentFactory = $shipmentFactory;
    $this->logger = $logger;
}

public function execute()
{
  $orderNumber = '00000001';
  $order = $this->orderFactory->loadByIncrementId($orderNumber);

  if($order->hasInvoices()){

  if($order->canShip()){

    $shipment = $this->orderModel->toShipment($order);

    foreach ($order->getAllItems() AS $orderItem) {

        if (!$orderItem->getQtyToShip() || $orderItem->getIsVirtual()) {
            continue;
        }
        $qtyShipped = $orderItem->getQtyToShip();

        $shipmentItem = $this->orderModel->itemToShipmentItem($orderItem)->setQty($qtyShipped);

        $shipment->addItem($shipmentItem);

    }

    $shipment->register();
    $shipment->getOrder()->setIsInProcess(true);

    try {

        $trackingIds = array(
                '0'=>array('carrier_code'=>'fedex','title' => 'Federal Express','number'=>'3131331230'),
                '1'=>array('carrier_code'=>'ups','title' => 'UPS Ground','number'=>'1312312')
        );

        /*Add Multiple tracking information*/
        foreach ($trackingIds as $trackingId) {
            $data = array(
                'carrier_code' => $trackingId['carrier_code'],
                'title' => $trackingId['title'],
                'number' => $trackingId['number'],
            );
            $track = $this->trackFactory->create()->addData($data);
            $shipment->addTrack($track)->save();
        }

        $shipment->save();
        $shipment->getOrder()->save();

        // Send email
        $this->shipmentFactory->notify($shipment);
        $shipment->save();

    } catch (Exception $e) {
        $this->logger->info($e->getMessage());
    }
  }else{
    $this->logger->info('You can not create an shipment:' . $orderNumber);
  }

  }else {
    $this->logger->info('Invoice is not created for order:' . $orderNumber);
  }
 }
}

Hope this code snippet helps in your Magento 2 development.To receive update about this type of code snippet, please like us on Facebook and follow us on Twitter.

Written by

Chirag

Chirag is a Founder & eCommerce Technology Leader at MageArmy. He leads the eCommerce development team and drives the company’s technology vision, helping businesses build, scale, and optimize high-performing online stores. With years of experience in eCommerce development, he has worked with businesses across industries to solve complex technical challenges and create scalable digital commerce solutions. He loves sharing practical insights about eCommerce development, Magento, Adobe Commerce, and the latest trends in digital commerce to help online businesses grow and succeed.