1

I'm currently working on a custom shipping method for Magento 2 and I'm facing a problem : I don't know how to retrieve the shipping address.

I tried first with something like this in the collectRates method :

$city = $request->getDestCity();
$street = $request->getDestStreet();

But it didn't worked ($city and $street are empty).

That's strange because I don't have any issue whit the getDestPostcode() method.

Is there a another way to retrieve the shipping address ?

Thanks.

2
  • I think it might be a bug.
    – cdauphin
    Feb 29, 2016 at 9:46
  • facing same issue need shipping address in collectRates Apr 7, 2016 at 7:26

2 Answers 2

0

This is a bug, see the following link on github: issue 3789

Basically the additional address fields need to be added to the payload within:

module-checkout/view/frontend/web/model/js/shipping-rate-processor/new-address.js

Also, you'll need to create another serviceUrl that will call a function that will hold the full address payload and adds the full address to the request.

0

please try this code :

<?php

namespace namespace\modulename\Model\Carrier;

use Magento\Quote\Model\Quote\Address\RateResult\Error;
use Magento\Quote\Model\Quote\Address\RateRequest;
use Magento\Shipping\Model\Carrier\AbstractCarrierOnline;
use Magento\Shipping\Model\Carrier\CarrierInterface;
use Magento\Shipping\Model\Rate\Result;
use Magento\Shipping\Model\Simplexml\Element;
use Magento\Framework\Xml\Security;

class Demo extends AbstractCarrierOnline implements CarrierInterface
{
    protected $_request;
    protected $_result;
    protected $_localeFormat;
    protected $_code;
    protected $_logger;

    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory,
        \Psr\Log\LoggerInterface $logger,
        Security $xmlSecurity,
        \Magento\Shipping\Model\Simplexml\ElementFactory $xmlElFactory,
        \Magento\Shipping\Model\Rate\ResultFactory $rateFactory,
        \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory,
        \Magento\Shipping\Model\Tracking\ResultFactory $trackFactory,
        \Magento\Shipping\Model\Tracking\Result\ErrorFactory $trackErrorFactory,
        \Magento\Shipping\Model\Tracking\Result\StatusFactory $trackStatusFactory,
        \Magento\Directory\Model\RegionFactory $regionFactory,
        \Magento\Directory\Model\CountryFactory $countryFactory,
        \Magento\Directory\Model\CurrencyFactory $currencyFactory,
        \Magento\Directory\Helper\Data $directoryData,
        \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry,
        \Magento\Framework\Locale\FormatInterface $localeFormat,
        \Demo\Shipping\Model\Api\DemoAPI $DemoApi,
        array $data = []
    ) {
        $this->_localeFormat = $localeFormat;
        $this->_DemoApi = $DemoApi;
        $this->_code = 'Demo';
        parent::__construct(
            $scopeConfig,
            $rateErrorFactory,
            $logger,
            $xmlSecurity,
            $xmlElFactory,
            $rateFactory,
            $rateMethodFactory,
            $trackFactory,
            $trackErrorFactory,
            $trackStatusFactory,
            $regionFactory,
            $countryFactory,
            $currencyFactory,
            $directoryData,
            $stockRegistry,
            $data
        );
    }

    protected function _doShipmentRequest(\Magento\Framework\DataObject $request) {}

    public function getAllowedMethods(){
    }

    public function collectRates(RateRequest $request)
    {
        if (!$this->getConfigFlag('active')) {
            return false;
        }
        $result = $this->_rateFactory->create();

        // Getting delivery address street
        $street_address = $request->getDestStreet();

        // Prepare address 1
        $address_line = explode(PHP_EOL, $street_address);
        $address1 = !empty($address_line[0]) ? $address_line[0] : $street_address;
        $address2 = !empty($address_line[1]) ? $address_line[1] : '';

        $zip = $request->getDestPostcode();
        $city = $request->getDestCity();
        $country_code = $request->getDestCountryId();
        $state = $request->getDestRegionCode();

        // Prepare delivery_address for quote
        $delivery_address = array(
            'address_1' => $address1,
            'address_2' => $address2,
            'zip' => $zip,
            'city' => $city,
            'country_code' => $country_code,
            'state' => $state
        );

        // Getting cart items
        $items = $request->getAllItems();

        $price = $request->getPackageValue();
        $weight = $request->getPackageWeight();

        $shipping_rates = $this->_demoApi->quoteRates(
            $delivery_address,
            $items,
            $price,
            $weight
        );
        if ($shipping_rates) {
            foreach ($shipping_rates as $rate) {
                if ($rate['shipping_rate']['require_drop_point']) {
                    $droppoints = $this->_DemoApi->getDroppoints(
                        $rate['shipping_rate']['id'],
                        $address1,
                        $zip,
                        $city,
                        $country_code,
                        $state
                    );
                    if (isset($droppoints) && is_array($droppoints)) {

                        // Get maximum number of droppoints from settings
                        $dp_limit = $this->getDroppointLimit();
                        if ((int)$dp_limit > 0) {
                            $dp_limit = (int)$dp_limit;
                        } else {
                            $dp_limit = 5;
                        }

                        // Loop through droppoints and generate shipping rate for each
                        foreach($droppoints as $index => $droppoint) {
                            if (((int)$index + 1) > $dp_limit)
                                break;

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

                            $method->setCarrier($this->_code);
                            $method->setCarrierTitle($rate['carrier_name']);

                            $method_code = $rate['shipping_rate']['id']."_".$droppoint['drop_point_id'];

                            $method->setMethod($method_code);
                            $method->setMethodTitle(
                                $rate['shipping_rate']['name'].' '.
                                $droppoint['name'].' '.
                                $droppoint['address_1'].' '.
                                $droppoint['country_code'].'-'.
                                $droppoint['zip']
                            );

                            $method->setPrice($rate['price']);
                            $method->setCost($rate['price']);

                            $result->append($method);
                        }
                    }
                } else {
                    $method = $this->_rateMethodFactory->create();

                    $method->setCarrier($this->_code);
                    $method->setCarrierTitle($rate['carrier_name']);

                    $method_code = $rate['shipping_rate']['id'];

                    $method->setMethod($method_code);
                    $method->setMethodTitle($rate['shipping_rate']['name']);

                    $method->setPrice($rate['price']);
                    $method->setCost($rate['price']);

                    $result->append($method);
                }
            }
        }
        return $result;
    }

    private function getDroppointLimit() {
        return $this->_scopeConfig->getValue(
            'carriers/Demo/droppoint_limit',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.