[英]Magento 2: Create Invoice Programmatically From Order Observer
I'm testing on Magento 2.2.3 and I've created an observer for the event sales_order_save_after
which I'm using to automatically create an invoice. 我正在Magento 2.2.3上进行测试,并且为事件sales_order_save_after
创建了一个观察器,之后该事件将用于自动创建发票。
Here is the current error that I'm receiving after placing an order: 这是下订单后收到的当前错误:
Order saving error: Rolled back transaction has not been completed correctly.
And my MyCompany/MyModule/Observer/SalesOrderSaveAfter.php
还有我的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;
}
}
}
If I remove the transaction portion of the code, eg: 如果我删除代码的交易部分,例如:
$transaction = $this->_transactionFactory->create()
->addObject($invoice)
->addObject($invoice->getOrder());
$transaction->save();
then the order will pass through with the products marked as invoiced, but no invoice is actually created or saved to the order. 则订单将通过标记为已开具发票的产品通过,但实际上并未创建或保存任何发票。
Any ideas what I could be missing? 有什么想法我可能会错过吗?
https://magento.stackexchange.com/questions/217045/magento-2-how-to-automatically-create-invoice-from-order-observer https://magento.stackexchange.com/questions/217045/magento-2-how-to-automatically-create-invoice-from-order-observer
The answer to this is that I was using the wrong event. 答案是我使用了错误的事件。 With the event sales_order_save_after
the order hasn't been committed to the Database yet. 对于事件sales_order_save_after
该订单尚未提交到数据库。
I changed my event to fire on checkout_submit_all_after
and my observer is now working. 我将事件更改为在checkout_submit_all_after
触发,我的观察器现在正在工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.