title: Creating orders programmatically
body: <p>I try to create an order in code, but sometimes the code works, but sometimes it goes wrong with exception "The requested Payment Method is not available." (first browser request is ok, but the second one goes wrong, etc..).</p>
  
  <p>My code is:</p>
  
  <pre><code>if (Mage::getSingleton('customer/session')-&gt;isLoggedIn()) {
      $customer = Mage::getSingleton('customer/session')-&gt;getCustomer();
      $customer-&gt;setWebsiteId(Mage::app()-&gt;getWebsite()-&gt;getId());
  } else {
      $customer = Mage::getModel('customer/customer');
      $email = 'test@example.com';
      $customer-&gt;setWebsiteId(Mage::app()-&gt;getWebsite()-&gt;getId());
      $customer-&gt;setStoreId(Mage::app()-&gt;getStore()-&gt;getId());
      $customer-&gt;loadByEmail($email);
      Mage::getSingleton('customer/session')-&gt;loginById($customer-&gt;getId());
  }
  
  $customAddress = Mage::getModel('customer/address')
          -&gt;setCustomerId($customer-&gt;getId())
          -&gt;getCustomer();
  
  $customAddressId = Mage::getSingleton('customer/session')-&gt;getCustomer()-&gt;getDefaultBilling();
  if ($customAddressId) {
      $customAddress = Mage::getModel('customer/address')-&gt;load($customAddressId);
  }
  
  Mage::getSingleton('checkout/session')-&gt;getQuote()
          -&gt;setBillingAddress(Mage::getSingleton('sales/quote_address')-&gt;importCustomerAddress($customAddress))
          -&gt;setShippingAddress(Mage::getSingleton('sales/quote_address')-&gt;importCustomerAddress($customAddress));
  
  $product = Mage::getModel('catalog/product')
          -&gt;setStoreId(Mage::app()-&gt;getStore()-&gt;getId())
          -&gt;load(2);
  
  $cart = Mage::getSingleton('checkout/cart');
  $cart-&gt;truncate();
  
  try {
      $cart-&gt;addProduct($product, array('qty' =&gt; 2));
      $cart-&gt;save();
  
      $message = $this-&gt;__('%s was successfully added to your shopping cart.', $product-&gt;getName());
      Mage::getSingleton('checkout/session')-&gt;addSuccess($message);
  } catch (Exception $ex) {
      echo $ex-&gt;getMessage();
  }
  
  $storeId = Mage::app()-&gt;getStore()-&gt;getId();
  $checkout = Mage::getSingleton('checkout/type_onepage');
  $checkout-&gt;initCheckout();
  $checkout-&gt;saveCheckoutMethod('register');
  $checkout-&gt;saveShippingMethod('flatrate_flatrate');
  
  $checkout-&gt;savePayment(array('method' =&gt; 'banktransfer'));
  
  try {
      $checkout-&gt;saveOrder();
  } catch (Exception $ex) {
      echo $ex-&gt;getMessage();
  }
  
  $cart-&gt;truncate();
  $cart-&gt;save();
  $cart-&gt;getItems()-&gt;clear()-&gt;save();
  Mage::getSingleton('customer/session')-&gt;logout();
  </code></pre>