Magento 2已经有一些内置的运输方式。但在某些情况下,我们可能想在Magento 2中创建自己的运输方式。这不是一个困难的过程。我们可以非常轻松地在Magento 2中创建自定义运输方式。这篇博客可以帮助您在短时间内创建自己的自定义运输方式。
创建自定义运输方法的步骤:
- 创建一个新模块
- 创建配置文件
- 定义运输模型
- 创建运输模型
- 模块安装
创建一个新模块:
在下面的文件路径中创建一个“registration.php”文件来注册我们的新模块,
文件路径:<Magento_2_Root> /app/code/Alwayly/CustomShipping/registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Alwayly_CustomShipping',
__DIR__
);
接下来,在下面的文件路径中创建一个“module.xml”文件来定义模块,
文件路径:<Magento_2_Root> /app/code/Alwayly/CustomShipping/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="Alwayly_CustomShipping" setup_version="1.0.0">
</module>
</config>
创建配置文件:
在Magento 2中,每个运输方式都应该在管理面板中有配置选项。我们可以通过system.xml文件为我们的运输方式创建配置选项。
文件路径:<Magento_2_Root> /app/code/Alwayly/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="customshipping" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Custom Shipping Method</label>
<field id="active" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="0" canRestore="1">
<label>Enabled</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
<field id="price" translate="label" type="text" sortOrder="4" showInDefault="1" showInWebsite="1" showInStore="0">
<label>Shipping Cost</label>
<validate>validate-number validate-zero-or-greater</validate>
</field>
<field id="name" translate="label" type="text" sortOrder="3" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
<label>Method Name</label>
</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" canRestore="1">
<label>Title</label>
</field>
<field id="sallowspecific" translate="label" type="select" sortOrder="90" 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="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" canRestore="1">
<label>Displayed Error Message</label>
</field>
</group>
</section>
</system>
</config>
定义运输模型:
现在在下面的路径中创建一个“config.xml”文件,并为我们的自定义运输方式设置默认配置,
文件路径:<Magento_2_Root> /app/code/Alwayly/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>
<customshipping>
<active>0</active>
<sallowspecific>0</sallowspecific>
<price>0</price>
<model>Alwayly\CustomShipping\Model\Carrier\Customshipping</model>
<name>Custom Shipping</name>
<title>Custom Shipping</title>
<specificerrmsg>This shipping method is not available. To use this shipping method, please contact us.</specificerrmsg>
</customshipping>
</carriers>
</default>
</config>
这里,<default>是父节点,其子节点是<carriers>,<customshipping>是我们的运输方式代码。<model>是重要的一个,在这个<model>标签中,我们应该定义我们的运输模型类。
创建运输模型:
在“config.xml”上定义运输模型后,我们需要在下面的文件路径中创建运输模型类“Customshipping.php”,
文件路径:<Magento_2_Root> /app/code/Alwayly/CustomShipping/Model/Carrier/Customshipping.php
<?php
namespace Alwayly\CustomShipping\Model\Carrier;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\DataObject;
use Magento\Shipping\Model\Carrier\AbstractCarrier;
use Magento\Shipping\Model\Carrier\CarrierInterface;
use Magento\Shipping\Model\Config;
use Magento\Shipping\Model\Rate\ResultFactory;
use Magento\Store\Model\ScopeInterface;
use Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory;
use Magento\Quote\Model\Quote\Address\RateResult\Method;
use Magento\Quote\Model\Quote\Address\RateResult\MethodFactory;
use Magento\Quote\Model\Quote\Address\RateRequest;
use Psr\Log\LoggerInterface;
class Customshipping extends AbstractCarrier implements CarrierInterface
{
/**
* @var string
*/
protected $_code = 'customshipping';
/**
* @var bool
*/
protected $_isFixed = true;
/**
* @var ResultFactory
*/
protected $_rateResultFactory;
/**
* @var MethodFactory
*/
protected $_rateMethodFactory;
/**
* @param ScopeConfigInterface $scopeConfig
* @param ErrorFactory $rateErrorFactory
* @param LoggerInterface $logger
* @param ResultFactory $rateResultFactory
* @param MethodFactory $rateMethodFactory
* @param array $data
*/
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);
}
/**
* @return array
* @api
*/
public function getAllowedMethods()
{
return [$this->getCarrierCode() => __($this->getConfigData('name'))];
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
* @param RateRequest $request
* @return DataObject|bool|null
* @api
*/
public function collectRates(RateRequest $request)
{
/**
* Make sure that shipping method is enabled
*/
if (!$this->isActive()) {
return false;
}
/** @var \Magento\Shipping\Model\Rate\Result $result */
$result = $this->_rateResultFactory->create();
$shippingPrice = $this->getConfigData('price');
$method = $this->_rateMethodFactory->create();
/**
* Set carrier's method data
*/
$method->setCarrier($this->getCarrierCode());
$method->setCarrierTitle($this->getConfigData('title'));
/**
* Displayed as shipping method under Carrier
*/
$method->setMethod($this->getCarrierCode());
$method->setMethodTitle($this->getConfigData('name'));
$method->setPrice($shippingPrice);
$method->setCost($shippingPrice);
$result->append($method);
return $result;
}
}
注意:
- 在Magento 2中,每个运输类都应继承\Magento\Shipping\Model\Carrier\AbstractCarrier并实现\Magento\Shipping\Model\Carrier\CarrierInterface类。
- $ _code的值应与system.xml中的group id相同。
- 抽象类和接口需要两个函数getAllowedMethods和collectRates。
- 在函数collectRates中,我们必须为自定义运费计算实现所有逻辑。
模块安装:
最后,我们必须启用扩展并安装它。为此,转到[magento_root]/bin目录并在CLI中运行以下命令,
php magento module:enable Alwayly_CustomShipping
然后,在CLI中运行以下命令以安装模块,
php magento setup:upgrade
然后,使用以下CLI命令清除缓存,
php magento c:c
现在,登录到Magento 2管理面板,导航到STORES > Configuration,从左侧面板展开SALES部分,然后单击Shipping Methods。您可以看到我们的自定义运输方式配置页面如下,

在这里,您可以启用我们的自定义运输方式,并根据您的需要设置配置值。
完成配置我们的送货方式后,运输计算将显示在结帐页面上,如下所示,

最后,运输方式将应用于结账页面,结果将显示如下,

希望这可以帮助你。

