# 编程方式创建订单

**URL:** https://forum.magentochina.org/t/%7F%E7%BC%96%E7%A8%8B%E6%96%B9%E5%BC%8F%E5%88%9B%E5%BB%BA%E8%AE%A2%E5%8D%95/803
**Category:** Magento 2.X
**Tags:** magento2, 教程
**Created:** [2020 年8 月 20 日 09:35 UTC](https://forum.magentochina.org/t/%7F%E7%BC%96%E7%A8%8B%E6%96%B9%E5%BC%8F%E5%88%9B%E5%BB%BA%E8%AE%A2%E5%8D%95/803 "2020-08-20T09:35:31Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### 作者： ![Vicky](https://forum.magentochina.org/letter_avatar_proxy/v4/letter/v/b19c9b/32.png) [@Vicky](https://forum.magentochina.org/u/Vicky)
#### 发布日期： [2020 年8 月 20 日 09:35 UTC](https://forum.magentochina.org/t/%7F%E7%BC%96%E7%A8%8B%E6%96%B9%E5%BC%8F%E5%88%9B%E5%BB%BA%E8%AE%A2%E5%8D%95/803/1 "2020-08-20T09:35:31Z")

</div>

这篇关于 Magento 2 以编程方式创建订单的教程对于开发人员来说是非常有用的。为什么这么说呢？因为这篇教程会教您通过使用 Magento 2 控制台以编程方式创建大量的 Magento 2 订单，用来替代费时的手工操作。但是，在开始创建订单的同时，同时也需要创建报价单（quote）。

### 如何以编程方式创建 Magento 2 订单

现在，您可以使用以下内容创建报价单（quote）和订单：

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

```

通过以下函数在模块的 helper 文件中继续声明订单：

```auto
<?php
namespace YourNameSpace\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 createMageOrder($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;
    }
}
 
?>

```

完成上述说明后，祝贺您已经用编程方式创建了 Magento 2 的订单！

## 本教程翻译自Mageplaza模块开发系列，其他内容请点击下面链接:

> [@Magento2模块开发中文教程索引](https://forum.magentochina.org/t/magento2%E6%A8%A1%E5%9D%97%E5%BC%80%E5%8F%91%E4%B8%AD%E6%96%87%E6%95%99%E7%A8%8B%E7%B4%A2%E5%BC%95/36):
>
> 本文翻译自mageplaza的Magento2模块开发教程,而且正在翻译中. 翻译也是非常好的学习方式，希望下列表中还有我们没有翻译，而你又想分享的内容,请发表文章之后，在下面附上地址。 如果觉得本站翻译得内容对您有帮助，又没有时间帮助翻译回馈社区.请打赏我们，您的支持是我们的动力: 转载说明:非常欢迎转载，但是必须保证文章的完整性并附上原文地址和翻译原文的地址，保证阅读者不会产生歧义. 目录索引: 索 引 中 文 原 文 1 [Magento2如何创建模块](https://forum.magentochina.org/t/Magento-2%E5%A6%82%E4%BD%95%E5%88%9B%E5%BB%BA%E6%A8%A1%E5%9D%97%E6%95%99%E7%A8%8B/38)[How to Create Module in Magento 2](https://www.mageplaza.com/kb/how-create-hello-world-module-magento-2.html) 2 [控制器详解](https://forum.magentochina.org/t/Magento-2%E6%8E%A7%E5%88%B6%E5%99%A8%E8%AF%A6%E8%A7%A3%E6%95%99%E7%A8%8B/39)[Create Controllers](https://www.mageplaza.com/magento-2-module-development/how-to-create-controllers-magento-2.html) 3 [CRUD 模型](https://forum.magentochina.org/t/Magento2-CRUD%E6%A8%A1%E5%9E%8B%E8%B5%84%E6%BA%90%E9%9B%86%E5%90%88%E5%B7%A5%E5%8E%82%E5%AF%B9%E8%B1%A1%E8%AF%A6%E8%A7%A3%E6%95%99%E7%A8%8B/43)[CRUD Models](https://www.mageplaza.com/magento-2-module-development/how-to-create-crud-model-magento-2.html) 4 [视图层:块,布局和模板](https://forum.magentochina.org/t/%E8%A7%86%E5%9B%BE%E5%B1%82%E5%9D%97%E5%B8%83%E5%B1%80%E5%92%8C%E6%A8%A1%E6%9D%BF%E6%A8%A1%E6%9D%BF%E6%95%99%E7%A8%8B/50/1)[View: Block, Layouts and templates](https://www.mageplaza.com/magento-2-module-development/view-block-layout-template-magento-2.html) 5 [配置system.xml](https://forum.magentochina.org/t/%E5%A6%82%E4%BD%95%E5%88%9B%E5%BB%BA%E7%B3%BB%E7%BB%9F%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6systemxml/55)[Configuration - System.xm…](https://www.mageplaza.com/magento-2-module-development/create-system-xml-configuration-magento-2.html)
