12

I did find sample codes for Magento 1.x. But I have no idea how to do this on Magento 2.

Can anyone describe how to implement this using Dependency Injection (DI)?

Thanks.

$trackingDetail = array(
    'carrier_code' => 'ups',
    'title' => 'United Parcel Service',
    'number' => 'TORD23254WERZXd3', // Replace with your tracking number
);

$track = Mage::getModel('sales/order_shipment_track')->addData($trackingDetail);
$shipment->addTrack($track);


$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($shipment)
->addObject($shipment->getOrder())
->save();

3 Answers 3

16

AFAIK the track object is the same in M2.

However, the rest of the code has changed.

$data = array(
    'carrier_code' => 'ups',
    'title' => 'United Parcel Service',
    'number' => 'TORD23254WERZXd3', // Replace with your tracking number
);

$track = $this->trackFactory->create()->addData($data);
$shipment->addTrack($track)->save();

Where $this->trackFactory an instance of Magento\Sales\Model\Order\Shipment\TrackFactory and $shipment is your shipment object.

6
  • BTW I wonder if you know how to get order shipment comments too for MG2. If you do please post it here. Thanks. Jan 25, 2017 at 6:50
  • 1
    How to add tracking URl in shipment? Feb 7, 2018 at 5:53
  • @Roshanruzaik, if you are asking how to add comment to the shipment then this is how i have done:$commentText = 'Test comment'; //Comment interface : \Magento\Sales\Api\Data\ShipmentCommentCreationInterface $comment= $this->commentInterface->setComment($commentText); //use $comment as one of the paramter while creating shipment as below example: //ship order service: \Magento\Sales\Model\ShipOrder $this->shipOrderService->execute($orderId,$shippedItems,$notify,$includeComment,$comment,$tracks); Jun 4, 2018 at 23:16
  • Hi @Raphael at digital pianism sipping tracking number, and carrier_code is saving in "sales_shipment_track" table in magento2 but where it will save the Shipping Charge ? Nov 19, 2018 at 11:55
  • can you please help on this similar question magento.stackexchange.com/questions/268844/… Apr 5, 2019 at 19:38
12

Adding to the accepted answer, it would be a good idea to use repositories instead of the deprecated save method. Also added the customer notification after the tracking creation.

/** @var Magento\Sales\Model\Order\ShipmentRepository */
protected $_shipmentRepository;

/** @var Magento\Shipping\Model\ShipmentNotifier */
protected $_shipmentNotifier;

/** @var Magento\Sales\Model\Order\Shipment\TrackFactory */
protected $_trackFactory; //missing ;

public function __construct(
  \Magento\Shipping\Model\ShipmentNotifier $shipmentNotifier, 
  \Magento\Sales\Model\Order\ShipmentRepository $shipmentRepository, 
  \Magento\Sales\Model\Order\Shipment\TrackFactory $trackFactory)
{
  $this->_shipmentNotifier = $shipmentNotifier;
  $this->_shipmentRepository = $shipmentRepository;
  $this->_trackFactory = $trackFactory;
}
public function addTrack($shipment, $carrierCode, $description, $trackingNumber) 
{
    /** Creating Tracking */
    /** @var Track $track */
    $track = $this->_trackFactory->create();
    $track->setCarrierCode($carrierCode);
    $track->setDescription($description);
    $track->setTrackNumber($trackingNumber);
    $shipment->addTrack($track);
    $this->_shipmentRepository->save($shipment);

    /* Notify the customer*/
    $this->_shipmentNotifier->notify($shipment);
 }

Where $shipment is your shipment object. Notify will notify (send email) to the user and add a history item to the order status history collection.

3
  • It did not work for me have created helper class , i am able to fetch getDeiveryTime(), getCancelTime(),getDispatchTime() but i am unable to get tracking number. Can you provide a list of functions to fetch rest details of the shipment Mar 15, 2019 at 22:54
  • can you help on this similar question? magento.stackexchange.com/questions/268844/… Apr 5, 2019 at 19:24
  • @carol Castro, how can we add the order id here?
    – Mujahidh
    Sep 26, 2019 at 14:19
0

In Magento 2.4.5-p1: By using the below code we can save tracking information in order shipment.

<?php
namespace Module\ImportTrackingNumber\Model\Shipment;

use Magento\Sales\Api\Data\OrderInterface;

class Track
{
    /**
     *
     * @var \Psr\Log\LoggerInterface;;
     */
    protected $logger;

    /**
     * @var \Magento\Sales\Model\Spi\OrderResourceInterface
     */
    protected $orderResource;

    /**
     * @var Magento\Sales\Api\Data\OrderInterfaceFactory
     */
    protected $orderInterfaceFactory;

    /**
     * @var \Magento\Sales\Api\Data\ShipmentTrackInterfaceFactory
     */
    protected $shipmentTrackInterfaceFactory;
           
    /**
     *
     * @var \Magento\Sales\Api\ShipmentTrackRepositoryInterface;
     */
    protected $shipmentTrackRepository;
    
   /**
    *
    * @param \Psr\Log\LoggerInterface $logger
    * @param \Magento\Sales\Model\Spi\OrderResourceInterface $orderResource
    * @param \Magento\Sales\Api\Data\OrderInterfaceFactory $orderInterfaceFactory
    * @param \Magento\Sales\Api\Data\ShipmentTrackInterfaceFactory $shipmentTrackInterfaceFactory
    * @param \Magento\Sales\Api\ShipmentTrackRepositoryInterface $shipmentTrackRepository
    */
    public function __construct(
        \Psr\Log\LoggerInterface $logger,
        \Magento\Sales\Model\Spi\OrderResourceInterface $orderResource,
        \Magento\Sales\Api\Data\OrderInterfaceFactory $orderInterfaceFactory,
        \Magento\Sales\Api\Data\ShipmentTrackInterfaceFactory $shipmentTrackInterfaceFactory,
        \Magento\Sales\Api\ShipmentTrackRepositoryInterface $shipmentTrackRepository
    ) {
        $this->logger = $logger;
        $this->orderResource = $orderResource;
        $this->orderInterfaceFactory = $orderInterfaceFactory;
        $this->shipmentTrackInterfaceFactory = $shipmentTrackInterfaceFactory;
        $this->shipmentTrackRepository = $shipmentTrackRepository;
    }

    /**
     * save the order tracking information
     *
     * @param array $data
     * @return bool
     */
    public function saveTrackingData($data)
    { 
        try {
            $incrementId = $data['increment_id'] ?: '';
            $trackingNumber = $data['tracking_number'] ?: '';
            $carrierCode = $data['carrier_code'] ?: '';
               
            $order = $this->orderInterfaceFactory->create();
            $this->orderResource->load($order, $incrementId, OrderInterface::INCREMENT_ID);

            $shipmentId = $this->getOrderShipmentId($order);

            if ($shipmentId) {
                $shipmentTrack = $this->shipmentTrackInterfaceFactory->create();

                $shipmentTrack->setParentId($shipmentId);
                $shipmentTrack->setOrderId($order->getId());
                $shipmentTrack->setCarrierCode($carrierCode);
                $shipmentTrack->setTrackNumber($trackingNumber);

                $this->shipmentTrackRepository->save($shipmentTrack);
            } 
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage());
        }

        return false;
    }

    /**
     * save the order tracking information
     *
     * @param \Magento\Sales\Api\Data\OrderInterface $order
     * @return int $shipmentId
     */
    public function getOrderShipmentId($order)
    {
        $shipmentId = 0;

        if ($order->hasShipments()) {

            $shipmentCollection = $order->getShipmentsCollection();

            foreach ($shipmentCollection as $shipment) {
                $shipmentId = $shipment->getId();
            }
        }

        return $shipmentId;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.