1

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

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

有什么想法我可能会错过吗?

4

1 回答 1

2

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

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

我将事件更改为启动checkout_submit_all_after,我的观察者现在正在工作。

于 2018-03-30T15:57:23.577 回答