Magento 2 – Create Order Programmatically Without Payment

magento2orderspayment-methods

I'm going to create an order programmatically without a payment. But it requires to set a valid payment method when I run the following code. Is there any way to skip it?

    $quote = $this->_quoteFactory->create();
    $quote->setStore($store);
    $quote->setCurrency($store->getCurrentCurrency()->getDataModel());
    $quote->assignCustomer($customer->getDataModel());
    $quote->addProduct($product);
    $quote->setPaymentMethod('checkmo'); 
    $quote->save();
    $order = $this->_quoteManagement->submit($quote);

Best Answer

As far as I know, in Magento 2.0.2 - 2.1 version, we cannot create an order without any payment methods.

Magento sets payment for order: vendor/magento/module-quote/Model/QuoteManagement.php

$order->setPayment($this->quotePaymentToOrderPayment->convert($quote->getPayment()));

Convert payment from quote object:

vendor/magento/module-quote/Model/Quote/Payment/ToOrderPayment.php

 $orderPayment->setAdditionalInformation(
            array_merge(
                $object->getAdditionalInformation(),
                [Substitution::INFO_KEY_TITLE => $object->getMethodInstance()->getTitle()]
            )
        );

And then getting method instance:

vendor/magento/module-payment/Model/Info.php

  public function getMethodInstance()
  {
        if (!$this->hasMethodInstance()) {
            if (!$this->getMethod()) {
                throw new \Magento\Framework\Exception\LocalizedException(
                    __('The payment method you requested is not available.')
                );
            }

            try {
                $instance = $this->_paymentData->getMethodInstance($this->getMethod());
            } catch (\UnexpectedValueException $e) {
                $instance = $this->_paymentData->getMethodInstance(Method\Substitution::CODE);
            }

            $instance->setInfoInstance($this);
            $this->setMethodInstance($instance);
        }

        return $this->_getData('method_instance');
  }

In cases, Magento will check the available payment methods. If it doesn't have any payment methods, it will throw exceptions.

A Substitution payment method is assigned if non-existing payments: vendor/magento/module-payment/Model/Method/Substitution.php

Related Topic