Magento 2 – How to Handle Duplicate Orders

duplicatemagento2orders

I'm getting an strange issue in Magento 2.2.7.

Some of the orders are duplicating despite us only receiving one payment.

It is the exact same order information except for the order number (which increments by 1 every time) and the time (about 5 – 10 seconds between each order) which I think might indicate someone pushing the "Place Order" button multiple times.

This seems to be happening at random and doesn't seem to be confined to a single product or payment method.

I was wondering if there was a way to resolve this error and stop us receiving multiple versions of the same order.

Best Answer

I found a solution over GIT :

Create an observer sales_order_place_before as below:

app/code/TB/FixDuplicateOrder/Observer/OrderPlacebefore.php

<?php
namespace TB\FixDuplicateOrder\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class OrderPlacebefore implements ObserverInterface
{
protected $_responseFactory;
protected $_url;


public function __construct(
    \Magento\Framework\App\ResponseFactory $responseFactory,
    \Magento\Framework\UrlInterface $url
) {
    $this->_responseFactory = $responseFactory;
    $this->_url = $url;
}

public function execute(\Magento\Framework\Event\Observer $observer)
{
    $event = $observer->getEvent();

    $order = $observer->getEvent()->getOrder();
    $quoteID = $order->getQuoteId();
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();  
    $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
    $connection = $resource->getConnection();
    $tableName = $resource->getTableName('sales_order');
    $selectedTime = date('Y-m-d h:i:s');
    $endTime = strtotime("-15 seconds", strtotime($selectedTime));
    $last15Sec = date('Y-m-d h:i:s', $endTime);

    echo $sql = "SELECT * FROM `".$tableName."` WHERE `quote_id` = ".$quoteID." and `created_at` >= '$last15Sec'";
    if($result = $connection->fetchRow($sql)){
        $customerBeforeAuthUrl = $this->_url->getUrl('checkout');
        $this->_responseFactory->create()->setRedirect($customerBeforeAuthUrl)->sendResponse();
        exit();
    }
    //var_dump($result);
    //echo  "Hello Testing ";
    //die();
}

Reference URL : https://github.com/magento/magento2/issues/13952

Related Topic