Creating Magento Shipments with Tracking Numbers Programmatically
In Magento, creating shipments for orders programmatically can be achieved through the built-in API or custom scripts. This process allows you to automate the shipment creation and tracking number assignment without manual intervention.
Understanding Magento Shipment Creation
Before diving into the code, let’s understand the key components involved:
- Order Entity: The order that contains the items to be shipped.
- Tracking Number: The unique identifier provided by the shipping carrier.
- Shipment Item: The individual items being shipped as part of this shipment.
Creating a Shipment Using Magento API
The most straightforward way is to use the Magento REST API’s shipments endpoint. This endpoint allows you to create shipments for an order and assign tracking numbers. Here’s a basic example using cURL:
curl -X POST -H "Content-Type: application/json" -d '{"tracking_number": "1234567890", "items": [{"order_item_id": 1, "qty": 1}]}' http://your-magento-url.com/rest/V1/shipments
Replace http://your-magento-url.com with your Magento site’s URL. In this example, we’re creating a shipment for an order item with ID 1 and assigning the tracking number “1234567890”.
Creating a Custom Script in Magento
For more complex scenarios or to integrate with external systems, you might opt for a custom PHP script using Magento’s API. Here’s a basic example of how this can be done:
<?php
require_once 'app/bootstrap.php';
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$orderRepository = $objectManager->get('\Magento\Sales\Model\OrderRepository');
$shipmentRepository = $objectManager->get('\Magento\Shipping\Model\ShipmentRepository');
$orderId = 123; // Replace with the order ID
$trackingNumber = '1234567890'; // Replace with the tracking number
try {
$order = $orderRepository->get($orderId);
foreach ($order->getItems() as $item) {
if (!$item->getIsDummy()) { // Skip dummy items
$shipmentItem = $objectManager->create('\Magento\Sales\Model\Order\ShipmentItem');
$shipmentItem->setOrderItem($item)->setQty($item->getQtyToShip());
$items[] = $shipmentItem;
}
}
if (!isset($items)) {
throw new Exception('No items to ship.');
}
$request = [
'order_id' => $orderId,
'tracking_number' => $trackingNumber,
'items' => $items
];
$shipment = $shipmentRepository->create($request);
$shipment->register();
$shipment->getOrder()->setIsInProcess(true);
echo "Shipment created with ID: {$shipment->getId()}";
} catch (Exception $e) {
echo 'Error creating shipment: ' . $e->getMessage();
}
This script demonstrates how to create a shipment for an order, assign tracking numbers, and register the shipment.
Best Practices
- Use Magento’s Built-in API: Whenever possible, use the built-in Magento API for operations like this. It ensures compatibility across updates.
- Handle Exceptions: Always wrap your code in try-catch blocks to handle any potential errors gracefully.
- Error Logging: Implement proper logging to track when shipments aren’t created successfully.
Remember, creating shipments programmatically should be done with caution and thorough testing. Incorrect implementations can lead to inventory mismatches or data inconsistencies.
Conclusion
Creating Magento shipments with tracking numbers programmatically is a powerful feature that allows for automated order fulfillment processes. Whether you’re using the built-in API or custom scripts, understanding the underlying objects and endpoints will help streamline your operations.
For more advanced scenarios like integrating with external carriers or implementing complex shipping logic, consider looking at our guide on Advanced Magento Shipping Extensions.
With these techniques in place, you can build a robust and efficient order fulfillment system for your Magento store.