如何在Magento 2中向订单总额添加费用


39

以下链接将描述

http://excellencemagentoblog.com/blog/2012/01/27/magento-add-fee-discount-order-total/

将费用添加到Magento 1的订单总额中。

现在,此功能已移至Magento 2中的Quote模块

我认为仍然像收集和获取方法一样的概念。有人在Magento 2中尝试过吗?


在magneto2 filedset中从报价到订单的顺序已删除或不起作用,但我不确定要收集总计
Pradeep Kumar

2
这个问题过于笼统,请尝试更具体。你试过什么了?
桑德·曼格尔


1
我开发了用于向订单总额添加额外费用的模块。这笔额外的费用将按订单,发票和贷记金额显示。您可以从GitHub下载:github.com/mageprince/magento2-extrafee
Prince Patel

可以使用适用于所有付款方式和运送国家/ 地区
user2804

Answers:


102

请执行以下步骤,它将为您提供帮助,在我的模块中,我刚刚添加了费用列,
这将在购物车总费用中添加一行,并在结帐页面中
添加侧栏,并且还将费用金额添加到总金额中(费用静态值,我一直保持为100 )一旦下订单,总计将包含费用,如果您在订单视图的前面登录,则可以在total块中看到Fee的新行,但如果有人实施,则管理方尚未实施,您可以发布该答案

在模块etc文件夹中创建sales.xml

<?xml version="1.0"?>

<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="fee" instance="Sugarcode\Test\Model\Total\Fee" sort_order="150"/>

        </group>  
    </section>
</config>

app \ code \ Sugarcode \ Test \ view \ frontend \ web \ js \ view \ checkout \ cart \ totals \ fee.js

/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
define(
    [
        'Sugarcode_Test/js/view/checkout/summary/fee'
    ],
    function (Component) {
        'use strict';

        return Component.extend({

            /**
             * @override
             */
            isDisplayed: function () {
                return true;
            }
        });
    }
);

app \ code \ Sugarcode \ Test \ view \ frontend \ web \ js \ view \ checkout \ summary \ fee.js

/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
/*jshint browser:true jquery:true*/
/*global alert*/
define(
    [
        'Magento_Checkout/js/view/summary/abstract-total',
        'Magento_Checkout/js/model/quote',
        'Magento_Catalog/js/price-utils',
        'Magento_Checkout/js/model/totals'
    ],
    function (Component, quote, priceUtils, totals) {
        "use strict";
        return Component.extend({
            defaults: {
                isFullTaxSummaryDisplayed: window.checkoutConfig.isFullTaxSummaryDisplayed || false,
                template: 'Sugarcode_Test/checkout/summary/fee'
            },
            totals: quote.getTotals(),
            isTaxDisplayedInGrandTotal: window.checkoutConfig.includeTaxInGrandTotal || false,
            isDisplayed: function() {
                return this.isFullMode();
            },
            getValue: function() {
                var price = 0;
                if (this.totals()) {
                    price = totals.getSegment('fee').value;
                }
                return this.getFormattedPrice(price);
            },
            getBaseValue: function() {
                var price = 0;
                if (this.totals()) {
                    price = this.totals().base_fee;
                }
                return priceUtils.formatPrice(price, quote.getBasePriceFormat());
            }
        });
    }
);

app \ code \ Sugarcode \ Test \ view \ frontend \ web \ template \ checkout \ summary \ fee.html

<!--
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<!-- ko -->

  <tr class="totals fee excl">
        <th class="mark" scope="row">
            <span class="label" data-bind="text: title"></span>
            <span class="value" data-bind="text: getValue()"></span>
        </th>
        <td class="amount">

            <span class="price"
                  data-bind="text: getValue(), attr: {'data-th': title}"></span>


        </td>
    </tr>   

<!-- /ko -->

app \ code \ Sugarcode \ Test \ view \ frontend \ web \ template \ checkout \ cart \ totals \ fee.html

<!--
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<!-- ko -->
<tr class="totals fee excl">
    <th class="mark" colspan="1" scope="row" data-bind="text: title"></th>
    <td class="amount">
        <span class="price" data-bind="text: getValue()"></span>
    </td>
</tr>
<!-- /ko -->

app \ code \ Sugarcode \ Test \ Model \ Total \ Fee.php

<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Sugarcode\Test\Model\Total;


class Fee extends \Magento\Quote\Model\Quote\Address\Total\AbstractTotal
{
   /**
     * Collect grand total address amount
     *
     * @param \Magento\Quote\Model\Quote $quote
     * @param \Magento\Quote\Api\Data\ShippingAssignmentInterface $shippingAssignment
     * @param \Magento\Quote\Model\Quote\Address\Total $total
     * @return $this
     */
    protected $quoteValidator = null; 

    public function __construct(\Magento\Quote\Model\QuoteValidator $quoteValidator)
    {
        $this->quoteValidator = $quoteValidator;
    }
  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);


        $exist_amount = 0; //$quote->getFee(); 
        $fee = 100; //Excellence_Fee_Model_Fee::getFee();
        $balance = $fee - $exist_amount;

        $total->setTotalAmount('fee', $balance);
        $total->setBaseTotalAmount('fee', $balance);

        $total->setFee($balance);
        $total->setBaseFee($balance);

        $total->setGrandTotal($total->getGrandTotal() + $balance);
        $total->setBaseGrandTotal($total->getBaseGrandTotal() + $balance);


        return $this;
    } 

    protected function clearValues(Address\Total $total)
    {
        $total->setTotalAmount('subtotal', 0);
        $total->setBaseTotalAmount('subtotal', 0);
        $total->setTotalAmount('tax', 0);
        $total->setBaseTotalAmount('tax', 0);
        $total->setTotalAmount('discount_tax_compensation', 0);
        $total->setBaseTotalAmount('discount_tax_compensation', 0);
        $total->setTotalAmount('shipping_discount_tax_compensation', 0);
        $total->setBaseTotalAmount('shipping_discount_tax_compensation', 0);
        $total->setSubtotalInclTax(0);
        $total->setBaseSubtotalInclTax(0);
    }
    /**
     * @param \Magento\Quote\Model\Quote $quote
     * @param Address\Total $total
     * @return array|null
     */
    /**
     * Assign subtotal amount and label to address object
     *
     * @param \Magento\Quote\Model\Quote $quote
     * @param Address\Total $total
     * @return array
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function fetch(\Magento\Quote\Model\Quote $quote, \Magento\Quote\Model\Quote\Address\Total $total)
    {
        return [
            'code' => 'fee',
            'title' => 'Fee',
            'value' => 100
        ];
    }

    /**
     * Get Subtotal label
     *
     * @return \Magento\Framework\Phrase
     */
    public function getLabel()
    {
        return __('Fee');
    }
}

app \ code \ Sugarcode \ Test \ etc \ module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Sugarcode_Test" setup_version="2.0.6" schema_version="2.0.6">
        <sequence>
            <module name="Magento_Sales"/>
            <module name="Magento_Quote"/>
            <module name="Magento_Checkout"/>
        </sequence>
    </module>
</config>

app \ code \ Sugarcode \ Test \ view \ frontend \ layout \ checkout_cart_index.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="checkout.cart.totals">
            <arguments>
                <argument name="jsLayout" xsi:type="array">
                    <item name="components" xsi:type="array">
                        <item name="block-totals" xsi:type="array">
                            <item name="children" xsi:type="array">


                                <item name="fee" xsi:type="array">
                                    <item name="component"  xsi:type="string">Sugarcode_Test/js/view/checkout/cart/totals/fee</item>
                                    <item name="sortOrder" xsi:type="string">20</item>
                                    <item name="config" xsi:type="array">
                                         <item name="template" xsi:type="string">Sugarcode_Test/checkout/cart/totals/fee</item>
                                        <item name="title" xsi:type="string" translate="true">Fee</item>
                                    </item>
                                </item>

                            </item>
                        </item>
                    </item>
                </argument>
            </arguments>
        </referenceBlock>
    </body>
</page>

app \ code \ Sugarcode \ Test \ view \ frontend \ layout \ checkout_index_index.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="checkout.root">
            <arguments>
                <argument name="jsLayout" xsi:type="array">
                    <item name="components" xsi:type="array">
                        <item name="checkout" xsi:type="array">
                            <item name="children" xsi:type="array">

                                <item name="sidebar" xsi:type="array">
                                    <item name="children" xsi:type="array">
                                        <item name="summary" xsi:type="array">
                                            <item name="children" xsi:type="array">
                                                <item name="totals" xsi:type="array">
                                                    <item name="children" xsi:type="array">
                                                       <item name="fee" xsi:type="array">
                                                            <item name="component"  xsi:type="string">Sugarcode_Test/js/view/checkout/cart/totals/fee</item>
                                                            <item name="sortOrder" xsi:type="string">20</item>
                                                            <item name="config" xsi:type="array">
                                                                 <item name="template" xsi:type="string">Sugarcode_Test/checkout/cart/totals/fee</item>
                                                                <item name="title" xsi:type="string" translate="true">Fee</item>
                                                            </item>
                                                        </item>
                                                    </item>
                                                </item>
                                                <item name="cart_items" xsi:type="array">
                                                    <item name="children" xsi:type="array">
                                                        <item name="details" xsi:type="array">
                                                            <item name="children" xsi:type="array">
                                                                <item name="subtotal" xsi:type="array">
                                                                    <item name="component" xsi:type="string">Magento_Tax/js/view/checkout/summary/item/details/subtotal</item>
                                                                </item>
                                                            </item>
                                                        </item>
                                                    </item>
                                                </item>
                                            </item>
                                        </item>
                                    </item>
                                </item>
                            </item>
                        </item>
                    </item>
                </argument>
            </arguments>
        </referenceBlock>
    </body>
</page>

app \ code \ Sugarcode \ Test \ view \ frontend \ layout \ sales_order_view.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

    <body>        
        <referenceContainer name="order_totals">
            <block class="Sugarcode\Test\Block\Sales\Order\Fee" name="fee"/>
        </referenceContainer>
    </body>
</page>

app \ code \ Sugarcode \ Test \ Block \ Sales \ Order \ Fee.php

<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * Tax totals modification block. Can be used just as subblock of \Magento\Sales\Block\Order\Totals
 */
namespace Sugarcode\Test\Block\Sales\Order;



class Fee extends \Magento\Framework\View\Element\Template
{
    /**
     * Tax configuration model
     *
     * @var \Magento\Tax\Model\Config
     */
    protected $_config;

    /**
     * @var Order
     */
    protected $_order;

    /**
     * @var \Magento\Framework\DataObject
     */
    protected $_source;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Tax\Model\Config $taxConfig
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Tax\Model\Config $taxConfig,
        array $data = []
    ) {
        $this->_config = $taxConfig;
        parent::__construct($context, $data);
    }

    /**
     * Check if we nedd display full tax total info
     *
     * @return bool
     */
    public function displayFullSummary()
    {
        return true;
    }

    /**
     * Get data (totals) source model
     *
     * @return \Magento\Framework\DataObject
     */
    public function getSource()
    {
        return $this->_source;
    } 
    public function getStore()
    {
        return $this->_order->getStore();
    }

      /**
     * @return Order
     */
    public function getOrder()
    {
        return $this->_order;
    }

    /**
     * @return array
     */
    public function getLabelProperties()
    {
        return $this->getParentBlock()->getLabelProperties();
    }

    /**
     * @return array
     */
    public function getValueProperties()
    {
        return $this->getParentBlock()->getValueProperties();
    }

    /**
     * Initialize all order totals relates with tax
     *
     * @return \Magento\Tax\Block\Sales\Order\Tax
     */
     public function initTotals()
    {

        $parent = $this->getParentBlock();
        $this->_order = $parent->getOrder();
        $this->_source = $parent->getSource();

        $store = $this->getStore();

        $fee = new \Magento\Framework\DataObject(
                [
                    'code' => 'fee',
                    'strong' => false,
                    'value' => 100,
                    //'value' => $this->_source->getFee(),
                    'label' => __('Fee'),
                ]
            );

            $parent->addTotal($fee, 'fee');
           // $this->_addTax('grand_total');
            $parent->addTotal($fee, 'fee');


            return $this;
    }

}

完成上述步骤后,请在命令下运行,这一点很重要,否则pub / static文件夹中的js和html文件将丢失。所以运行下面的命令,它将在pub / static文件夹中创建js和html文件

bin \ magento设置:静态内容:部署

如果作品接受我的回答,对别人有帮助


16
您写出了模块...令人印象深刻!为此+1
桑德·曼格尔

4
做得好praseep
阿米特·贝拉

4
您好Pradeep Kumar,很棒的文章,但是该代码存在一个问题,费用加起来等于两倍,这有什么解决方案吗?
Sunil Patel

3
有人在上面的代码中修复了两次收费的错误吗?
帕拉维

4
对不起,我必须道歉。“两次费用”-错误​​很可能是由于app \ code \ Sugarcode \ Test \ Model \ Total \ Fee.php扩展了\ Magento \ Quote \ Model \ Quote \ Address \ Total \ AbstractTotal而引起的。由于您通常在结帐中有两个地址(开票和运输),因此报价保存被调用了两次。M1中也有类似的行为,不幸的是M1-Fix在这里不适用...
mybinaryromance

7

我开发了一个自定义模块,以增加订购的额外费用。

额外费用将显示在购物车页面,结帐页面,发票和creditmemo上。您还可以从管理员配置中选择固定价格类型和百分比

https://github.com/mageprince/magento2-extrafee/


如何从文本框中添加费用prnt.sc/hfsni5
nagendra

此扩展程序仅适用于任何特定付款方式吗?
Piyush

仍然没有此功能未包含在此模块中。我将在模块的下一版本中添加此功能。
帕特尔王子'18

此扩展程序仅适用于为任何特定付款方式添加费用吗..
Mano M

如果更改费用值,则额外费用不会反映在结帐页面中。
马诺M

3

Pradeep的答案非常有帮助,但是遗漏了一个重点。

Magento的Magento \ Quote \ Model \ QuoteTotalsCollector :: collect()函数对Sugarcode \ Test \ Model \ Total :: collect()函数两次调用,每个地址一次。此时,它将创建一个合并的总计,并将其存储在报价表中。它不会显示在订单中,也不会显示在结帐的网站上。

因此,仅在一次调用collect()的情况下收取费用非常重要。可以通过检查是否有可用的运送物品来完成:

    $items = $shippingAssignment->getItems();
    if (!count($items)) {
        return $this;
    }

在Sugarcode \ Test \ Model \ Total :: collect()的变体开头处添加此代码


2
仍然添加两次
nagendra

这事有进一步更新吗?它仍然两次增加费用。不幸的是,它无法正常工作。
hallleron


1

请给出意见

        $total->setGrandTotal($total->getGrandTotal() + $balance);

表格app \ code \ Sugarcode \ Test \ Model \ Total \ Fee.php进行双重定制费用发行

希望对你有帮助!!

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.