Skip to content

Magento 2 Order Status is not changing

I created a module that changes the status of the order from pending to processing based on specific payment status and if the payment status doesn’t match, it cancel those order. the module is working fine for canceling the orders but not changing the status to processing.
Here’s my code

protected $searchCriteriaBuilder;

/**
 * @var MagentoSalesApiOrderManagementInterface
 */
protected $orderManagement;
protected $date;
protected $orderFactory;
/**
 * CancelOrder constructor.
 * @param MagentoSalesApiOrderRepositoryInterface $orderRepository
 * @param MagentoFrameworkApiSearchCriteriaBuilder $searchCriteriaBuilder
 * @param MagentoSalesApiOrderManagementInterface $orderManagement
 */
public function __construct(
    MagentoSalesApiOrderRepositoryInterface $orderRepository,
    MagentoFrameworkApiSearchCriteriaBuilder $searchCriteriaBuilder,
    MagentoSalesApiOrderManagementInterface $orderManagement,
    MagentoFrameworkStdlibDateTimeTimezoneInterface $date,
    MagentoSalesModelOrderFactory $orderFactory
) {
    $this->orderFactory = $orderFactory;
    $this->orderRepository = $orderRepository;
    $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    $this->orderManagement = $orderManagement;
    $this->date = $date;
}

public function execute()
{
    $today          = date("Y-m-d h:i:s");
    $to             = strtotime('-120 min', strtotime($today));
    $time = date("Y-m-d h:i:s", $to);
    //$agoDate = '2016-11-07'; // For example date, your logic to calculate the date here
    $searchCriteria = $this->searchCriteriaBuilder
        ->addFilter(
            'updated_at',
            array('from' => $time),
            'lteq'
        )->addFilter(
            'status',
            'pending',
            'eq'
        )->create();

    $orders = $this->orderRepository->getList($searchCriteria);
    foreach ($orders->getItems() as $order) {
        $payment = $order->getPayment();
        $paymentStatus = $payment->getAdditionalInformation('payment_status');
        if($paymentStatus == 'SETTLED_BY_MERCHANT' || $paymentStatus == 'AUTHORISED') {
            $orderState = Order::STATE_PROCESSING;
            $order->setStatus($orderState);
            $this->orderRepository->save($order);
        } 
        else {
            $order->setStatus(Order::STATE_CANCELED);
            $this->orderRepository->save($order); // Cancel Order
            
        }
    }
}

}