Question

How can I export Magento 2 orders and then import them on a new system?

The new system has the same products in front-end and as far as customers are concerned. However, the way it works in the back is completely different so products & their IDs may not match up.

Was it helpful?

Solution

This is going to be a really difficult task.

As your product IDs are different you can't import from db using direct SQL. Therefore you are going to have to programmatically create orders.

If you are programmatically creating orders the products have to exist. Also you have to have a payment and shipping method available for import. This will get you most of the way but order totals are recalculated based on current conditions. So for example you will have trouble if you have variable tax rates or use different currencies. You will struggle to get all the order values the same. Plus you will be missing things like payment transaction references. If you choose to go this route you could use a single SKU with the sole purpose of creating these migrated orders to simplify the process - i.e. MIGRATESKU. But then the orders are going to be noticeably different with all the same SKU used but just has different amounts.

I wouldn't recommend using the Magento API as it is slow. Unless you are happy to feed the migrated orders from one system to another over a period of time.

My best advice is create an archive section on the website. And put the migrated orders into the archive section. This could be direct SQL or by other means. In the account area you could have a seperate section for historic orders. Call it the archive or similar.

How to create an order programatically

https://github.com/DominicWatts/Faker/blob/master/Helper/Order.php#L117-L208

    public function createOrder($storeId = 1)
    {

        // bypass Area code not set
        $this->_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $this->cartManagementInterface = $this->_objectManager->create(CartManagementInterface::class);

        try {
            $store = $this->storeManagerInterface->getStore($storeId);
        } catch (\Exception $e) {
            $this->logger->critical($e);

            return;
        }

        $websiteId = $store->getWebsiteId();
        $customerIds = $this->getRandomCustomerId($websiteId);
        if (empty($customerIds)) {
            new \Exception(__('Please add some customers for this store first'));
        }

        $customer = $this->getCustomerById($customerIds[0]);
        if (!$customer) {
            new \Exception(__('Problem loading customer'));
        }

        $cartId = $this->cartManagementInterface->createEmptyCart(); //Create empty cart
        $quote = $this->cartRepositoryInterface->get($cartId); // load empty cart quote
        $quote->setStore($store);
        $quote->setCurrency();
        $quote->assignCustomer($customer);

        $productIds = $this->getRandomProductId(rand(1, 10), true);

        if (empty($productIds)) {
            new \Exception(__('Please add some produts for this store first'));
        }

        foreach ($productIds as $productId) {
            try {
                $product = $this->getProductById($productId);
                if ($product->isSalable()) {
                    $qty = $this->stockItem->getStockQty($product->getId(), $websiteId);
                    if ($qty > 1) {
                        $product->setStore($store);
                        $product->setPrice($this->faker->randomFloat(4, 0, 100));
                        $quote->addProduct($product, (int) (rand(1, 2)));
                    }
                }
            } catch (\Exception $e) {
                $this->logger->critical($e);
            }
        }

        $billingAddress = $this->addressFactory->create()->load($customer->getDefaultBilling());
        $shippingAddress = $this->addressFactory->create()->load($customer->getDefaultShipping());

        $quote->getBillingAddress()->addData($billingAddress->getData());
        $quote->getShippingAddress()->addData($shippingAddress->getData());

        $shippingAddress = $quote->getShippingAddress();
        $shippingAddress->setCollectShippingRates(true)
            ->collectShippingRates()
            ->setShippingMethod('flatrate_flatrate');

        $quote->setPaymentMethod('checkmo');
        $quote->setInventoryProcessed(false);

        $quote->getPayment()->importData(['method' => 'checkmo']);

        try {
            $this->cartRepositoryInterface->save($quote);
        } catch (\Exception $e) {
            $this->logger->critical($e);
            return;
        }

        $quote->collectTotals();
        $quote = $this->cartRepositoryInterface->get($quote->getId());

        try {
            $orderId = $this->cartManagementInterface->placeOrder($quote->getId());
            $this->generateInvoice($orderId);
            if ($this->getRandomTrueOrFalse()) {
                $this->generateShipment($orderId, $this->getRandomTrueOrFalse());
            }

            return $orderId;
        } catch (\Exception $e) {
            $this->logger->critical($e);
        }
    }

Note: I use object manager because you can't inject that particular class as frontend session needs to be set. This enables you to build a cart via command line.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top