First create a module using free module creator tool called silk software
Magento 2 Module Creator Tool Using Silk Software
and enable using following commands below.
php bin/magento module:enable Tw_Cart
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy
1. php bin/magento module:enable Tw_Cart
2. php bin/magento setup:upgrade
3. php bin/magento setup:di:compile
4. php bin/magento setup:static-content:deploy
create events.xml in the path:- app/code/Tw/Cart/etc/frontend/events.xml
<?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="Tw_Cart_Addtocart_Customprice" instance="TW\Cart\Observer\CustomPrice" />
</event>
</config>
create CustomPrice.php in the path: app/code/Tw/Cart/Observer/ & keep the below code
<?php
namespace TW\Cart\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
use Psr\Log\LoggerInterface;
class CustomPrice implements ObserverInterface
{
public function execute(\Magento\Framework\Event\Observer $observer)
{
$writer = new \Zend\Log\Writer\Stream(BP.'/var/log/stackexchange.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
/* Code here */
$quote_item = $observer->getEvent()->getQuoteItem();
$price = 400; //set your price here
$quote_item->setCustomPrice($price);
$quote_item->setOriginalCustomPrice($price);
$quote_item->getProduct()->setIsSuperMode(true);
$logger->info("success !!!!");
}
}