1

I need to change price of product, before rendering the payment gateway in magento2.

I have two conditions to change price for particular states with_in state Price and out of state price.

SO, we planned to change a price once click next button after enter the shipping address in the checkout page.

I checked this class Magento\Checkout\Model\DefaultConfigProvider get method getConfig, this method to get all checkout data and proceed in checkout page. its not update after change in cart price. for following cases.

  1. I try to use checkout_cart_product_add_after to change price, its change cart price, but its not change checkout checkout page.

  2. Then, try to use checkout session to get quote product, then change price, that also not working me.

Update:

what i did:

I add this js file to my theme. app/design/frontend/Vendor/Theme/Magento_Checkout/web/js/view/shipping.js and update setShippingInformation function to call my ajax controller to checkout shipping address and update my price.

      /**
         * Set shipping information handler
         */
        setShippingInformation: function () {
            if (this.validateShippingInformation()) {
              //for change Price for functionality
               this.priceChange();
                setShippingInformationAction().done(
                    function () {
                        stepNavigator.next();
                    }
                );

            }
        },

      //Price Change Calling

      priceChange: function() {
        $.ajax({
               showLoader: true,
               url: '<base_url>/change/price',
               type: 'POST',
           complete: function(response) {
              console.log(response);
               if(response == "success"){
                 console.log("successfully change price");
               }else{
                 console.log("not change price");
               }

          },
               error: function (xhr, status, errorThrown) {
                   console.log('Error happens. Try again.');
               }
           });

      },

add Price Controller:

        <?php
        namespace Vendor\Module\Controller\Change;

        use Magento\Framework\App\Action\Context;

        class Price extends  \Magento\Framework\App\Action\Action
        {

            protected $logger;

            protected $_cart;

            protected $_eventManager;

            protected $productFactory;

            public function __construct(
                Context $context,
                \Psr\Log\LoggerInterface $logger,
                \Magento\Checkout\Model\Cart $cartModel,
                \Magento\Framework\Event\Manager $eventManager,
                \Magento\Catalog\Model\ProductFactory $productFactory
            ) {
                parent::__construct($context);
                $this->logger = $logger;
                $this->_cart = $cartModel;
                $this->_eventManager = $eventManager;
                $this->productFactory = $productFactory;
            }

            public function execute()
            {
                try {

                //get Shipping Details

                    $dest_country = $this->_cart->getQuote()->getShippingAddress()->getCountryId();
                    $dest_state = $this->_cart->getQuote()->getShippingAddress()->getRegionCode();
                    $this->logger->addDebug($dest_country);
                    $this->logger->addDebug($dest_state);

                    $priceChange ="";
                    if($dest_country == "IN" && $dest_state == "KL"){

                    $productModel  = $this->productFactory->create();
                    $items = $this->_cart->getItems();
                    foreach($items as $item) {
                        $sku = $item->getSku();
                        $product = $productModel->loadByAttribute('sku', $sku);
                        $attribute_code = 'price_ik';
                        $price_ik =  $product->getResource()->getAttribute($attribute_code)->getFrontend()->getValue($product);
                        $this->logger->addDebug("Price Change Inside State");
                        $this->logger->addDebug($price_ik);
                        $beforePrice = $item->getPrice();

                        $this->logger->addDebug("Before Price Change");
                        $this->logger->addDebug($beforePrice);

                        $priceChange = $this->_eventManager->dispatch(
                            'checkout_cart_product_add_after',
                            ['quote_item' => $item,  'avp_price' => $price_ik]
                        );

                        //after change price:
                        $changePrice = $item->getPrice();

                        $this->logger->addDebug("After Price Change");
                        $this->logger->addDebug($changePrice);



                        }

                        return $priceChange;

                    }else{

                    $productModel  = $this->productFactory->create();
                    $items = $this->_cart->getItems();
                    foreach($items as $item) {
                        $sku = $item->getSku();
                        $product = $productModel->loadByAttribute('sku', $sku);
                        $attribute_code = 'price_ok';
                        $price_ok =  $product->getResource()->getAttribute($attribute_code)->getFrontend()->getValue($product);
                        $this->logger->addDebug("Price Change Outside State");
                        $this->logger->addDebug($price_ok);
                        $priceChange = $this->_eventManager->dispatch(
                            'checkout_cart_product_add_after',
                            ['quote_item' => $item,  'avp_price' => $price_ok ]
                        );

                        }

                        return $priceChange;
                    }

                } catch (\Exception $e) {


                }

            }
        }

add events.xml to app/code/AVP/Checkout/etc/

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
  <event name="checkout_cart_product_add_after">
    <observer name="xxx_price_change" instance="Vendor\Module\Observer\CustomPrice" />
  </event>
</config>

add CustomPrice observer to app\code\Vendor\Module\Observer\CustomPrice

        <?php

            namespace Vendor\Module\Observer;

            use Magento\Framework\Event\ObserverInterface;
            use Magento\Framework\App\RequestInterface;

            class CustomPrice implements ObserverInterface
            {
            protected $_cart;

            protected $logger;

            protected $_messageManager;

            protected $resultRedirect;

            public function __construct(
                \Psr\Log\LoggerInterface $logger,
                \Magento\Checkout\Model\Cart $cartModel,
                \Magento\Framework\Message\ManagerInterface $messageManager,
                \Magento\Framework\Controller\ResultFactory $result
            ){
                $this->_cart = $cartModel;
                $this->_messageManager = $messageManager;
                $this->resultRedirect = $result;

            }
                public function execute(\Magento\Framework\Event\Observer $observer) {


                    $this->pricelog->info("Custom Price Event Calling");
                if($observer->getEvent()->getData('avp_price') !== ""){
                    $customPrice = $observer->getEvent()->getData('avp_price');

                    if($customPrice > 0) {
                        $item = $observer->getEvent()->getData('quote_item');
                        $item->setCustomPrice($customPrice);
                        $item->setOriginalCustomPrice($customPrice);
                        $item->getProduct()->setIsSuperMode(true);
                        $item->save();
                        $this->_messageManager->addSuccess(__("You have changed Price based on your shipping address"));
                        echo "sucess";
                    }else {
                        $this->pricelog->info("avp price 0");
                    }
                }else{
                    $this->pricelog->info("avp price Not Found");
                }

                }

            }

Update 1:

Now, I changed quote custom price. But it's not updated in the Order summary. I need to update the product price and order total and cart total in order summary in the checkout page.

Reference:

enter image description here

Suggest me, how to update order summary after change cart price.

  • Please share your code. – Anshu Mishra Oct 1 '18 at 13:22
  • @AnshuMishra I update my question – Rajkumar .E Oct 1 '18 at 13:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.