有quote:
<?php
class Emily_Order_Model_orderCreate extends Mage_Core_Model_Abstract {
private $_storeId = '1';
private $_groupId = '1';
private $_sendConfirmation = '0';
private $orderData = array();
private $_product;
private $_sourceCustomer;
private $_sourceOrder;
public function setOrderInfo(Varien_Object $sourceOrder) {
$this->_sourceOrder = $sourceOrder;
$this->_sourceCustomer = Mage::getModel('customer/customer')->load($sourceOrder->getCustomerId());
//You can extract/refactor this if you have more than one product, etc.
$this->_product = Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('sku', 'HRFD')
->addAttributeToSelect('*')
->getFirstItem();
$this->_product2 = Mage::getModel('catalog/product')->load('38');
//Load full product data to product object
$this->_product->load($this->_product->getId());
$this->_orderAddress = $this->_sourceOrder->getBillingAddress();
$this->orderData = array(
'session' => array(
'customer_id' => $this->_sourceCustomer->getId(),
'store_id' => $this->_storeId,
),
'payment' => array(
'method' => 'checkmo',
),
'add_products' => array(
$this->_product->getId() => array('qty' => 1),
$this->_product2->getId() => array('qty' => 1),
),
'order' => array(
'currency' => 'USD',
'account' => array(
'group_id' => $this->_groupId,
'email' => $this->_sourceCustomer->getEmail()
),
'billing_address' => array(
'customer_address_id' => $this->_orderAddress->getId(),
'prefix' => '',
'firstname' => $this->_orderAddress->getFirstname(),
'middlename' => '',
'lastname' => $this->_orderAddress->getLastname(),
'suffix' => '',
'company' => '',
'street' => array($this->_orderAddress->getStreet(), ''),
'city' => $this->_orderAddress->getCity(),
'country_id' => $this->_orderAddress->getCountryId(),
'region' => '',
'region_id' => $this->_orderAddress->getRegionId(),
'postcode' => $this->_orderAddress->getPostcode(),
'telephone' => $this->_orderAddress->getTelephone(),
'fax' => '',
),
'shipping_address' => array(
'customer_address_id' => $this->_orderAddress->getId(),
'prefix' => '',
'firstname' => $this->_orderAddress->getFirstname(),
'middlename' => '',
'lastname' => $this->_orderAddress->getLastname(),
'suffix' => '',
'company' => '',
'street' => array($this->_orderAddress->getStreet(), ''),
'city' => $this->_orderAddress->getCity(),
'country_id' => $this->_orderAddress->getCountryId(),
'region' => '',
'region_id' => $this->_orderAddress->getRegionId(),
'postcode' => $this->_orderAddress->getPostcode(),
'telephone' => $this->_orderAddress->getTelephone(),
'fax' => '',
),
'shipping_method' => 'flatrate_flatrate',
'comment' => array(
'customer_note' => 'This order has been programmatically created via import script.',
),
'send_confirmation' => $this->_sendConfirmation
),
);
}
/**
* Retrieve order create model
*
* @return Mage_Adminhtml_Model_Sales_Order_Create
*/
protected function _getOrderCreateModel() {
return Mage::getSingleton('adminhtml/sales_order_create');
}
/**
* Retrieve session object
*
* @return Mage_Adminhtml_Model_Session_Quote
*/
protected function _getSession() {
return Mage::getSingleton('adminhtml/session_quote');
}
/**
* Initialize order creation session data
*
* @param array $data
* @return Mage_Adminhtml_Sales_Order_CreateController
*/
protected function _initSession($data) {
/* Get/identify customer */
if (!empty($data['customer_id'])) {
$this->_getSession()->setCustomerId((int) $data['customer_id']);
}
/* Get/identify store */
if (!empty($data['store_id'])) {
$this->_getSession()->setStoreId((int) $data['store_id']);
}
return $this;
}
/**
* Creates order
*/
public function create() {
$orderData = $this->orderData;
if (!empty($orderData)) {
$this->_initSession($orderData['session']);
try {
$this->_processQuote($orderData);
if (!empty($orderData['payment'])) {
$this->_getOrderCreateModel()->setPaymentData($orderData['payment']);
$this->_getOrderCreateModel()->getQuote()->getPayment()->addData($orderData['payment']);
}
$item1 = $this->_getOrderCreateModel()->getQuote()->getItemByProduct($this->_product);
$item1->addOption(new Varien_Object(
array(
'product' => $this->_product,
'code' => 'option_ids',
'value' => '96' /* Option id goes here. If more options, then comma separate */
)
));
$item1->addOption(new Varien_Object(
array(
'product' => $this->_product,
'code' => 'option_96',
'value' => 'Some value here'
)
));
$item2 = $this->_getOrderCreateModel()->getQuote()->getItemByProduct($this->_product2);
$item2->addOption(new Varien_Object(
array(
'product' => $this->_product2,
'code' => 'option_ids',
'value' => '94' /* Option id goes here. If more options, then comma separate */
)
));
$item2->addOption(new Varien_Object(
array(
'product' => $this->_product2,
'code' => 'option_94',
'value' => 'Some value here'
)
));
Mage::app()->getStore()->setConfig(Mage_Sales_Model_Order::XML_PATH_EMAIL_ENABLED, "0");
$_order = $this->_getOrderCreateModel()
->importPostData($orderData['order'])
->createOrder();
$this->_getSession()->clear();
Mage::unregister('rule_data');
return $_order;
} catch (Exception $e) {
var_dump($e);
Mage::log("Order save error...");
}
}
return null;
}
protected function _processQuote($data = array()) {
/* Saving order data */
if (!empty($data['order'])) {
$this->_getOrderCreateModel()->importPostData($data['order']);
}
$this->_getOrderCreateModel()->getBillingAddress();
$this->_getOrderCreateModel()->setShippingAsBilling(true);
/* Just like adding products from Magento admin grid */
if (!empty($data['add_products'])) {
$this->_getOrderCreateModel()->addProducts($data['add_products']);
}
/* Collect shipping rates */
$this->_getOrderCreateModel()->collectShippingRates();
/* Add payment data */
if (!empty($data['payment'])) {
$this->_getOrderCreateModel()->getQuote()->getPayment()->addData($data['payment']);
}
$this->_getOrderCreateModel()
->initRuleData()
->saveQuote();
if (!empty($data['payment'])) {
$this->_getOrderCreateModel()->getQuote()->getPayment()->addData($data['payment']);
}
return $this;
}
}
?>
注意$this->product和$this->product2. 及它们的options.一定要存在的product,customerID,product option也要填写正确的id号.不然validate过不去.
无quote:
$id = 41; // get Customer Id
$customer = Mage::getModel('customer/customer')->load($id);
$transaction = Mage::getModel('core/resource_transaction');
$storeId = $customer->getStoreId();
$reservedOrderId = Mage::getSingleton('eav/config')->getEntityType('order')->fetchNewIncrementId($storeId);
$order = Mage::getModel('sales/order')
->setIncrementId($reservedOrderId)
->setStoreId($storeId)
->setQuoteId(0)
->setGlobal_currency_code('INR')
->setBase_currency_code('INR')
->setStore_currency_code('INR')
->setOrder_currency_code('INR');
//Set your store currency USD or any other
// set Customer data
$order->setCustomer_email($customer->getEmail())
->setCustomerFirstname($customer->getFirstname())
->setCustomerLastname($customer->getLastname())
->setCustomerGroupId($customer->getGroupId())
->setCustomer_is_guest(0)
->setCustomer($customer);
// set Billing Address3
$billing = $customer->getDefaultBillingAddress();
$billingAddress = Mage::getModel('sales/order_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING)
->setCustomerId($customer->getId())
->setCustomerAddressId($customer->getDefaultBilling())
->setCustomer_address_id($billing->getEntityId())
->setPrefix($billing->getPrefix())
->setFirstname($billing->getFirstname())
->setMiddlename($billing->getMiddlename())
->setLastname($billing->getLastname())
->setSuffix($billing->getSuffix())
->setCompany($billing->getCompany())
->setStreet($billing->getStreet())
->setCity($billing->getCity())
->setCountry_id($billing->getCountryId())
->setRegion($billing->getRegion())
->setRegion_id($billing->getRegionId())
->setPostcode($billing->getPostcode())
->setTelephone($billing->getTelephone())
->setFax($billing->getFax());
$order->setBillingAddress($billingAddress);
$shipping = $customer->getDefaultShippingAddress();
$shippingAddress = Mage::getModel('sales/order_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING)
->setCustomerId($customer->getId())
->setCustomerAddressId($customer->getDefaultShipping())
->setCustomer_address_id($shipping->getEntityId())
->setPrefix($shipping->getPrefix())
->setFirstname($shipping->getFirstname())
->setMiddlename($shipping->getMiddlename())
->setLastname($shipping->getLastname())
->setSuffix($shipping->getSuffix())
->setCompany($shipping->getCompany())
->setStreet($shipping->getStreet())
->setCity($shipping->getCity())
->setCountry_id($shipping->getCountryId())
->setRegion($shipping->getRegion())
->setRegion_id($shipping->getRegionId())
->setPostcode($shipping->getPostcode())
->setTelephone($shipping->getTelephone())
->setFax($shipping->getFax());
$order->setShippingAddress($shippingAddress)
->setShipping_method('flatrate_flatrate');
/* ->setShippingDescription($this->getCarrierName('flatrate')); */
/* some error i am getting here need to solve further */
//you can set your payment method name here as per your need
$orderPayment = Mage::getModel('sales/order_payment')
->setStoreId($storeId)
->setCustomerPaymentId(0)
->setMethod('purchaseorder')
->setPo_number(' – ');
$order->setPayment($orderPayment);
// let say, we have 2 products
//check that your products exists
//need to add code for configurable products if any
$subTotal = 0;
$products = array(
'1' => array(
'qty' => 1
),
'2' => array(
'qty' => 1
)
);
foreach ($products as $productId => $product) {
$_product = Mage::getModel('catalog/product')->load($productId);
$rowTotal = $_product->getPrice() * $product['qty'];
$orderItem = Mage::getModel('sales/order_item')
->setStoreId($storeId)
->setQuoteItemId(0)
->setQuoteParentItemId(NULL)
->setProductId($productId)
->setProductType($_product->getTypeId())
->setQtyBackordered(NULL)
->setTotalQtyOrdered($product['rqty'])
->setQtyOrdered($product['qty'])
->setName($_product->getName())
->setSku($_product->getSku())
->setPrice($_product->getPrice())
->setBasePrice($_product->getPrice())
->setOriginalPrice($_product->getPrice())
->setRowTotal($rowTotal)
->setBaseRowTotal($rowTotal);
$subTotal += $rowTotal;
$order->addItem($orderItem);
}
$order->setSubtotal($subTotal)
->setBaseSubtotal($subTotal)
->setGrandTotal($subTotal)
->setBaseGrandTotal($subTotal);
$transaction->addObject($order);
$transaction->addCommitCallback(array($order, 'place'));
$transaction->addCommitCallback(array($order, 'save'));
$transaction->save();
无quote代码转自:http://pragneshkaria.com/programmatically-create-order-in-magento/
需要非常注意product和customer属性.如果出错,不会生成order.