简体   繁体   English

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

[英]magento programmatically create order for configurable product

I'm using custom script to create an order, it works fine for simple products which have no custom attributes. 我正在使用自定义脚本来创建订单,它对于没有自定义属性的简单产品效果很好。

Now I want to create an order for configureable products, like the product prices changes from original price to different with respect to product attributes selection. 现在,我想为可配置产品创建一个订单,例如产品价格从原始价格更改为关于产品属性选择的不同。

I have an example of my demanding product, I have installed magento 1.7.0.2 with sample data which has a product [T-Shirt] with product id as 126, its original price is 13.5 and it is configurable product. 我有一个要求苛刻的产品的示例,我已经安装了带有样品数据的magento 1.7.0.2,该样品数据具有产品ID为126的产品[T恤],其原始价格为13.5,并且是可配置的产品。

On item detail page, its prices changes by selecting [Size:Medium] & [Color:Green] to 18.75. 在商品详细信息页面上,其价格可以通过选择[大小:中]和[颜色:绿色]更改为18.75。

In my case I send its all information to my site. 就我而言,我将其所有信息发送到我的网站。

On my site I get this product's SKU as 'zol_g_m' with specific quantity. 在我的网站上,我获得此产品的SKU为'zol_g_m',并带有特定数量。 Now I send its information on magento store to create order but my script on magento store consider it as simple product and create order for it with price as 13.5 not as 18.75 现在,我在magento商店上发送其信息以创建订单,但是我在magento商店上的脚本将其视为简单产品,并以13.5而不是18.75的价格为其创建订单。

My script based on two function like this 我的脚本基于这样的两个功能

    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;
}

Please help is required to adjust this code for configurable product, so order is placed with price on the basis of attributes selection. 请为调整此可配置产品的代码而需要帮助,因此根据属性选择确定订单的价格。

Don't handcraft your quotes with $quote->addItem() , there's too much to consider and it's not necessary at all to make it complicated. 不要用$quote->addItem()手工$quote->addItem()报价,因为要考虑的东西太多了,也没有必要使其变得复杂。

What you need instead is $quote->addProduct() . 您需要的是$quote->addProduct() The method has the following signature: 该方法具有以下签名:

 /**
  * 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 can either be just a number (the quantity) or a Varien_Object that contains all data which a "add to cart" request would send. $request可以只是一个数字(数量),也可以是Varien_Object ,它包含“添加到购物车”请求将发送的所有数据。 You need this for configurable products: 您需要此用于可配置产品:

Which data can $buyRequest contain? $ buyRequest可以包含哪些数据?

Besides product and qty it is bundle options for bundle products, configurable attributes for configurable products, selected links for downloadable products and custom options. 除了产品和数量外,它还是捆绑产品的捆绑选项,可配置产品的可配置属性,可下载产品的选定链接和自定义选项。

All product types 所有产品类型

  • product : the product ID 产品 :产品编号
  • qty : Requested quantity. 数量 :要求数量。 When the quantity in the quote item or wishlist item changes, it is adjusted here as well. 当报价项目或愿望清单项目中的数量发生更改时,也会在此处进行调整。
  • original_qty : In case that the value of qty has changed, original_qty contains the originally requested quantity. original_qty :如果qty的值已更改,则original_qty包含原始请求的数量。
  • reset_count : is used for updating items in the cart [...] reset_count :用于更新购物车中的物品[...]
  • Further request parameters from the add to cart form that are not relevant for the quote generation: 添加到购物车表单中与报价生成无关的其他请求参数:
    • related_product 相关产品
    • uenc uenc
    • form_key form_key

Configurable Products 可配置产品

  • super_attribute : Array with the configured attributes in the form attribute_id => value_id super_attribute :具有配置属性的数组,格式为attribute_id => value_id

(Source) (资源)

The minimal request object for your configurable product will look like this: 可配置产品的最小请求对象将如下所示:

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

This should point you in the right direction. 这应该为您指明正确的方向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM