Try Our Programmatic Shipping Method In Magento 2
E-commerce is all about customer convenience. Offering a convenient shipping method is an inevitable part of customer experience in an online store. By default, there are 7 Magento 2 shipping methods:
- Free Shipping
- Flat Rates
- Table Rates
- UPS
- USPS
- FedEx
- DHL
You can also learn how to configure Magento 2 shipping methods easily.
However, as E-commerce popularity increases, more and more types of businesses opt for an online shopping platform, particularly Magento, owing to its features and performance. But, these default shipping methods are not enough for all the types of businesses these days.
So, I’ve come up with a programmatic method to create shipping method in Magento 2 store.
A custom shipping method implemented keeping in mind the business requirement is a feasible option. A shipping strategy must be such that it does not end in the cost of order fulfillment more than the profit from that order.
An ideal shipping method must be manageable, quick, as well as affordable. It is not necessary that every store owner can find such a shipping method from the default Magento 2 shipping methods for his/her business.
Programmatically creating a custom shipping method in Magento 2 store that suits your business requirements and is feasible is the most optimized solution for having the correct shipping system. Also if you want to enhance the user experience by providing real time cost calculation, transparency and essential shipping information then update checkout summary on selecting shipping method in Magento 2.
Why am I stressing so much about having an optimized shipping strategy?
The below statistics explains why:
- 61% shoppers report leaving a transaction due to an extra cost such as shipping fees – 99firms
- 79% of US consumers said that free shipping would make them more likely to shop online. – Walkersands
- 46.5% of small to mid-sized businesses say that offering free shipping increases their profits. – MCM
Steps to Create Shipping Method In Magento 2:
- Create registration.php file at app/code/Meetanshi/CustomShipping/registration.php and add below code to this file:
123456<?php\Magento\Framework\Component\ComponentRegistrar::register(\Magento\Framework\Component\ComponentRegistrar::MODULE,'Meetanshi_CustomShipping',__DIR__); - Create module.xml file at app/code/Meetanshi/CustomShipping/etc/module.xml and add below code to this file:
12345<?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="Meetanshi_CustomShipping" setup_version="1.0.0"></module></config> - Create system.xml file at app/code/Meetanshi/CustomShipping/etc/adminhtml/system.xml and add below code to this file:
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152<?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="custom" translate="label" type="text" sortOrder="0" showInDefault="1" showInWebsite="1" showInStore="1"><label>Custom Shipping</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="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="title" translate="label" type="text" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1"><label>Title</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></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> - Create config.xml file at app/code/Meetanshi/CustomShipping/etc/config.xml and add below code to this file:
12345678910111213141516171819<?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><custom><active>1</active><sallowspecific>0</sallowspecific><model>Meetanshi\CustomShipping\Model\Carrier\Custom</model><name>Custom Shipping</name><handling_type>F</handling_type><price>15.00</price><title>Custom Method</title><type>I</type><specificerrmsg>This shipping method is not available right now.</specificerrmsg></custom></carriers></default></config> - Create Custom.php file at app/code/Meetanshi/CustomShipping/Model/Carrier/Custom.php and add below code to this file:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071<?phpnamespace Meetanshi\CustomShipping\Model\Carrier;use Magento\Quote\Model\Quote\Address\RateRequest;use Magento\Shipping\Model\Rate\Result;use Magento\Shipping\Model\Carrier\AbstractCarrier;use Magento\Shipping\Model\Carrier\CarrierInterface;use Magento\Framework\App\Config\ScopeConfigInterface;use Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory;use Psr\Log\LoggerInterface;use Magento\Shipping\Model\Rate\ResultFactory;use Magento\Quote\Model\Quote\Address\RateResult\MethodFactory;class Custom extends AbstractCarrier implements CarrierInterface{protected $_code = 'custom';protected $rateResultFactory;protected $rateMethodFactory;public function __construct(ScopeConfigInterface $scopeConfig,ErrorFactory $rateErrorFactory,LoggerInterface $logger,ResultFactory $rateResultFactory,MethodFactory $rateMethodFactory,array $data = []){$this->rateResultFactory = $rateResultFactory;$this->rateMethodFactory = $rateMethodFactory;parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data);}public function getAllowedMethods(){return ['custom' => $this->getConfigData('name')];}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('custom');$method->setCarrierTitle($this->getConfigData('title'));$method->setMethod('custom');$method->setMethodTitle($this->getConfigData('name'));/*you can fetch shipping price from different sources over some APIs, we used price from config.xml - xml node price*/$amount = $this->getConfigData('price');$shippingPrice = $this->getFinalPriceWithHandlingFee($amount);$method->setPrice($shippingPrice);$method->setCost($amount);$result->append($method);return $result;}}
That’s all to create a custom shipping method in Magento 2. Once you have created Magento 2 custom shipping method, it’s configuration is shown in the backend:
Once the custom shipping method is configured and enabled, it’s shown in the frontend:
Showing multiple shipping methods to customers, learn auto select shipping method in Magento 2 and offer a convenient experience to the customers. You may directly use the Magento 2 Shipping Table Rates extension instead of implementing the above solution yourself.
Have a look at the range of Magento 2 Shipping Extensions to enhance the shipping system of your Magento 2 store!
Any doubts about the shipping methods or the steps can be mentioned in the Comments section below.
I’ll be happy to help you out.
Please share the post with the Magento community via social media.
Thank you.
Calculate shipping rates in your Magento 2 store based on various conditions & attributes such as destination, weight, etc.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
DIY: Create Payment Method in Magento 2 Using Our Guide
How To Get Payment Method Title Of Order In Magento 2
Next