Magento – How to create guest order programmatically for Guest User

create-orderguest-checkoutmagento2programmatically

I have followed Create order programmatically in Magento 2

But it is saving the customer.

And When I skip customer set data and customer save then It's getting an error report like

"Please enter customer email".

Any thoughts ??

Best Answer

The above answer is correct but the standard way is not to create the Customer in case of Guest Checkout.

            $cartId = $this->cartManagementInterface->createEmptyCart();

            /** @var \Magento\Quote\Model\Quote $quote */
            $quote = $this->cartRepositoryInterface->get($cartId);

            $guest = true;
            if ($guest) {
                // Set Customer Data on Qoute, Do not create customer.
                $quote->setCustomerFirstname("Guest First Name");
                $quote->setCustomerLastname("Guest Last Name");
                $quote->setCustomerEmail("guest@123.com");
                $quote->setCustomerIsGuest(true);
            } else {
                // Create customer object and assign to qoute 
                /** @var \Magento\Customer\Api\Data\CustomerInterface $customer */
                $quote->assignCustomer($customer);
            }

Also, the best place to check the sample code for anything to do programmatically is in Magento Integration test cases present in dev/tests/integration/testsuite/.

https://github.com/magento/magento2/tree/2.3-develop/dev/tests/integration/testsuite/Magento/Sales/_files

Related Topic