Skip to content

Instantly share code, notes, and snippets.

@godriccao
Forked from TheFrankman/create.php
Last active June 3, 2021 15:37
Show Gist options
  • Save godriccao/de490ca3f0ba96733b0a84c2928f0458 to your computer and use it in GitHub Desktop.
Save godriccao/de490ca3f0ba96733b0a84c2928f0458 to your computer and use it in GitHub Desktop.
Programatically create an order in Magento 2.1
<?php
/**
* @author Godric Cao
*/
namespace Vendor\Namespace\Model\Subscription\Order;
class Create
{
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\ProductFactory $productFactory,
\Magento\Quote\Model\QuoteManagement $quoteManagement,
\Magento\Customer\Model\CustomerFactory $customerFactory,
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
\Magento\Sales\Model\Service\OrderService $orderService,
\Magento\Quote\Api\CartRepositoryInterface $cartRepositoryInterface,
\Magento\Quote\Api\CartManagementInterface $cartManagementInterface,
\Magento\Quote\Model\Quote\Address\Rate $shippingRate
) {
$this->_storeManager = $storeManager;
$this->_productFactory = $productFactory;
$this->quoteManagement = $quoteManagement;
$this->customerFactory = $customerFactory;
$this->customerRepository = $customerRepository;
$this->orderService = $orderService;
$this->cartRepositoryInterface = $cartRepositoryInterface;
$this->cartManagementInterface = $cartManagementInterface;
$this->shippingRate = $shippingRate;
}
/**
* Create Order On Your Store
*
* Sample Test Data
*
* $orderData=[
* 'currency_id' => 'USD',
* 'email' => 'test@webkul.com', //buyer email id
* 'shipping_address' =>[
* 'firstname' => 'jhon', //address Details
* 'lastname' => 'Deo',
* 'street' => 'xxxxx',
* 'city' => 'xxxxx',
* 'country_id' => 'IN',
* 'region' => 'xxx',
* 'postcode' => '43244',
* 'telephone' => '52332',
* '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]
* ]
* ];
*
* @param array $orderData
* @return int $orderId
*
*/
public function createOrder($orderData) {
//init the store id and website id @todo pass from array
$store = $this->_storeManager->getStore();
$websiteId = $this->_storeManager->getStore()->getWebsiteId();
//init the customer
$customer=$this->customerFactory->create();
$customer->setWebsiteId($websiteId);
$customer->loadByEmail($orderData['email']);// load customet by email address
//check the customer
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();
}
//init the quote
$cart_id = $this->cartManagementInterface->createEmptyCart();
$cart = $this->cartRepogitoryInterface->get($cart_id);
$cart->setStore($store);
// if you have already buyer id then you can load customer directly
$customer= $this->customerRepository->getById($customer->getEntityId());
$cart->setCurrency();
$cart->assignCustomer($customer); //Assign quote to customer
//add items in quote
foreach($orderData['items'] as $item){
$product = $this->_productFactory->create()->load($item['product_id']);
$cart->addProduct(
$product,
intval($item['qty'])
);
}
//Set Address to quote @todo add section in order data for seperate billing and handle it
$cart->getBillingAddress()->addData($orderData['shipping_address']);
$cart->getShippingAddress()->addData($orderData['shipping_address']);
// Collect Rates and Set Shipping & Payment Method
$this->shippingRate
->setCode('freeshipping_freeshipping')
->getPrice(1);
$shippingAddress = $cart->getShippingAddress();
//@todo set in order data
$shippingAddress->setCollectShippingRates(true)
->collectShippingRates()
->setShippingMethod('flatrate_flatrate'); //shipping method
$cart->getShippingAddress()->addShippingRate($this->rate);
$cart->setPaymentMethod('checkmo'); //payment method
//@todo insert a variable to affect the invetory
$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 = $this->cartRepogitoryInterface->get($cart->getId());
$order_id = $this->cartManagementInterface->placeOrder($cart->getId());
return $order_id;
}
@chi07
Copy link

chi07 commented Nov 15, 2016

It's does not work with Table rate - Weight and Destination. Please give me the advice

@tricore-arpit
Copy link

Please note that there is a spelling mistake in cartRepogitoryInterface. Should be cartRepositoryInterface on line 89.

@creative-git
Copy link

creative-git commented Aug 25, 2017

shipment method is not getting saved . order created but :Shipping & Handling Information show : No shipping information available in the backend

@mgomma
Copy link

mgomma commented Jan 26, 2018

I got "message": "Notice: Array to string conversion in ......./Magento/Framework/DB/Adapter/Pdo/Mysql.php on line 2930

@esguhan
Copy link

esguhan commented Feb 2, 2018

It doesn't work for multiple order items. It takes only the last one from an array. But the calculation of quantity works properly.

@lucasqm
Copy link

lucasqm commented Aug 17, 2018

Thanks, you saved my life.

@sunil0372
Copy link

It is only add one product bur quanity are multiple

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment