Chat with us, powered by LiveChat

This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

An In-Depth Guide On Magento Shipping Methods and Custom Modules

October 31, 2019

10 Min Read
Magento-Shipment
Reading Time: 10 minutes

As an ecommerce store owner, you would want to control every aspect of the store. Things such as how your store looks, how it will attract customers, and how can you generate more sales through it, all play a vital role in your ecommerce strategy.

This includes representing your products through pictures, attractive descriptions, and optimized keywords. When you’re done, you wait for visitors. But is that all? Is it everything you would need to do on an ecommerce store for its growth? Wrong. You are leaving a major part of the ecommerce process and that is logistics. So, we decided to remind you of how Magento logistics work by focusing on various Magento shipping methods and modules. Let’s learn how to configure Magento shipping methods to improve your store sales.

Why Magento Shipping Is So Important?

Once you ship customer orders, what happens next is out of your control. That’s why choose your preferred shipping method plays an important role in order fulfillment success.

If you select the wrong method of Magento shipping, you and your customers will face many problems. 

Another thing is the type of web hosting you choose for your ecommerce store. So, get the best Magento Hosting for your ecommerce store and add a shipping method that works like a charm.

Magento 2 already has many built-in shipping methods, so let’s learn how to configure them. We will also discuss how to create a custom Magento shipping extension so that you can set one up even if the built-in module stops working.

Configuration of Magento 2 Shipping Methods

Launch the admin panel of your Magento 2 store and then navigate to STORES → Configuration:

stores- config magento 2 shipping

And then go to Shipping Methods listed under SALES tab:

sales-shipping methods magento 2 shipping

 

You will see list of Magento 2 Shipping Methods:

magento 2 shipping methods

 

Let’s discuss each Magento Shipping methods in detail:

  1. Flat Rate

Flat rate offers a fixed shipping charge for customers. Most store owners set up this Magento 2 shipping method for their ecommerce stores.

To learn how to set a flat rate module, unfold the Flat Rate section:

flat rate magento 2 shipping

flat rate magento 2 shipping 1

 

Now apply the following changes:

  • Set the value of Enabled to “Yes” to enable the Flat Rate
  • Add Title as “Flat Rate.”
  • Enter the name of the method in Method Name
  • Depending on your requirement set value for Type Per Order or Per Item
  • Next is Price. Add that fee to charge your customers for shipping services
  • In Calculate Handling Fee, calculate the shipping cost which can be a fixed amount, or it can be percent amount
  • In case of any error, type the error message in Displayed Error Message.
  • The Ship to Applicable Countries option depends on developing the plan of your store, that means you can set it to All Allow Countries or Specific Countries
  • Click the Save Config from the top of the page.
  1. Free Shipping

The first Magento 2 shipping method is the most fulfilling method over the other three because it contains promotion. To attract your customers, you set the standard condition for the customer. For example, if I want to give my customers free shipping, I must set some conditions. Supposing that free shipping is for those customers who generate an invoice of more than $200, so due to this condition my customers will shop up to $200. So this is a smart and efficient way to increase sales.

To configure, unfold the Free Shipping section:

free shipping magento 2

free shipping magento 2 (1)

 

Fill in all the required information:

  • To activate the Free Shipping option just set Enabled to “Yes.”
  • Now you need to add Title box.
  • Next, enter Method Name
  • To get free shipping put Minimum Order amount
  • Put Displayed Error Message
  • The Ship to Applicable Countries develops a plan for your store. It means you can set it to All Allow Countries or Specific Countries.
  • Based on your decision, you have to configure a value of the Show Method if Not Applicable to “Yes” or “No”.
  • In the last option Sort Order, set when you want to position the free shipping method in Magento 2
  • Last but not the least hit Save Config.

Now you have to configure the carrier. Unfold the carrier service that you will like to use. In my case, I am configuring UPS section:

ups magento 2 shipping

  • In the Free Method field, select the option that you will use to ship the products. I am selecting Ground
  • The Enable Free Shipping Amount Threshold option will allow you to restrict Free Shipping service for orders above a minimum amount.
  • The Free Shipping Amount Threshold option allows you to set a specific amount for your customer to unlock free shipping. You can set any amount like $100, $200, etc.
  • Again press Save Config to complete the setup for this method.
  1. Table Rate Shipping

This Magento 2 shipping method itself calculates the shipping charges according to the weight or destination or price of the product that the customer has bought.

In order to configure, unfold Table Rate section:

table rates magento 2

table rates magento 2 (1)

  • Set the value of Enable to “Yes.”
  • Add Title. We have written it as “Best Way.”
  • Enter the name of the method in Method Name field that displays on the checkout page
  • The next and most crucial step is to choose a formula that will calculate the shipping fee. Magento provides you three different methods. (Weight VS Destination, Price VS Destination, No. of Items VS Destination)
  • Now, if your store has virtual products, set the value of Include Virtual Products in Price Calculate
  • In Calculate Handling Fee, you can keep the shipping fee either as a fixed amount, or a percent amount
  • Enter an error message in the Displayed Error Message box that will appear in case of any error type.
  • Ship to Applicable Countries, this option depends on the developing plan of your store, which means you can set it to All Allow Countries or Specific Countries.
  • In the last option Sort Order, set where you want to position this Magento 2 shipping method.
  • Last but not the least hit Save Config

Now you have to build table rate data:

To apply these changes first, you have to choose the Store view in the admin view of Magento 2.

Once done, then you will see these two new options under your table rate section:

table rate new option magento 2 shipping

Here is how to export or import table rate file:

  • To download the file, click on Export CSV
  • Update the file according to your needs and requirements
  • Then to import the file, click on Choose File (Make sure you’re still selecting the Store View where you want to apply your table rates.)
  • Once uploading is done, hit the Save Config button.

To ensure the rates calculated accurately go through the payment process using a different address. This process will assure you that you have calculated the shipping and handling rate correctly using the above steps.

  1. Magento Shipping

‘Magento Shipping’ method is a multi-carrier shipping and fulfillment solution loaded with AI. It gives access to global carrier networks with seamless integration directly controlled from the Magento Admin panel.

These are benefits that you can avail with Magento Shipping:

  • It helps to escalate the revenue and business efficiency.
  • Capable enough to manage multiple carriers from a single concatenated portal.
  • Auto-check the errors at the time of extension setup to avoid ambiguities during development and testing procedures.
  • Ease the maintenance process by automatically embedding new characteristics without any update.

Note: In order to use Magento Shipping, you must have the Magento account as well as the Magento Shipping account. The access to your Magento Shipping portal is always based on your Magento account ID.

  1. Dimensional Weight

Another shipping method in Magento 2 is Dimensional Weight. This shipping method calculates the shipping charges of any product based on its volume. Many shipping companies use dimensional weight to enhance the delivery process.

Magento 2 supports the following carriers for Dimensional Weight Shipping Method:

  • United Parcel Service (UPS): An American multinational package delivery and supply chain management company that allows deliveries to more than 220 countries by land and air.
  • United States Postal Service (USPS): An independent United States Federal Government entity responsible for providing postal service within the United States.
  • FedEx: FedEx is a multinational courier company that offers both domestic and international shipping service to approximately 200 countries around the globe.
  • DHL: DHL is a division of the German logistics Deutsche Post, providing the international courier and express mail services. It is considered one of the world’s largest logistics service.

All these four courier companies share primary Magento 2 shipping method configurations. Keep in mind that you will require to signup and open a shipping account to integrate and offer these shipping methods to your customers.

That’s it. You have successfully configured Magento 2 Shipping methods. Now let’s learn how you can create your own custom Magento shipping module.

Create Custom Magento 2 Shipping Extension

To create Magento 2 shipping extension, create a custom module. You should not edit the core files as that isn’t the right practice. If you are not familiar with it, check out this guide on Create Module in Magento 2.

  1. First of all, create a configuration and registration file of the Magento 2 shipping module.
  2. Create module.xml in Magento2Root/app/code/Cloudways/CustomShipping/etc and paste the following code:
<?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="Cloudways_CustomShipping" >
        <sequence>
            <module name="Magento_Store"/>
            <module name="Magento_Sales"/>
            <module name="Magento_Quote"/>
            <module name="Magento_SalesRule"/>
        </sequence>
    </module>
</config>

  1. Create a registration.php in app/code/Cloudways/CustomShipping with the following code:
<?php

use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(
    ComponentRegistrar::MODULE,
    'Cloudways_CustomShipping',
    __DIR__
);
  1. Now, create a class which will handle the Magento Shipping Method. Keep in mind that the shipping method should be defined in Cloudways/CustomShipping/etc/config.xmlfile. Without this file, the method in Magento 2 shipping module won’t work.

In the config.xml file, the parent node is <default>, and its child node is <carriers> which further defines the property with the same name as the $_code in shipping class. It also has a <model> node that defines the shipping class Cloudways\Shippingmodule\Model\Carrier\CustomShipping

Create a config.xml file in app/code/Cloudways/CustomShipping/etc and add the following code:

<?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>0</active>
                <title>Shipping Title</title>
                <name>Shipping Name</name>
                <shipping_cost>10</shipping_cost>
                <sallowspecific>0</sallowspecific>
                <sort_order>15</sort_order>
                <model>Cloudways\CustomShipping\Model\Carrier\Customshipping</model>
            </customshipping>
        </carriers>
    </default>
</config>

Every shipping method should have configuration options in the admin panel. Let’s add shipping method options through the system.xml file that can be created in Cloudways\CustomShipping\etc\adminhtml directory with the following code:

<?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="900" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Cloudways Custom Shipping Module</label>
                <field id="active" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="0" canRestore="1">
                    <label>Enabled</label>
                    <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                </field>
                <field id="title" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="0">
                    <label>Title</label>
                </field>
                <field id="name" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="0">
                    <label>Method Name</label>
                </field>
                <field id="shipping_cost" translate="label" type="text" sortOrder="40" showInDefault="1" showInWebsite="1" showInStore="0" >
                    <label>Shipping Cost</label>
                    <validate>validate-number validate-zero-or-greater</validate>
                </field>
                <field id="sallowspecific" translate="label" type="select" sortOrder="60" 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="70" 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="80" 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="sort_order" translate="label" type="text" sortOrder="90" showInDefault="1" showInWebsite="1" showInStore="0">
                    <label>Sort Order</label>
                </field>
            </group>
        </section>
    </system>
</config>

Last but not the least, you have to create a Shipping Class as defined in the <model> node in the config.xml file. Create Customshipping.php file in Cloudways\CustomShipping\Model\Carrier directory and add the following code to it:

<?php

namespace Cloudways\CustomShipping\Model\Carrier;

use Magento\Quote\Model\Quote\Address\RateRequest;
use Magento\Shipping\Model\Carrier\AbstractCarrier;
use Magento\Shipping\Model\Carrier\CarrierInterface;

/**

 * Custom shipping model

 */

class Customshipping extends AbstractCarrier implements CarrierInterface
{
    /**

     * @var string

     */

    protected $_code = 'customshipping';

    /**

     * @var bool

     */

    protected $_isFixed = true;

    /**

     * @var \Magento\Shipping\Model\Rate\ResultFactory

     */

    private $rateResultFactory;

    /**

     * @var \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory

     */
    private $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 = []
    ) {

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

        $this->rateResultFactory = $rateResultFactory;
        $this->rateMethodFactory = $rateMethodFactory;

    }

    /**

     * Custom Shipping Rates Collector

     *

     * @param RateRequest $request

     * @return \Magento\Shipping\Model\Rate\Result|bool

     */

    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'));
        $shippingCost = (float)$this->getConfigData('shipping_cost');
        $method->setPrice($shippingCost);
        $method->setCost($shippingCost);
        $result->append($method);
        return $result;
    }

    /**

     * @return array

     */

    public function getAllowedMethods()
    {
        return [$this->_code => $this->getConfigData('name')];
    }
}

In this class, you can see I have added some Magento 2 rules. Every class in Magento 2 shipping extension extends \Magento\Shipping\Model\Carrier\AbstractCarrier and implements the \Magento\Shipping\Model\Carrier\CarrierInterface class. I have also defined a variable $_code with its value. This value is related to the config.xml file node structure.

Moreover, I have created two functions getAllowedMethods and collectRates. These methods are required by the abstract class and interface.

The function collectRates has a parameter $request which is the instance of RateRequest class. This Magento\Quote\Model\Quote\Address\RateRequest class contains all the information about the items in the cart: quote, weight, shipping/billing address, etc. In this method, I have implemented all logic for shipping calculation.

That’s it, you’re all done. Now, to enable this Magento 2 shipping extension, connect your Magento hosting server via SSH and run the following CLI command in the root directory of your Magento 2 store:

rm -rf var/page_cache/*
rm -rf var/cache/*
rm -rf generated/*
rm -rf var/log/*
rm -rf var/report/*
rm -rf var/view_preprocessed/*
rm -rf pub/static/*
php bin/magento setup:upgrade
php bin/magento setup:db-schema:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy -f
php bin/magento cache:clean
php bin/magento cache:flush
php bin/magento indexer:reindex

Here is the result!

Log in to your Magento 2 Admin panel, navigate to STORES > Configuration, expand the SALES section from the left panel and click Shipping Methods. Here, you’ll see that the new Magento shipping method successfully added to your store.

Enable it and set the values according to your needs:

If you have implemented everything as it is, your store’s checkout page will have a custom Magento 2 shipping method:

 

magento shipping method list

Click Next, and you will see that your custom Magento shipping method applied to the order summary:

result magento custom shipping module

 

The above result indicates that you have successfully created your own custom Magento Shipping extension.

Bottom-line

I have discussed Magento to shipping methods and custom modules in-depth as promised. The tutorial includes configuration, setup, and development of Magento shipping methods and modules. After following this guide, I believe you will have gained vast knowledge about Magento shipping.

If you have any questions or need help, I’d be happy to assist you. Feel free to get in touch by commenting in the box below.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Boost Your Magento Store Performance by 5x Times & Maximize Your Sales

Our fastest Magento hosting can help you in growing your business revenue by 500%

Syed Muneeb Ul Hasan

Syed Muneeb Ul Hasan is a Magento Community Manager at Cloudways - A Managed Magento Hosting Platform. He is an expert in PHP and Magento and prefers to educate users in the implementation of Magento. When not working, he loves to play games and watch cricket.

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

BFCM 2019