Implementation of new Freight Cost in Websites.

How to install the “Meetpxny Iconsignit” Shipping Extension? 

  1. Download/purchase the extension (like zip or tar.gz archive) 
  1. Upload Extension (as Zip or tar.gz) to your Magento installation root directory. 
  1. Unzip the zip. Make sure file path is “app/code/Meetpxny/Iconsignit/”. 
  1. Run the following command in the terminal. 
  • php bin/magento setup: upgrade 
  • bin/magento setup:static-content:deploy –f 
  • sudo chmod 777 -R /var/www/html/thefencingstore/ 

5. We can see our module name while upgrading: 

6. Inside the Iconsignit folder, there will 3 folders and 2 files:

  • etc
  • Model
  • Observer
  • composer.json
  • registration.php

7. Inside etc folder:

there is a subfolder inside adminhtml i.e., system.xml

system.xml 
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <section id="carriers" translate="label" type="text" sortOrder="320" showInDefault="1" showInWebsite="1" showInStore="1">
            <group id="iconsignitshipping" translate="label" type="text" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Iconsignit Shipping</label>
                <field id="active" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="0" canRestore="1">
                    <label>Enabled</label>
                    <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                </field>
                <field id="name" translate="label" type="text" sortOrder="3" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
                    <label>Method Name</label>
                </field>
                <field id="shipping_api_url" translate="label" type="text" sortOrder="5" showInDefault="1" showInWebsite="1" showInStore="0" canRestore="1">
                    <label>Shipping Api Url</label>
                </field>
                <field id="api_url" translate="label" type="text" sortOrder="7" showInDefault="1" showInWebsite="1" showInStore="0" canRestore="1">
                    <label>Api Url</label>
                </field>
                <field id="api_token" translate="label" type="text" sortOrder="8" showInDefault="1" showInWebsite="1" showInStore="0" canRestore="1">
                    <label>Api Token</label>
                </field>
                <field id="product_attributes_width" translate="comment label" type="select" sortOrder="40"
                       showInStore="0" showInWebsite="1" showInDefault="1">
                    <label>Product Attribute for Width</label>
                    <source_model>Meetpxny\Iconsignit\Model\Config\Configuration\Productattributes</source_model>
                </field>
                <field id="product_attributes_height" translate="comment label" type="select" sortOrder="40"
                       showInStore="0" showInWebsite="1" showInDefault="1">
                    <label>Product Attribute for Height</label>
                    <source_model>Meetpxny\Iconsignit\Model\Config\Configuration\Productattributes</source_model>
                </field>
                <field id="product_attributes_length" translate="comment label" type="select" sortOrder="40"
                       showInStore="0" showInWebsite="1" showInDefault="1">
                    <label>Product Attribute for Length</label>
                    <source_model>Meetpxny\Iconsignit\Model\Config\Configuration\Productattributes</source_model>
                </field>
                
                <!--<field id="handling_type" translate="label" type="select" sortOrder="7" showInDefault="1" showInWebsite="1" showInStore="0" canRestore="1">
                    <label>Calculate Handling Fee</label>
                    <source_model>Magento\Shipping\Model\Source\HandlingType</source_model>
                </field>
                <field id="handling_fee" translate="label" type="text" sortOrder="8" showInDefault="1" showInWebsite="1" showInStore="0">
                    <label>Handling Fee</label>
                    <validate>validate-number validate-zero-or-greater</validate>
                </field>-->
                
                <field id="sort_order" translate="label" type="text" sortOrder="100" showInDefault="1" showInWebsite="1" showInStore="0">
                    <label>Sort Order</label>
                </field>
                <field id="title" translate="label" type="text" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
                    <label>Title</label>
                </field>
                <field id="sallowspecific" translate="label" type="select" sortOrder="90" showInDefault="1" showInWebsite="1" showInStore="0" canRestore="1">
                    <label>Ship to Applicable Countries</label>
                    <frontend_class>shipping-applicable-country</frontend_class>
                    <source_model>Magento\Shipping\Model\Config\Source\Allspecificcountries</source_model>
                </field>
                <field id="specificcountry" translate="label" type="multiselect" sortOrder="91" showInDefault="1" showInWebsite="1" showInStore="0">
                    <label>Ship to Specific Countries</label>
                    <source_model>Magento\Directory\Model\Config\Source\Country</source_model>
                    <can_be_empty>1</can_be_empty>
                </field>
                <field id="showmethod" translate="label" type="select" sortOrder="92" showInDefault="1" showInWebsite="1" showInStore="0">
                    <label>Show Method if Not Applicable</label>
                    <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                    <frontend_class>shipping-skip-hide</frontend_class>
                </field>
                <field id="specificerrmsg" translate="label" type="textarea" sortOrder="80" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
                    <label>Displayed Error Message</label>
                </field>
                <field id="extra_cost" translate="label" type="text" sortOrder="89" showInDefault="1" showInWebsite="1" showInStore="0">
                    <label>Extra(%)</label>
                </field>
            </group>
        </section>
    </system>
</config>

There is a subfolder inside the frontend i.e., system.xml

events.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_onepage_controller_success_action">
        <observer name="mymodule_controller_success_action" instance="Meetpxny\Iconsignit\Observer\CheckoutOnepageControllerSuccessAction"  />
    </event>
</config>
config.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <default>
        <carriers>
            <iconsignitshipping>
                <active>1</active>
                <sallowspecific>0</sallowspecific>
                <model>Meetpxny\Iconsignit\Model\Carrier\Shipping</model>
                <name>Iconsignit Shipping</name>
                <price>10.00</price>
                <title>Iconsignit Shipping</title>
                <specificerrmsg>This shipping method is not available. To use this shipping method, please contact us.</specificerrmsg>
                <handling_type>F</handling_type>
                <product_attributes_width>ts_dimensions_width</product_attributes_width>
                <product_attributes_height>ts_dimensions_height</product_attributes_height>
                <product_attributes_length>ts_dimensions_length</product_attributes_length>
            </iconsignitshipping>
        </carriers>
    </default>
</config>
module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Meetpxny_Iconsignit" setup_version="2.0.0" />
</config>

8. Inside the Model folder, there is 2 subfolder

  • Carrier
  • Config

Inside the subfolder Carrier, there is one file where we write all code regarding shipping

shipping.php
<?php
namespace Meetpxny\Iconsignit\Model\Carrier;

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

class Shipping extends \Magento\Shipping\Model\Carrier\AbstractCarrier implements
    \Magento\Shipping\Model\Carrier\CarrierInterface
{
    //const SHIPPING_API_URL = 'http://kis.iconsignit.com.au/api/getconsignrate';
    const SHIPPING_API_URL = 'http://test9.iconsignit.com.au/api/getconsignrate';

    /**
     * @var string
     */
    protected $_code = 'iconsignitshipping';

    /**
     * @var \Magento\Shipping\Model\Rate\ResultFactory
     */
    protected $_rateResultFactory;

    /**
     * @var \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory
     */
    protected $_rateMethodFactory;

    /*
     * var \Magento\Framework\HTTP\Client\Curl
    */

    protected $_curl;

    /*
     * var \Magento\Catalog\Model\ProductFactory
    */

    protected $_logger;

    /*
     * var \Psr\Log\LoggerInterface
    */

    protected $_product;

    /**
     * @var Meetpxny\Iconsignit\Helper\Data
     */
    private $dataHelper;

    /**
     * Rate result data
     *
     * @var Result|null
     */
    protected $_result = null;


    /**
     * Shipping constructor.
     *
     * @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 \Magento\Framework\HTTP\Client\Curl                           $curl,
       @param \Magento\Catalog\Model\ProductFactory                         $_product,
       @param \Meetpxny\Iconsignit\Helper\Data                              $helperData,
     * @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,
        \Magento\Framework\HTTP\Client\Curl $curl,
        \Magento\Catalog\Model\ProductFactory $_product,
        \Magento\Directory\Helper\Data $helperData,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Checkout\Model\Cart $cart,
        \Magento\Customer\Model\Session $session,
        array $data = []
    ) {
        $this->_rateResultFactory = $rateResultFactory;
        $this->_rateMethodFactory = $rateMethodFactory;
        $this->_curl = $curl;
        $this->_logger = $logger;
        $this->_product = $_product;
        $this->dataHelper = $helperData;
        $this->_checkoutSession = $checkoutSession;
        $this->_cart = $cart;
        $this->_session = $session;

        parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data);
    }

    /**
     * get allowed methods
     * @return array
     */
    public function getAllowedMethods()
    {
        return [$this->_code => $this->getConfigData('name')];
    }


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

        $this->_result = $this->_getQuotes($request);
        return $this->getResult();
    }


    /*
     * Load catalog products
     * @param $id
     * @return \Magento\Catalog\Model\ProductFactory
     */

    public function getLoadProduct($id){
        return $this->_product->create()->load($id);
    }


    /*
     * Get Shipping Rates
     * @param \Magento\Quote\Model\Quote\Address\RateRequest $request
     * @return \Magento\Shipping\Model\Rate\ResultFactory
     */

    protected function _getQuotes($request){
        $this->_logger->addDebug('inn');
        $_items = array();
        $attr_width = $this->getConfigData('product_attributes_width');
        $attr_height = $this->getConfigData('product_attributes_height');
        $attr_length = $this->getConfigData('product_attributes_length');

        $this->_logger->addDebug("$attr_width,$attr_height,$attr_length",array());

        if ($request->getAllItems()) {
            $this->_logger->addDebug("getAllItems");
            foreach ($request->getAllItems() as $item) {
                if ($item->getHasChildren()) {
                    foreach ($item->getChildren() as $child) {
                        if (!$child->getProduct()->isVirtual()) {

                            //$this->_logger->addDebug('config and other');

                            $_product = $this->getLoadProduct($child->getProduct()->getId());
                            $_item = array();
                            $_item['item_qty'] = $item->getQty();
                            $_item['item_code'] = $_product->getSku();
                            $_item['item_desc'] = $item->getName();
                            $_item['item_length'] = 1;
                            $_item['item_width']  = 1;
                            $_item['item_height'] = 1;
                            $this->_logger->addDebug("child",array());

                            if (null !== $_product->getCustomAttribute($attr_length)) {
                                $_item['item_length'] = $_product->getCustomAttribute($attr_length)->getValue();
                            } else {
                                $_item['item_length'] = $_product->getAttributeText($attr_length);
                            }

                            if (null !== $_product->getCustomAttribute($attr_width)) {
                                $_item['item_width'] = $_product->getCustomAttribute($attr_width)->getValue();
                            } else {
                                $_item['item_width'] = $_product->getAttributeText($attr_width);
                            }

                            if (null !== $_product->getCustomAttribute($attr_height)) {
                                $_item['item_height'] = $_product->getCustomAttribute($attr_height)->getValue();
                            } else {
                                $_item['item_height'] = $_product->getAttributeText($attr_height);
                            }

                            $_item['item_weight'] = $_product->getWeight();

                            $pdtOption = $_product->getResource()->getAttribute('product_in_carton')->getFrontend()->getValue($_product);
                            if ($pdtOption == 'Yes') {
                                $_item['item_palletised'] = 0;
                            }
                            else {
                                $_item['item_palletised'] = 1;
                            }
                            $_items[$child->getProduct()->getId()] = $_item;
                        }
                    }
                } else {
                    if (!$item->getParentItem()) {
                        $_item = array();
                        $_product = $this->getLoadProduct($item->getProductId());
                        $_item['item_qty']  = $item->getQty();
                        $_item['item_code'] = $item->getSku();
                        $_item['item_desc'] = $item->getName();

                        if (!empty($attr_width)) {
                            if (null !== $_product->getCustomAttribute($attr_length)) {
                                $_item['item_length'] = $_product->getCustomAttribute($attr_length)->getValue();
                            } else {
                                $_item['item_length'] = $_product->getAttributeText($attr_length);

                            }
                        } else {
                            $_item['item_length'] = '';
                        }
                        if (!empty($attr_width)) {
                            if (null !== $_product->getCustomAttribute($attr_width)) {
                                $_item['item_width'] = $_product->getCustomAttribute($attr_width)->getValue();
                            } else {
                                $_item['item_width'] = $_product->getAttributeText($attr_width);
                            }
                         } else {
                            $_item['item_width'] = '';
                        }
                        if (!empty($attr_height)) {
                            if (null !== $_product->getCustomAttribute($attr_height)) {
                                $_item['item_height'] = $_product->getCustomAttribute($attr_height)->getValue();
                            } else {
                                    $_item['item_height'] = $_product->getAttributeText($attr_height);
                            }
                        } else {
                            $_item['item_height'] = '';
                        }

                        $_item['item_weight']   = $_product->getWeight();
                        // $_item['item_length']   = '';
                        // $_item['item_width']    = '';
                        // $_item['item_height']   = '';
                        //$_item['item_weight']   = 4;

                        $pdtOption = $_product->getResource()->getAttribute('product_in_carton')->getFrontend()->getValue($_product);
                        if ($pdtOption == 'Yes') {
                            $_item['item_palletised'] = 0;
                            $_item['item_height'] = $_item['item_height'] ? ($_item['item_height'] / 10) : $_item['item_height'];
                            $_item['item_width'] = $_item['item_width'] ? ($_item['item_width'] / 10) : $_item['item_width'];
                            $_item['item_length'] = $_item['item_length'] ? ($_item['item_length'] / 10) : $_item['item_length'];
                        }
                        else {
                            $_item['item_palletised'] = 1;
                            $_item['item_height'] = $_item['item_height'] ? ($_item['item_height'] / 10) : $_item['item_height'];
                            $_item['item_width'] = $_item['item_width'] ? ($_item['item_width'] / 10) : $_item['item_width'];
                            $_item['item_length'] = $_item['item_length'] ? ($_item['item_length'] / 10) : $_item['item_length'];
                        }
                        $_items[$item->getProductId()] = $_item;
                    }
                }


            }
        }


        $shippingOrigin = $this->getShippingOrigin();
        //$this->_logger->addDebug(json_encode($_items),array());


        // if (!empty($this->_checkoutSession->getQuote()->getShippingAddress()->getCity())) {
        //     $logger->info('session');
        //     $logger->info($this->_checkoutSession->getQuote()->getShippingAddress()->getCity());
        // }
        $delivery = '';
        if (!$this->_session->isLoggedIn() || ($this->_session->isLoggedIn() && isset($_COOKIE['_home_delivery_']))) {
            if (isset($_COOKIE['_home_delivery_'])) {
                if ($_COOKIE['_home_delivery_']) {
                    $delivery = $_COOKIE['_home_delivery_'];
                }
            } else {
                $delivery = $this->_cart->getQuote()->getShippingAddress()->getHomeDelivery();
                if(!$delivery) {
                    if (isset($_COOKIE['_home_delivery_checkout_'])) {
                        $delivery = $_COOKIE['_home_delivery_checkout_'];
                    }
                }
            }
        } else {
            $delivery = $this->_cart->getQuote()->getShippingAddress()->getHomeDelivery();
            if(!$delivery) {
                if (isset($_COOKIE['_home_delivery_checkout_'])) {
                    $delivery = $_COOKIE['_home_delivery_checkout_'];
                    $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/shipping.log');
                    $logger = new \Zend\Log\Logger();
                    $logger->addWriter($delivery);
                }
            }
        }


        $fields = array(
            'ApiUrl' => $this->getConfigData('api_url'),
            'ApiToken' => $this->getConfigData('api_token'),
            'PickupTown' => $shippingOrigin['city'],
            'PickupPostcode' => $shippingOrigin['postcode'],
            'DeliveryTown' => !is_null($request->getDestCity()) ? $request->getDestCity() : 'Lawnton',
            'DeliveryPostcode' => $request->getDestPostcode(),
            'IsDangerousGoods' => 0,
            'IsResidential' => ($delivery == 2) ? 0 : 1,
            'IsTailgate'=>0,
            'Items' => $_items
        );

        $this->_logger->addDebug(json_encode($fields),array());

        //$this->_curl->post(self::SHIPPING_API_URL, $fields);
        $shipping_api_url = $this->getConfigData('shipping_api_url');
        $shipping_api_url = trim($shipping_api_url, '/') . '/api/getconsignrate';
        $this->_curl->post($shipping_api_url, $fields);

        $apiResponse = $this->_curl->getBody();

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


        // if($request->getDestCity()=='' || $request->getDestPostcode()=='') {
        //     return $result;
        // }

        $apiResponse = json_decode($apiResponse,true);

        $this->_logger->addDebug('api Response');

        $this->_logger->addDebug(json_encode($apiResponse),array());

        if($apiResponse['status']!==false){
            if (!empty($apiResponse['result'])) {
                $methodCount = count($apiResponse['result']);
                // foreach($apiResponse['result'] as $res){
                //     $methodCode = preg_replace('/\s+-\s*|\s*-\s+/','_',$res['carrier_nm']."-(".$res['service_nm'].")");
                //     // $methodTitle = $res['carrier_nm']."-(".$res['service_nm'].")";
                //     $methodTitle = "Roadfast Express";

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

                //     $method->setCarrier($this->_code);
                //     $method->setCarrierTitle($this->getConfigData('title'));

                //     $method->setMethod($methodCode.'___'.$res['QuoteRateID']);
                //     $method->setMethodTitle($methodTitle);

                //     $freightCost = $res['total_charge'];
                //     $additionalCost = $this->getConfigData('extra_cost');
                //     $extraCost = 0;
                //     if ($additionalCost) {
                //         $extraCost = (($freightCost * $additionalCost)/100);
                //     }

                //     // $extraCost = (($freightCost * 75)/100);
                //     $finalCost = $freightCost + $extraCost;
                //     if ( $finalCost < 30) {
                //         $finalCost = 30;
                //     }

                //     $method->setPrice($finalCost);
                //     $method->setCost($finalCost);

                //     $result->append($method);
                // }

                $res = [];
                $shippingArray = $apiResponse['result'];
//                $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/shipping.log');
//                $logger = new \Zend\Log\Logger();
//                $logger->addWriter($writer);

                $logger->info("Info");
                $logger->info($methodCount);
                if ($methodCount > 1) {
                    for ($i=0;$i<$methodCount;$i++)
                    {
                        for ($j=0;$j<$methodCount;$j++)
                        {
                            if ( $shippingArray[$i]['total_charge'] <= $shippingArray[$j]['total_charge'] )
                            {
                                $temp = $shippingArray[$i];
                                $shippingArray[$i] = $shippingArray[$j];
                                $shippingArray[$j] = $temp;
                            }
                        }
                    }
                    $logger->info("inn");
                    $res = $shippingArray[1];
                } else {
                    $logger->info("not inn");
                    $res = $shippingArray[0];
                }
                $methodCode = '';
                if (!empty($res)) {
                    $logger->info('res');
                    $logger->info($res);
                    $methodCode = preg_replace('/\s+-\s*|\s*-\s+/','_',$res['carrier_nm']."-(".$res['service_nm'].")");
                    // $methodTitle = $res['carrier_nm']."-(".$res['service_nm'].")";
                    $methodTitle = "Roadfast Express";

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

                    $method->setCarrier($this->_code);
                    $method->setCarrierTitle($this->getConfigData('title'));

                    $method->setMethod($this->_code);
                    $method->setMethodTitle($methodTitle);

                    $freightCost = $res['total_charge'];
                    $additionalCost = $this->getConfigData('extra_cost');
                    $extraCost = 0;
                    if ($additionalCost) {
                        $extraCost = (($freightCost * $additionalCost)/100);
                    }

                    // $extraCost = (($freightCost * 75)/100);
                    $finalCost = $freightCost + $extraCost;
                    if ( $finalCost < 30) {
                        $finalCost = 30;
                    }

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

                    $result->append($method);
                }
            }
        }

        return $result;
    }


    /**
     * Get result of request
     *
     * @return Result|null
     */
    public function getResult(){
        return $this->_result;
    }


    /**
    * Get Shipping origin data from store scope config
    * Displays data on storefront
    * @return array
    */


    protected function getShippingOrigin(){

        return [
            'country_id' => $this->_scopeConfig->getValue(
                \Magento\Sales\Model\Order\Shipment::XML_PATH_STORE_COUNTRY_ID,
                \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
                $this->getData('store')
            ),
            'region_id' => $this->_scopeConfig->getValue(
                \Magento\Sales\Model\Order\Shipment::XML_PATH_STORE_REGION_ID,
                \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
                $this->getData('store')
            ),
            'postcode' => $this->_scopeConfig->getValue(
                \Magento\Sales\Model\Order\Shipment::XML_PATH_STORE_ZIP,
                \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
                $this->getData('store')
            ),
            'city' => $this->_scopeConfig->getValue(
                \Magento\Sales\Model\Order\Shipment::XML_PATH_STORE_CITY,
                \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
                $this->getData('store')
            )
        ];
    }
}

Inside Config, we have one more subfolder and inside that, we have a php file.

productattributes.php
<?php

namespace Meetpxny\Iconsignit\Model\Config\Configuration;

class Productattributes implements \Magento\Framework\Data\OptionSourceInterface
{
    /**
     * @var \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory
     */
    private $attributes;

    /**
     * Exclude incompatible product attributes from the mapping.
     * @var array
     */
    private $excluded = [
        'quantity_and_stock_status',
        'name',
        'sku',
        'activity',
        'category_gear',
        'category_ids',
        'climate',
        'collar',
        'color',
        'cost',
        'country_of_manufacture',
        'custom_design',
        'custom_design_from',
        'custom_design_to',
        'custom_layout',
        'custom_layout_update',
        'description',
        'eco_collection',
        'erin_recommends',
        'features_bags',
        'format',
        'gallery',
        'gender',
        'gift_message_available',
        'image',
        'manufacturer',
        'material',
        'media_gallery',
        'meta_description',
        'meta_keyword',
        'meta_title',
        'msrp',
        'msrp_display_actual_price_type',
        'new',
        'news_from_date',
        'news_to_date',
        'options_container',
        'page_layout',
        'pattern',
        'performance_fabric',
        'price_type',
        'price_view',
        'sale',
        'shipment_type',
        'short_description',
        'sku_type',
        'sleeve',
        'small_image',
        'special_from_date',
        'special_price',
        'special_to_date',
        'status',
        'strap_bags',
        'style_bags',
        'style_bottom',
        'style_general',
        'swatch_image',
        'tax_class_id',
        'thumbnail',
        'tier_price',
        'ts_country_of_origin',
        'ts_hs_code',
        'ts_packaging_id',
        'ts_packaging_type',
        'url_key',
        'visibility',
        'weight_type',
        'price'
    ];

    /**
     * Productattributes constructor.
     *
     * @param \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory $collectionFactory
     */
    public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory $collectionFactory
    ) {
        $this->attributes = $collectionFactory;
    }

    /**
     * Get options.
     *
     * @return array
     */
    public function toOptionArray()
    {
        $attributes = $this->attributes
            ->create()
            ->addVisibleFilter();

        $attributeArray = [];
        $attributeArray[] = [
            'label' => __('---- Default Option ----'),
            'value' => '0',
        ];

        foreach ($attributes as $attribute) {
            $attributeCode = $attribute->getAttributeCode();

            if (!in_array($attributeCode, $this->excluded)) {
                $attributeArray[] = [
                    'label' => $attribute->getFrontendLabel(),
                    'value' => $attributeCode,
                ];
            }
        }
        return $attributeArray;
    }
}

9. Inside Observer, we have to files:

CheckoutOnepageControllerSuccessAction.php
<?php
/**
 * Copyright © 2017 Rejoiner. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Meetpxny\Iconsignit\Observer;

use Meetpxny\Iconsignit\Model\Carrier\Shipping;
use Magento\Framework\Event\ObserverInterface;
use Psr\Log\LoggerInterface;
class CheckoutOnepageControllerSuccessAction implements \Magento\Framework\Event\ObserverInterface
{
    const CONSIGMENT_API_URL = 'http://test9.iconsignit.com.au/api/CreateConsignment';

    protected $_code = 'iconsignitshipping';

    protected $_objectManager;
    protected $logger;
    protected $_curl;
    protected $iconsignitShipping;
    protected $_productFactory;
    protected $_trackFactory;

    /** @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone */
    private $timezone;

    /** @var \Magento\Sales\Model\OrderFactory $orderFactory */
    private $orderFactory;

    /**
     * CheckoutOnepageControllerSuccessAction constructor.
     * @param \Magento\Sales\Model\OrderFactory $orderFactory
     * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone
     */
    public function __construct(
        \Magento\Framework\ObjectManagerInterface $objectManager,
        \Magento\Sales\Model\OrderFactory $orderFactory,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Sales\Model\Order\Shipment\TrackFactory $trackFactory,
        \Meetpxny\Iconsignit\Model\Carrier\Shipping $iconsignitShipping,
        \Magento\Framework\HTTP\Client\Curl $curl,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone
    ) {
        $this->_objectManager = $objectManager;
        $this->orderFactory = $orderFactory;
        $this->_productFactory = $productFactory;
        $this->_trackFactory = $trackFactory;
        $this->iconsignitShipping = $iconsignitShipping;
        $this->_curl = $curl;
        $this->logger       = $logger;
        $this->timezone     = $timezone;
    }

    /**
     * @param \Magento\Framework\Event\Observer $observer
     * @return $this
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $attr_width = $this->iconsignitShipping->getConfigData('product_attributes_width');
        $attr_height = $this->iconsignitShipping->getConfigData('product_attributes_height');
        $attr_length = $this->iconsignitShipping->getConfigData('product_attributes_length');

        $lastOrderId = $observer->getEvent()->getData('order_ids');
        /** @var \Magento\Sales\Model\Order $order */

        $order = $this->orderFactory->create()->load($lastOrderId[0]);
        if (!$order->getId()) {
            return $this;
        }

        $shippingMethod = $order->getShippingMethod();
        $check_patterns = explode('_', $shippingMethod);
        if($check_patterns && isset($check_patterns[0]) && $check_patterns[0] === $this->_code) {
            $quote_patterns = explode('___', $shippingMethod);
            if($quote_patterns && isset($quote_patterns[1])) {
                $QuoteRateID = $quote_patterns[1];
                $post_data = [];
                $post_data['ApiUrl'] = $this->iconsignitShipping->getConfigData('api_url');
                $post_data['ApiToken'] = $this->iconsignitShipping->getConfigData('api_token');
                $post_data['QuoteRateID'] = $QuoteRateID;
                $post_data['DeliveryTown'] = $order->getShippingAddress()->getCity();
                $post_data['DeliveryPostcode'] = $order->getShippingAddress()->getPostcode();
                $post_data['DeliveryName'] = $order->getShippingAddress()->getFirstname() . ' ' . $order->getShippingAddress()->getLastname();
                $post_data['DeliveryAddressLine1'] = $order->getShippingAddress()->getStreetLine(1);
                $post_data['DeliveryPhoneNumber'] = $order->getShippingAddress()->getTelephone();
                $post_data['DeliveryContactName'] = $order->getShippingAddress()->getFirstname();
                $post_data['DeliveryEmail'] = $order->getShippingAddress()->getEmail();
                $post_data['DeliveryInstruction'] = NULL;

                $cnt = 0;
                foreach ($order->getAllItems() as $item) {
                    //$_product = $this->_productFactory->create()->load($item->getId());
                    $_product =  $item->getProduct();
                    if($_product) {
                        $post_data['Items'][$cnt]['item_code'] = $_product->getSku();
                    } else {
                        $post_data['Items'][$cnt]['item_code'] = $item->getId();
                    }
                    $post_data['Items'][$cnt]['item_desc'] = $item->getName();
                    $post_data['Items'][$cnt]['item_qty'] = intval($item->getQtyOrdered());

                    if (null !== $_product->getCustomAttribute($attr_length)) {
                        $post_data['Items'][$cnt]['item_length'] = $_product->getCustomAttribute($attr_length)->getValue();
                    } else {
                        $post_data['Items'][$cnt]['item_length'] = $_product->getAttributeText($attr_length);
                    }

                    if (null !== $_product->getCustomAttribute($attr_width)) {
                        $post_data['Items'][$cnt]['item_width'] = $_product->getCustomAttribute($attr_width)->getValue();
                    } else {
                        $post_data['Items'][$cnt]['item_width'] = $_product->getAttributeText($attr_width);
                    }

                    if (null !== $_product->getCustomAttribute($attr_height)) {
                        $post_data['Items'][$cnt]['item_height'] = $_product->getCustomAttribute($attr_height)->getValue();
                    } else {
                        $post_data['Items'][$cnt]['item_height'] = $_product->getAttributeText($attr_height);
                    }

                    //$post_data['Items'][$cnt]['item_length'] = '';
                    //$post_data['Items'][$cnt]['item_width']  = '';
                    //$post_data['Items'][$cnt]['item_height'] = '';
                    $post_data['Items'][$cnt]['item_weight'] = $_product->getWeight();
                    
                    $post_data['Items'][$cnt]['item_palletised'] = 0;
                    $cnt++;
                }

                //$this->_curl->post(self::CONSIGMENT_API_URL, $post_data);
                $consigment_api_url = $this->iconsignitShipping->getConfigData('shipping_api_url');
                $consigment_api_url = trim($consigment_api_url, '/') . '/api/CreateConsignment';
                $this->_curl->post($consigment_api_url, $post_data);

                $apiResponse = $this->_curl->getBody();
                $this->logger->critical('Quate1: '.print_r($post_data, true), array());
                $this->logger->critical('Quate2: '.print_r($apiResponse, true), array());
                $resp = json_decode($apiResponse, true);
                if (isset($resp['status'])) {
                    $data = array(
                        'carrier_code' => $this->_code,
                        'title' => 'Iconsignit Tracking Number',
                        'number' => $resp['result']['ConsignCode'], // Replace with your tracking number
                    );

                    $convertOrder = $this->_objectManager->create('Magento\Sales\Model\Convert\Order');
                    $shipment = $convertOrder->toShipment($order);

                    // Loop through order items
                    foreach ($order->getAllItems() AS $orderItem) {
                        // Check if order item has qty to ship or is virtual
                        if (! $orderItem->getQtyToShip() || $orderItem->getIsVirtual()) {
                            continue;
                        }

                        $qtyShipped = $orderItem->getQtyToShip();

                        // Create shipment item with qty
                        $shipmentItem = $convertOrder->itemToShipmentItem($orderItem)->setQty($qtyShipped);

                        // Add shipment item to shipment
                        $shipment->addItem($shipmentItem);
                    }

                    // Register shipment
                    $shipment->register();

                    //$shipment->getOrder()->setIsInProcess(true);

                    try {
                        // Save created shipment and order
                        $shipment->save();
                        $shipment->getOrder()->save();

                        // Send email
                        //$this->_objectManager->create('Magento\Shipping\Model\ShipmentNotifier')->notify($shipment);
                        $track = $this->_trackFactory->create()->addData($data);
                        $shipment->addTrack($track)->save();

                        $shipment->save();
                        $this->logger->critical('Shipment passed: '.$resp['result']['ConsignCode']);
                    } catch (\Exception $e) {
                        $this->logger->critical('Shipment error:'.$e->getMessage());
                    }
                }
            }
        }
        return $this;
    }
}
ShippingAmount.php
<?php
namespace Meetpxny\Iconsignit\Observer;

class ShippingAmount implements \Magento\Framework\Event\ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
       $quote = $observer->getEvent()->getQuote();
    }
}

10. composer.json file

composer.json
{
    "name": "meetpxny/magento-2-iconsignit-shipping",
    "description": "A Magento 2 module that is for iconsignit shipping method",
    "type": "magento2-module",
    "version": "1.0.0",
    "license": [
        "meetpxny"
    ],
    "require": {
          "php": "~5.6.0|7.0.2|7.0.4|~7.0.6|~7.1.0|~7.1.3|~7.2.0",
          "magento/module-backend": "100.0.*|100.1.*|100.2.*|101.0.*",
          "magento/framework": "100.0.*|100.1.*|101.0.*|102.0.*"
      },
    "autoload": {
      "files": [ "registration.php" ],
      "psr-4": {
        "Meetpxny\\Iconsignit\\": ""
      }
    }
}

11. Registration.php file

Registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Meetpxny_Iconsignit',
    __DIR__
);

After running the following command in the terminal we can see freight cost extension enabled on the Magento admin side as shown in the photo below:

  • php bin/magento setup: upgrade 
  • bin/magento setup:static-content:deploy –f 
  • sudo chmod 777 -R /var/www/html/thefencingstore/ 

To make Transfreight shipping enabled in frontend 

  1. At first, we need to log in to Magento admin using credentials. 
  1. And click on Stores, then sales -> Delivery methods and click on Iconsignit shipping method as shown below: 

3. We need to give yes on the enabled column. 

A new freight cost method will be enabled.

To disable old freight cost

Stores> configuration> sales> delivery methods> Freight Cost 
 
Enable it to No. 

Leave a comment

Your email address will not be published. Required fields are marked *