我尝试在客户单击下订单按钮并重定向到成功页面后执行cron作业。
因此,我的工作目的是,如果管理员在3天内未响应订单,则订单状态将自动取消。
取消3天以上的订单。在这种情况下,我们需要创建Cron作业。因此,我们将当前日期与创建的日期进行比较(看一下表sales_order
,找到列created_at
)。
我们应该使用服务合同层:
\Magento\Sales\Api\OrderRepositoryInterface $orderRepository
并且\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
用于获取订单商品。\Magento\Sales\Api\OrderManagementInterface
用于取消订单。
我们的Cron:
namespace Mymodule\Checkout\Cron;
class CancelOrder
{
/**
* @var \Magento\Sales\Api\OrderRepositoryInterface
*/
protected $orderRepository;
/**
* @var \Magento\Framework\Api\SearchCriteriaBuilder
*/
protected $searchCriteriaBuilder;
/**
* @var \Magento\Sales\Api\OrderManagementInterface
*/
protected $orderManagement;
/**
* CancelOrder constructor.
* @param \Magento\Sales\Api\OrderRepositoryInterface $orderRepository
* @param \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
* @param \Magento\Sales\Api\OrderManagementInterface $orderManagement
*/
public function __construct(
\Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
\Magento\Sales\Api\OrderManagementInterface $orderManagement
)
{
$this->orderRepository = $orderRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->orderManagement = $orderManagement;
}
public function execute()
{
$agoDate = '2016-11-07'; // For example date, your logic to calculate the date here
$searchCriteria = $this->searchCriteriaBuilder
->addFilter(
'created_at',
$agoDate,
'gt'
)->addFilter(
'status'
'pending'
'eq'
)->create();
$orders = $this->orderRepository->getList($searchCriteria);
foreach ($orders->getItems() as $order) {
$this->orderManagement->cancel($order->getEntityId()); // Cancel Order
};
}
}
您应该将Cron设置为每分钟运行一次: https ://crontab.guru/
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
<group id="custom_group">
<job name="test_cronjob" instance="Mymodule\Checkout\Cron\CancelOrder" method="execute">
<schedule>* * * * *</schedule>
</job>
</group>
</config>