Magento 2:从 Order Observer 以编程方式创建发票

Magento 2: Create Invoice Programmatically From Order Observer

我正在 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();

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

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

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

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

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