[英]Magento 1.7: Create invoice from an order OK, but the transaction is missing
[英]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();
則訂單將通過標記為已開具發票的產品通過,但實際上並未創建或保存任何發票。
有什么想法我可能會錯過嗎?
答案是我使用了錯誤的事件。 對於事件sales_order_save_after
該訂單尚未提交到數據庫。
我將事件更改為在checkout_submit_all_after
觸發,我的觀察器現在正在工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.