Programmatisch erstellte Bestellung, die Bundle-Produkte nicht korrekt hinzufügt

7

Ich habe einen Auftragsfluss außerhalb von Magento, der sowohl Magentos direkte Methoden als auch API-SOAP-Methoden verwendet, um einen Auftrag zu erstellen. (Die API wurde zunächst vollständig verwendet, bis wir herausfanden, dass die Zahlung bei Abschluss der Bestellung nicht bestanden wird.) Zum größten Teil funktioniert sie hervorragend, außer wenn es um das Bündeln von Produkten geht. Unsere Bundle-Produkte haben 2 einfache Produkte mit In. Wenn die Bestellung abgeschlossen ist, befindet sich eines der Produkte im Bundle und das andere wird separat hinzugefügt. Ich habe festgestellt, wann meine benutzerdefinierte Klasse das Angebot erneut abruft, anstatt das vorhandene Angebot zu verwenden, aber dann wird der Versand nicht hinzugefügt, obwohl die Versandmethoden durchlaufen werden. Ich kann nicht herausfinden, was dazu führen würde.

Meine benutzerdefinierte Klasse:

class createOrder{
    // Variables, construct, and address stuff here
    function getParams($item){
        $super_group = array();
        $parentId = $item['parentID'];
        $children = array($item['childID']);
        $child_qty = $item['qty'];
        foreach($children as $child){
            if(intval($child)){
                $super_group[$child] = $child_qty;
            }
        }
        // set params for product
        if (!empty($super_group)) {
            $params = array('super_group' => $super_group);
        }
        else {
            // bundled product
            if ($parentId == 121) { //Product1:
                $params = array(
                    'product' => '121',
                    'related_product' => '',
                    'qty' => "{$item['qty']}",
                    'bundle_option' => array(7=>'3',8=>'14'),
                    'bundle_option_qty' => array(7=>'1',8=>'1'),
                );
            }
            else if ($parentId == 120) { //Product2:
                $params = array(
                    'product' => '120',
                    'related_product' => '',
                    'qty' =>"{$item['qty']}",
                    'bundle_option' => array(5=>"1",6=>"2"),
                );
            }
            else if ($parentId == 146) { //Product3:
                $params = array(
                    'product' => '146',
                    'related_product' => '',
                    'qty' => "{$item['qty']}",
                    'bundle_option' => array(13=>'9',14=>'10'),
                );
            }
            else if($parentId == 382){ //Product4:
                $params = array(
                    'product' => '382',
                    'related_product' => '',
                    'qty' => "{$item['qty']}",
                    'bundle_option' => array(15=>'11',16=>'12'),
                    'bundle_option_qty'=>array(15=>'1',16=>'1'),
                );
            }   
        }
        return $params;
    }

    function completeOrder($shopping_cart_id,$pay,$gift = null,$newOTO = false){
        Mage::log(' -- start completeOrder ---');
        $error = NULL;

        // Get quote and set stuff
        // With this uncommented, products added correctly, but no shipping
        // if(!empty($this->_quote))
            // $quote = $this->_quote;
        // else
            $quote = Mage::getModel('sales/quote')->load($shopping_cart_id);
        $quote->setIsMultiShipping(false);
        $quote->setCheckoutMethod('guest');
        $quote->setCustomerId(null);
        if(isset($_SERVER['REMOTE_ADDR']))
            $quote->setRemoteIp($_SERVER['REMOTE_ADDR']);

        if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
            $quote->setXForwardedFor($_SERVER['HTTP_X_FORWARDED_FOR']);

        $quote->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
        $quote->reserveOrderId();

        // Add shipping
        $quote->getShippingAddress()->setCollectShippingRates(true);
        $quote->getShippingAddress()->collectShippingRates();

        // $quote->collectTotals();
        $quote->save();

        $payment=$quote->getPayment();
        $convertQuote = Mage::getSingleton('sales/convert_quote');
        $order = $convertQuote->addressToOrder($quote->getShippingAddress());

        $order->setPayment($convertQuote->paymentToOrderPayment($payment));
        $order->getPayment()->setCcNumber($pay['cc_number']);
        $order->getPayment()->setCcType($payment->getCcType());
        $order->getPayment()->setCcExpMonth($payment->getCcExpMonth());
        $order->getPayment()->setCcExpYear($payment->getCcExpYear());
        $order->getPayment()->setCcLast4(substr($pay['cc_number'],-4));

        $order->setBillingAddress($convertQuote->addressToOrderAddress($quote->getBillingAddress()));
        $order->setShippingAddress($convertQuote->addressToOrderAddress($quote->getShippingAddress()));
        foreach($quote->getAllItems() as $item){
            $orderItem = $convertQuote->itemToOrderItem($item);
            if ($item->getParentItem()) {
                $orderItem->setParentItem($order->getItemByQuoteItemId($item->getParentItem()->getId()));
            }
            $order->addItem($orderItem);
        }

        try{
            $order->place();
            $order->save();

            $this->orderID = $order->getIncrementId();
            if($newOTO)
                $order->sendNewOrderEmail();
        } catch (Exception $e){
            Mage::log($e->getMessage());
            Mage::log($e->getTraceAsString());
            if($e->getMessage() == "Error in capturing the payment") {
                $error = "A problem has occured with the credit card you are providing. Please try again, or call us at 1-877-371-1807.";
            }
            else {
                $error = "There has been an error placing your order. Please review the information below.";
            }
        }
        return $error;  
    }

Diese werden aufgerufen mit:

Produkte und Versand:

foreach ($_SESSION['cart'] as $item) {
    Mage::log('item');
    $params = $OTOrder->getParams($item);
    $parentId = $item['parentID'];
    $parentIDs[] = $parentId;
    if($parentId) {
        try {
            //Get object of main grouped product
            $product = Mage::getModel('catalog/product')->load($parentId);

            //Check product availability
            if (!$product) {
                Mage::log("Error in product! ".$parentId);
                return;
            }

            //Get cart object
            $cart = Mage::getModel('checkout/cart');
            $quote = Mage::getModel('sales/quote')->load($shopping_cart_id);
            if (!$quote) {
                Mage::log("Error in quote! ".$parentId);
                return;
            }
            //Add product to cart with specified parameters and save the cart object
            $quote->addProduct($product, new Varien_Object($params))->save();
            $quote->collectTotals()->save();
            $OTOrder->setQuote($quote);
            Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

        }
        catch (Mage_Core_Exception $e){
            $_SESSION['orderError'] = 'Error in "'.$item['desc'].'"';
            Mage::log("parentID: ".$e->getMessage());
            if (Mage::getSingleton('checkout/session')->getUseNotice(true)){
                header("Location: OrderForm.php?keycode=" . $keystring);
                exit;
            }
            else{
                $messages = array_unique(explode("\n", $e->getMessage()));
                foreach ($messages as $message) {
                    $_SESSION['orderError'] .= "<br />".$message;
                }
                header("Location: OrderForm.php?keycode=" . $keystring);
                exit;
            }
        }
        catch (Exception $e){
            $_SESSION['orderError'] = 'Error in "'.$item['desc'].'"';
            $_SESSION['orderError'] .= "Cannot add the item to shopping cart.";
            Mage::log("Adding product: ".$e->getMessage());
            header("Location: OrderForm.php?keycode=" . $keystring);
            exit;
        } 
    }
}
    $pass = false;
while(!$pass) {
    try{
        $methods = $soap->shoppingCartShippingList($session_id, $shopping_cart_id);
        foreach($methods as $method){
            if($method->method_title != 'Priority')
                $shipCode = $method->code;              
        }
        if(!empty($shipCode))
            $soap->shoppingCartShippingMethod($session_id, $shopping_cart_id, $shipCode);
        $pass = true;
    }
    catch(Exception $e)
    {
        if($e->getMessage() == 'Error Fetching http headers')
            $pass == false;
        else{
            $_SESSION['orderError'] = "Problem with billing or shipping address.";
            $_SESSION['error'] = true;
            Mage::log("shoppingCartShippingList: ".$e->getMessage());
            header("Location: OrderForm.php?keycode=" . $keystring);
            exit;
        }
    }
}

Der Auftragsabschluss erfolgt mit:

$err = $OTOrder->completeOrder($shopping_cart_id,$paymentMethod,$giftOption);
aynber
quelle
Interessanterweise hat einer der Entwickler, mit denen ich zusammenarbeite, dasselbe Problem. Wir untersuchen es jetzt
Jeffrey L. Roberts,
Dies könnte uns allen helfen, eine Lösung zu finden ... magento.stackexchange.com/questions/1214/…
Jeffrey L. Roberts
Es sieht so aus, als ob meine Parameter seinen ähnlich sind. Meins ist etwas anders, da ich die Methode $ quote-addProduct verwende und er einfach alles in orderData festlegt.
Aynber
Hat eine dieser Antworten geholfen? Wenn ja, akzeptieren Sie bitte eine.
Philwinkle
Ja, irgendwie habe ich es vergessen, da ich 24 Stunden warten musste.
aynber

Antworten:

2

Mit dem folgenden Code konnte ich eine Bestellung mit einem Bundle-Produkt erstellen

<?php

require_once 'app/Mage.php';
define('MAGENTO_ROOT', getcwd());

$compilerConfig = MAGENTO_ROOT . '/includes/config.php';
if (file_exists($compilerConfig)) {
    include $compilerConfig;
}

class JLR_Orders_Create {
  public function CreateOrder2() {

        try {
            $storeObject = Mage::getModel('core/store')->load(4); // Store ID
        }
        catch(Exeception $ex)
        {
            echo $ex->getMessage();
        }


        $cart_api = Mage::getModel('checkout/cart_api');
        $quoteId = $cart_api->create($storeObject->getStoreId());
        $quote = Mage::getModel('sales/quote')->loadByIdWithoutStore($quoteId);

        $product = Mage::getModel('catalog/product');
        $productId = $product->getIdBySku('SBTEMP075'); // Bundle Product SKU

        $params = array(
            'product' =>  $productId,
            'related_product' => null,
            'bundle_option' => array(
                    164 => '3235', // Bundle Options
                    165 => '3240',
                    166 => '3241'

                ),
             'bundle_option_qty' => array(
                    164 => 1, // Bundle Quantities
                    165 => 1,
                    166 => 1
                ),
        );

        $request = new Varien_Object();
        $request->setData($params);

        $_value['Email'] = '[email protected]';
        $_value['First Name'] = 'Jeffrey';
        $_value['Last Name'] = 'Roberts';
        $_value['Address'] = 'Biscayne Blvd';
        $_value['City'] = 'Miami';
        $_value['Post Code'] = '33137';
        $_value['Telephone'] = '305-555-1155';

        // create customer
        $customer = Mage::getModel('customer/customer');
        $password = 'stackexchange';

        $customer->setWebsiteId(4); // Set Website ID
        $customer->loadByEmail($_value['Email']);
        $customer->setWebsiteId(4); // Set Website ID AGAIN!

        if(!$customer->getId()) {
            $customer->setEmail($_value['Email']);
            $customer->setFirstname($_value['First Name']);
            $customer->setLastname($_value['Last Name']);
            $customer->setPassword($password);
            $customer->setMode(Mage_Checkout_Model_Cart_Customer_Api::MODE_REGISTER);
        }
        else
        {
            $customer->setMode(Mage_Checkout_Model_Cart_Customer_Api::MODE_CUSTOMER);
        }

        try {
            $customer->save();
            $customer->setConfirmation(null);
            $customer->save();
        }
        catch (Exception $ex) {
            error_log(var_dump($ex));
        }

        if (! $customer->getId() ){
            return $this;                
        }

        $dataShipping = array(
            'firstname'  => $_value['First Name'],
            'lastname'   => $_value['Last Name'],
            'street'     => $_value['Address'],
            'city'       => $_value['City'],
            'region'     => '',
            'region_id'  => '',
            'postcode'   => $_value['Post Code'],
            'country_id' => 'CZ', //todo: un-hardcode this.
            'telephone'  => $_value['Telephone'],
        );

        $customerAddress = Mage::getModel('customer/address');

        if ($defaultShippingId = $customer->getDefaultShipping()){
             $customerAddress->load($defaultShippingId); 
        } else {   
             $customerAddress
                ->setCustomerId($customer->getId())
                ->setIsDefaultShipping('1')
                ->setSaveInAddressBook('1')
             ;
             $customer->addAddress($customerAddress);
        }            

        try {
            $customerAddress
                ->addData($dataShipping)
                ->save()
            ;           
        } catch(Exception $e){
            Mage::log('Address Save Error::' . $e->getMessage());
        }

        $customer->save();

        $product = new Mage_Catalog_Model_Product();
        $product->load($productId);

        $quote->addProduct($product, $request);
        $quote->setCustomer($customer);
        $quote->assignCustomer($customer);
        $quote->getShippingAddress()->addData($dataShipping)->setShippingMethod('tablerate_bestway');
        $quote->getShippingAddress()->setShippingMethod('tablerate_bestway');
        $quote->getShippingAddress()->setCollectShippingRates(true);
        $quote->getShippingAddress()->collectShippingRates(); 
        $quote->setPayment($quote->getPayment()->setMethod('free'));
        $quote->collectTotals();
        $quote->save();

        $convertQuoteObj = Mage::getModel('sales/convert_quote');
        $orderObj = $convertQuoteObj->toOrder($quote);

        $orderPaymentObj=$convertQuoteObj->paymentToOrderPayment($quote->getPayment());

        $orderObj->setBillingAddress($convertQuoteObj->addressToOrderAddress($quote->getBillingAddress()));
        $orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quote->getPayment()));
        $orderObj->setShippingAddress($convertQuoteObj->addressToOrderAddress($quote->getShippingAddress()));


        $qty=1;
        foreach ($quote->getShippingAddress()->getAllItems() as $item) {
            //@var $item Mage_Sales_Model_Quote_Item
            $item->setQty($qty);
            $orderItem = $convertQuoteObj->itemToOrderItem($item);
            if ($item->getParentItem()) {
                $orderItem->setParentItem($orderObj->getItemByQuoteItemId($item->getParentItem()->getId()));
            }
            $orderObj->addItem($orderItem);
        }

        $orderObj->setCanShipPartiallyItem(false);

        $totalDue=$orderObj->getTotalDue();
        echo "<p>total due: $totalDue</p>";
        $orderObj->place(); //calls _placePayment
        $orderObj->save();
        $orderId=$orderObj->getId();
        echo "<p>orderId: $orderId</p>";

    }
}

Mage::app();

$JLR = new JLR_Orders_Create();
$JLR->CreateOrder2();
Jeffrey L. Roberts
quelle
Ich habe es eingegrenzt, bis das Anführungszeichen in meiner completeOrder-Funktion neu geladen wird. Das Produkt ist in Ordnung, bis und nur wenn ich $ quote = Mage :: getModel ('sales / quote') -> load ($ purchase_cart_id) aufrufe;
aynber
1

Da das erneute Abrufen des Angebots zu Beginn meiner Funktion die Bündelprodukte durcheinander gebracht hat, habe ich nur den Warenkorb geleert und alle Produkte erneut eingegeben. Ich habe ein Array erstellt:

$allProducts[$parentId] = $params;

Habe das mit $ OTOrder-> setProducts () gespeichert und dann meine Funktion in folgende geändert:

function completeOrder($shopping_cart_id,$pay,$gift = null,$newOTO = false){
    Mage::log(' -- start completeOrder ---');
    $error = NULL;

    $quote = Mage::getModel('sales/quote')->load($shopping_cart_id);

    foreach($quote->getAllItems() as $item){
        $quote->removeItem($item->getId()); 
    }
    $quote->save();
    foreach($this->_products as $parentId=>$params)
    {
        //Get object of main grouped product
        $product = Mage::getModel('catalog/product')->load($parentId);

        //Check product availability
        if (!$product) {
            Mage::log("Error in product! ".$parentId);
            return;
        }

        //Get cart object
        $cart = Mage::getModel('checkout/cart');
        $quote = Mage::getModel('sales/quote')->load($shopping_cart_id);
        if (!$quote) {
            Mage::log("Error in quote! ".$parentId);
            return;
        }
        //Add product to cart with specified parameters and save the cart object
        $quote->addProduct($product, new Varien_Object($params))->save();
        $quote->collectTotals()->save();
        Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
    }

Es ist sperriger als ich möchte, aber es scheint zu funktionieren.

aynber
quelle