Implementation of Shipping Methods in Magento® 2.0

August 12, 2016 Written By M-Connect Media

Talk to Experts Need expert help? Don’t hesitate to talk.

You can do direct email atinfo@mconnectmedia.com

WE'RE HERE FOR YOU

We would love to hear about your Magento project, challenge, or opportunity. We'll respond within 24 hours!

Magento 2 Shipping Method Implementation

The shipping methods can affect a customer’s decision to buy a certain product. However, it becomes really important that the online stores have various shipping methods to add to their convenience.

We have already seen the four default shipping methods in Magento® 2.0. Now let us show you how you can implement the custom module or new shipping method extensions in your Magento® 2.0 store.

To add a new shipping method in Magento® 2 please follow below steps:

First, create folder hierarchy,

app/code/<YOUR_PACKAGE_NAME>/<YOUR_MODULE_NAME>

e.g. app/code/Mconnect/Customflatrate

And then create registration.php in your module folder to register your module to Magento® 2.0

<?php

/**

* Copyright © 2015 Ihor Vansach (ihor@magefan.com). All rights reserved.

* See LICENSE.txt for license details (http://opensource.org/licenses/osl-3.0.php).

*

* Glory to Ukraine! Glory to the heroes!

*/

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

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

‘Mconnect_Customflatrate’,

__DIR__

);

Create composer.json in same folder. It will provide information about your module to the composer.

{

“name”: “mconnect/module-customflatrate”,

“description”: “N/A”,

“require”: {

“php”: “~5.5.0|~5.6.0|~7.0.0”,

“magento/module-store”: “100.0.0”,

“magento/module-catalog”: “100.0.0”,

“magento/module-email”: “100.0.0”,

“magento/module-ui”: “100.0.0”,

“magento/module-variable”: “100.0.0”,

“magento/module-media-storage”: “100.0.0”,

“magento/framework”: “100.0.0”

},

“type”: “magento2-module”,

“version”: “2.0.0”,

“license”: [

“OSL-3.0”,

“AFL-3.0”

],

“autoload”: {

“files”: [ “registration.php” ],

“psr-4”: {

“Mconnect\\Customflatrate\\”: “”

}

}

}

Create a folder named “etc” in your module root folder

  • Create a file module.xml which will store your module version info

<?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=”Mconnect_Customflatrate” setup_version=”2.0.0″>

<sequence>

<module name=”Magento_Catalog”/>

<module name=”Magento_OfflineShipping”/>

</sequence>

</module>

</config>

  • In “etc” folder create config.xml file as below

<?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>

<mconnectcustomflatrate>

<active>1</active>

<model>Mconnect\Customflatrate\Model\Carrier\Customflatrate</model>

<name>Flat Rate</name>

<title>Mconnect</title>

<shipping_default_value_enable>0</shipping_default_value_enable>

<show_method>0</show_method>

<allow_free_shipping>0</allow_free_shipping>

<sallowspecific>0</sallowspecific>

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

<sort_order>10</sort_order>

</mconnectcustomflatrate>

</carriers>

</default>

</config>

  • For admin configuration please create folder “adminhtml” in “etc” folder and create system.xml file for admin configuration options

It will contain below 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=”mconnectcustomflatrate” translate=”label” type=”text” sortOrder=”2″ showInDefault=”1″ showInWebsite=”1″ showInStore=”1″>

<label>Mconnect Flat Rate</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=”shipping_default_value_enable” translate=”label” type=”select” sortOrder=”6″ showInDefault=”1″ showInWebsite=”1″ showInStore=”0″>

<label>Shipping Rate</label>

<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>

<comment>If set to “Yes”, the default rate will be used for products which do not have shipping rate assigned. If set to “No”, 0 will be used for all products which do not have shipping rate.</comment>

</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=”show_method” 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>

</field>

<field id=”specificerrmsg” translate=”label” type=”textarea” sortOrder=”93″ showInDefault=”1″ showInWebsite=”1″ showInStore=”1″>

<label>Displayed Error Message</label>

<depends>

<field id=”show_method”>1</field>

</depends>

</field>

<field id=”sort_order” translate=”label” type=”text” sortOrder=”100″ showInDefault=”1″ showInWebsite=”1″ showInStore=”0″>

<label>Sort Order</label>

</field>

</group>

</section>

</system>

</config>

Create a folder named “Model/ Carrier” in your module root folder

Create one class file in above folder Customflatrate.php, this class will extend \Magento\Shipping\Model\Carrier\AbstractCarrier class and implements \Magento\Shipping\Model\Carrier\CarrierInterface interface

We are going to override collectRates method and have our login inside it.

So,  Customflatrate.php will have below code.

<?php

namespace Mconnect\Customflatrate\Model\Carrier;

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

use Magento\Shipping\Model\Rate\Result;

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

\Magento\Shipping\Model\Carrier\CarrierInterface

{

protected $_code = ‘mconnectcustomflatrate’;

protected $_isFixed = true;

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 collectRates(RateRequest $request)

{

if (!$this->getConfigFlag(‘active’)) {

return false;

}

$items = $request->getAllItems();

$perOrderRate = array();

$shippingPrice = $this->getConfigData(‘default_shipping_cost’);

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

$grandTotal = $request->getBaseSubtotalInclTax();

$free_shipping_over_total = $this->getConfigData(‘free_shipping_over_total’);`

if ($shippingPrice !== false) {

$method = $this->_rateMethodFactory->create();

$method->setCarrier(“mconnectcustomflatrate”);

$method->setCarrierTitle($this->getConfigData(‘title’));

$method->setMethod(“mconnectflatrate”);

$method->setMethodTitle($this->getConfigData(‘name’));

$method->setPrice($shippingPrice);

$method->setCost($shippingPrice);

$result->append($method);

}

return $result;

}

public function getAllowedMethods()

{

return [“mconnectflatrate” => $this->getConfigData(‘name’)];

}

}

It’s all done. That was all about the the implementation of shipping methods in Magento 2. Have you liked it ? Tell us your reviews via comments. If you need any help while adding new shipping method in your store, feel free to contact our Magento® 2 Developers. We will be happy to help you out! Happy Coding.

Need Magento expert help?

We provide result-driven solutions to expand the competency level and productivity.

Instant Help CenterAvailable!

Monday to FridayResponse promised within 24 hours!

Call Us

+1 319 804-8627

Search Autocomplete Magento 2 Extension

2 comments

  1. This blog post has shared the steps or various coding things which I can apply for creating a new customized shipping method for my Magento 2 Based Store. Great work guys!

Load Comments

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

5 4 3 2 1

  • Worried for deadlines? Our Magento Experts are effortlessly Working from Home.
  • Check out our Magento Developer Hiring Packages for Agency as well as individuals.
View Packages

Talk to Experts Need expert help? Don’t hesitate to talk.

You can do direct email atinfo@mconnectmedia.com

WE'RE HERE FOR YOU

We would love to hear about your Magento project, challenge, or opportunity. We'll respond within 24 hours!

Please fill this form, Mr.Yogesh will reply by email asap.


Please fill this form, Mr.Darshit will reply by email asap.


Please fill this form, Mr.Jayesh will reply by email asap.


Please fill this form, Mr.Jiten will reply by email asap.