0

I want to create order from quote programmatically without submit quote.

Because if customer redirect to failure page then we have one button like Make payment which redirect to customer on checkout page and this we want all data which customer filled up last time.

Please help me how to create order from quote without submit quote programmatically?

0

you can create quote and order with the below content:

$tempOrder=[
     'currency_id'  => 'USD',
     'email'        => 'helloworld@oscp.com', //buyer email id
     'shipping_address' =>[
            'firstname'    => 'John', //address Details
            'lastname'     => 'Doe',
                    'street' => '123 Demo',
                    'city' => 'oscp',
            '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]
            ]
];

Continuing to declare the order in the module helper file by the following function:

<?php
namespace OSCP\ModuleName\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
     /**
    * @param Magento\Framework\App\Helper\Context $context
    * @param Magento\Store\Model\StoreManagerInterface $storeManager
    * @param Magento\Catalog\Model\Product $product
    * @param Magento\Framework\Data\Form\FormKey $formKey $formkey,
    * @param Magento\Quote\Model\Quote $quote,
    * @param Magento\Customer\Model\CustomerFactory $customerFactory,
    * @param Magento\Sales\Model\Service\OrderService $orderService,
    */
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Catalog\Model\Product $product,
        \Magento\Framework\Data\Form\FormKey $formkey,
        \Magento\Quote\Model\QuoteFactory $quote,
        \Magento\Quote\Model\QuoteManagement $quoteManagement,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
        \Magento\Sales\Model\Service\OrderService $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 createOscpOrder($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;
    }
}

?>

When you have done the above instruction,

congratulate you have created Magento 2 orders programmatically!

0

You can use Magento 2 API to create order programmatically:

<?php
    $access_token = '********************';

    $url = 'http://magento2.local/index.php/rest/V1/guest-carts/';

    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 
         'Authorization: Bearer ' . $access_token));

    $result = curl_exec($ch);

    $cartId = str_replace('"', '', $result);



    //Get Quote Id and Item Id
    $body = json_encode(['cartItem' => ['quote_id' => $cartId, 'qty' => 1, 'sku' => '24-MB04']]);

    $url = 'http://magento2.local/index.php/rest/V1/guest-carts/'. $cartId . '/items';

    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer ' . $access_token));

    $result = curl_exec($ch);

    $obj = json_decode($result);

    var_dump($obj);

   $body = json_encode([ 'addressInformation' =>[
     'shippingAddress' => [
        "country_id" => 'US',
         "street" =>[
            "123 Main Str"
         ],
       "company" => "Company",
       "telephone" => "123456",
       "postcode" => "91000",
       "city" => "El Monten",
       "firstname" => "Guo",
       "lastname" => "Jing",
       "region_id" => "12",
       "region" => "California",
       "email" => "dummy@example.com",
       "sameAsBilling" => 1
     ],
       "billingAddress" => [
       "country_id" => 'US',
       "street" =>[
            "123 Main Str"
       ],
       "company" => "Company",
       "telephone" => "123456",
       "postcode" => "91000",
       "city" => "El Monten",
       "firstname" => "Guo",
       "lastname" => "Jing",
       "region_id" => "12",
       "region" => "California",
       "email" => "dummy@example.com",
     ],
     "shipping_method_code" => "flatrate",
     "shipping_carrier_code" => "flatrate" 
    ]
]);

$url = 'http://magento2.local/index.php/rest/V1/guest-carts/'. $cartId . '/shipping-information';

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer ' . $access_token));

$result = curl_exec($ch);

var_dump($result);

$body = json_encode([
   "paymentMethod" => [ 
       "method" => "checkmo"
   ]
]);
$url = 'http://magento2.local/index.php/rest/V1/guest-carts/'. $cartId . '/order';

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer ' . $access_token));

$result = curl_exec($ch);

var_dump($result);

curl_close($ch);

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.