Unique constraint violation found when creating order programmaticallyCreate Mage_Sales_Model_Quote from orderOrder Import or order creation via apiPlacing and order via API and payment processingRemoved payment method, old orders not loadingCreate an order on API callMagento: Convert Quote to OrderOrder Total and Order Item issue when creating order magento 2Get Payment card details then set it Magento1.9Request for quote and checkout at same timeUnique constraint violation found

What is appropriate short form for "laboratoires" in French?

Music theory behind A chord in the key of G

What is the highest voltage from the power supply a Raspberry Pi 3 B can handle without getting damaged?

Count All Possible Unique Combinations of Letters in a Word

Android Material and appcompat Manifest merger failed in react-native or ExpoKit

Can a rogue use Sneak Attack in a Darkness spell cast by another player?

Is it illegal to withhold someone's passport and green card in California?

Confusion over 220 and 230 volt outlets

Why are < or > required to use /dev/tcp

Hit the Bulls Eye with T in the Center

Does Doppler effect happen instantly?

Is there any difference between Т34ВМ1 and КМ1858ВМ1/3?

What's currently blocking the construction of the wall between Mexico and the US?

How many people are necessary to maintain modern civilisation?

Why is it easier to balance a non-moving bike standing up than sitting down?

Did the CIA blow up a Siberian pipeline in 1982?

What can I do with a research project that is my university’s intellectual property?

Has there been any indication at all that further negotiation between the UK and EU is possible?

How to make clear to people I don't want to answer their "Where are you from?" question?

Constitutionality of U.S. Democratic Presidential Candidate's Supreme Court Suggestion

RandomInteger with equal number of 1 and -1

`-` in tar xzf -

Can White Castle?

How can lift be less than thrust that is less than weight?



Unique constraint violation found when creating order programmatically


Create Mage_Sales_Model_Quote from orderOrder Import or order creation via apiPlacing and order via API and payment processingRemoved payment method, old orders not loadingCreate an order on API callMagento: Convert Quote to OrderOrder Total and Order Item issue when creating order magento 2Get Payment card details then set it Magento1.9Request for quote and checkout at same timeUnique constraint violation found






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I've been trying to create an order programatically in Magento 2.3 and the order is created but my code dies and I get the error : "Unique constraint violation found".



What do I need to add or change? Here is my code (I´ll remove objectmanager when it´s working):



 $store=$this->_storeManager->getStore();

$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$cartManagementInterface = $objectManager->get('MagentoQuoteApiCartManagementInterface');
$cartRepositoryInterface = $objectManager->get('MagentoQuoteApiCartRepositoryInterface');

$cart_id = $cartManagementInterface->createEmptyCart();
$quote = $cartRepositoryInterface->get($cart_id);

//$quote=$this->quote->create(); //Create object of quote
$quote->setStore($store); //set store for which you create quote
// if you have allready buyer id then you can load customer directly
$customer= $this->customerRepository->get($orderData["email"]);
$quote->setCurrency();
$quote->assignCustomer($customer); //Assign quote to customer

//add items in quote
$this->productHelper->setSkipSaleableCheck(true);
foreach($orderData['items'] as $item)

$product=$this->_product->create()->load($item['product_id']);
$quote->addProduct(
$product,
intval($item['qty'])
);

$this->productHelper->setSkipSaleableCheck(false);

//Set Address to quote
$quote->getBillingAddress()->addData($orderData['shipping_address']);

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

$this->shippingRate
->setCode('freeshipping_freeshipping')
->getPrice(1);

// Collect Rates and Set Shipping & Payment Method

$shippingAddress=$quote->getShippingAddress();
$shippingAddress->setCollectShippingRates(true)
->collectShippingRates()
->setShippingMethod('freeshipping_freeshipping'); //shipping method

$quote->getShippingAddress()->addShippingRate($this->shippingRate);

$quote->setPaymentMethod('cashondelivery'); //payment method
$quote->setInventoryProcessed(true); //not effetc inventory
$quote->save(); //Now Save quote and your quote is ready

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

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

// Create Order From Quote

$cartManagementInterface = $objectManager->get('MagentoQuoteApiCartManagementInterface');

$order = $cartManagementInterface->placeOrder($quote->getId());

//give a result back
if($order->getEntityId())
$result['order_id'] = $order->getEntityId();
else
$result=['error'=>1,'msg'=>'Your custom message'];


return $result;









share|improve this question




























    0















    I've been trying to create an order programatically in Magento 2.3 and the order is created but my code dies and I get the error : "Unique constraint violation found".



    What do I need to add or change? Here is my code (I´ll remove objectmanager when it´s working):



     $store=$this->_storeManager->getStore();

    $objectManager = MagentoFrameworkAppObjectManager::getInstance();
    $cartManagementInterface = $objectManager->get('MagentoQuoteApiCartManagementInterface');
    $cartRepositoryInterface = $objectManager->get('MagentoQuoteApiCartRepositoryInterface');

    $cart_id = $cartManagementInterface->createEmptyCart();
    $quote = $cartRepositoryInterface->get($cart_id);

    //$quote=$this->quote->create(); //Create object of quote
    $quote->setStore($store); //set store for which you create quote
    // if you have allready buyer id then you can load customer directly
    $customer= $this->customerRepository->get($orderData["email"]);
    $quote->setCurrency();
    $quote->assignCustomer($customer); //Assign quote to customer

    //add items in quote
    $this->productHelper->setSkipSaleableCheck(true);
    foreach($orderData['items'] as $item)

    $product=$this->_product->create()->load($item['product_id']);
    $quote->addProduct(
    $product,
    intval($item['qty'])
    );

    $this->productHelper->setSkipSaleableCheck(false);

    //Set Address to quote
    $quote->getBillingAddress()->addData($orderData['shipping_address']);

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

    $this->shippingRate
    ->setCode('freeshipping_freeshipping')
    ->getPrice(1);

    // Collect Rates and Set Shipping & Payment Method

    $shippingAddress=$quote->getShippingAddress();
    $shippingAddress->setCollectShippingRates(true)
    ->collectShippingRates()
    ->setShippingMethod('freeshipping_freeshipping'); //shipping method

    $quote->getShippingAddress()->addShippingRate($this->shippingRate);

    $quote->setPaymentMethod('cashondelivery'); //payment method
    $quote->setInventoryProcessed(true); //not effetc inventory
    $quote->save(); //Now Save quote and your quote is ready

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

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

    // Create Order From Quote

    $cartManagementInterface = $objectManager->get('MagentoQuoteApiCartManagementInterface');

    $order = $cartManagementInterface->placeOrder($quote->getId());

    //give a result back
    if($order->getEntityId())
    $result['order_id'] = $order->getEntityId();
    else
    $result=['error'=>1,'msg'=>'Your custom message'];


    return $result;









    share|improve this question
























      0












      0








      0








      I've been trying to create an order programatically in Magento 2.3 and the order is created but my code dies and I get the error : "Unique constraint violation found".



      What do I need to add or change? Here is my code (I´ll remove objectmanager when it´s working):



       $store=$this->_storeManager->getStore();

      $objectManager = MagentoFrameworkAppObjectManager::getInstance();
      $cartManagementInterface = $objectManager->get('MagentoQuoteApiCartManagementInterface');
      $cartRepositoryInterface = $objectManager->get('MagentoQuoteApiCartRepositoryInterface');

      $cart_id = $cartManagementInterface->createEmptyCart();
      $quote = $cartRepositoryInterface->get($cart_id);

      //$quote=$this->quote->create(); //Create object of quote
      $quote->setStore($store); //set store for which you create quote
      // if you have allready buyer id then you can load customer directly
      $customer= $this->customerRepository->get($orderData["email"]);
      $quote->setCurrency();
      $quote->assignCustomer($customer); //Assign quote to customer

      //add items in quote
      $this->productHelper->setSkipSaleableCheck(true);
      foreach($orderData['items'] as $item)

      $product=$this->_product->create()->load($item['product_id']);
      $quote->addProduct(
      $product,
      intval($item['qty'])
      );

      $this->productHelper->setSkipSaleableCheck(false);

      //Set Address to quote
      $quote->getBillingAddress()->addData($orderData['shipping_address']);

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

      $this->shippingRate
      ->setCode('freeshipping_freeshipping')
      ->getPrice(1);

      // Collect Rates and Set Shipping & Payment Method

      $shippingAddress=$quote->getShippingAddress();
      $shippingAddress->setCollectShippingRates(true)
      ->collectShippingRates()
      ->setShippingMethod('freeshipping_freeshipping'); //shipping method

      $quote->getShippingAddress()->addShippingRate($this->shippingRate);

      $quote->setPaymentMethod('cashondelivery'); //payment method
      $quote->setInventoryProcessed(true); //not effetc inventory
      $quote->save(); //Now Save quote and your quote is ready

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

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

      // Create Order From Quote

      $cartManagementInterface = $objectManager->get('MagentoQuoteApiCartManagementInterface');

      $order = $cartManagementInterface->placeOrder($quote->getId());

      //give a result back
      if($order->getEntityId())
      $result['order_id'] = $order->getEntityId();
      else
      $result=['error'=>1,'msg'=>'Your custom message'];


      return $result;









      share|improve this question














      I've been trying to create an order programatically in Magento 2.3 and the order is created but my code dies and I get the error : "Unique constraint violation found".



      What do I need to add or change? Here is my code (I´ll remove objectmanager when it´s working):



       $store=$this->_storeManager->getStore();

      $objectManager = MagentoFrameworkAppObjectManager::getInstance();
      $cartManagementInterface = $objectManager->get('MagentoQuoteApiCartManagementInterface');
      $cartRepositoryInterface = $objectManager->get('MagentoQuoteApiCartRepositoryInterface');

      $cart_id = $cartManagementInterface->createEmptyCart();
      $quote = $cartRepositoryInterface->get($cart_id);

      //$quote=$this->quote->create(); //Create object of quote
      $quote->setStore($store); //set store for which you create quote
      // if you have allready buyer id then you can load customer directly
      $customer= $this->customerRepository->get($orderData["email"]);
      $quote->setCurrency();
      $quote->assignCustomer($customer); //Assign quote to customer

      //add items in quote
      $this->productHelper->setSkipSaleableCheck(true);
      foreach($orderData['items'] as $item)

      $product=$this->_product->create()->load($item['product_id']);
      $quote->addProduct(
      $product,
      intval($item['qty'])
      );

      $this->productHelper->setSkipSaleableCheck(false);

      //Set Address to quote
      $quote->getBillingAddress()->addData($orderData['shipping_address']);

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

      $this->shippingRate
      ->setCode('freeshipping_freeshipping')
      ->getPrice(1);

      // Collect Rates and Set Shipping & Payment Method

      $shippingAddress=$quote->getShippingAddress();
      $shippingAddress->setCollectShippingRates(true)
      ->collectShippingRates()
      ->setShippingMethod('freeshipping_freeshipping'); //shipping method

      $quote->getShippingAddress()->addShippingRate($this->shippingRate);

      $quote->setPaymentMethod('cashondelivery'); //payment method
      $quote->setInventoryProcessed(true); //not effetc inventory
      $quote->save(); //Now Save quote and your quote is ready

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

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

      // Create Order From Quote

      $cartManagementInterface = $objectManager->get('MagentoQuoteApiCartManagementInterface');

      $order = $cartManagementInterface->placeOrder($quote->getId());

      //give a result back
      if($order->getEntityId())
      $result['order_id'] = $order->getEntityId();
      else
      $result=['error'=>1,'msg'=>'Your custom message'];


      return $result;






      orders magento2.3 quote programmatically






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jun 12 at 14:58









      Gonzalo GutiérrezGonzalo Gutiérrez

      526




      526




















          1 Answer
          1






          active

          oldest

          votes


















          1














          I encountered the exact same problem. It was down to the syntax used of certain parts of the process.



          Take a look at this.



          https://github.com/DominicWatts/Faker/blob/master/Helper/Order.php#L60-L143



           public function createOrder($storeId = 1)

          // bypass Area code not set
          $this->_objectManager = MagentoFrameworkAppObjectManager::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);




          Very similar to your approach so maybe we followed the same guidelines. There is some extra stuff in with regards to loading customer and generating shipment. Also I used object manager to bypass error as this is used within console script. You don't need those parts. But hopefully you can follow what I did.






          share|improve this answer























          • Thank you so much @Dominic! I´m gonna give it a try

            – Gonzalo Gutiérrez
            Jun 12 at 20:55












          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "479"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f278141%2funique-constraint-violation-found-when-creating-order-programmatically%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          I encountered the exact same problem. It was down to the syntax used of certain parts of the process.



          Take a look at this.



          https://github.com/DominicWatts/Faker/blob/master/Helper/Order.php#L60-L143



           public function createOrder($storeId = 1)

          // bypass Area code not set
          $this->_objectManager = MagentoFrameworkAppObjectManager::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);




          Very similar to your approach so maybe we followed the same guidelines. There is some extra stuff in with regards to loading customer and generating shipment. Also I used object manager to bypass error as this is used within console script. You don't need those parts. But hopefully you can follow what I did.






          share|improve this answer























          • Thank you so much @Dominic! I´m gonna give it a try

            – Gonzalo Gutiérrez
            Jun 12 at 20:55
















          1














          I encountered the exact same problem. It was down to the syntax used of certain parts of the process.



          Take a look at this.



          https://github.com/DominicWatts/Faker/blob/master/Helper/Order.php#L60-L143



           public function createOrder($storeId = 1)

          // bypass Area code not set
          $this->_objectManager = MagentoFrameworkAppObjectManager::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);




          Very similar to your approach so maybe we followed the same guidelines. There is some extra stuff in with regards to loading customer and generating shipment. Also I used object manager to bypass error as this is used within console script. You don't need those parts. But hopefully you can follow what I did.






          share|improve this answer























          • Thank you so much @Dominic! I´m gonna give it a try

            – Gonzalo Gutiérrez
            Jun 12 at 20:55














          1












          1








          1







          I encountered the exact same problem. It was down to the syntax used of certain parts of the process.



          Take a look at this.



          https://github.com/DominicWatts/Faker/blob/master/Helper/Order.php#L60-L143



           public function createOrder($storeId = 1)

          // bypass Area code not set
          $this->_objectManager = MagentoFrameworkAppObjectManager::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);




          Very similar to your approach so maybe we followed the same guidelines. There is some extra stuff in with regards to loading customer and generating shipment. Also I used object manager to bypass error as this is used within console script. You don't need those parts. But hopefully you can follow what I did.






          share|improve this answer













          I encountered the exact same problem. It was down to the syntax used of certain parts of the process.



          Take a look at this.



          https://github.com/DominicWatts/Faker/blob/master/Helper/Order.php#L60-L143



           public function createOrder($storeId = 1)

          // bypass Area code not set
          $this->_objectManager = MagentoFrameworkAppObjectManager::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);




          Very similar to your approach so maybe we followed the same guidelines. There is some extra stuff in with regards to loading customer and generating shipment. Also I used object manager to bypass error as this is used within console script. You don't need those parts. But hopefully you can follow what I did.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jun 12 at 17:05









          Dominic XigenDominic Xigen

          1,7601311




          1,7601311












          • Thank you so much @Dominic! I´m gonna give it a try

            – Gonzalo Gutiérrez
            Jun 12 at 20:55


















          • Thank you so much @Dominic! I´m gonna give it a try

            – Gonzalo Gutiérrez
            Jun 12 at 20:55

















          Thank you so much @Dominic! I´m gonna give it a try

          – Gonzalo Gutiérrez
          Jun 12 at 20:55






          Thank you so much @Dominic! I´m gonna give it a try

          – Gonzalo Gutiérrez
          Jun 12 at 20:55


















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Magento Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f278141%2funique-constraint-violation-found-when-creating-order-programmatically%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

          Circuit construction for execution of conditional statements using least significant bitHow are two different registers being used as “control”?How exactly is the stated composite state of the two registers being produced using the $R_zz$ controlled rotations?Efficiently performing controlled rotations in HHLWould this quantum algorithm implementation work?How to prepare a superposed states of odd integers from $1$ to $sqrtN$?Why is this implementation of the order finding algorithm not working?Circuit construction for Hamiltonian simulationHow can I invert the least significant bit of a certain term of a superposed state?Implementing an oracleImplementing a controlled sum operation

          Magento 2 “No Payment Methods” in Admin New OrderHow to integrate Paypal Express Checkout with the Magento APIMagento 1.5 - Sales > Order > edit order and shipping methods disappearAuto Invoice Check/Money Order Payment methodAdd more simple payment methods?Shipping methods not showingWhat should I do to change payment methods if changing the configuration has no effects?1.9 - No Payment Methods showing upMy Payment Methods not Showing for downloadable/virtual product when checkout?Magento2 API to access internal payment methodHow to call an existing payment methods in the registration form?