Magento代碼之訂單建立流程

Magento代碼之訂單建立流程

        直接看代碼吧。下面的代碼是如何經過程序建立一個完美訂單。

        <?php
        require_once 'app/Mage.php';
         
        Mage::app('default');//初始化程序,設置當前店鋪
         
        $store = Mage::app()->getStore('default');
        //經過電子郵件獲取用戶,固然也能夠不獲取,建立guest訂單
        $customer = Mage::getModel('customer/customer');
        $customer->setStore($store);
        $customer->loadByEmail('email_address@gmail.com');
         
        //初始化Quote,Magento的訂單是經過Quote來轉化過去的
        $quote = Mage::getModel('sales/quote');
        $quote->setStore($store);
        $quote->assignCustomer($customer);//若是有用戶則執行這個
         
        $product1 = Mage::getModel('catalog/product')->load(166); /* HTC Touch Diamond */
        $buyInfo1 = array('qty' => 1);
         
        $product2 = Mage::getModel('catalog/product')->load(18); /* Sony Ericsson W810i */
        $buyInfo2 = array('qty' => 3);
        //添加商品到Quote
        $quote->addProduct($product1, new Varien_Object($buyInfo1));
        $quote->addProduct($product2, new Varien_Object($buyInfo2));
        //設置帳單和收貨品地址
        $billingAddress = $quote->getBillingAddress()->addData($customer->getPrimaryBillingAddress());
        $shippingAddress = $quote->getShippingAddress()->addData($customer->getPrimaryShippingAddress());
        //設置配送和支付方式
        $shippingAddress->setCollectShippingRates(true)->collectShippingRates()
                        ->setShippingMethod('flatrate_flatrate')
                        ->setPaymentMethod('checkmo');
         
        $quote->getPayment()->importData(array('method' => 'checkmo'));
        //Quote計算運費
        $quote->collectTotals()->save();
        //將Quote轉化爲訂單
        $service = Mage::getModel('sales/service_quote', $quote);
        $service->submitAll();
        $order = $service->getOrder();
        /***至此訂單已經成功生成,下面是註冊付款信息***/
         
        $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
        $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
        $invoice->register();
         
        $transaction = Mage::getModel('core/resource_transaction')
                            ->addObject($invoice)
                            ->addObject($invoice->getOrder());
         
        $transaction->save();
        
        ?>php

相關文章
相關標籤/搜索