Magento 2:从订单观察器以编程方式创建发票

时间:2018-03-09 16:47:59

标签: php magento2 invoice magento2.2

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

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

我可能遗失的任何想法?

1 个答案:

答案 0 :(得分: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,我的观察员现在正在工作。