Adicionando à resposta aceita, seria uma boa idéia usar repositórios em vez do método obsoleto de salvar. Também foi adicionada a notificação do cliente após a criação do rastreamento.
/** @var Magento\Sales\Model\Order\ShipmentRepository */
protected $_shipmentRepository;
/** @var Magento\Shipping\Model\ShipmentNotifier */
protected $_shipmentNotifier;
/** @var Magento\Sales\Model\Order\Shipment\TrackFactory */
protected $_trackFactory; //missing ;
public function __construct(
\Magento\Shipping\Model\ShipmentNotifier $shipmentNotifier,
\Magento\Sales\Model\Order\ShipmentRepository $shipmentRepository,
\Magento\Sales\Model\Order\Shipment\TrackFactory $trackFactory)
{
$this->_shipmentNotifier = $shipmentNotifier;
$this->_shipmentRepository = $shipmentRepository;
$this->_trackFactory = $trackFactory;
}
public function addTrack($shipment, $carrierCode, $description, $trackingNumber)
{
/** Creating Tracking */
/** @var Track $track */
$track = $this->_trackFactory->create();
$track->setCarrierCode($carrierCode);
$track->setDescription($description);
$track->setTrackNumber($trackingNumber);
$shipment->addTrack($track);
$this->_shipmentRepository->save($shipment);
/* Notify the customer*/
$this->_shipmentNotifier->notify($shipment);
}
Onde $ shipment é o seu objeto de envio. Notify notificará (enviará email) ao usuário e adicionará um item de histórico à coleção de histórico de status do pedido.