I am having trouble getting my Script to create an order on my live site that uses Magento 1.7. The error I am getting is “please specify a shipping method” more detail is
blockquote Fatal error: Uncaught exception 'Mage_Core_Exception' with message 'Please specify a shipping method.' in /home/mysite/public_html/app/Mage.php:594 Stack trace: #0 /home/mysite/public_html/app/code/core/Mage/Sales/Model/Service/Quote.php(303): Mage::throwException('Please specify ...') #1 /home/mysite/public_html/app/code/core/Mage/Sales/Model/Service/Quote.php(222): Mage_Sales_Model_Service_Quote->_validate() #2 /home/mysite/public_html/app/code/core/Mage/Sales/Model/Service/Quote.php(238): Mage_Sales_Model_Service_Quote->submitNominalItems() #3 /home/mysite/public_html/apitest/magento_order_create.php(82): Mage_Sales_Model_Service_Quote->submitAll() #4 {main} thrown in /home/mysite/public_html/app/Mage.php on line 594
I am trying to use the script below to create the order and I am passing the skus and quantities in the post from another page. `
<?php
// Link Mage Class
require ('../app/Mage.php');
// Initialize Magento framework
Mage::app('mysite');
//create a cart
$quote = Mage::getModel('sales/quote')
->setStoreId(Mage::app()->getStore('mysite')->getId());
//Get Customer by Id
$customer = Mage::getModel('customer/customer')->load('1');
//attach customer to cart
$quote->assignCustomer($customer);
//attach products
foreach ($_POST as $sku=>$qty)
{
$product = Mage::helper('catalog/product')->getProduct($sku,Mage::app()->getStore()->getId(), 'sku');
$buyInfo = array(
'qty' => $qty,
// custom option id => value id
// or
// configurable attribute id => value id
);
$quote->addProduct($product, new Varien_Object($buyInfo));
}
//get and set customer billing address
//need to work on this encase we use diffrent billing and shipping addresses
$addressData = Mage::getModel('customer/address')->load('1');
$billingAddress = $quote->getBillingAddress()->addData($addressData);
$shippingAddress = $quote->getShippingAddress()->addData($addressData);
// set shipping and payment methods. assumes freeshipping and check payment
// have been enabled.
/*
$shippingAddress->setCollectShippingRates(true)->collectShippingRates()
->setShippingMethod('freeshipping_freeshipping')
->setPaymentMethod('checkmo');
*/
// THIS IS WHERE THE ERROR SEEMS TO BE
$quote->getShippingAddress()->setShippingMethod('freeshipping_freeshipping');
$quote->getShippingAddress()->setCollectShippingRates(true);
$quote->getShippingAddress()->collectShippingRates();
//set payment method
$quote->getPayment()->importData(array('method' => 'checkmo'));
//save cart and check out
$quote->collectTotals()->save();
$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();
$order = $service->getOrder();
printf("Created order %s\n", $order->getIncrementId());
`
The above script originally came from http://pastebin.com/8cft4d8v
and it works like a charm on my test environment (also 1.7). I have commented out the original shipping method code and broke is out into separate lines.
The live site has two sites and two stores, I have made sure that free shipping is enabled on the backend and tested that it shows up when I run this script.
<?php
// Link Mage Class
require ('../app/Mage.php');
// Initialize Magento framework
Mage::app('mysite');
$methods = Mage::getSingleton('shipping/config')->getActiveCarriers();
var_dump($methods);
I am fairly certain the address is set correctly, if I echo is out to the screen that address is there.
I have tried reading the documentation, looking at other sample code and changing parts of it to see if I can get the shipping method set, but no luck.
Well the main solution seems to be something that was solved during a server reboot. But I am also going to post the final script that we are going to use. For some reason setting shipping method on a quote object does not seem to work, so I also went back to the “orginal” script that I had found on http://pastebin.com/8cft4d8v. I also got rid of some lines that did not seem to matter if they existed or not. Hope this may help someone down the line
<?php
// Link Mage Class
require ('..\app\Mage.php');
// Initialize Magento framework
Mage::app('my');
//create a cart
$quote = Mage::getModel('sales/quote')
->setStoreId(Mage::app()->getStore('default')->getId());
//Get Customer by Id
$customer = Mage::getModel('customer/customer')->load('1');
//attach customer to cart
$quote->assignCustomer($customer);
//attach products
foreach ($_POST as $sku=>$qty)
{
$product = Mage::helper('catalog/product')->getProduct($sku, Mage::app()->getStore()->getId(), 'sku');
$buyInfo = array(
'qty' => $qty,
// custom option id => value id
// or
// configurable attribute id => value id
);
$quote->addProduct($product, new Varien_Object($buyInfo));
}
$billingAddress = $quote->getBillingAddress()->addData();
$shippingAddress = $quote->getShippingAddress()->addData();
// set shipping and payment methods. assumes freeshipping and check payment
// have been enabled.
$shippingAddress->setCollectShippingRates(true)->collectShippingRates()
->setShippingMethod('flatrate_flatrate');
$quote->getPayment()->importData(array('method' => 'checkmo'));
//save cart and check out
$quote->collectTotals()->save();
$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();
$order = $service->getOrder();
printf("Created order %s\n", $order->getIncrementId());
Related
How to add Custom option value on coupon rules Magneto 2. I have a product which have some custom option like size, color etc. with different value, I want give discount on basic of size = 7'. I don't want use sku custom option.. Let me know how I fix it.
https://github.com/Turiknox/magento2-custom-total
Moulde I use for Discount but i have face a problem.
one Data I can't get cart information
$obj = $bootstrap->getObjectManager();
// Set the state (not sure if this is neccessary)
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
// Getting the object managers dependencies
$quote = $obj->get('Magento\Checkout\Model\Session')->getQuote();
$helper = $obj->get('\Magento\Checkout\Helper\Cart');
// Get quote and cart items collection
$quote = $helper->getQuote();
$quoteitems = $quote->getAllItems();
$coupon_code = 'Test23';
// Get cart contents
$cart= $helper->getCart();
foreach ($quoteitems as $item)
{
}
It goes to the infinity loop.
This one Run fast that's why here we can't load quote total, For Discount given you must set session core cookies which allow giving discount...
I have the following issue:
I make calculations via jQuery in the frontend and want to add a product to the cart with the price calculated in the frontend.
I already wrote a custom module with an AjaxController to achieve the adding to cart part, but I know struggle with setting the custom price.
My script looks like this:
$_prod = json_decode(Mage::app()->getRequest()->getPost('zapfsaeule_product'));
$id = 347; // there is only this one bundle product added to the cart viar this scipt, so a static id is enough.
$params = array(
'product' => $id,
'related_product' => null,
'bundle_option' => array(
6 => 17, // static options for testing purpouses
5 => 13), //
'qty' => 1 // static qty for testing as well
);
$cart = Mage::getSingleton('checkout/cart');
$product = new Mage_Catalog_Model_Product();
$product->load($id);
$cart->addProduct($product, $params);
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
$this->getResponse()->setBody('true'); // setting response to true, because its an ajax request.
$this->getResponse()->setHeader('Content-type', 'text/plain');
That's the code for adding the product.
For setting the price I tried the approach as mentioned in this thread on stackexchange:
https://magento.stackexchange.com/questions/4318/dynamically-calculated-prices-save-before-add-to-cart
But it didn't work. I guess the event observed here doesn't occur in my case, because I wrote a custom script.
But then there still would be the problem, IF the observer approach would work, how would I pass the calculated price to the observer?
I hope you understand the problem and can help me solve it.
Thanks in advance!
Best regards,
Martin
Reading through Mage_Checkout_Model_Cart::addProduct(), there doesn't appear to be a way to set the item's price from the parameters. Instead, you'll need to add the product, then grab the resulting item, and set its price:
$cart->addProduct($product, $params)
->save();
// grab the corresponding item
$item = $cart->getQuote()->getItemByProduct($product);
// set its custom price
$item->setOriginalCustomPrice($customPrice)
->save();
Haven't had the time to try this out, but it should be the right idea. Make sure that you set the original_custom_price field (using setOriginalCustomPrice()), not one of the other prices. The other prices are recalculated during the totals process.
This comes pretty late, but I just stumbled upon this.
I got it to work like this:
$cart = Mage::getSingleton('checkout/cart');
$cart->addProduct($product, 1); // 1 = qty. Pass your qty and params.
$item = $cart->getQuote()->getItemByProduct($product);
$item->setCustomPrice(0); // or some other value
$item->setOriginalCustomPrice(0); // or some other value
$item->getProduct()->setIsSuperMode(true); // this is crucial
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
If the params don't work, fetch the returned item from $cart->addProduct and change the price on the item before saving the cart.
$item = $cart->addProduct(...);
$item->setCustomPrice(...); {or whatever price attribute you like to set}
$cart->save();
I have test php script running outside of Magento that will add an item to the cart. Works great. This code was found here and used by many people in quite a few posts. When I place this code into an existing module, the item is not added, from a fresh session. If I go to the store and add a regular product (have an item in my cart) the module will add the item properly. I Know the code to add the item works. The problem I have is with creating the FIRST instance of a cart.
This code works just fine if already have a normal magento product in my cart:
// this section of code only works if the customer already has a cart item added (cart established)
// for some reason this script fails when no cart exists
$session = Mage::getSingleton('customer/session');
// Get cart instance
$cart = Mage::getSingleton('checkout/cart');
$cart->init();
$productId=971;
$productInstance = Mage::getModel('catalog/product')->load($productId);
$param = array(
'product' => $productId,
'qty' => $rfqdata['option_quantity'],
'options' => array(
27 => $rfqdata['option_layers'], // Layers
26 => $rfqdata['option_thickness'], // Thickness
25 => $rfqdata['option_length'], // Length
24 => $rfqdata['option_width'], // Width
23 => $rfqdata['option_color'], // Color
22 => $rfqdata['option_finish'], // Finish
29 => $rfqdata['option_rush'], // Rush
30 => 'tbd' // RFQ Number
)
);
$request = new Varien_Object();
$request->setData($param);
$cart->addProduct($productInstance, $param);
$session->setCartWasUpdated(true);
$cart->save();
This somehow causes an error, and the module addtocart action is not completed. I cannot find any useful error messages. I have searched 100s of pages on stack, google, and I can find nothing to resolve this issue. Obviously my module is worthless if it doesn't work from page load 1.
I tried to post this before and got no response. I really need some help. If you cannot answer, can you tell me where I can find paid Magento support?
here is the solution, it was very hard to find too....
if(empty($quote)){
$checkout = Mage::getSingleton('checkout/session');
$quote = $checkout->getQuote();
$session = Mage::getSingleton('customer/session');
if($session->isLoggedIn()) {
// look up customer
$customerSession = $session->getCustomer();
$customer = Mage::getModel('customer/customer')->load($customerSession->getId());
$quote->assignCustomer($customer);
$quote->setIsMultiShipping(false);
}
$quote->save();
}
Brief: I am using "Magestore giftvoucher" module in that by default Shipping Address not getting saved, when an order is placed (with gift card product only). As Gift-voucher is not a Physical product and hence not been shipped. It goes to recipient by Email. But somehow I want to make shipping address similar to Billing Address.
So What I have tried :
under app/code/local/Magestore/Giftvoucher/Model/Observer.php
In Function :-> orderSaveAfter I wrote below code but with no luck it was not working.
$order = $observer->getEvent()->getOrder();
$billing_address = $order->getBillingAddress();
$shippingAddress = Mage::getModel('sales/order_address')
->setCustomerId($billing_address->getCustomerId())
->setCustomerAddressId($billing_address->getCustomerAddressId())
->setFirstname($billing_address->getFirstname())
->setMiddlename($billing_address->getMiddlename())
->setLastname($billing_address->getLastname())
->setSuffix($billing_address->getSuffix())
->setCompany($billing_address->getCompany())
->setStreet($billing_address->getStreet())
->setCity($billing_address->getCity())
->setCountry_id($billing_address->getCountryId())
->setRegion($billing_address->getRegion())
->setRegion_id($billing_address->getRegionId())
->setPostcode($billing_address->getPostcode())
->setTelephone($billing_address->getTelephone())
->setFax($billing_address->getFax());
$order = Mage::getModel('sales/order')->load($order->getId());
$order->setShippingAddress($shippingAddress);
$order->save();
Please suggest what is wrong over here!
Thanks
you need to add code in sales_order_place_before event
public function orderPlaceBefore($observer) {
$order = $observer->getEvent()->getOrder();
$billing_address = $order->getBillingAddress();
$shippingAddress = Mage::getModel('sales/order_address')
->setCustomerId($billing_address->getCustomerId())
->setCustomerAddressId($billing_address->getCustomerAddressId())
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING)
->setFirstname($billing_address->getFirstname())
->setMiddlename($billing_address->getMiddlename())
->setLastname($billing_address->getLastname())
->setSuffix($billing_address->getSuffix())
->setCompany($billing_address->getCompany())
->setStreet($billing_address->getStreet())
->setCity($billing_address->getCity())
->setCountry_id($billing_address->getCountryId())
->setRegion($billing_address->getRegion())
->setRegion_id($billing_address->getRegionId())
->setPostcode($billing_address->getPostcode())
->setTelephone($billing_address->getTelephone())
->setFax($billing_address->getFax());
$order->setShippingAddress($shippingAddress);
...
}
I can't seem to find anywhere documentation of the 'bundle_option' field in the product options array, when adding a bundled product to the cart programatically in Magento. So I can't be sure how to do this correctly.
But this is my attempt:
$json_obj = json_decode($json_string, true);
//define cart
$cart = Mage::getSingleton('checkout/cart');
$bundle = array();
$bundle_qty = array();
for ($i=0; $i<count($json_obj['basket']['products']); $i++) {
$product_id = int($json_obj['basket']['products'][$i]['id']);
#add individual products to cart
#$product = new Mage_Catalog_Model_Product();
#$product->load($product_id);
#$params = array('product'=>$product_id,'qty'=>1);
#if ($product->getName()) $cart->addProduct($product, $params);
#add products to bundle
$bundle[$i] = $product_id;
if (isset($bundle_qty[$product_id])) $bundle_qty[$product_id] += (int)1;
else $bundle_qty[$product_id] = (int)1;
}
#add to bundled product to cart
$product = new Mage_Catalog_Model_Product();
$product->load(833); #833 = test bundle
$cart->addProduct($product, array('product'=>833,
'qty'=>min(1,int($json_obj['basket']['quantity'])),
'bundle_option'=>$bundle,
'bundle_option_qty'=>$bundle_qty));
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
$message = $this->__('Notice: %s item(s) were successfully added to your shopping cart.', $i);
Mage::getSingleton('checkout/session')->addSuccess($message);
}
So the commented out code is adding products individually which works correctly. Now I'm trying to add the products to a 'Test Bundle' product instead.
What I'm now doing in the loop is compiling the arrays for 'bundle_option' and 'bundle_option_qty' fields. Once the loop has finished I'm adding the bundle product (ID:833) to the cart with the options array of the bundled items.
The result is that nothing is added to the cart. I've also played around with the code a bit to no success.
Can anyone see where I'm going wrong or if you could point me to a doc/tutorial of the product options parameter that details the bundle_option array (what the indexes are, and what the values are) that would also help?
I had to check the POST variables sent to the cart URL from the front-end to figure this one out.
These were the variables posted for one bundle:
bundle_option[1][] 17
bundle_option[1][] 19
bundle_option_qty[1][17] 1
bundle_option_qty[1][19] 1
product 833
qty 2
related_product
From that I figured out that bundle_option[1] referred to Option 1 in the bundle.
I also figured that the values of the indexes bundle_option[1][0]=17 and bundle_option[1][1]=19 - the 17 and 19 referred to selection_id.
Analysing the form on the front-end revealed my list of selection_id's. I figured that the selection ID's would change once the bundle was altered in Admin>Manage Products so I used a look-up to get the selection IDs rather than hard-coding them in.
The code I ended up with was this:
$json_string = isset($_POST["json"])? $_POST["json"] : null;
if (!is_null($json_string)) {
$json_obj = json_decode($json_string, true);
#define cart
$cart = Mage::getSingleton('checkout/cart');
#look-up bundle selection ids
$bundled_product = new Mage_Catalog_Model_Product();
$bundled_product->load(833); #833 = test bundle
$selectionCollection = $bundled_product->getTypeInstance(true)->getSelectionsCollection(
$bundled_product->getTypeInstance(true)->getOptionsIds($bundled_product), $bundled_product
);
$bundled_items = array();
foreach ($selectionCollection as $option) {
$bundled_items[$option->product_id] = $option->selection_id;
}
#get bundle items, quantities
$bundle = array();
$bundle_qty = array();
for ($i=0; $i<count($json_obj['basket']['products']); $i++) {
$product_id = (int)$json_obj['basket']['products'][$i]['id'];
$selection_id = $bundled_items[$product_id];
if(!in_array($selection_id,$bundle)) array_push($bundle,$selection_id);
if (isset($bundle_qty[$selection_id])) $bundle_qty[$selection_id] += (int)1;
else $bundle_qty[$selection_id] = (int)1;
}
#add to bundled product to cart
$options = array('product'=>833,
'related_product'=>null,
'bundle_option'=>array(1=>$bundle),
'bundle_option_qty'=>array(1=>$bundle_qty),
'qty'=>(int)$json_obj['basket']['quantity']
);
$cart->addProduct($bundled_product, $options);
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
$message = $this->__('Notice: %s item(s) were successfully added to your shopping cart.', $i);
Mage::getSingleton('checkout/session')->addSuccess($message);
}
I hope this saves somebody a lot of time!
Edit
Still trying to solve why bundle_option_qty is not setting the quantity (all items are qty:1 added to the bundle product)
Edit 2
It turned out the built-in front-end bundle add-to-cart feature couldn't add multiple quantities of items to the cart either! Looking into the issue I found that the bundle-quantity feature was an extension called Kabel BundlePlus, it probably wasn't installed correctly by the previous developers so I downloaded it again and reinstalled the plugin and now the bundle_option_qty is working in both the frontend and my plugin!