programmaticlly Create Order in Magento2 with custom options in order


<?php

namespace Custom\Api\Controller\Index;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;


class Createbooking extends \Magento\Framework\App\Action\Action
{

/**
     * @var \Magento\Framework\App\Cache\TypeListInterface
     */
    protected $_cacheTypeList;

    /**
     * @var \Magento\Framework\App\Cache\StateInterface
     */
    protected $_cacheState;

    /**
     * @var \Magento\Framework\App\Cache\Frontend\Pool
     */
    protected $_cacheFrontendPool;

    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * @param Action\Context $context
     * @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList
     * @param \Magento\Framework\App\Cache\StateInterface $cacheState
     * @param \Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     */
   
    public function __construct(
       \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
        \Magento\Framework\App\Cache\StateInterface $cacheState,
        \Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
           \Magento\Framework\Data\Form\FormKey $formKey,
        PageFactory $resultPageFactory

    ) {
        parent::__construct($context);
        $this->_cacheTypeList = $cacheTypeList;
        $this->_cacheState = $cacheState;
        $this->_cacheFrontendPool = $cacheFrontendPool;
        $this->resultPageFactory = $resultPageFactory;
        $this->formKey = $formKey;
        $this->resultPageFactory = $resultPageFactory;
       
    }
  
    /**
     * Flush cache storage
     *
     */
    public function execute()
    {   
      $params = (array) json_decode(file_get_contents('php://input'), TRUE);
        
      // echo "<pre>";
       //print_r($params['paymentMethod']['method']);

         


//exit();
       if (!empty($params)) {
       
        $customerid=$params['categoryid'];
        $productid=$params['product_id'];
        $qty=$params['qty'];
        $price=$params['price'];
        $currency_id=$params['currency_id'];
        $email=$params['email'];
        $firstname=$params['firstname'];   
        $lastname=$params['lastname'];  

        
        $shipfirstname=$params['addressInformation']['shippingAddress']['firstname'];
        $shiplastname=$params['addressInformation']['shippingAddress']['lastname'];
        $shipstreet=$params['addressInformation']['shippingAddress']['street']['0']; 
        $shipcity=$params['addressInformation']['shippingAddress']['city']; 
        $shipstate_province=$params['addressInformation']['shippingAddress']['state_province'];
        $shipcountry_id=$params['addressInformation']['shippingAddress']['country_id']; 
        $shipregion=$params['addressInformation']['shippingAddress']['region']; 
        $shipregion_id=$params['addressInformation']['shippingAddress']['region_code'];
        $shippostcode= $params['addressInformation']['shippingAddress']['postcode'];
        $shiptelephone=$params['addressInformation']['shippingAddress']['telephone'];
        $shipfax=$params['addressInformation']['shippingAddress']['fax'];

       
        $booking_from=$params['booking_from'];
        $booking_till=$params['booking_till']; 

        $billfirstname=$params['addressInformation']['billingAddress']['firstname'];
        $billlastname=$params['addressInformation']['billingAddress']['lastname'];
        $billstreet=$params['addressInformation']['billingAddress']['street']['0']; 
        $billcity=$params['addressInformation']['billingAddress']['city']; 
        $billstate_province=$params['addressInformation']['billingAddress']['state_province'];
        $billcountry_id=$params['addressInformation']['billingAddress']['country_id']; 
        $billregion=$params['addressInformation']['billingAddress']['region']; 
        $billregion_id=$params['addressInformation']['billingAddress']['region_code'];
        $billpostcode= $params['addressInformation']['billingAddress']['postcode'];
        $billtelephone=$params['addressInformation']['billingAddress']['telephone']; 
        $billfax=$params['addressInformation']['billingAddress']['fax'];

         $shippingmethod=$params['addressInformation']['shipping_method_code'];
         $paymentmethod=$params['paymentMethod']['method'];



//exit();
          
          $orderData =[
            'product_id'=>$productid,
     'currency_id'  => $currency_id,
     'email'        => $email, //buyer email id
     'shipping_address' =>[
            'firstname'    => $shipfirstname, //shipping address Details
            'lastname'     => $shiplastname,
            'street' =>$shipstreet,
            'city' => $shipcity,
            'state/province'=>$shipstate_province,
            'country_id' => $shipcountry_id,
            'region' => $shipregion,
            'region_id'=>$shipregion_id,
            'postcode' => $shippostcode,
            'telephone' => $shiptelephone,
            'shipfax' => $shipfax,
            'save_in_address_book' => 1
                 ],
     'billing_address'=>[
            'firstname'=> $billfirstname, //billing address Details
            'lastname'=> $billlastname,
            'street' => $billstreet,
            'city' => $billcity,
            'state/province'=>$billstate_province,
            'country_id' => $billcountry_id,
            'region' => $billregion,
            'region_id'=>$billregion_id,
            'postcode' => $billpostcode,
            'telephone' => $billtelephone,
            'billfax' => $billfax,
            'save_in_address_book' => 1


     ],            
            'booking_from'=>$booking_from,
             'booking_till'=>$booking_till,
   'items'=> [ 
 //array of product which order you want to create
              ['product_id'=>$productid,'qty'=>$qty,'price'=>$price,$options = array(
                    array(
                        "sort_order"    => 1,
                        "title"         => "Field Option",
                        'label'         => "Booking From",
                        "price_type"    => "fixed",
                        "price"         => "",
                        "type"          => "field",
                        'value' => "9 February, 2018, 01:00 AM",
                        "is_require"    => 0
                    ),
                    array(
                        "sort_order"    => 1,
                        "title"         => "Field Option",
                        'label'         => "Booking Till",
                        "price_type"    => "fixed",
                        "price"         => "",
                        "type"          => "field",
                        'value' => "9 February, 2018, 01:00 AM",
                        "is_require"    => 0
                    )
                   
                ) ]
            ],
     'shippingmethod'=>$shippingmethod,       
      'paymentmethod'=>$paymentmethod
]; 
        }else{

                  
          $orderData =[
     'product_id'=>2114,
     'currency_id'  => 'USD',
     'email'        => 'johndoe@example.com', //buyer email id
     'shipping_address' =>[
            'firstname'    => 'John', //address Details
            'lastname'     => 'Deo',
            'street' => 'Main Street',
            'city' => 'Pheonix',
            'state/province'=>'new york',
            'country_id' => 'US',
            'region' => 'Arizona',
            'region_id'=>'1',
            'postcode' => '85001',
            'telephone' => '823322565',
            'fax' => '3245845623',
            'save_in_address_book' => 1
                 ],
      'billing_address' =>[
            'firstname'    => 'John', //address Details
            'lastname'     => 'Deo',
            'street' => 'Main Street',
            'city' => 'Pheonix',
            'state/province'=>'new york',
            'country_id' => 'US',
            'region' => 'Arizona',
            'region_id'=>'1',
            'postcode' => '85001',
            'telephone' => '823322565',
            'fax' => '3245845623',
            'save_in_address_book' => 1
                 ],           
             'booking_from'=>"9 February, 2018, 01:00 AM",
             'booking_till'=>"9 February, 2018, 01:00 PM",    
   'items'=> [ 
 //array of product which order you want to create
              ['product_id'=>'2114','qty'=>1,'price'=>200,'options'=>[[ 'label' => "Booking From",
                'value' => "9 February, 2018, 01:00 AM"],['label' => "Booking Till",
                'value' => "9 February, 2018, 01:00 PM"]]],
               ['product_id'=>'2114','qty'=>1,'price'=>200 ]
              
            ],
    'shippingmethod'=>"freeshipping_freeshipping",       
      'paymentmethod'=>"checkmo"        

]; 
}
    
  
            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $product = $objectManager->get('Magento\Catalog\Model\Product');
            $storeManager=$objectManager->get('Magento\Store\Model\StoreManagerInterface');
            $formkey=$objectManager->get('Magento\Framework\Data\Form\FormKey');
            $quote=$objectManager->get('Magento\Quote\Model\QuoteFactory');
            $quoteManagement=$objectManager->create('Magento\Quote\Model\QuoteManagement');
            $customerFactory=$objectManager->get('Magento\Customer\Model\CustomerFactory');
            $customerRepository=$objectManager->get('Magento\Customer\Api\CustomerRepositoryInterface');
            $orderService=$objectManager->get('Magento\Sales\Model\Service\OrderService');
            $cartManagementInterface=  $objectManager->get('Magento\Quote\Api\CartManagementInterface');  
            $cartRepositoryInterface=$objectManager->get('Magento\Quote\Api\CartRepositoryInterface'); 
            $ordermodel=$objectManager->get('Magento\Sales\Model\Order'); 
            $observer=$objectManager->get('Magento\Framework\Event\Observer'); 
            $productFactory=$objectManager->get('Magento\Catalog\Model\ProductFactory');
            $rate=$objectManager->get('Magento\Quote\Model\Quote\Address\Rate');
            $orderRepository=$objectManager->get('Magento\Sales\Api\OrderRepositoryInterface');

           
            //init the store id and website id
            $store=$storeManager->getStore();
            $websiteId = $storeManager->getStore()->getWebsiteId();
             
            //init the customer
            $customer = $customerFactory->create();
            $customer->setWebsiteId($websiteId);
            $customer->loadByEmail($orderData['email']);// load customer by email address
           
            //check the customer
            if (!$customer->getEntityId()) {

                //If not available 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();
            }
           
            //init the quote
            $cart_id = $cartManagementInterface->createEmptyCart();
            $cart = $cartRepositoryInterface->get($cart_id);

            $cart->setStore($store);
            
            // if you have already buyer id then you can load customer directly
            $customer = $customerRepository->getById($customer->getEntityId());
            $cart->setCurrency();
            $cart->assignCustomer($customer); //Assign quote to customer
             
            $_productModel = $productFactory->create();
            //add items in quote
            foreach ($orderData['items'] as $item) {
                $product = $_productModel->load($item['product_id']);
                  $product->setPrice($item['price']);

                    $additionalOptions = [];
                    $additionalOptions[0] = array(
                        'label' => "Booking From",
                        'value' => $orderData['booking_from'],
                    );
                    $additionalOptions[1] = array(
                        'label' => "Booking Till",
                        'value' => $orderData['booking_till'],
                    );
                 $product->addCustomOption('additional_options',serialize($additionalOptions));
                 
             /*    $customOptions = $objectManager->get('Magento\Catalog\Model\Product\Option')->getProductOptionCollection($product);
                  
                  echo "<pre>";
                  print_r($customOptions->getData());


                  exit();*/


                   try {
                    // print_r($product); die();
                    $params = array('product' => $item['product_id'], 'qty' => $item['qty']);
                    if (array_key_exists('options', $item) && $item['options']) {
                        $params['options'] = json_decode(json_encode($item['options']), True);
                    }
                    if ($product->getTypeId() == 'configurable') {
                        $params['super_attribute'] = $item['super_attribute'];
                    } elseif ($product->getTypeId() == 'bundle') {
                        $params['bundle_option'] = $item['bundle_option'];
                        $params['bundle_option_qty'] = $item['bundle_option_qty'];
                    } elseif ($product->getTypeId() == 'grouped') {
                        $params['super_group'] = $item['super_group'];
                    }



                    $objParam = new \Magento\Framework\DataObject();
                    $objParam->setData($params);
                     //print_r($objParam); die();
                    $cart->addProduct($product, $objParam);

                } catch (Exception $e) {
                    $response[$item['product_id']]= $e->getMessage();
                }
            }
          

      /*      echo "<pre>";
            print_r($cart->getData());

            exit();*/
            //Set Address to quote
            $cart->getBillingAddress()->addData($orderData['billing_address']);
            $cart->getShippingAddress()->addData($orderData['shipping_address']);
            
            // Collect Rates and Set Shipping & Payment Method
            $rate->setCode($orderData['shippingmethod'])
                ->getPrice(1);

            $shippingAddress = $cart->getShippingAddress();
           
            $shippingAddress->setCollectShippingRates(true)
                ->collectShippingRates()
                ->setShippingMethod($orderData['shippingmethod']); //shipping method
            $cart->getShippingAddress()->addShippingRate($rate);
     
            $cart->setPaymentMethod($orderData['paymentmethod']); //payment method

            $cart->setInventoryProcessed(false);

            // Set sales order payment
            $cart->getPayment()->importData(['method' => 'checkmo']);
            
            // Collect total and saeve
            $cart->collectTotals();

            // Submit the quote and create the order
            $cart->save();
            $cart = $cartRepositoryInterface->get($cart->getId());
           
            
        /*    echo "<pre>";
            print_r($cart->getId());
            exit();*/



            try{

                $order_id = $cartManagementInterface->placeOrder($cart->getId());
                if(isset($order_id) && !empty($order_id)) {
                    $order = $orderRepository->get($order_id);
                    //$this->deleteQuoteItems(); //Delete cart items
                    $response['success'] = TRUE;
           echo "Ordered placed OrderId".$response['success_data']['increment_id'] = $order->getIncrementId();
                }
            } catch (Exception $e) {
                $response['error_msg']=$e->getMessage();
            }
        
         















    }
}

Comments

Popular posts from this blog

Through Postman Api send data through JSON and create simple product in Magento2

Getting product Image in PHTML in Magento2