How to Programmatically Apply Discount Amount During Order Process in Magento 1.9

discountmagento-1.9ordersprogrammatically

For more details:- I am facing the same issue as this given below link.
https://magento.stackexchange.com/questions/99767/creating-an-order-in-magento-with-fixed-discount-amount-via-models

My Magento version is 1.9.

Would you please help me for the same?

Thanks in advance!

Best Answer

Finally I found out the answer myself, after several experiment.



//ini_set("display_errors", "1");
//error_reporting(E_ALL);
require_once 'D:\xampp\htdocs\progaming\app\Mage.php'; // This path should be as per your Mage.php path
umask(0);
Mage::app("default");
Mage::app()->loadArea('frontend');
Mage::getSingleton('core/session', array('name' => 'frontend'));
$jason_data=json_decode(file_get_contents("php://input")); // Complete data (User Id,Address Id, Products details and Couponcode) as json format for web-service.

$usr_id=$jason_data->User_id;//$_POST['User_id'];//144; // get Customer Id

$post_products=$jason_data->products;

foreach($post_products as $post_product)
{
  $Id=$post_product->Id;
  //$products[$i]=$Id;
  $products[$Id]['qty']=$post_product->qty;
 // $i++;
}


$customer = Mage::getModel('customer/customer')->load($usr_id);
$couponCode=$jason_data->Coupon_code;

if($couponCode=='')
{
    // If there is no couponcode means we can treat it as a new cart details. so we need to add this details to "sales/quote".
    $quote = Mage::getModel('sales/quote')->setStoreId(Mage::app()->getStore('default')->getId());
    foreach ($products as $productId=>$product) {
    $_product = Mage::getModel('catalog/product')->load($productId);
    $buyInfo = array(
    'qty' => $product['qty'],
    );
    $quote->addProduct($_product, new Varien_Object($buyInfo));
    }
}
else
{

foreach($post_products as $post_product)
{
  $Id=$post_product->Id;
  //$products[$i]=$Id;
  $products[$Id]['qty']=$post_product->qty;
 // $i++;
 $product_id = $Id; // Replace id with your product id 
$qty = $products[$Id]['qty']; // Replace qty with your qty 
$product = Mage::getModel('catalog/product')->load($product_id); 
$cart = Mage::getSingleton('checkout/cart'); 
$cart->init(); 
$cart->addProduct($product, array('qty' => $qty)); 
$cart->save(); 
Mage::getSingleton('checkout/session')->setCartWasUpdated(true); 

}
$couponCode=$jason_data->Coupon_code; 
$oCoupon = Mage::getModel('salesrule/coupon')->load($couponCode, 'code');
if($oCoupon->getRuleId()>0)
{
    $rules = Mage::getModel('salesrule/rule')->getCollection()
       ->addFieldToFilter('rule_id', $oCoupon->getRuleId())
       //      ->addFieldToFilter('is_active', 1)
       ;
//$oRules = Mage::getModel('salesrule/rule')->load($oCoupon->getRuleId());
//print_r($rules);

foreach ($rules as $rule){
    if (!$rule->getCode()) {//skip rules without codes
        continue;
    }
    if(!$rule->is_active)
    {
        $coupon['Status']='Failed';
        $coupon['Errors'][0]='This is not a valid coupon code.';
    break;
    }
    //normaly there should be only one rule that gets here since you can apply only one coupon code
    $quote = Mage::helper('checkout/cart')->getCart()->getQuote();
    $quote->setCouponCode($rule->getCode())->collectTotals()->save(); 
    $quoteCouponCode = $quote->getCouponCode();//get the applied coupon code from the quote
    if ($quoteCouponCode){
        //$rule is valid and $rule->getCode() is a valid coupon code
    $coupon['Status']='Success';
    //$coupon['Errors'][0]='This is not a valid coupon.';
    $cart_details=Mage::helper('checkout')->getQuote();
    $coupon['SubTotal_with_discount']=$cart_details->getSubtotalWithDiscount();
    $coupon['Total_amount']=$cart_details->getSubtotal();
    $coupon['TotalDiscountAmount']=$cart_details->getGrandTotal()-$cart_details->getSubtotal();
    $coupon['Grandtotal']=$cart_details->getGrandTotal();

    }
    else
    {
        $coupon['Status']='Failed';
        $coupon['Errors'][0]='This is not a valid coupon code.';

    }
}


}
else
{
    $coupon['Status']='Failed';
    $coupon['Errors'][0]='This is not a valid coupon code.';
}

// We have already applied for coupon-code. so it should be taken from the "checkout/cart". Otherwise we won't get the discounted price to the order.
$quote =Mage::getSingleton('checkout/cart')->getQuote();


}
    $quote->assignCustomer($customer);
    $address = Mage::getModel('customer/address')->load($jason_data->Address_id);

    $addrs=$address->getStreet();
    $addressData = array(
    'firstname' => $address->getFirstname(),
    'lastname' => $address->getLastname(),
    'street' => $addrs[0],
    'city' => $address->getCity(),
    'postcode' => $address->getPostcode(),
    'telephone' => $address->getTelephone(),
    'country_id' => $address->getCountryId(),
    'region_id' => $address->getRegionId()// id from directory_country_region table
    );
    $billingAddress = $quote->getBillingAddress()->addData($addressData);
    $shippingAddress = $quote->getShippingAddress()->addData($addressData);
    $shippingAddress->setCollectShippingRates(true)->collectShippingRates()
        //->setShippingMethod('freeshipping_freeshipping')
        ->setShippingMethod('flatrate_flatrate')
        ->setPaymentMethod('checkmo');
    $quote->getPayment()->importData(array('method' => 'checkmo'));
    $service = Mage::getModel('sales/service_quote', $quote);
    $service->submitAll();
    $order = $service->getOrder();
    if($order->getIncrementId()!='')
    {
    $order_log['Status']="Success";
    $order_log['Order_id']=$order->getIncrementId();
    }
    else
    {
        $order_log['Status']="Failed";
    }
 echo json_encode($order_log);


Related Topic