I want to add a custom discount on the order total and want to show it on Cart and Checkout Page.

But, I want to apply that discount based on the Loyalty Points available for Customers. I have added a Loyalty Form on the checkout page.

When that form is submitted then and then I want to apply that discount. So How can I make a custom post API and achieve this in Magento 2.



Try with sales.xml in you module etc folder

<?xml version="1.0"?>
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Sales:etc/sales.xsd">
     <section name="quote">
       <group name="totals">
         <item name="customer_discount" instance="Vendor\Module\Model\Total\Quote\Custom" sort_order="400"/>

Set the value of discount

namespace Vendor\Module\Model\Total\Quote;

class Custom extends \Magento\Quote\Model\Quote\Address\Total\AbstractTotal
        * @var \Magento\Framework\Pricing\PriceCurrencyInterface
       protected $priceCurrency;
        * Custom constructor.
        * @param \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency
       public function __construct(
           \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency
           $this->priceCurrency = $priceCurrency;

       public function collect(
           \Magento\Quote\Model\Quote $quote,
           \Magento\Quote\Api\Data\ShippingAssignmentInterface $shippingAssignment,
           \Magento\Quote\Model\Quote\Address\Total $total
           parent::collect($quote, $shippingAssignment, $total);
               $baseDiscount = 10;
               $discount =  $this->priceCurrency->convert($baseDiscount);
               $total->addTotalAmount('customdiscount', -$discount);
               $total->addBaseTotalAmount('customdiscount', -$baseDiscount);
               $total->setBaseGrandTotal($total->getBaseGrandTotal() - $baseDiscount);
           return $this;
| improve this answer | |
  • Yes, I tried with the same way before. But i want to show the discount through the API. LIke, if i post 10 loyality point at some route and then "$10" should discount should be added with the title "Loyality Discount". Is there any way to achieve this? – Sujeet Pandit Dec 30 '19 at 9:01
  • when you want to apply discount set sort_order="400" appropriate that. – Birjitsinh Zala Dec 30 '19 at 9:08
  • Sales.xml working for both area web & API – Birjitsinh Zala Dec 30 '19 at 9:10

Your Answer

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

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