【问题标题】:Magento 2: Create Invoice Programmatically From Order ObserverMagento 2:从 Order Observer 以编程方式创建发票
【发布时间】:2018-03-09 16:47:59
【问题描述】:

我正在 Magento 2.2.3 上进行测试,并为事件 sales_order_save_after 创建了一个观察者,我用它来自动创建发票。

这是我在下订单后收到的当前错误:

Order saving error: Rolled back transaction has not been completed correctly.

还有我的MyCompany/MyModule/Observer/SalesOrderSaveAfter.php

<?php
namespace MyCompany\MyModule\Observer;

use Magento\Framework\Event\ObserverInterface;

class SalesOrderSaveAfter implements ObserverInterface
{
    protected $_invoiceService;
    protected $_transactionFactory;

    public function __construct(
      \Magento\Sales\Model\Service\InvoiceService $invoiceService,
      \Magento\Framework\DB\TransactionFactory $transactionFactory
    ) {
       $this->_invoiceService = $invoiceService;
       $this->_transactionFactory = $transactionFactory;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $order = $observer->getEvent()->getOrder();

        try {
            if(!$order->canInvoice()) {
                return null;
            }
            if(!$order->getState() == 'new') {
                return null;
            }

            $invoice = $this->_invoiceService->prepareInvoice($order);
            $invoice->setRequestedCaptureCase(\Magento\Sales\Model\Order\Invoice::CAPTURE_ONLINE);
            $invoice->register();

            $transaction = $this->_transactionFactory->create()
              ->addObject($invoice)
              ->addObject($invoice->getOrder());

            $transaction->save();

        } catch (\Exception $e) {
            $order->addStatusHistoryComment('Exception message: '.$e->getMessage(), false);
            $order->save();
            return null;
        }
    }
}

如果我删除代码的事务部分,例如:

$transaction = $this->_transactionFactory->create()
    ->addObject($invoice)
    ->addObject($invoice->getOrder());

    $transaction->save();

然后订单将通过标记为已开票的产品,但实际上并未创建发票或将发票保存到订单中。

有什么我可能会遗漏的想法吗?

【问题讨论】:

  • 嘿,您找到发票创建问题的任何解决方案了吗?我也面临类似的问题..如果您已经找到任何解决方案,请提供帮助..提前致谢!
  • @Hemantpaliwal 是的,我做到了!抱歉,我会更新答案

标签: php magento2 invoice magento2.2


【解决方案1】:

https://magento.stackexchange.com/questions/217045/magento-2-how-to-automatically-create-invoice-from-order-observer

答案是我使用了错误的事件。对于事件sales_order_save_after,订单尚未提交到数据库。

我将事件更改为在 checkout_submit_all_after 上触发,我的观察者现在正在工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 2017-01-08
    • 2012-08-11
    • 1970-01-01
    • 2012-11-15
    • 1970-01-01
    相关资源
    最近更新 更多