How To Create Custom Shipping Method In Magento 2

Hello Everyone,

In this blog, we will learn about how to Create Custom Shipping Methods in Magento 2.

Magento 2 provides default shipping methods like, Free Shipping, Flat Rate, Table Rate, UPS, USPS, FedEx, DHL.

Sometimes Magento default Shipping Methods are not enough then come up with to create new custom shipping methods.

Without wasting your time, let us guide you straight away. Follow the easy step given below to Create Custom Shipping Method in Magento 2.

STEPS FOR CREATE CUSTOM SHIPPING METHOD IN MAGENTO 2

Step 1: Create module.xml file

app/code/Vendor/Extension/etc/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="Vendor_Extension" setup_version="1.0.0">

    <sequence>

            <module name="Magento_Store"/>

            <module name="Magento_Sales"/>

            <module name="Magento_Quote"/>

            <module name="Magento_SalesRule"/>

        </sequence>

    </module>

</config>

We Just add dependencies of other modules under the <sequence> tag.

Step 2: Create registration.php file

app/code/Vendor/Extension/registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(

    \Magento\Framework\Component\ComponentRegistrar::MODULE,

    'Vendor_Extension',

    __DIR__

);

Step 3: Create system.xml file

app/code/Vendor/Extension/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="customshipping" translate="label" type="text" sortOrder="0" showInDefault="1" showInWebsite="1" showInStore="1">

                <label>Magecurious - 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>Method Name</label>

                </field>

                <field id="price" translate="label" type="text" sortOrder="5" showInDefault="1" showInWebsite="1" showInStore="0">

                    <label>Price</label>

                    <validate>validate-number validate-zero-or-greater</validate>

                </field>

                <field id="handling_type" translate="label" type="select" sortOrder="7" showInDefault="1" showInWebsite="1" showInStore="0">

                    <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="sallowspecific" translate="label" type="select" sortOrder="90" 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="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">

                    <label>Displayed Error Message</label>

                </field>

            </group>

        </section>

    </system>

</config>

Step 4: Create config.xml file

app/code/Vendor/Extension/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>

            <customshipping>

                <active>1</active>

                <sallowspecific>0</sallowspecific>

                <model>Vendor\Extension\Model\Carrier\CustomShipping</model>

                <name>Magecurious Custom Shipping Method</name>

                <price>10.00</price>

                <title>Magecurious Custom Shipping Method</title>

                <specificerrmsg>This shipping method is not available. To use this shipping method, please contact us.</specificerrmsg>

                <handling_type>F</handling_type>

            </customshipping>

        </carriers>

    </default>

</config>

Step 5: Create CustomShipping.php file

app/code/Vendor/Extension/Model/Carrier/CustomShipping.php

<?php

namespace Vendor\Extension\Model\Carrier;

use Magento\Quote\Model\Quote\Address\RateRequest;

use Magento\Shipping\Model\Rate\Result;

class CustomShipping extends \Magento\Shipping\Model\Carrier\AbstractCarrier implements

    \Magento\Shipping\Model\Carrier\CarrierInterface

{

    protected $_code = 'customshipping';

    protected $_rateResultFactory;

    protected $_rateMethodFactory;

    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);

    }

    public function getAllowedMethods()

    {

        return [$this->_code => $this->getConfigData('name')];

    }

    private function getShippingPrice()

    {

        $configPrice = $this->getConfigData('price');

        $shippingPrice = $this->getFinalPriceWithHandlingFee($configPrice);

        return $shippingPrice;

    }

    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($this->_code);

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

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

        $method->setMethodTitle($this->getConfigData('name'));

        $amount = $this->getShippingPrice();

        $method->setPrice($amount);

        $method->setCost($amount);

        $result->append($method);

        return $result;

    }

}

Step 6: Finally run the below commands

$ php bin/magento setup:upgrade

$ php bin/magento cache:clean

$ php bin/magento cache:flush

Step 7: Output:

Now open Magento Admin panel and go to stores->Configuration->Sales->Delivery Methods

Now go to frontend, add the product to cart and go to checkout.

Final Thoughts:

So this was the easiest way which we have told you in this blog. This is how you can Create a Custom Shipping Method in Magento 2. Hope you liked the blog.

So quickly go to the comment box and tell me how you like this blog?

Stay tuned with us on our site to get new updates of Magento.

Thanks for reading and visiting our site.                  

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

Leave a Reply

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