I have a requirement In Magento 2.4.6 to create an order with bundle product Programatically. here i need to add selected bundle option along with related product while creating order, can anyone help me on this
2 Answers
Can you try this below code with the order data as (API Body)
{ "orderData": { "currency_id": "USD", "email": "[email protected]", "shipping_address": { "firstname": "john", "lastname": "doe", "street": "xxxx", "city": "xxxx", "country_id": "MY", "region": "xxxx", "postcode": "4324", "telephone": "523432", "fax": "32423", "save_in_address_book": 1 }, "items": [ { "product_id": "8", "qty": 2, "price": 10 }, { "product_id": "12", "qty": 1, "sku": "bundle-product-1", "bundle_options":{ "3" : "5", // 3 is option id and 5 is selected id (not product id) "4": "7" } } ] } }
public function createOrder($orderData)
{
try {
// $this->validateOrderData($orderData);
foreach($orderData['items'] as $item){
if (isset($item['bundle_options'])) {
$product = $this->productRepository->getById($item['product_id']);
$params = [
'product' => 12,
'bundle_option' => $item['bundle_options'],
'qty' => $item['qty']
];
$this->cart->addProduct($product,$params);
}
$cart = $this->cart->save();
$quoteId = $cart->getQuote()->getId();
}
$store=$this->storeManager->getStore();
$websiteId = $this->storeManager->getStore()->getWebsiteId();
$customer=$this->customerFactory->create();
$customer->setWebsiteId($websiteId);
$customer->loadByEmail($orderData['email']);
if(!$customer->getEntityId()){
$customer->setWebsiteId($websiteId)
->setStore($store)
->setFirstname($orderData['shipping_address']['firstname'])
->setLastname($orderData['shipping_address']['lastname'])
->setEmail($orderData['email'])
->setPassword($orderData['email']);
$customer->save();
}
$quote=$this->quote->create()->load($quoteId);
$quote->setStore($store);
$customer= $this->customerRepository->getById($customer->getEntityId());
$quote->setCurrency();
$quote->assignCustomer($customer);
foreach($orderData['items'] as $item){
if (!isset($item['bundle_options'])) {
$product=$this->product->load($item['product_id']);
$product->setPrice($item['price']);
$quote->addProduct(
$product,
intval($item['qty'])
);
}
}
// Set addresses
$quote->getBillingAddress()->addData($orderData['shipping_address']);
$quote->getShippingAddress()->addData($orderData['shipping_address']);
// Shipment mwthod and rates
$shippingAddress=$quote->getShippingAddress();
$shippingAddress->setCollectShippingRates(true)
->collectShippingRates()
->setShippingMethod('freeshipping_freeshipping');
// Payment method dummy Credit memo
$quote->setPaymentMethod('checkmo');
$quote->setInventoryProcessed(false);
$quote->save();
$quote->getPayment()->importData(['method' => 'checkmo']);
// Collect Totals & Save Quote
$quote->collectTotals()->save();
// Create Order From Quote
$order = $this->quoteManagement->submit($quote);
$order->setStatus(OrderStatus::PAYMENT_INITIATED);
$order->setEmailSent(0);
$order->save();
$increment_id = $order->getRealOrderId();
if($order->getEntityId()){
$result['order_id']= $order->getRealOrderId();
}else{
$result=['error'=>1,'msg'=>'Your custom message'];
}
return $result;
} catch (\Exception $e) {
throw new CouldNotSaveException(__('Could not save order: %1', $e->getMessage()));
}
}
Try the below code and change your option id as per your current id.
<?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
// Load necessary classes
$quoteFactory = $objectManager->get('\Magento\Quote\Model\QuoteFactory');
$orderService = $objectManager->get('\Magento\Sales\Model\Service\OrderService');
$productRepository = $objectManager->get('\Magento\Catalog\Api\ProductRepositoryInterface');
$customerRepository = $objectManager->get('\Magento\Customer\Api\CustomerRepositoryInterface');
$customer = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create()->load(1);
// Load bundle product by SKU
$productSku = 'your_bundle_product_sku';
$product = $productRepository->get($productSku);
// Create new quote
$quote = $quoteFactory->create();
$quote->setStore($objectManager->getStore());
// Add customer to the quote
$quote->assignCustomer($customer);
// Add bundle product to the quote
$quote->addProduct($product);
// Set bundle options
$options = [
'bundle_option' => [
// Enter your bundle option ids and selection ids here
// Example:
// '1' => ['1' => '5'],
// '2' => ['2' => '10'],
// ...
],
'bundle_option_qty' => [
// Enter quantity for each bundle option here
// Example:
// '1' => 1,
// '2' => 2,
// ...
]
];
$quote->addData($options);
$quote->getBillingAddress()->addData($customer->getDefaultBillingAddress()->getData());
$quote->getShippingAddress()->addData($customer->getDefaultShippingAddress()->getData());
// Collect totals
$quote->collectTotals();
// Submit the quote and create the order
$order = $orderService->prepare($quote);
$order->setCustomerId($quote->getCustomerId());
$order->setCustomerEmail($quote->getCustomerEmail());
$order->setCustomerIsGuest(0);
$order->setCustomerGroupId($quote->getCustomerGroupId());
$order->setStoreId($quote->getStoreId());
$order->setCurrency();
$order->setSubtotal($quote->getSubtotal());
$order->setBaseSubtotal($quote->getBaseSubtotal());
$order->setGrandTotal($quote->getGrandTotal());
$order->setBaseGrandTotal($quote->getBaseGrandTotal());
$order->save();
$order->getPayment()->importData(['method' => 'checkmo']);
$order->setState("new")->setStatus("pending");
$order->save();
echo "Order created successfully. Order ID: " . $order->getId();
Let me know if any queries.
Thank your