Automatically Adding Tracking Numbers to Magento Orders
As an e-commerce business owner, streamlining your operations is key to maintaining efficiency and customer satisfaction. One common task that can be automated in Magento is the process of adding tracking numbers to orders once they are available.
Understanding the Problem
The user’s request involves automatically populating the last 4 digits of invoices as a tracking number for every order, assuming an invoice exists. This requires integration with your shipping provider’s API and proper handling within the Magento system.
The Magento Solution
Magento provides several events that you can hook into to perform custom logic. For this scenario, we’ll use the sales_order_place_after event. Here’s how to implement the solution:
- First, create a new module for your extension. In the
etc/events.xmlfile of your module, define the following configuration:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="sales_order_place_after">
<observer name="add_tracking_number" instance="Vendor\Module\Model\Observer" />
</event>
</config>
- Create the observer class
Vendor\Module\Model\Observer. This is where the logic to add tracking numbers will be implemented.
<?php
namespace Vendor\Module\Model;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Request\Http;
class Observer implements ObserverInterface
{
private $http;
private $shipmentRepository;
private $carrierFactory;
public function __construct(
Http $http,
\Magento\Shipping\Model\ShipmentRepository $shipmentRepository,
\Magento\Shipping\Model\CarrierFactory $carrierFactory
) {
$this->http = $http;
$this->shipmentRepository = $shipmentRepository;
$this->carrierFactory = $carrierFactory;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$order = $observer->getOrder();
$shippingAddress = $order->getShippingAddress();
// Check if the shipments have been created
foreach ($order->getShipmentsCollection() as $shipment) {
if (!$shipment->getTrackingNumbers()) {
continue;
}
// Get the last tracking number
end($shipment->getTrackingNumbers());
$lastTrackingNumber = current($shipment->getTrackingNumbers());
// Extract the last 4 digits (assuming a standard invoice format)
preg_match('/\d{4}$/', $lastTrackingNumber, $matches);
if (isset($matches[0])) {
$trackingCode = $matches[0];
} else {
continue; // Skip if no match is found
}
// Assign the tracking code to the order
$order->setData(' Tracking Code', $trackingCode);
$order->save();
}
}
}
This observer class hooks into the sales_order_place_after event. It retrieves the shipments associated with each order and checks for available tracking numbers. If a tracking number is found, it extracts the last 4 digits using regular expressions and assigns this value as the tracking code to the order.
Best Practices
When working with Magento events and observers:
- Always use a dedicated module for your custom functionality.
- Keep your observer classes lean and focused on their specific tasks.
- Use dependency injection for all required resources.
- Ensure that your solution is compatible with future Magento updates by following coding standards and best practices.
For more in-depth information on Magento event-observer communication, check out the official documentation: Magento Event-Observer Communication
Conclusion
Automating the process of adding tracking numbers to Magento orders significantly reduces manual effort and improves operational efficiency. By using the sales_order_place_after event, you can implement a clean and efficient solution within your custom Magento extension.
Remember, every business has unique shipping requirements. You may need to adapt this solution based on your specific shipping workflows and provider integrations. Always test thoroughly before deploying changes in a production environment.
With proper implementation and regular monitoring, you’ll see a noticeable improvement in your order fulfillment process, leading to enhanced customer satisfaction and potentially reduced costs through automated tracking management.