How can I create a Magento 2 order programmatically with specific shipping method and payment method
Here is the example to explain how to create a Magento 2 order programmatically
$email = "demo@demo.com"; $fname = "fname"; $lname = "lname"; $password = "password"; $product_id = 1; $object = \Magento\Framework\App\ObjectManager::getInstance(); $storeManager = $object->get('Magento\Store\Model\StoreManagerInterface'); $customerFactory = $object->get('Magento\Customer\Model\CustomerFactory'); $cartManagementInterface = $object->get('Magento\Quote\Api\CartManagementInterface'); $cartRepositoryInterface = $object->get('Magento\Quote\Api\CartRepositoryInterface'); $customerRepository= $object->get('Magento\Customer\Api\CustomerRepositoryInterface'); $shippingRate= $object->get('Magento\Quote\Model\Quote\Address\Rate'); $store = $storeManager->getStore(); $websiteId = $storeManager->getStore()->getWebsiteId(); $customer=$customerFactory->create(); $customer->setWebsiteId($websiteId); $customer->loadByEmail($email); if(!$customer->getEntityId()){ $customer->setWebsiteId($websiteId) ->setStore($store) ->setFirstname($fname) ->setLastname($lname) ->setEmail($email) ->setPassword($password); $customer->save(); } $cart_id = $cartManagementInterface->createEmptyCart(); $cart = $cartRepositoryInterface->get($cart_id); $cart->setStore($store); $customer= $customerRepository->getById($customer->getEntityId()); $cart->setCurrency(); $cart->assignCustomer($customer); $product = $this->_productFactory->create()->load($product_id); $cart->addProduct($product,1); $orderData = [ 'shipping_address' => [ 'firstname' => $customer->getData('firstname'), 'lastname' => $customer->getData('lastname'), 'street' => $address->getData('street'), 'city' => $address->getData('city'), 'country_id' => $address->getData('country_id'), 'region' => $address->getData('region'), 'postcode' => $address->getData('postcode'), 'telephone' => $address->getData('telephone'), 'fax' => $address->getData('fax'), 'save_in_address_book' => 1 ] ]; $cart->getBillingAddress()->addData($orderData['shipping_address']); $cart->getShippingAddress()->addData($orderData['shipping_address']); $shippingRate->setCode('freeshipping_freeshipping')->getPrice(1); $shippingAddress = $cart->getShippingAddress(); $cart->setPaymentMethod('checkmo'); $cart->setInventoryProcessed(false); $cart->getPayment()->importData(['method' => 'checkmo']); $cart->collectTotals(); $cart->save(); $cart = $cartRepositoryInterface->get($cart->getId()); $order_id = $cartManagementInterface->placeOrder($cart->getId());