How to Get Shipment Tracking Information Programmatically in Magento 2?

 

 

Today, we’re going to teach you guys how to get shipment tracking information programmatically in your Magento 2 store.

As you might already know that it’s extremely crucial to stay in touch with customers in the eCommerce business.

After receiving their orders, especially, it is essential for an eCommerce business to regularly provide information regarding their order such as expected delivery date, the status of their shipment, and so on.

And in Magento 2, it is quite easy to get shipment tracking information and notify the customers.

In this post, we’ll show you exactly how to get the shipment tracking information in your Magento 2 store.

Step Get Shipment Tracking Information Programmatically in Magento 2

Please follow the below steps to learn how to get shipment tracking information in Magento 2.

Step 1.

First of all, create an event.xml file in the app\code\Vendor\Extension\etc\ folder and paste the following code.

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

           xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">

    <event name="sales_order_shipment_save_after">

          <observer name="track_shipment" instance="Vendor\Extension\Observer\Shipment" />

     </event>

</config>

 

Step 2.

Next, open the Shipment.php file from the app\code\Vendor\Extension\Observer\ folder and paste the following code.

<?php

namespace Vendor\Extension\Observer;

use Magento\Framework\Event\ObserverInterface;

class Shipment implements ObserverInterface

{

    public function execute(\Magento\Framework\Event\Observer $observer)

    {

        try {

            $shipment = $observer->getEvent()->getShipment();

            $tracksCollection = $shipment->getTracksCollection();

            foreach ($tracksCollection->getItems() as $track) {

                $track_number = $track->getTrackNumber();

                $carrier_name = $track->getTitle();

            }

        } catch (\Exception $e) {

        }

    }

}

?>

Also read: How to Create Shipment Programmatically in Magento 2?

Conclusion

And it’s done!

This is how easy it is to get shipment tracking information in Magento 2.

And if you need our professional assistance with Magento 2 Development, feel free to reach out to us at any time.