0

How can I add programmtically tracking numbers while creating shipping for order? Right now I have created observer sales_order_shipment_save_before for my shipping method. I think that there should be some logic to prepare label and tracking data:

public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $shipment = $observer->getEvent()->getShipment();
        $order = $shipment->getOrder();

        if ($order->getShippingMethod() == 'shipping_method_name') {
            some logic
        }
    }

and in my carrier class:

<?php

use Magento\Quote\Model\Quote\Address\RateRequest;
use Magento\Shipping\Model\Rate\Result;

class Carrier
    extends \Magento\Shipping\Model\Carrier\AbstractCarrierOnline
    implements \Magento\Shipping\Model\Carrier\CarrierInterface
{

    const CODE = 'codename';
    /**
     * @var string
     */
    protected $_code = self::CODE;
    protected $_rateResultFactory ;
    protected $_rateMethodFactory ;

    /**
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory
     * @param \Psr\Log\LoggerInterface $logger
     * @param \Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory
     * @param \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory,
        \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory,
        array $data = []
    ) {
        $this->_rateResultFactory = $rateResultFactory;
        $this->_rateMethodFactory = $rateMethodFactory;
        parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data);
    }

    /**
     * @return array
     */
    public function getAllowedMethods()
    {
        return [self::CODE => $this->getConfigData('name')];
    }

    /**
     * Check if carrier has shipping label option available
     *
     * @return bool
     */
    public function isShippingLabelsAvailable()
    {
        return true;
    }


    /**
     * @param RateRequest $request
     * @return bool|Result
     */
    public function collectRates(RateRequest $request)
    {
        if (!$this->getConfigFlag('active')) {
            return false;
        }

        /** @var \Magento\Shipping\Model\Rate\Result $result */
        $result = $this->_rateResultFactory->create();

        /** @var \Magento\Quote\Model\Quote\Address\RateResult\Method $method */
        $method = $this->_rateMethodFactory->create();

        $method->setCarrier(self::CODE);
        $method->setCarrierTitle($this->getConfigData('title'));

        $method->setMethod(self::CODE);
        $method->setMethodTitle($this->getConfigData('name'));

        /*you can fetch shipping price from different sources over some APIs, we used price from config.xml - xml node price*/
        $amount = $this->getConfigData('price');

        $method->setPrice($amount);
        $method->setCost($amount);

        $result->append($method);

        return $result;
    }

    /**
     * Do shipment request to carrier web service, obtain Print Shipping Labels and process errors in response
     *
     * @param \Magento\Framework\DataObject $request
     * @return \Magento\Framework\DataObject
     */
    protected function _doShipmentRequest(\Magento\Framework\DataObject $request)
    {
        $result = new \Magento\Framework\DataObject();
        $result->setShippingLabelContent('Shipping Label Content');
        $result->setTrackingNumber('12342342342');

        return $result;
    }

    /**
     * Do request to shipment
     *
     * @param \Magento\Shipping\Model\Shipment\Request $request
     * @return array|\Magento\Framework\DataObject
     */
    public function requestToShipment($request)
    {
        $result = $this->_doShipmentRequest($request);

        $response = new \Magento\Framework\DataObject(
            [
                'info' => [
                    [
                        'tracking_number' => $result->getTrackingNumber(),
                        'label_content' => $result->getShippingLabelContent(),
                    ],
                ],
            ]
        );

        return $response;
    }

}
1
  • have you get any solution for this ? I am stuck with the same issue. Jul 17 '19 at 11:50
1

Check below code, I hope this will help you.

 $shipmentCollection = $objectManager->create('Magento\Sales\Model\Order\Shipment')->getCollection()->addAttributeToFilter('order_id', $order->getId());
                foreach ($shipmentCollection as $shipmentValue) {
                    $orderTrackingNumber = array();
                    foreach($shipmentValue->getAllTracks() as $orderTrackData){
                        $orderTrackingNumber[] =  $orderTrackData->getNumber()."<br>";
                    }
                    if(count($orderTrackingNumber) == 0){

                        $shipmentData = $objectManager->create('Magento\Sales\Model\Order\Shipment')->load($shipmentValue->getIncrementId());
                        if($shipmentData->getId() != '') {
                            $track = $objectManager->create('Magento\Sales\Model\Order\Shipment\Track')
                                        ->setShipment($shipmentData)
                                        ->setTitle($shippingTitle)
                                        ->setNumber($fileValue['tracking'])
                                        ->setCarrierCode($shippingMethod)
                                        ->setOrderId($shipmentData->getData('order_id'))
                                        ->save();
                                //echo "<h1>SHIPMENT TRACKING NUMBER CREATED</h1><br>";
                        }
                    }
                }

Not the answer you're looking for? Browse other questions tagged or ask your own question.