You can get the Shipment Tracking information, like tracking_number, carrier code, title, order_id from the shipment id using Magento 2.
Using Magento\Sales\Api\ShipmentRepositoryInterface interface to retrieve shipment object and based on shipment object we can fetch all the tracking information for a shipment.
getTracks() method of Shipping object contains the Tracking information data.
ShipmentTrackInterface contains the basic function of Tracking Details.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | <?php namespace Jesadiya\Model\Shipment; use Exception; use Psr\Log\LoggerInterface; use Magento\Sales\Api\Data\ShipmentInterface; use Magento\Sales\Api\Data\ShipmentTrackInterface; use Magento\Sales\Api\ShipmentRepositoryInterface; class Tracking { /** * @var ShipmentRepositoryInterface */ private $shipmentRepository; /** * @var LoggerInterface */ private $logger; public function __construct( ShipmentRepositoryInterface $shipmentRepository, LoggerInterface $logger ) { $this->shipmentRepository = $shipmentRepository; $this->logger = $logger; } /** * Get Shipment Trackig data by Shipment Id * * @param $id * * @return ShipmentTrackInterface|null */ public function getTracking($id) { $shipmentId = 1; //shipment id $shipment = $this->getShipmentById($shipmentId); if ($shipment) { return $shipment->getTracks(); } return null; } /** * Get Shipment data by Shipment Id * * @param $id * * @return ShipmentInterface|null */ public function getShipmentById($id) { try { $shipment = $this->shipmentRepository->get($id); } catch (Exception $exception) { $this->logger->critical($exception->getMessage()); $shipment = null; } return $shipment; } } |
Now you can call the function under the template file or any PHP class,
1 2 3 4 5 6 7 8 | $shipmentId = 1; // shipment id $shipmment = $this->getTracking($shipmentId); foreach ($shipment->getTracks() as $track) { echo $track->getTrackingNumber(); // 3333333333 echo $track->getTitle(); //Federal Express echo $track->getCarrierCode(); // fedex echo $track->getOrderId(); //10 } |
Using the above details code snippet, You can get the tracking information of shipment in Magento 2.