Chapters Close

How to create a shipping method in Magento 2?

This piece of information will throw some light on how one can create a shipping method in Magento 2.

For this, we need to create a custom module in order to add a new shipping method.

Step 1

Create a file named config.xml at app/code/Aureatelabs/Customshipping/etc/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>
			<alcustomshipping>
				<active>1</active>
				<allowed_methods>delivery</allowed_methods>
				<methods>delivery</methods>
				<sallowspecific>0</sallowspecific>
				<model>Aureatelabs\Customshipping\Model\Carrier</model>
				<name>Aureatelabs custom Shipping</name>
				<title>Aureatelabs custom Shipping</title>
				<handling_type>F</handling_type>
			</alcustomshipping>
		</carriers>
	</default>
</config>

This file is used for defining the shipping method code, which should be unique for each method.

Next, we need to define our model, which is already defined in config.xml under the <model> tag. Model is used for calculating our shipping cost.

app/code/Aureatelabs/Customshipping/Model/Carrier.php

<?php
namespace Aureatelabs\Customshipping\Model;

use Magento\Quote\Model\Quote\Address\RateResult\Error;
use Magento\Quote\Model\Quote\Address\RateRequest;
use Magento\Shipping\Model\Carrier\AbstractCarrierOnline;
use Magento\Shipping\Model\Carrier\CarrierInterface;
use Magento\Shipping\Model\Rate\Result;
use Magento\Shipping\Model\Simplexml\Element;
use Magento\Ups\Helper\Config;
use Magento\Framework\Xml\Security;

class Carrier extends AbstractCarrierOnline implements CarrierInterface
{
    const CODE = 'alcustomshipping';
    protected $_code = self::CODE;
    protected $_request;
    protected $_result;
    protected $_baseCurrencyRate;
    protected $_xmlAccessRequest;
    protected $_localeFormat;
    protected $_logger;
    protected $configHelper;
    protected $_errors = [];
    protected $_isFixed = true;

    public function __construct(\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory, \Psr\Log\LoggerInterface $logger, Security $xmlSecurity, \Magento\Shipping\Model\Simplexml\ElementFactory $xmlElFactory, \Magento\Shipping\Model\Rate\ResultFactory $rateFactory, \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory, \Magento\Shipping\Model\Tracking\ResultFactory $trackFactory, \Magento\Shipping\Model\Tracking\Result\ErrorFactory $trackErrorFactory, \Magento\Shipping\Model\Tracking\Result\StatusFactory $trackStatusFactory, \Magento\Directory\Model\RegionFactory $regionFactory, \Magento\Directory\Model\CountryFactory $countryFactory, \Magento\Directory\Model\CurrencyFactory $currencyFactory, \Magento\Directory\Helper\Data $directoryData, \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry, \Magento\Framework\Locale\FormatInterface $localeFormat, Config $configHelper, array $data = [])
    {
        $this->_localeFormat = $localeFormat;
        $this->configHelper = $configHelper;
        parent::__construct($scopeConfig, $rateErrorFactory, $logger, $xmlSecurity, $xmlElFactory, $rateFactory, $rateMethodFactory, $trackFactory, $trackErrorFactory, $trackStatusFactory, $regionFactory, $countryFactory, $currencyFactory, $directoryData, $stockRegistry, $data);
    }
    protected function _doShipmentRequest(\Magento\Framework\DataObject $request)
    {
        // Do shipment request to carrier web service, obtain Print Shipping Labels and process errors in response
        
    }

    public function getAllowedMethods()
    {
        //Return shipping method unique code and its values from here.
        return [$this->_code => $this->getConfigData('name') ];
    }

    public function collectRates(RateRequest $request)
    {
        $result = $this
            ->_rateFactory
            ->create();

        /*store shipping in session*/
        $method = $this
            ->_rateMethodFactory
            ->create();
        $method->setCarrier($this->_code);
        $method->setCarrierTitle('Aureatelabs custom Shipping');
        /* Use method name */
        $method->setMethod($this->_code);
        $method->setMethodTitle('Aureatelabs Custom Shipping');
        $method->setCost(10);
        $method->setPrice(10);
        $result->append($method);
        return $result;
    }

    public function proccessAdditionalValidation(\Magento\Framework\DataObject $request)
    {
        return true;
    }
}

After this you can see that the shipping method will get displayed at the frontend.

In order to define custom setting for shipping method, we need to create system.xml , which is located at the path given below:

app/code/Aureatelabs/Customshipping/etc/adminhtml/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="alcustomshipping" translate="label" type="text" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1">
				<label>Aureatelabs Custom Shipping Method</label>
				<field id="active" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="0">
					<label>Enabled</label>
					<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
				</field>
				<field id="title" translate="label" type="text" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1">
					<label>Title</label>
				</field>
				<field id="name" translate="label" type="text" sortOrder="3" showInDefault="1" showInWebsite="1" showInStore="1">
					<label>Name</label>
				</field>
				<field id="sallowspecific" translate="label" type="select" sortOrder="7" showInDefault="1" showInWebsite="1" showInStore="0">
					<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="7" 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>
			</group>
		</section>
	</system>
</config>

Now please visit to Stores > Settings > Configuration > Sales > Shipping Methods.

I hope you found this article valuable. Please leave any comments below and contact us for support in customizing your Magento store

Speak your Mind

Post a Comment

Got a question? Have a feedback? Please feel free to leave your ideas, opinions, and questions in the comments section of our post! ❤️

* This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Grow your online business like 3,895 subscribers

    * This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
    envelope

    Thank You!

    We are reviewing your submission, and will be in touch shortly.