0

I'm trying to create an order programmatically using the following code in a cron script:

$order = [
          'currency_id' => 'USD',
          'email' => 'test@test.com',
          'shipping_address' => [
            'firstname' => 'John',
            'lastname' => 'Doe',
            'street' => 'Test Main St.',
            'city' => 'Tulsa',
            'country_id' => 'US',
            'region' => 'OK',
            'postcode' => '74146',
            'telephone' => '+1 555-444-3333',
            'save_in_address_book' => 1],
            'items' => [
              ['product_id' => '1', 'qty' => 1]
            ]
          ];

          $store = $this->storeManager->getStore();
          $websiteId = $this->storeManager->getStore()->getWebsiteId();
          $customer = $this->customerFactory->create();
          $customer->setWebsiteId($websiteId);
          $customer->loadByEmail($order['email']); // load customet by email address
          if (!$customer->getEntityId()) {
            //If not avilable then create this customer
            $customer->setWebsiteId($websiteId)->setStore($store)->setFirstname($order['shipping_address']['firstname'])->setLastname($order['shipping_address']['lastname'])->setEmail($order['email'])->setPassword($order['email']);
            $customer->save();
          }
          $quote = $this->quote->create(); // Create Quote Object
          $quote->setStore($store); // Set Store
          $customer = $this->customerRepository->getById($customer->getEntityId());
          $quote->setCurrency();
          $quote->assignCustomer($customer); // Assign quote to Customer

          //add items in quote
          foreach ($order['items'] as $item) {
            $product = $this->product->load($item['product_id']);
            $product->setPrice(99.99);
            $quote->addProduct($product, intval($item['qty']));
          }

          $quote->getBillingAddress()->addData($order['shipping_address']);
          $quote->getShippingAddress()->addData($order['shipping_address']);

          // Collect Rates and Set Shipping & Payment Method
          $shippingAddress = $quote->getShippingAddress();
          $shippingAddress->setCollectShippingRates(true)->collectShippingRates()->setShippingMethod('flatrate_flatrate');
          $quote->setPaymentMethod('cashondelivery');
          $quote->save();

          // Set Sales Order Payment
          $quote->getPayment()->importData(['method' => 'cashondelivery']);

          // Collect Totals & Save Quote
          $quote->setTotalsCollectedFlag(false)->collectTotals()->save();

          // Create Order From Quote
          $orderdata = $this->quoteManagement->submit($quote);

          $orderdata->setEmailSent(0);
          $increment_id = $order->getRealOrderId();
          if ($orderdata->getEntityId()) {
            $result['order_id'] = $orderdata->getRealOrderId();
          } else {
            $result = ['error' => 1, 'msg' => 'Your custom message'];
          }
          return $result;

But receiving the following error:

[Magento\Framework\Exception\LocalizedException] The shipping method is missing. Select the shipping method and try again.

The flatrate shipping method that is being called is enabled. Any ideas?

1

I do it via console in my script I put together

https://github.com/DominicWatts/Faker/blob/master/Helper/Order.php#L109-L192

    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));

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

        foreach ($productIds as $productId) {
            $product = $this->getProductById($productId);
            $product->setStore($store);
            $product->setPrice($this->faker->randomFloat(4, 0, 100));
            $quote->addProduct($product, (int) (rand(1, 2)));
        }

        $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);
            }

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.