You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Magento 2创建发票时运费及手续费未计入致到期款项问题

解决Magento 2自动创建发票时未包含运费及手续费的问题

我完全懂你碰到的这个麻烦——用采购订单支付时,自动生成的发票只算了商品成本,结果运费和手续费还留在到期款项里,订单始终显示未结清。这是因为默认的发票创建逻辑如果只处理商品项,就会漏掉这些额外费用。

咱们直接修改代码,让自动创建的发票把所有待结算金额都涵盖进去,包括运费、手续费这类费用:

if ($order->getTotalDue() > 0) {
    try {
        sleep(2);
        if (!$order->canInvoice()) {
            // 保留你的异常处理逻辑,比如抛出订单无法开票的提示
            throw new \Magento\Framework\Exception\LocalizedException(__('Cannot create an invoice for this order.'));
        }

        // 创建发票对象,自动关联订单所有可开票金额
        $invoice = $this->invoiceService->prepareInvoice($order);
        
        // 校验:避免创建无商品的空发票
        if (!$invoice->getTotalQty()) {
            throw new \Magento\Framework\Exception\LocalizedException(__('Cannot create an invoice without products.'));
        }

        // 设置发票结算所有费用,适配采购订单支付方式
        $invoice->setRequestedCaptureCase(\Magento\Sales\Model\Order\Invoice::CAPTURE_ONLINE);
        $invoice->register();
        
        // 保存发票并同步更新订单状态
        $transactionSave = $this->transactionFactory->create()
            ->addObject($invoice)
            ->addObject($invoice->getOrder());
        $transactionSave->save();
        
    } catch (\Exception $e) {
        // 异常处理:记录日志或输出错误提示
        $this->logger->error('Failed to create invoice automatically: ' . $e->getMessage());
    }
}

关键细节说明:

  • prepareInvoice($order)方法会自动识别订单里所有待开票的金额,包括商品、运费、手续费,不用手动去逐个添加费用项;
  • setRequestedCaptureCase设为CAPTURE_ONLINE,能让采购订单支付方式正确标记所有金额为已结算状态;
  • 加$invoice->getTotalQty()校验是为了符合Magento的规则,避免生成无效的空发票。

另外你可以先在订单后台查一下发票记录,确认之前有没有开过包含运费/手续费的发票——如果这些费用已经被开过票,自然不会再出现在新发票里。

内容的提问来源于stack exchange,提问作者Rahul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:16:25