0

I've created a module to programmatically create orders on Magento CE 1.9.2.2. Everything works perfectly fine in a workbench testing script but when I attempt to execute the same code from a custom controller, it breaks when trying to set shipping method (i.e. freeshipping). The free shipping option is enabled in Magento but I feel like I should be doing something differently.

Here is my controller's class & indexAction:

<?php

class MyCompany_Api_OrderController extends Mage_Core_Controller_Front_Action
{

  public function indexAction()
  {
      $storeId = 1;

  $quote = Mage::getModel('sales/quote')
  ->setStoreId($storeId);

  $quote->setCustomerEmail('[email protected]');

  // add product(s)
  $product_sku = 'SKU1234'; // use your own sku number
  echo "Product SKU: " . $product_sku . "\n";
  $product_id = Mage::getModel("catalog/product")->getIdBySku( $product_sku );
  echo "Product ID: " . $product_id . "\n";
  $product = Mage::getModel('catalog/product')->load($product_id);

  $params = array();

  $params['qty'] = 1;
  $request = new Varien_Object();
  $request->setData($params);

  $price = "19";
  $quoteItem = $quote->addProduct($product, $request);
  $quoteItem->setCustomPrice($price);
  $quoteItem->setOriginalCustomPrice($price);

  $addressData = array(
    'firstname' => 'John',
    'lastname' => 'Doe',
    'street' => 'Sample Street 10',
    'city' => 'Somewhere',
    'postcode' => '123456',
    'telephone' => '123456',
    'country_id' => 'US',
    'region_id' => 12, // id from directory_country_region table
  );

  $billingAddress = $quote->getBillingAddress()->addData($addressData);
  $shippingAddress = $quote->getShippingAddress()->addData($addressData);

  $shippingAddress->setFreeShipping( true )
  ->setCollectShippingRates(true)->collectShippingRates()
  ->setShippingMethod('freeshipping')
  ->setPaymentMethod('checkmo');

  $quote->getPayment()->importData(array('method' => 'checkmo'));

  $quote->collectTotals()->save();
  $service = Mage::getModel('sales/service_quote', $quote);
  $service->submitAll();
  $order = $service->getOrder();
  printf("Created order %s\n", $order->getIncrementId());
  }
}

The only difference between this and my workbench script is that I've removed the necessary 2 lines for workbenching:

include 'app/Mage.php';
Mage::app();

I believe I need to use Mage::getSingleton('shipping/config')->getAllCarriers somewhere before I attempt to call shipping methods but not certain. Any ideas? Thanks in advance.

1 Answer 1

0

I figured out what was wrong. It appears that when selecting shipping methods, you need the module name and method. Like this:

      ->setShippingMethod('freeshipping_freeshipping')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.