0

How to do automatically cancel payment_pending orders in Magento 2.

Older than 10 minutes + status is Payment_pending.

This is my code

<?php

   namespace Arnavcancleorder\Cancleorder\Cron;

   use Magento\Sales\Model\Order;

   class CancelPendingOrders

   {

protected $logger;

/**
 * Constructor
 *
 * @param \Psr\Log\LoggerInterface $logger
 */

public function __construct(\Psr\Log\LoggerInterface $logger)
{
    $this->logger = $logger;
}

/**
 * Execute the cron
 *
 * @return void
 */

public function execute()
{
     $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
     $orders = $objectManager->create('\Magento\Sales\Model\Order')
               ->getCollection()
               ->addFieldToFilter('status', 'pending_payment');
               ->addFieldToFilter('updated_at', array('lt' =>  new Zend_Db_Expr("DATE_ADD('".now()."', INTERVAL -'10' HOUR)"))) ;



              foreach ($orders as $order) {

              $order->cancel()->save();

               }
            }

}
0

You must execute the cron every minute and check if the last update of the orders were 10 min ago. For this, you have to create the next files:

Vendor/Namespace/etc/crontab.xml

<?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="default">
    <job name="vendor_namespace_cancel_order_pending" instance="Vendor\Namespace\Cron\CancelOrderPending" method="execute">
        <schedule>* * * * *</schedule>
    </job>
</group>

Vendor/Namespace/Cron/CancelOrderPending.php

<?php
namespace Vendor\Namespace\Cron;

use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\Search\FilterGroup;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Sales\Api\OrderManagementInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;

/**
 * Class CancelOrderPending
 */
class CancelOrderPending
{

    /**
     * @var OrderRepositoryInterface
     */
    private $orderRepository;

    /**
     * @var SearchCriteriaBuilder
     */
    private $searchCriteriaBuilder;

    /**
     * @var FilterBuilder
     */
    private $filterBuilder;

    /**
     * @var FilterGroup
     */
    private $filterGroup;

    /**
     * @var OrderManagementInterface
     */
    private $orderManagement;

    /**
     * CancelOrderPending constructor.
     *
     * @param OrderRepositoryInterface $orderRepository
     * @param SearchCriteriaBuilder $searchCriteriaBuilder
     * @param FilterBuilder $filterBuilder
     * @param FilterGroup $filterGroup
     * @param OrderManagementInterface $orderManagement
     */
    public function __construct(
        OrderRepositoryInterface $orderRepository,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        FilterBuilder $filterBuilder,
        FilterGroup $filterGroup,
        OrderManagementInterface $orderManagement
    ) {
        $this->orderRepository       = $orderRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->filterBuilder         = $filterBuilder;
        $this->filterGroup           = $filterGroup;
        $this->orderManagement       = $orderManagement;
    }

    /**
     * @throws \Exception
     */
    public function execute()
    {
        $today          = date("Y-m-d h:i:s");
        $to             = strtotime('-10 min', strtotime($today));
        $to             = date('Y-m-d h:i:s', $to);

        $filterGroupDate      = $this->filterGroup;
        $filterGroupStatus    = clone($filterGroupDate);

        $filterDate      = $this->filterBuilder
            ->setField('updated_at')
            ->setConditionType('to')
            ->setValue($to)
            ->create();
        $filterStatus    = $this->filterBuilder
            ->setField('status')
            ->setConditionType('eq')
            ->setValue('pending_payment')
            ->create();

        $filterGroupDate->setFilters([$filterDate]);
        $filterGroupStatus->setFilters([$filterStatus]);

        $searchCriteria = $this->searchCriteriaBuilder->setFilterGroups(
            [$filterGroupDate, $filterGroupStatus]
        );
        $searchResults  = $this->orderRepository->getList($searchCriteria->create());

        /** @var Order $order */
        foreach ($searchResults->getItems() as $order) {
            $this->orderManagement->cancel($order->getId());
        }
    }
}
0

You have to create a cronjob for this requirement.

That cronjob will run 20mins interval <schedule>*/20 * * * *</schedule>

And at job class Magento/SampleMinimal/Cron/Test.php, You have to create order collection and status Payment_pending.

  • Thanks for replay Amit Bera ,,,,, Iam new to magento 2 could you please help if its possible how to do in observer for cron Job i have compelted – Chala Chalapathi Jun 22 '18 at 12:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.