Magento Forum

   
Trouble creating a quote/order through custom code (programmatically for use with API)
 
Nicholas Amorim
Jr. Member
 
Total Posts:  6
Joined:  2009-05-11
 

This code works perfectly fine except that the order price is always set to ‘0.00’.

Can you explain me why ? :(

 
Magento Community Magento Community
Magento Community
Magento Community
 
jesse_dev
Jr. Member
 
Total Posts:  27
Joined:  2009-03-03
 

The items aren’t being attached to your order correctly. Make sure they are in stock with a sufficient inventory.
When you call collectTotals() on the quote and order models , it pulls in the subtotal, tax, shipping, and grand total.
I recommend getting familiar with creating an order at the quote level before converting to orders and invoices.

 
Magento Community Magento Community
Magento Community
Magento Community
 
Nicholas Amorim
Jr. Member
 
Total Posts:  6
Joined:  2009-05-11
 

Yeah, it was that.

The item was out of stock and the scripts doesn’t accuse any errors in screen.

smile

 
Magento Community Magento Community
Magento Community
Magento Community
 
FOOMAN
Guru
 
Avatar
Total Posts:  669
Joined:  2007-12-13
Auckland, New Zealand
 

thanks jesse_dev for posting your solution - it worked a treat.

@CVinson86 and Freshwebservices
If you want a different price than the current store price try with
$quoteItem->setCustomPrice(’10.00’);

not sure any more if the following is needed additionally
$quoteItem->setCalculationPrice(’10.00’);

good luck

 
Magento Community Magento Community
Magento Community
Magento Community
 
mfernandez
Jr. Member
 
Total Posts:  14
Joined:  2009-05-06
 

Any help ?

this code add correctly a new order with correct product, BUT when I have a downloadable product, the link is not present ... see attachment

If I create an order using the admin and adding the same downloadable product, all works ...

function PrepareOrder($storeId$productId$customerEmail{
    $customer 
Mage::getModel('customer/customer')->setWebsiteId(Mage::app()->getStore()->getWebsiteId())->loadByEmail($customerEmail);
    
    
$quote Mage::getModel('sales/quote')->assignCustomer($customer);
    
$store $quote->getStore()->load($storeId);
    
$quote->setStore($store);
    
    
$product Mage::getModel('catalog/product')
                ->
setStore($store)
                ->
setStoreId($storeId)
                ->
load($productId);

    
$product->setSkipCheckRequiredOption(true);
    
$item $quote->addProduct($product1);
    
$product->unsSkipCheckRequiredOption();
    
$item->checkData();
    
    
$quote->collectTotals();
    
$quote->save();

    return 
$quote->getId();
}

function ConfirmOrder($quoteId{
    $quoteConvert 
Mage::getModel('sales/convert_quote');
    
    
$quote=Mage::getModel('sales/quote')->load($quoteId);
    
    
$payment=$quote->getPayment();
    
$payment->setMethod('purchaseorder');
    
$quote->setPayment($payment);
    
    if (
$quote->getIsVirtual()) {
        $order 
$quoteConvert->addressToOrder($quote->getBillingAddress());
    
}
    
else {
        $order 
$quoteConvert->addressToOrder($quote->getShippingAddress());
    
}
    
    $order
->setBillingAddress($quoteConvert->addressToOrderAddress($quote->getBillingAddress()))->setPayment($quoteConvert->paymentToOrderPayment($quote->getPayment()));
    if (!
$quote->getIsVirtual()) {
        $order
->setShippingAddress($quoteConvert->addressToOrderAddress($quote->getShippingAddress()));
    
}
    
    
if (!$quote->getIsVirtual()) {
        
foreach ($quote->getShippingAddress()->getAllItems() as $item{
            
/* @var $item Mage_Sales_Model_Quote_Item */
            
$orderItem $quoteConvert->itemToOrderItem($item);
            
$options = array();
            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($order->getItemByQuoteItemId($item->getParentItem()->getId()));
            
}

            $order
->addItem($orderItem);
        
}
    }
    
if ($quote->hasVirtualItems()) {
        
foreach ($quote->getBillingAddress()->getAllItems() as $item{
            
/* @var $item Mage_Sales_Model_Quote_Item */
            
$orderItem $quoteConvert->itemToOrderItem($item);
            
$options = array();
            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($order->getItemByQuoteItemId($item->getParentItem()->getId()));
            
}

            $order
->addItem($orderItem);
        
}
    }
       
    $order
->place();
    
    
//check if downlable is virtual
    //$order->setState('complete', true, 'Complete by system.', true);
    
$order->save();
    
    return 
$order->getId();
}

Image Attachments
Untitled-2.jpg
 
Magento Community Magento Community
Magento Community
Magento Community
 
MoOx
Jr. Member
 
Avatar
Total Posts:  14
Joined:  2008-01-29
 

Hi,

I’m using the code found in the great Yournamespace_Yourmodule_IndexController but i’ve a little problem.
I use this script because I import orders from a partner.
I parse a CSV file and transform it into lots of orders (csv => array => loop on magento session_quote => create order).
But when i use this code, i’m not able to clean the quote correctly.
My orders contains all products from others orders imported before.
Eg :
order 1 - product x * 2

order 2 - product from order 1 and prodcut from 2

order 3 - product from order 1and 2 and from 3… etc

I use this to clean quote at the end of my loop but this doesn’t seems to work well :(

foreach(...)
{
    
//create quote
    //...
    // use importPostData...
    //...
    // createOrder and save
    //...
    
Mage::getSingleton('adminhtml/session_quote')->clear();
}

I take a look at the code into “Mage::getSingleton(’adminhtml/sales_order_create’)” but it seems to use the session_quote too. I dont find who to make this work

Any idea please ?

 
Magento Community Magento Community
Magento Community
Magento Community
 
outcom
Jr. Member
 
Total Posts:  7
Joined:  2009-02-14
 

I’m trying to migrate orders from a custom system to Magento for historical purposes.  So far, I’ve leveraged the ext_order.create method in the Drupal extension for Magento.  From what I can tell, this process essentially uses the code found here: http://www.magentocommerce.com/boards/viewthread/28426/#t96650.

I’ve run into an issue with setting the price for items, since they’ve changed over time.  The default process seems to use only the current item price in Magento.

I have tried, unsuccessfully, to implement Fooman’s suggestion (http://www.magentocommerce.com/boards/viewthread/28426/P30/#t154489) of using setCustomPrice().

I’m curious to know if anyone has had success migrating historical orders with fluctuating item prices and, if so, what methods they deployed. 

Overall, I’m disappointed that this issue of importing orders into Magento has gone on for so long without a formal module to show for it, either from Varien or the community.  If I can figure this, it will definitely be offered back up for the community.  This feature is a “must have” in order for Magento to realize it’s full potential.

 
Magento Community Magento Community
Magento Community
Magento Community
 
FOOMAN
Guru
 
Avatar
Total Posts:  669
Joined:  2007-12-13
Auckland, New Zealand
 

hi outcom,

the code snippit I used only works with the approach initially posted by jesse_dev:
http://www.magentocommerce.com/boards/viewreply/128780/

good luck

 
Magento Community Magento Community
Magento Community
Magento Community
 
Destreyf
Jr. Member
 
Total Posts:  26
Joined:  2009-01-20
 
jesse_dev - 25 June 2009 05:05 AM

The items aren’t being attached to your order correctly. Make sure they are in stock with a sufficient inventory.
When you call collectTotals() on the quote and order models , it pulls in the subtotal, tax, shipping, and grand total.
I recommend getting familiar with creating an order at the quote level before converting to orders and invoices.

Hello jesse_dev, i’m very pleased with your code, i must say its great code to work with, but i’m having some troubles with the totals showing up properly in my store as well, my functions are as follows

public function makeQuote($customer_id,$products){
        
//foreach($params as $k=>$v) { $$k=$v; }
        
        
$customer        Mage::getModel('customer/customer')->load($customer_id);
        
$storeId        $customer->getStoreId();
        
$quote            Mage::getModel('sales/quote')->assignCustomer($customer); //sets ship/bill address
        
$store            $quote->getStore()->load($storeId);
        
$quote->setStore($store);
        
$product_model    Mage::getModel('catalog/product');
        
        foreach(
$products as $product_id{
            $product    
$product_model->load($product_id);
            
$quote_item    Mage::getModel('sales/quote_item')->setProduct($product);
            
$quote_item->setQuote($quote);
            
$quote_item->setQty(1);
            
$quote->addItem($quote_item);
        
}
        $quote
->collectTotals();
        
$quote->save();
        
$quoteId $quote->getId();
        return 
$quoteId;
    
}
    
function ConfirmOrder($quote_id,$cc_details{
        
        $quote    
Mage::getModel('sales/quote')->load($quote_id);
        
$items    $quote->getAllItems();
        
$quote->collectTotals();
        
$quote->reserveOrderId();
    
        
$quotePaymentObj $quote->getPayment();
        if(!isset(
$cc_details['method'])){ $cc_details['method''ccsave'}
        $method 
$cc_details['method'];
        
$quotePaymentObj Mage::helper('recurring/method_'.strtolower(eregi_replace('[^a-zA-Z0-9]','',$method)))
                                                                    ->
Expose($quotePaymentObj,$cc_details);
        
//Methods Via Dynamic System above.
        
$quote->setPayment($quotePaymentObj);
        
$convertquote=Mage::getSingleton('sales/convert_quote');
        
$orderObj $convertquote->addressToOrder($quote->getShippingAddress());
        
$orderPaymentObj=$convertquote->paymentToOrderPayment($quotePaymentObj);
    
        
$orderObj->setBillingAddress($convertquote->addressToOrderAddress($quote->getBillingAddress()));
        
$orderObj->setShippingAddress($convertquote->addressToOrderAddress($quote->getShippingAddress()));
        
$orderObj->setPayment($convertquote->paymentToOrderPayment($quote->getPayment()));
        
        foreach (
$items as $item{
            
//@var $item Mage_Sales_Model_Quote_Item
            
$orderItem $convertquote->itemToOrderItem($item);
            if (
$item->getParentItem()) {
                $orderItem
->setParentItem($orderObj->getItemByQuoteItemId($item->getParentItem()->getId()));
            
}
            $orderObj
->addItem($orderItem);
        
}
        
        $orderObj
->setCanShipPartiallyItem(false);
        
//$orderObj->collectTotals();
        
$totalDue=$orderObj->getTotalDue();
        
$orderObj->place();
        
$orderObj->save(); 
        
$orderId=$orderObj->getId();
        return 
true;
    
}

i have some renamed variables for my purposes, but this shouldn’t be affecting the code. I’m also getting ready to implement shipping into this as i found possible from another prior post of yours.

Attached are 2 screen shots, I’ve tested the code countless times, and the payment processor the client uses (sage pay) will gets the “total” passed to it, not the amount to charge, so it cannot charge the card at all.

Do you have any suggestions on how to approach this, and if so, what do you recommend as the best course of action.

I appreciate what you’ve done, you’ve taken the complex Magento order system, and turned it into a 75-150 line set of functions that completely handles all orders and relations of that aspect, making the code far more flexible and extensible.

Any thoughts from anyone would be very welcomed.

Image Attachments
empty_tots.jpgquantity setup.jpg
 
Magento Community Magento Community
Magento Community
Magento Community
 
jesse_dev
Jr. Member
 
Total Posts:  27
Joined:  2009-03-03
 

hi there, I wish I could help you more. It would take me a long time to debug your code. A couple of things pop out. The first one is that I think you need to be invoicing the order. Creating the order is 1 step, paying for it is another. I’ve only had to do purchase order payments so far, so I might be wrong there. Another thing that pops out is you have collectTotals commented out towards the bottom, and you mentioned you’re not getting totals. You should be getting a full array of totals. I would focus on that array of totals and look at invoicing the order. The code you need is in the magento code somewhere, I would look at other areas of magento where orders are being created. good luck

 
Magento Community Magento Community
Magento Community
Magento Community
 
Destreyf
Jr. Member
 
Total Posts:  26
Joined:  2009-01-20
 

Hello i’ve been able to debug my problem, its detecting the special price for some reason, when the special price is changed, you’ll see that it does work, i’ve set the “special price” to end before the current date, now its using the propery information now.

 
Magento Community Magento Community
Magento Community
Magento Community
 
Destreyf
Jr. Member
 
Total Posts:  26
Joined:  2009-01-20
 

Hello i’ve been able to debug my problem, its detecting the special price for some reason, when the special price is changed, you’ll see that it does work, i’ve set the “special price” to end before the current date, now its using the proper information now.  Thank you for the code, its very appreciated.

 
Magento Community Magento Community
Magento Community
Magento Community
 
Saggy
Sr. Member
 
Total Posts:  131
Joined:  2009-02-03
 

First of all thanks Jesse for your code.

I need a way to create customer as well at the same time. Has anyone figured this out as yet?

Cheers
S

 
Magento Community Magento Community
Magento Community
Magento Community
 
jesse_dev
Jr. Member
 
Total Posts:  27
Joined:  2009-03-03
 

you’re welcome :D

function CreateCustomer() {

    
require_once '../app/Mage.php';
    
$app=Mage::app();
    
Mage::register('isSecureArea'true);
    
    
    
$customer Mage::getModel('customer/customer');
    
    
///make sure dob is mm/dd/yy

///start hard-coding

$password="tester";
$company="";
$city="Minneapolis";
$telephone="3332224444";
$fax="";
$email="youremail@yourdomain.com";

$prefix="";
$firstname="Tester6";
$middlename="";
$lastname="Tester6";
$suffix="";

$dob="5/6/88";
$taxvat="";
$street1="3216 Some St.";
$street2="";
$postcode="55417";

$country_id="US";
$region=34;//getRegionByZip($postcode);

$street_r=array("0"=>$street1,"1"=>$street2);
$group_id=1///double-check this
$website_id=1;
    

$default_billing="_item1";
$index="_item1";

///end hard-coding//*/

$salt="XD";
//$hash=md5($salt . $password).":$salt";
$hash="";

    
$customerData=array(
        
"prefix"=>$prefix,
        
"firstname"=>$firstname,
        
"middlename"=>$middlename,
        
"lastname"=>$lastname,
        
"suffix"=>$suffix,
        
"email"=>$email,
        
"group_id"=>$group_id,
        
"dob"=>$dob,
        
"password_hash"=>$hash,
        
"taxvat"=>$taxvat,
        
"website_id"=>$website_id,
        
"password"=>$password,
        
"default_billing"=>$default_billing
    
);

    
$customer->addData($customerData); ///make sure this is enclosed in arrays correctly

    
$addressData=array(
        
"prefix"=>$prefix,
        
"firstname"=>$firstname,
        
"middlename"=>$middlename,
        
"lastname"=>$lastname,
        
"suffix"=>$suffix,
        
"company"=>$company,
        
"street"=>$street_r,
        
"city"=>$city,
        
"region"=>$region,
        
"country_id"=>$country_id,
        
"postcode"=>$postcode,
        
"telephone"=>$telephone,
        
"fax"=>$fax
    
);
    
    
    
$address Mage::getModel('customer/address');
    
$address->setData($addressData);

    
/// We need set post_index for detect default addresses
    ///pretty sure index is a 0 or 1
    
$address->setPostIndex($index);
    
$customer->addAddress($address);
    
$customer->setIsSubscribed(false);

    
///make sure password is encrypted
    
$customer->setPassword($password);
    
$customer->setForceConfirmed(true);
    
    
///adminhtml_customer_prepare_save

    
$customer->save();

    
///adminhtml_customer_save_after
    
$customerId=$customer->getId();

    
Mage::log("customerId:$customerId");

    return 
$customerId;
}

 
Magento Community Magento Community
Magento Community
Magento Community
 
Saggy
Sr. Member
 
Total Posts:  131
Joined:  2009-02-03
 

Thank you very much Jesse for your swift reply. Highly appreciated.

Sorry I wasn’t clear in my post, I want to create an order using guest profile. I have the following fields on my form

title, first name, last name, email address, telephone and address but don’t want to create customer with password. Exactly in the same manner when you place order on the website using the guest profile.

Cheers
S

 
Magento Community Magento Community
Magento Community
Magento Community
Magento Community
Magento Community
    Back to top