Skip to content

How to create Shipping Cost Calculator by select country in magento 2?

i created a shipping method, for example, the cost of delivery is $15, but if you deliver to the USA, then multiply the amount by 2

Model/Carrier/Custom.php

  <?php

  namespace CustomShippingMethodModelCarrier;

   use MagentoQuoteModelQuoteAddressRateRequest;
   use MagentoShippingModelRateResult;
   use MagentoShippingModelCarrierAbstractCarrier;
   use MagentoShippingModelCarrierCarrierInterface;
   use MagentoFrameworkAppConfigScopeConfigInterface;
   use MagentoQuoteModelQuoteAddressRateResultErrorFactory;
   use PsrLogLoggerInterface;
   use MagentoShippingModelRateResultFactory;
   use MagentoQuoteModelQuoteAddressRateResultMethodFactory;


 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 MagentoShippingModelRateResult $result */
    $result = $this->rateResultFactory->create();

    /** @var MagentoQuoteModelQuoteAddressRateResultMethod $method */
    $method = $this->rateMethodFactory->create();

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

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


    $amount = $this->getConfigData('price');
    $shippingPrice = $this->getFinalPriceWithHandlingFee($amount);
    $method->setPrice($shippingPrice);
    $method->setCost($amount);

    $result->append($method);

    return $result;
}

Example i have country rate {US: 4,UA: 5,}
price * country rate