0

I am trying to create an order programatically. This is my code so far:

<?php

// Init magento base class
require_once 'app/Mage.php';
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

// Dummy data source
$settings   = array
(
    'WebsiteId' => 2,
    'StoreId' => 4,
    'ShippingMethod' => 'icw_shipping',
    'PaymentMethod' => 'icw_payment'
);
$jsonOrderData = '{"DiscountAmount":0, "DiscountReason":"", "STPointsUsed": 0, "STPointsEarned": 0,"CustomerId":17557,"SendConfirmation":true,"BasketData":[{"ProductId":18844,"Price":8.88,"Qty":1}],"ShippingMethod":"Flat Rate","DeliveryDate":"21/01/2016","SalesRep":"latheesan","PaymentMethod":"PayPal Here","PPHPaymentType":"CreditCard","PPHInvoiceId":"INV2-AHWG-SQHP-QMLT-1234","PPHTxId":"111-22-3333","ShippingAmount":15}';

//
// Test
//
echo '<pre>';
try
{
    // Init
    $orderCreator = new Ordercreator(
        $settings,
        $jsonOrderData
    );

    // Create order
    print_r($orderCreator->create());

    // Clean-up
    $orderCreator = null;
}
catch (Exception $ex)
{
    echo 'Failed to create order: '. $ex->getMessage() .' @ '. basename($ex->getFile()) .':'. $ex->getLine();
}
echo '</pre>';
//
// Test
//

/**
 * Helper class
 */
class Ordercreator
{
    // Class properties
    private $_settings        = array();
    private $_orderData       = array();
    private $_customer        = null;
    private $_quote           = null;
    private $_salesOrder      = null;

    // Class constructor
    function __construct(array $settings, string $jsonOrderData)
    {
        // Remember settings
        $this->_settings = $settings;

        // Parse sales order data
        $this->parseSalesOrderData($jsonOrderData);

        // Load order sales order customer
        $this->loadSalesOrderCustomer();

        // Initialise a new sales order quote
        $this->initSalesOrderQuote();
    }

    // Main method to initialise the order creation process
    function create()
    {
        // Add order lines to sales order quote
        $this->addOrderLinesToQuote();

        // Set shipping & payment method on quote
        $this->_quote
            ->getShippingAddress()
            ->setCollectShippingRates(true)
            ->collectShippingRates()
            ->setShippingMethod($this->_settings['ShippingMethod'])
            ->setPaymentMethod($this->_settings['PaymentMethod']);

        // Import additional payment data
        $this->_quote
            ->getPayment()
            ->importData(array(
                'method'          => $this->_settings['PaymentMethod'],
                'additional_data' => $this->_orderData->PaymentMethod 
            ));

        // Save quote and convert it to a real sales order
        $this->_quote
            ->collectTotals()
            ->save();
        $service = Mage::getModel('sales/service_quote', $quote);
        $service->submitAll();
        $this->_salesOrder = $service->getOrder();

        // Update custom sales order attributes
        $this->updateSalesOrderAttributes();

        // Parse result data
        $resultData = $this->_salesOrder->getData();

        // Clean-up
        $service                = null;
        $this->_settings        = null;
        $this->_orderData       = null;
        $this->_customer        = null;
        $this->_quote           = null;
        $this->_salesOrder      = null;

        // Success
        return $resultData;
    }

    // Method to parse sales order data
    protected function parseSalesOrderData($jsonOrderData)
    {
        $this->_orderData = @json_decode($jsonOrderData);
        if (!$this->_orderData)
            throw new Exception('Invalid order data');
    }

    // Method to load order customer
    protected function loadSalesOrderCustomer()
    {
        $this->_customer = Mage::getModel('customer/customer');
        $this->_customer->setWebsiteId($this->_settings['WebsiteId']);
        $this->_customer->load($this->_orderData->CustomerId);
        if (!$this->_customer->getId())
            throw new Exception('Invalid customer id '. $this->_orderData->CustomerId);
    }

    // Method to initialise a new sales order quote
    protected function initSalesOrderQuote()
    {
        // Create a new quote
        $this->_quote = Mage::getModel('sales/quote');
        $this->_quote->setStoreId($this->_settings['StoreId']);
        $this->_quote->setWebsiteId($this->_settings['WebsiteId']);

        // Validate customer's default address data
        if (!$this->_customer->getPrimaryBillingAddress())
            throw new Exception('Customer does not have a default billing address');
        if (!$this->_customer->getPrimaryShippingAddress())
            throw new Exception('Customer does not have a default shipping address');

        // Assign customer to the new quote
        $this->_quote->assignCustomer($this->_customer);

        // Set quote's billing & shipping address
        $this->_quote->getBillingAddress()->addData(
            $this->_customer->getPrimaryBillingAddress()
        );
        $this->_quote->getShippingAddress()->addData(
            $this->_customer->getPrimaryShippingAddress()
        );
    }

    // Method to add order lines to sales order quote
    protected function addOrderLinesToQuote()
    {
        // Validate basket data
        if (!sizeof($this->_orderData->BasketData))
            throw new Exception('Basket data is empty');

        // Add basket data to sales order quote
        foreach ($this->_orderData->BasketData as $orderLine)
        {
            // Load product
            $product = Mage::getModel('catalog/product');
            $product->load($orderLine->ProductId);
            if (!$product || !$product->getId())
                throw new Exception('Product with id #'. $orderLine->ProductId .' does not exists');

            // Add product to sales order quote
            $this->_quote->addProduct($product, new Varien_Object(array(
                'price' => $orderLine->Price,
                'qty' => $orderLine->Qty
            )));
        }
    }

    // Method to update sales order attributes
    protected function updateSalesOrderAttributes()
    {
        $this->_salesOrder
            ->setSalesRep($this->_orderData->SalesRep)
            ->setDeliveryDate($this->_orderData->DeliveryDate)
            ->setPphPaymentType($this->_orderData->PPHPaymentType)
            ->setPphInvoiceId($this->_orderData->PPHInvoiceId)
            ->setPphTxId($this->_orderData->PPHTxId)
            ->save();
    }
}

When I execute the above, I get the following error:

Fatal error: Call to a member function isVirtual() on null in /home/www-data/test.domain.com/public_html/app/code/core/Mage/Sales/Model/Service/Quote.php on line 292

Any ideas what this is about?

1

Replace

$service = Mage::getModel('sales/service_quote', $quote);

with

$service = Mage::getModel('sales/service_quote', $this->_quote);

in the Ordercreator::create method.
the problem is that $quote is not defined anywhere.

  • I am getting another error Failed to create order: Please specify a shipping method. @ Mage.php:594 but I am setting the shipping method. Should I post this as a new question? – Latheesan Feb 10 '16 at 16:15
  • Yes please. New question. – Marius Feb 10 '16 at 18:23
  • ok done - magento.stackexchange.com/questions/101322/… – Latheesan Feb 11 '16 at 10:53

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.