Creating an order programmatically in Magento 2 is a complex process, and there isn’t a one-size-fits-all example that covers all possible scenarios. However, I can provide you with a basic example that you can use as a starting point. Keep in mind that you may need to adapt and extend this example to fit your specific requirements.
<?php
use Magento\Framework\App\Bootstrap;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Payment;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
// Replace with your customer and product data
$customerId = 1;
$productIds = [1, 2]; // Array of product IDs
$shippingAddressData = [
'firstname' => 'John',
'lastname' => 'Doe',
'street' => '123 Main St',
'city' => 'Anytown',
'postcode' => '12345',
'telephone' => '555-555-5555',
'country_id' => 'US',
'region' => 'New York',
];
// Load the customer and products
$customer = $objectManager->create('Magento\Customer\Model\Customer')->load($customerId);
$productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
$quote = $objectManager->create('Magento\Quote\Model\Quote');
$quote->setStoreId(1); // Set the store ID for your store
$quote->assignCustomer($customer);
foreach ($productIds as $productId) {
$product = $productRepository->getById($productId);
$quote->addProduct($product, 1); // 1 is the quantity
}
$quote->getShippingAddress()->addData($shippingAddressData);
$quote->setPaymentMethod('checkmo'); // Payment method code (e.g., checkmo for Check/Money Order)
$quote->setInventoryProcessed(false); // Do not decrement stock
$quote->collectTotals();
// Create an order
$quote->save();
$quote->getPayment()->importData(['method' => 'checkmo']); // Set payment method
$quote->setInventoryProcessed(true);
$order = $objectManager->create('Magento\Quote\Model\Quote\ToOrder')->convert($quote);
$order->getPayment()->importData(['method' => 'checkmo']); // Set payment method again
$order->place();
$order->save();
// Display the order ID
echo 'Order ID: ' . $order->getIncrementId() . ' has been created successfully.';
In this example:
- Replace
$customerId
with the customer’s ID,$productIds
with an array of product IDs, and$shippingAddressData
with the shipping address data for the order. - The script loads the customer, products, and creates a new quote.
- It assigns the customer, adds products to the quote, sets the shipping address and payment method.
- Finally, it converts the quote into an order and places it.
- Please note that this is a basic example and may not cover all possible scenarios. Depending on your specific use case and requirements, you may need to adjust and expand this script. Additionally, consider implementing error handling and validation to make the process more robust.
Leave a Reply