Problem in Creating Custom Order Programmatically












0















I need to create a custom order programmatically to be used with a subscription program.




How can I call to this createCustomOrder function in the helper file
when Renew Subscription button is called?




<form method="post" action="https://mysite/placeSubscriptionOrder.php">   
<input type="submit" value="Renew Subscription">
</form> ';


Data for the custom order



$tempOrder=[
'currency_id' => 'USD',
'email' => 'ashan@gmail.com', //buyer email id
'shipping_address' =>[
'firstname' => 'John', //address Details
'lastname' => 'Doe',
'street' => '123 Demo',
'city' => 'California',
'country_id' => 'US',
'region' => 'xxx',
'postcode' => '10019',
'telephone' => '0123456789',
'fax' => '32423',
'save_in_address_book' => 1
],
'items'=> [ //array of product which order you want to create
['product_id'=>'1','qty'=>1],
['product_id'=>'2','qty'=>2]
]
];


Module Helper file to create custom order PlaceCustomerOrder.php



    <?php
namespace MyVendorModuleNameHelper;

class Data extends MagentoFrameworkAppHelperAbstractHelper
{
/**
* @param MagentoFrameworkAppHelperContext $context
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param MagentoCatalogModelProduct $product
* @param MagentoFrameworkDataFormFormKey $formKey $formkey,
* @param MagentoQuoteModelQuote $quote,
* @param MagentoCustomerModelCustomerFactory $customerFactory,
* @param MagentoSalesModelServiceOrderService $orderService,
*/
public function __construct(
MagentoFrameworkAppHelperContext $context,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoCatalogModelProduct $product,
MagentoFrameworkDataFormFormKey $formkey,
MagentoQuoteModelQuoteFactory $quote,
MagentoQuoteModelQuoteManagement $quoteManagement,
MagentoCustomerModelCustomerFactory $customerFactory,
MagentoCustomerApiCustomerRepositoryInterface $customerRepository,
MagentoSalesModelServiceOrderService $orderService
) {
$this->_storeManager = $storeManager;
$this->_product = $product;
$this->_formkey = $formkey;
$this->quote = $quote;
$this->quoteManagement = $quoteManagement;
$this->customerFactory = $customerFactory;
$this->customerRepository = $customerRepository;
$this->orderService = $orderService;
parent::__construct($context);
}

/**
* Create Order On Your Store
*
* @param array $orderData
* @return array
*
*/
public function createCustomOrder($orderData) {
$store=$this->_storeManager->getStore();
$websiteId = $this->_storeManager->getStore()->getWebsiteId();
$customer=$this->customerFactory->create();
$customer->setWebsiteId($websiteId);
$customer->loadByEmail($orderData['email']);// load customet by email address
263135
if(!$customer->getEntityId()){
//If not avilable then create this customer
$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(); //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->getById($customer->getEntityId());
$quote->setCurrency();
$quote->assignCustomer($customer); //Assign quote to customer

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

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

// Collect Rates and Set Shipping & Payment Method

$shippingAddress=$quote->getShippingAddress();
$shippingAddress->setCollectShippingRates(true)
->collectShippingRates()
->setShippingMethod('freeshipping_freeshipping'); //shipping method
$quote->setPaymentMethod('checkmo'); //payment method
$quote->setInventoryProcessed(false); //not effetc inventory
$quote->save(); //Now Save quote and your quote is ready

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

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

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

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

?>









share|improve this question





























    0















    I need to create a custom order programmatically to be used with a subscription program.




    How can I call to this createCustomOrder function in the helper file
    when Renew Subscription button is called?




    <form method="post" action="https://mysite/placeSubscriptionOrder.php">   
    <input type="submit" value="Renew Subscription">
    </form> ';


    Data for the custom order



    $tempOrder=[
    'currency_id' => 'USD',
    'email' => 'ashan@gmail.com', //buyer email id
    'shipping_address' =>[
    'firstname' => 'John', //address Details
    'lastname' => 'Doe',
    'street' => '123 Demo',
    'city' => 'California',
    'country_id' => 'US',
    'region' => 'xxx',
    'postcode' => '10019',
    'telephone' => '0123456789',
    'fax' => '32423',
    'save_in_address_book' => 1
    ],
    'items'=> [ //array of product which order you want to create
    ['product_id'=>'1','qty'=>1],
    ['product_id'=>'2','qty'=>2]
    ]
    ];


    Module Helper file to create custom order PlaceCustomerOrder.php



        <?php
    namespace MyVendorModuleNameHelper;

    class Data extends MagentoFrameworkAppHelperAbstractHelper
    {
    /**
    * @param MagentoFrameworkAppHelperContext $context
    * @param MagentoStoreModelStoreManagerInterface $storeManager
    * @param MagentoCatalogModelProduct $product
    * @param MagentoFrameworkDataFormFormKey $formKey $formkey,
    * @param MagentoQuoteModelQuote $quote,
    * @param MagentoCustomerModelCustomerFactory $customerFactory,
    * @param MagentoSalesModelServiceOrderService $orderService,
    */
    public function __construct(
    MagentoFrameworkAppHelperContext $context,
    MagentoStoreModelStoreManagerInterface $storeManager,
    MagentoCatalogModelProduct $product,
    MagentoFrameworkDataFormFormKey $formkey,
    MagentoQuoteModelQuoteFactory $quote,
    MagentoQuoteModelQuoteManagement $quoteManagement,
    MagentoCustomerModelCustomerFactory $customerFactory,
    MagentoCustomerApiCustomerRepositoryInterface $customerRepository,
    MagentoSalesModelServiceOrderService $orderService
    ) {
    $this->_storeManager = $storeManager;
    $this->_product = $product;
    $this->_formkey = $formkey;
    $this->quote = $quote;
    $this->quoteManagement = $quoteManagement;
    $this->customerFactory = $customerFactory;
    $this->customerRepository = $customerRepository;
    $this->orderService = $orderService;
    parent::__construct($context);
    }

    /**
    * Create Order On Your Store
    *
    * @param array $orderData
    * @return array
    *
    */
    public function createCustomOrder($orderData) {
    $store=$this->_storeManager->getStore();
    $websiteId = $this->_storeManager->getStore()->getWebsiteId();
    $customer=$this->customerFactory->create();
    $customer->setWebsiteId($websiteId);
    $customer->loadByEmail($orderData['email']);// load customet by email address
    263135
    if(!$customer->getEntityId()){
    //If not avilable then create this customer
    $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(); //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->getById($customer->getEntityId());
    $quote->setCurrency();
    $quote->assignCustomer($customer); //Assign quote to customer

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

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

    // Collect Rates and Set Shipping & Payment Method

    $shippingAddress=$quote->getShippingAddress();
    $shippingAddress->setCollectShippingRates(true)
    ->collectShippingRates()
    ->setShippingMethod('freeshipping_freeshipping'); //shipping method
    $quote->setPaymentMethod('checkmo'); //payment method
    $quote->setInventoryProcessed(false); //not effetc inventory
    $quote->save(); //Now Save quote and your quote is ready

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

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

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

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

    ?>









    share|improve this question



























      0












      0








      0








      I need to create a custom order programmatically to be used with a subscription program.




      How can I call to this createCustomOrder function in the helper file
      when Renew Subscription button is called?




      <form method="post" action="https://mysite/placeSubscriptionOrder.php">   
      <input type="submit" value="Renew Subscription">
      </form> ';


      Data for the custom order



      $tempOrder=[
      'currency_id' => 'USD',
      'email' => 'ashan@gmail.com', //buyer email id
      'shipping_address' =>[
      'firstname' => 'John', //address Details
      'lastname' => 'Doe',
      'street' => '123 Demo',
      'city' => 'California',
      'country_id' => 'US',
      'region' => 'xxx',
      'postcode' => '10019',
      'telephone' => '0123456789',
      'fax' => '32423',
      'save_in_address_book' => 1
      ],
      'items'=> [ //array of product which order you want to create
      ['product_id'=>'1','qty'=>1],
      ['product_id'=>'2','qty'=>2]
      ]
      ];


      Module Helper file to create custom order PlaceCustomerOrder.php



          <?php
      namespace MyVendorModuleNameHelper;

      class Data extends MagentoFrameworkAppHelperAbstractHelper
      {
      /**
      * @param MagentoFrameworkAppHelperContext $context
      * @param MagentoStoreModelStoreManagerInterface $storeManager
      * @param MagentoCatalogModelProduct $product
      * @param MagentoFrameworkDataFormFormKey $formKey $formkey,
      * @param MagentoQuoteModelQuote $quote,
      * @param MagentoCustomerModelCustomerFactory $customerFactory,
      * @param MagentoSalesModelServiceOrderService $orderService,
      */
      public function __construct(
      MagentoFrameworkAppHelperContext $context,
      MagentoStoreModelStoreManagerInterface $storeManager,
      MagentoCatalogModelProduct $product,
      MagentoFrameworkDataFormFormKey $formkey,
      MagentoQuoteModelQuoteFactory $quote,
      MagentoQuoteModelQuoteManagement $quoteManagement,
      MagentoCustomerModelCustomerFactory $customerFactory,
      MagentoCustomerApiCustomerRepositoryInterface $customerRepository,
      MagentoSalesModelServiceOrderService $orderService
      ) {
      $this->_storeManager = $storeManager;
      $this->_product = $product;
      $this->_formkey = $formkey;
      $this->quote = $quote;
      $this->quoteManagement = $quoteManagement;
      $this->customerFactory = $customerFactory;
      $this->customerRepository = $customerRepository;
      $this->orderService = $orderService;
      parent::__construct($context);
      }

      /**
      * Create Order On Your Store
      *
      * @param array $orderData
      * @return array
      *
      */
      public function createCustomOrder($orderData) {
      $store=$this->_storeManager->getStore();
      $websiteId = $this->_storeManager->getStore()->getWebsiteId();
      $customer=$this->customerFactory->create();
      $customer->setWebsiteId($websiteId);
      $customer->loadByEmail($orderData['email']);// load customet by email address
      263135
      if(!$customer->getEntityId()){
      //If not avilable then create this customer
      $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(); //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->getById($customer->getEntityId());
      $quote->setCurrency();
      $quote->assignCustomer($customer); //Assign quote to customer

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

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

      // Collect Rates and Set Shipping & Payment Method

      $shippingAddress=$quote->getShippingAddress();
      $shippingAddress->setCollectShippingRates(true)
      ->collectShippingRates()
      ->setShippingMethod('freeshipping_freeshipping'); //shipping method
      $quote->setPaymentMethod('checkmo'); //payment method
      $quote->setInventoryProcessed(false); //not effetc inventory
      $quote->save(); //Now Save quote and your quote is ready

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

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

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

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

      ?>









      share|improve this question
















      I need to create a custom order programmatically to be used with a subscription program.




      How can I call to this createCustomOrder function in the helper file
      when Renew Subscription button is called?




      <form method="post" action="https://mysite/placeSubscriptionOrder.php">   
      <input type="submit" value="Renew Subscription">
      </form> ';


      Data for the custom order



      $tempOrder=[
      'currency_id' => 'USD',
      'email' => 'ashan@gmail.com', //buyer email id
      'shipping_address' =>[
      'firstname' => 'John', //address Details
      'lastname' => 'Doe',
      'street' => '123 Demo',
      'city' => 'California',
      'country_id' => 'US',
      'region' => 'xxx',
      'postcode' => '10019',
      'telephone' => '0123456789',
      'fax' => '32423',
      'save_in_address_book' => 1
      ],
      'items'=> [ //array of product which order you want to create
      ['product_id'=>'1','qty'=>1],
      ['product_id'=>'2','qty'=>2]
      ]
      ];


      Module Helper file to create custom order PlaceCustomerOrder.php



          <?php
      namespace MyVendorModuleNameHelper;

      class Data extends MagentoFrameworkAppHelperAbstractHelper
      {
      /**
      * @param MagentoFrameworkAppHelperContext $context
      * @param MagentoStoreModelStoreManagerInterface $storeManager
      * @param MagentoCatalogModelProduct $product
      * @param MagentoFrameworkDataFormFormKey $formKey $formkey,
      * @param MagentoQuoteModelQuote $quote,
      * @param MagentoCustomerModelCustomerFactory $customerFactory,
      * @param MagentoSalesModelServiceOrderService $orderService,
      */
      public function __construct(
      MagentoFrameworkAppHelperContext $context,
      MagentoStoreModelStoreManagerInterface $storeManager,
      MagentoCatalogModelProduct $product,
      MagentoFrameworkDataFormFormKey $formkey,
      MagentoQuoteModelQuoteFactory $quote,
      MagentoQuoteModelQuoteManagement $quoteManagement,
      MagentoCustomerModelCustomerFactory $customerFactory,
      MagentoCustomerApiCustomerRepositoryInterface $customerRepository,
      MagentoSalesModelServiceOrderService $orderService
      ) {
      $this->_storeManager = $storeManager;
      $this->_product = $product;
      $this->_formkey = $formkey;
      $this->quote = $quote;
      $this->quoteManagement = $quoteManagement;
      $this->customerFactory = $customerFactory;
      $this->customerRepository = $customerRepository;
      $this->orderService = $orderService;
      parent::__construct($context);
      }

      /**
      * Create Order On Your Store
      *
      * @param array $orderData
      * @return array
      *
      */
      public function createCustomOrder($orderData) {
      $store=$this->_storeManager->getStore();
      $websiteId = $this->_storeManager->getStore()->getWebsiteId();
      $customer=$this->customerFactory->create();
      $customer->setWebsiteId($websiteId);
      $customer->loadByEmail($orderData['email']);// load customet by email address
      263135
      if(!$customer->getEntityId()){
      //If not avilable then create this customer
      $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(); //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->getById($customer->getEntityId());
      $quote->setCurrency();
      $quote->assignCustomer($customer); //Assign quote to customer

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

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

      // Collect Rates and Set Shipping & Payment Method

      $shippingAddress=$quote->getShippingAddress();
      $shippingAddress->setCollectShippingRates(true)
      ->collectShippingRates()
      ->setShippingMethod('freeshipping_freeshipping'); //shipping method
      $quote->setPaymentMethod('checkmo'); //payment method
      $quote->setInventoryProcessed(false); //not effetc inventory
      $quote->save(); //Now Save quote and your quote is ready

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

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

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

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

      ?>






      magento2 sales-order






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 5 mins ago









      Muhammad Hasham

      16310




      16310










      asked 17 mins ago









      ashanrashanr

      82




      82






















          0






          active

          oldest

          votes











          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%2f259931%2fproblem-in-creating-custom-order-programmatically%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          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%2f259931%2fproblem-in-creating-custom-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

          What other Star Trek series did the main TNG cast show up in?

          Berlina muro

          Berlina aerponto