Magento 2 – How to Add Tracking Number to Order Shipment

dependency-injectionmagento2shipment-trackingshipping

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();

Best Answer

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.

Related Topic