How to Create Shipment With Tracking Information Programmatically in Magento 2

shipment_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 Codextblog\Autoshipment\Cron;

class GenerateAutoShipment
{

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

public function __construct(
    \Magento\Sales\Api\Data\OrderInterface $orderFactory,
    \Magento\Sales\Model\Convert\Order $orderModel,
    \Magento\Sales\Model\Order\Shipment\TrackFactory $trackFactory,
    \Magento\Shipping\Model\ShipmentNotifier $shipmentFactory,
    \Psr\Log\LoggerInterface $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.

Leave a Comment

(0 Comments)

All the comments are goes into moderation before approval. Please do not spam. Your email address will not be published. Required fields are marked *

Enjoy this post? Please support Us!

Like our social page for daily new updates….


Want to become
a Magento 2 Expert?

If Yes! Then Subscribe to our newsletter and get weekly article to you email id.
Subscribe Here
SUBSCRIBE NOW
close-link

To Avoid Spam Downloads, We Want Your Email

We will send you download link right
away. Please submit form below.
SEND ME DOWNLOAD LINK
Close