Creating orders programmatically - magento

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..).
My code is:
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
$customer = Mage::getSingleton('customer/session')->getCustomer();
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
} else {
$customer = Mage::getModel('customer/customer');
$email = 'test#example.com';
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->setStoreId(Mage::app()->getStore()->getId());
$customer->loadByEmail($email);
Mage::getSingleton('customer/session')->loginById($customer->getId());
}
$customAddress = Mage::getModel('customer/address')
->setCustomerId($customer->getId())
->getCustomer();
$customAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultBilling();
if ($customAddressId) {
$customAddress = Mage::getModel('customer/address')->load($customAddressId);
}
Mage::getSingleton('checkout/session')->getQuote()
->setBillingAddress(Mage::getSingleton('sales/quote_address')->importCustomerAddress($customAddress))
->setShippingAddress(Mage::getSingleton('sales/quote_address')->importCustomerAddress($customAddress));
$product = Mage::getModel('catalog/product')
->setStoreId(Mage::app()->getStore()->getId())
->load(2);
$cart = Mage::getSingleton('checkout/cart');
$cart->truncate();
try {
$cart->addProduct($product, array('qty' => 2));
$cart->save();
$message = $this->__('%s was successfully added to your shopping cart.', $product->getName());
Mage::getSingleton('checkout/session')->addSuccess($message);
} catch (Exception $ex) {
echo $ex->getMessage();
}
$storeId = Mage::app()->getStore()->getId();
$checkout = Mage::getSingleton('checkout/type_onepage');
$checkout->initCheckout();
$checkout->saveCheckoutMethod('register');
$checkout->saveShippingMethod('flatrate_flatrate');
$checkout->savePayment(array('method' => 'banktransfer'));
try {
$checkout->saveOrder();
} catch (Exception $ex) {
echo $ex->getMessage();
}
$cart->truncate();
$cart->save();
$cart->getItems()->clear()->save();
Mage::getSingleton('customer/session')->logout();

I checked your code in my local server, It s working fine 1st time, but second time it shows error like The requested Shipping Method is not available not like you mentioned above. But after I enabled that shipping method it working fine, So try to enable the shipping and payment methods that you used in your code in admin..

Related

I want to know how Magento save order when return after successful payment in paypal_express

Here is a condition in my latest project where I have to create order after successful payment done through Paypal Express programatically.
When I do it through Magento normal flow it is working very fine, but I want to do it programatically myself.
I tried this but it gives error that payment method is not available.
$quote->collectTotals();
$service = Mage::getModel("sales/service_quote", $quote);
$service->submitAll();
$order = $service->getOrder();
if($order) {
Mage::dispatchEvent("checkout_type_onepage_save_order_after", array("order" => $order, "quote" => $quote));
try {
$order->sendNewOrderEmail();
}
catch(Exception $e) {
Mage::logException($e);
}
}
I tried this also but nothing works
$quote = Mage::getModel("sales/quote")->setStore(Mage::getSingleton("core/store")->load(1))->load($shoppingCartId);
$checkout = Mage::getSingleton('paypal/express_checkout', array(
'config' => Mage::getModel('paypal/config', array(Mage_Paypal_Model_Config::METHOD_WPP_EXPRESS)),
'quote' => $quote,
));
$detailsBlock = new Mage_Paypal_Block_Express_Review_Details();
$detailsBlock->setQuote($quote);
$checkout->updateShippingMethod("ups_GND");
$session->setLastQuoteId($shoppingCartId)->setLastSuccessQuoteId($shoppingCartId);
$order = $checkout->getOrder();
if ($order){
$session->setLastOrderId($order->getId())->setLastRealOrderId($order->getIncrementId());
echo "<br>".$order->getData();
}
Any help is much appreciated. :)

Programatically adding product to magento cart not working at the first time only

I'm creating custom functions for sign up and adding product to customer cart.
If user signed up using my function first product that he/she added will not be added to the cart unless he added another product after that everything working perfect and the first product also appear in the cart.
If user signed up by using magento sign up form then used my function to add product to the cart everything working.
Sign up code
public function signupAction() {
$email = $this->getRequest()->getPost('email');
$password = $this->getRequest()->getPost('password');
$firstName = $this->getRequest()->getPost('firstName');
$LastName = $this->getRequest()->getPost('LastName');
$session = Mage::getSingleton('customer/session');
$session->setEscapeMessages(true);
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer->setWebsiteId($websiteId)
->setStore($store)
->setFirstname($firstName)
->setLastname($LastName)
->setEmail($email)
->setPassword($password);
try {
$customer->cleanPasswordsValidationData();
$customer->save();
$this->_dispatchRegisterSuccess($customer);
$this->_successProcessRegistration($customer);
} catch (Mage_Core_Exception $e) {
} catch (Exception $e) {
}
}
Add to cart code
public function addAction() {
$form_key = Mage::getSingleton('core/session')->getFormKey();
$json = $this->getRequest()->getPost('json');
$jsonObj = json_decode($json);
$cart = $this->_getCart();
$cart->init();
$response = array();
try {
foreach ($jsonObj as $data) {
$param = ['form_key' => $form_key,
'qty' => $data->qty, 'product' => $data->productId];
$product = $this->_initProduct($param['product']);
if ($data->type == 'simple') {
$cart->addProduct($product, $param);
}
}
$cart->save();
$this->_getSession()->setCartWasUpdated(true)
/**
* #todo remove wishlist observer processAddToCart
*/
Mage::dispatchEvent('checkout_cart_add_product_complete',
array('product' => $product,
'request' => $this->getRequest(),
'response' => $this->getResponse()));
if (!$cart->getQuote()->getHasError()) {
$response['status'] = 'SUCCESS';
} else {
$response['status'] = 'Error';
}
} catch (Mage_Core_Exception $e) {
$msg = "";
if ($this->_getSession()->getUseNotice(true)) {
$msg = $e->getMessage();
} else {
$messages = array_unique(explode("\n", $e->getMessage()));
foreach ($messages as $message) {
$msg .= $message . '<br/>';
}
}
$response['status'] = 'ERROR';
$response['message'] = $msg;
} catch (Exception $e) {
$response['status'] = 'ERROR';
$response['message'] = $this->__('Cannot add items.');
Mage::logException($e);
}
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
return;
}
refresh the page is solution because magento use the form key to validate the data
so when login a customer then session is change according to that and it working
let me know if you have more Questions .

Magento : Add product to wish list programatically

I have added the below code in my controller to add the product to wishlist programmatically. But whenever ajax request goes to the controller it replaces my previously added product from the wishlist and adds the new one to wishlist.
Can somebody please help with this.
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
// Load the customer's data
$customer = Mage::getSingleton('customer/session')->getCustomer();
//echo $customer->getName(); // Full Name
$customerId = $customer->getId(); // First Name
$wishlist = Mage::getModel('wishlist/wishlist')->loadByCustomer($customerId, true);
$product = Mage::getModel('catalog/product')->load($productId);
$result = $wishlist->addNewItem($product);
$wishlist->save();
echo "added to wishlist";
}
You can try below :
$product = Mage::getModel('catalog/product')->load($productId);
if (!$product->getId() || !$product->isVisibleInCatalog()) {
//$this->__('Cannot specify product.');
}
try {
$requestParams = $this->getRequest()->getParams();
$buyRequest = new Varien_Object($requestParams=array());
$result = $wishlist->addNewItem($product, $buyRequest);
if (is_string($result)) {
Mage::throwException($result);
}
$wishlist->save();
Mage::dispatchEvent(
'wishlist_add_product',
array(
'wishlist' => $wishlist,
'product' => $product,
'item' => $result
)
);
Mage::helper('wishlist')->calculate();
$message = $this->__('%1$s has been added to your wishlist. Click here to continue shopping.',
$product->getName(), Mage::helper('core')->escapeUrl($referer));
} catch (Mage_Core_Exception $e) {
echo $this->__('An error occurred while adding item to wishlist: %s', $e->getMessage());
}
catch (Exception $e) {
echo ($this->__('An error occurred while adding item to wishlist.'));
}

Magento auto-confirm order instead of admin

I see my orders in my admin panel and all have status "pending".
Is it possible that the orders are auto-confirmed without the admin having to do this?
You can make a custom extension for it, you can get help from here.
http://www.atwix.com/magento/auto-invoice-and-custom-order-status-upon-checkout/
Or
http://inchoo.net/magento/magento-orders/automatically-invoice-ship-complete-order-in-magento/
Yes There is a way to achieve this use the below code and call in from a cron on ur time basis, The code will change the state from pending to processing after 1 hour of placing order.
<?php
require_once('app/Mage.php');
Mage::app('admin');
$orders = Mage::getModel('sales/order')->getCollection()
->addFieldToFilter('status','pending')
->addFieldToFilter('created_at', array('lt' => new Zend_Db_Expr("DATE_ADD('".now()."', INTERVAL -'60:00' HOUR_MINUTE)")))
->addAttributeToSelect('customer_email')
->addAttributeToSelect('increment_id');
Mage::log("cod diret run from script cron start");
foreach ($orders as $order) {
$incrementId = $order->getIncrementId();
$individualOrder = Mage::getModel("sales/order")->loadByIncrementId($incrementId);
try {
if(!$individualOrder->canInvoice())
{
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice.'));
}
$invoice = Mage::getModel('sales/service_order', $individualOrder)->prepareInvoice();
Mage::log("next");
if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
$invoice->register();
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
$transactionSave->save();
}
catch (Mage_Core_Exception $e) {
}
$OrderStatus = Mage::getModel("sales/order")->loadByIncrementId($incrementId);
$OrderStatus->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true)->save();
$orderid= $individualOrder->getEntityId();
$email = $order->getCustomerEmail();
}

How to send email after successful checkout process?

In my store, I have created a custom module for one-step checkout process.
All the code works fine. But the order detail email is not sent to the customer after the checkout process. Here is the relevant part of my code.
$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();
$order = $service->getOrder();
//This one is the email send code
$order_mail = new Mage_Sales_Model_Order();
$incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order_mail->loadByIncrementId($incrementId);
$order_mail->sendNewOrderEmail();
$this->_redirect('downloadable/customer/products/');
To send/resend an order email in magento
try {
$incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$_order = Mage::getModel('sales/order')->loadByIncrementId($incrementId);
$_order->sendNewOrderEmail();
$this->_getSession()->addSuccess($this->__('The order email has been sent.'));
} catch (Exception $e) {
$this->_getSession()->addError($this->__('Failed to send the order email.'));
Mage::logException($e);
}
try putting it in a try catch to see what the error is like this
<?php
$order_mail = new Mage_Sales_Model_Order();
$incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order_mail->loadByIncrementId($incrementId);
try
{
$order_mail->sendNewOrderEmail();
} catch (Exception $ex) { }
?>
Did you debug when it goes into sendNewOrderEmail? Maybe this helps to figure out where the problem is?
Regards
Try this,
< ?php
$order = new Mage_Sales_Model_Order();
$incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order->loadByIncrementId($incrementId);
try
{
$order->sendNewOrderEmail();
} catch (Exception $ex) { }
?>
Save the above snippet as .phtml and upload it in app/code/core/Mage.
Now make an order in your site and check after successful checkout Email is sending or not.Hope your problem should solved now.

Resources