I’m developing a module to show shipping rate at product’s page, I followed this link: https://magento.stackexchange.com/a/299107/85869.
[Short question]
When I request estimate for the first time it don’t works as expect, but when I add any product to cart it works normally!
[First request at anonymous session]
After add any product to cart:
[What I tried:]
In Postman (same behavior)
If I use in header Cookie with PHPSESSID value (only PHPSESSID no more any other value in cookie is needed) it course doesn’t work at first time, if I keep it as it is and go to navigator and add product to cart, It works also in Postman.
I’m using a 3rd party Module to calculate shipping for Brazil (the only I’ll use in store, once it will only sell to Brazil):
https://bitbucket.org/imagination-media/correios/wiki/Home
IDK it this problem only happens with that module
Cookies in browser:
First request:
Second Request: (From now, using PHPSESSID value, works even in Postman)
I can put my module in github it someone what to try it (just let me know)
Is there a way to force a session like adding a product in cart does? how?
Solved! Go to Solution.
All I needed to do was: instead use the Magento\Quote\Model\Quote instance provided in constructor (dependency injection) I used the following approach:
$this->_quote = $this->_session_model->getQuote();
$this->_quote->setStore($this->_store);
$this->_quote->removeAllItems();
Hello @syssolutions
After adding one product in the cart, Magento gets shipping address and its required elements, that's why shipping rate is showing over there.
So you need to overcome this situation using set default shipping address but I think this is a very bad idea.
Thanks.
I don't need handle with cart directly, what I do for simulate shipping rate is:
$p = $this->_product->getById($productID)
$this->_itemQuote->setProduct($p);
$this->_itemQuote->setQty($qty);
$this->_quote->addItem($this->_itemQuote);
$shipping = $this->_quote->getShippingAddress();
$shipping->addData($this->extractAddressData($address)); //Method to get Address from JSON
$shipping->setCollectShippingRates(true);
$this->_totalsCollector->collectAddressTotals($this->_quote, $shipping);
$rates = $shipping->collectShippingRates()->getAllShippingRates(); // $rates have all I need
All I needed to do was: instead use the Magento\Quote\Model\Quote instance provided in constructor (dependency injection) I used the following approach:
$this->_quote = $this->_session_model->getQuote();
$this->_quote->setStore($this->_store);
$this->_quote->removeAllItems();