受け入れられた回答に加えて、非推奨のsaveメソッドの代わりにリポジトリを使用することをお勧めします。追跡作成後の顧客通知も追加しました。
/** @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);
}
$ shipmentは配送オブジェクトです。Notifyはユーザーに通知(メールを送信)し、注文ステータス履歴コレクションに履歴項目を追加します。