Magento以编程方式为可配置产品创建订单


magento programmatically create order for configurable product

我使用自定义脚本创建订单,它适用于没有自定义属性的简单产品。

现在我想为可配置的产品创建一个订单,就像产品价格从原始价格变化到不同的产品属性选择。

我有一个我要求的产品的例子,我已经安装了magento 1.7.0.2与样本数据有一个产品[t恤]与产品id为126,其原价是13.5,它是可配置的产品。

在商品详情页面,通过选择[Size:Medium] &[Color:Green] to 18.75.

在我的情况下,我把所有的信息发送到我的网站。

在我的网站上,我得到这个产品的SKU为'zol_g_m'与特定数量。现在我将其信息发送到magento商店以创建订单,但我在magento商店上的脚本将其视为简单产品并为其创建订单,价格为13.5而不是18.75

我的脚本基于两个函数,像这样

    public function PrepareOrder($params, $paymentData, array $shippingAddress, array $billingAddress, $shippingMethod, $couponCode = null) 
{
    require_once 'app/Mage.php';
    $app = Mage::app();
    $req_result = array();
    Mage::register('isSecureArea', true);
    $customerModel = Mage::getModel('customer/customer');
    $customerModel->setWebsiteId(Mage::app()->getWebsite()->getId());
    $customerObj = $customerModel->loadByEmail('abc@hotmail.com');  //with customer email
    $storeId=$customerObj->getStoreId();
    $quoteObj=Mage::getModel('sales/quote')->assignCustomer($customerObj); //sets ship/bill address
    $storeObj=$quoteObj->getStore()->load($storeId);
    $quoteObj->setStore($storeObj);
    $product_id = Mage::getModel('catalog/product')->getIdBySku('zol_g_med');
    $productModel=Mage::getModel('catalog/product');
    $productObj=$productModel->load(129);
    $productObj->setSkipCheckRequiredOption(true); 
    $quoteItem=Mage::getModel('sales/quote_item')->setProduct($productObj);
    $quoteItem->setQuote($quoteObj);
    $quoteItem->setQty($product_qty);
    $quoteObj->addItem($quoteItem);
    $productObj->unsSkipCheckRequiredOption(); 
    $quoteItem->checkData();                            
    $quoteObj->getPayment()->importData(array('method' => 'ccsave', 
    'cc_owner' => $paymentData['cc_owner'],
    'cc_type' => $paymentData['cc_type'],
    'cc_number' => $paymentData['cc_number'],
    'cc_exp_month' => $paymentData['cc_exp_month'],
    'cc_exp_year' => $paymentData['cc_exp_year'],
    'cc_cid' => $paymentData['cc_cid']));
    // addresses
    $quoteShippingAddress = new Mage_Sales_Model_Quote_Address();
    $quoteShippingAddress->setData($shippingAddress);
    $quoteBillingAddress = new Mage_Sales_Model_Quote_Address();
    $quoteBillingAddress->setData($billingAddress);
    $quoteObj->setShippingAddress($quoteShippingAddress);
    $quoteObj->setBillingAddress($quoteBillingAddress);
    // coupon code
    $quoteObj->getShippingAddress()->setShipping_method($shippingMethod)->setShippingDescription($shippingMethod);   
    $quoteObj->getShippingAddress()->setCollectShippingRates(true);   //
    $quoteObj->getShippingAddress()->collectShippingRates();   //
    $quoteObj -> addMessage('Auto Order Code');   //after separately            
    $quoteObj->setTotalsCollectedFlag(false);
    $quoteObj->getShippingAddress()->unsetData('cached_items_all');
    $quoteObj->getShippingAddress()->unsetData('cached_items_nominal');
    $quoteObj->getShippingAddress()->unsetData('cached_items_nonnominal');
    $quoteObj->collectTotals();
    //end shipping charges block
    $quoteObj->setIsActive(0);     //if it is commented the shopping cart has last order items against customer logged in, also the order is displayed in my account block in frontend
    $quoteObj->save();
    $quoteId=$quoteObj->getId();
    return $quoteId;
}   

    public function createOrderCustom($quoteId,$cartData) 
{
    $status_arr = array();
    $quoteObj = Mage::getModel('sales/quote')->load($quoteId); // Mage_Sales_Model_Quote
    $items = $quoteObj->getAllItems();
    $quoteObj->reserveOrderId();        
    // convert quote to order
    $convertQuoteObj = Mage::getSingleton('sales/convert_quote');
    $orderObj = $convertQuoteObj->addressToOrder($quoteObj->getShippingAddress());      
    // convert quote addresses
    $orderObj->setBillingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getBillingAddress()));
    $orderObj->setShippingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getShippingAddress()));        
    // set payment options
    $orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quoteObj->getPayment()));        
    // convert quote items
    foreach ($items as $item) {
        // @var $item Mage_Sales_Model_Quote_Item
        $item->setOriginalPrice($item->getProduct()->getPrice());
        $orderItem = $convertQuoteObj->itemToOrderItem($item);          
    //custom block of code to add/show product attributes/optinns, ***STAR FROM HERE...............................................//
    $existentOptions['additional_options'] = array();
    $current_product_id = '';
    $current_product_id =  $item->getProductId();
    foreach($cartData as $part){
        $productIdBySkuManual = Mage::getModel('catalog/product')->getIdBySku($part['product_sku']);
            if(($current_product_id==$productIdBySkuManual) && isset($part['attributes']) && sizeof($part['attributes'])>0){
                if($part['attributes']['attribute']['label']!='' && $part['attributes']['attribute']['value']!=''){ 
                        $existentOptions['additional_options'][] = array(
                            'label' => $part['attributes']['attribute']['label'],
                            'value' => $part['attributes']['attribute']['value'],
                            'print_value' => $part['attributes']['attribute']['print_value']
                        );
                }else{
                    foreach($part['attributes']['attribute'] as $ic_product_options){   
                        $existentOptions['additional_options'][] = array(
                            'label' => $ic_product_options['label'],
                            'value' => $ic_product_options['value'],
                            'print_value' => $ic_product_options['print_value']
                        );
                    }   
                }
            }
    }       
    $orderItem->setProductOptions($existentOptions);
    $existentOptions['additional_options']='';                  
    if ($productOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct())) {
//                $productOptions['info_buyRequest']['options'] = prepareOptionsForRequest($item);
        $options = $productOptions;
    }
    if ($addOptions = $item->getOptionByCode('additional_options')) {
        $options['additional_options'] = unserialize($addOptions->getValue());
    }
    if ($options) {
        //$orderItem->setProductOptions($options);
    }
    if ($item->getParentItem()) {
        $orderItem->setParentItem($orderObj->getItemByQuoteItemId($item->getParentItem()->getId()));
    }
    $orderObj->addItem($orderItem);
    }
    $orderObj->setCanShipPartiallyItem(false);
    $orderObj->setState(Mage_Sales_Model_Order::STATE_NEW, true);
    try {
        $orderObj->place();
    } catch (Exception $e){     
        Mage::log($e->getMessage());
        Mage::log($e->getTraceAsString());
    }
    //$orderObj->sendNewOrderEmail(); //it doesnot work
    $orderObj->setEmailSent(true);
    $orderObj->save(); 
    $last_insert_order_id = $orderObj->getRealOrderId();
    return $last_insert_order_id;
}

请帮助调整此代码为可配置的产品,所以在属性选择的基础上以价格下单。

不要用$quote->addItem()手工制作你的报价,有太多要考虑的,根本没有必要把它弄复杂。

你需要的是$quote->addProduct()。该方法具有以下签名:

 /**
  * Add product to quote
  *
  * return error message if product type instance can't prepare product
  *
  * @param mixed $product
  * @param null|float|Varien_Object $request
  * @return Mage_Sales_Model_Quote_Item|string
  */
  public function addProduct(Mage_Catalog_Model_Product $product, $request = null)

$request可以是一个数字(数量),也可以是包含"添加到购物车"请求将发送的所有数据的Varien_Object。对于可配置的产品,您需要这个:

$buyRequest可以包含哪些数据?

除了产品和数量,它是捆绑产品的捆绑选项,可配置的属性用于可配置的产品,选择链接用于可下载的产品和自定义选项。

所有产品类型

  • product:产品ID
  • qty:请求的数量。当报价项目或愿望清单项目的数量发生变化时,此处也会进行调整。
  • original_qty:如果qty的值发生了变化,original_qty包含最初请求的数量。
  • reset_count:用于更新购物车中的商品[…]
  • 从添加到购物车表单中进一步请求与报价生成无关的参数:
    • related_product
    • uenc
    • form_key

可配置的产品
  • super_attribute:包含表单中配置属性的数组attribute_id => value_id

(源)

您的可配置产品的最小请求对象看起来像这样:

new Varien_Object(array(
    'qty' => $qty,
    'super_attribute' => [ $sizeAttribute->getId() => $valueMedium, $colorAttribute->getId() => $valueGreen ]
));