.

.

Logged In User Order Detail By Order Id in Magento Programmatically


Here , we get all shipping & billing Information , Shipping Method & Payment Method, & also
Item List with Order Subtotal & Grand Total. Let See Below Code



<?php
require_once 'app/Mage.php';
Mage::app('default');    
Mage::getSingleton("core/session", array("name" => "frontend"));
?> 
<?php
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
// print_r($ordercol);
if($_REQUEST['orderId']!='')
{
$orderid=$_REQUEST['orderId'];
$order   = Mage::getModel('sales/order')->load($orderid);
$numorder=count($order);
// get order id or order number
$ordernumber=$order->getIncrementId();
$date=$order->getCreatedAtStoreDate();
$orderdt= str_replace(","," ",$date);
//get order total value:
$orderTotalValue = number_format ($order->getGrandTotal(), 2, '.' , $thousands_sep = '');
$paymentmethod = $order->getPayment()->getMethodInstance()->getCode();
$status= $order->getStatusLabel();
$firstname = $order->getCustomerFirstname();
$lastname = $order->getCustomerLastname();
$billingname=$order->getBillingAddress()->getName();
$billingname=$order->getBillingAddress()->getStreetFull();
//print_r($order->getBillingAddress());
//get Billing Information
$_billingAddress = $order->getBillingAddress();
$billingfname= $_billingAddress->getFirstname();
$billinglname= $_billingAddress->getLastname();
$billingaddres=$_billingAddress->getStreetFull();
$billingregion = $_billingAddress->getRegion();
$billingcity = $_billingAddress->getCity();
$billingpostcode= $_billingAddress->getPostcode();
$billingphone = $_billingAddress->getTelephone();
$billingcountrycode=$_billingAddress->getCountry_id();
// get countryname  by country code
 $billingcountry = Mage::app()->getLocale()->getCountryTranslation($billingcountrycode);
// get shipping Information
$_shippingAddress = $order->getShippingAddress();

$shippingfname= $_shippingAddress->getFirstname();
$shippinglname= $_shippingAddress->getLastname();
$shippingaddres=$_shippingAddress->getStreetFull();
$shippingregion = $_shippingAddress->getRegion();
$shippingcity = $_shippingAddress->getCity();
$shippingpostcode= $_shippingAddress->getPostcode();
$shippingphone = $_shippingAddress->getTelephone();
$shippingcountrycode=$_shippingAddress->getCountry_id();
// get countryname  by country code
 $shippingcountry = Mage::app()->getLocale()->getCountryTranslation($shippingcountrycode);

// get shipping Method Details
$shippingdesc=$order->getShippingDescription();
 $shippingmethod = $order->getShippingMethod();

 //get Order Items Collections
 
 $orderItems = $order->getItemsCollection();
 $i=0;
foreach ($orderItems as $item){
    $productid = $item->product_id;
    $productsku = $item->sku;
     $productprice = $item->getPrice();
     $productname = $item->getName();
  $productqty = $item->getData('qty_ordered');
 //echo $productsubtotal = $item->getSubTotal();
    $productsubtotal = $productqty * $productprice;
   
 $itemdetail[$i]=array("productId"=>$productid,"productName"=>$productname,"productSku"=>$productsku,"productQty"=>$productqty,"productPrice"=>$productprice,"productSubTotal"=>$productsubtotal);
 
$i++; 
}
 
 // order subtotal
 $ordersubtotal=$order->getSubtotal();
 
 // order shipping Amount
 $ordershipping=$order->getShippingAmount();
 
 //order grand total
$ordergrandtotal=$order->getGrandTotal(); 
 

$data['responseCode']='1';
$data['msg']='successful';
$data['orderDetailOutput']=array("orderNumber"=>$ordernumber,"orderDate"=>$orderdt,"shippingFirstName"=>$shippingfname,"shippingLastName"=>$shippinglname,"shippingAdress"=>$shippingaddres,"shippingRegion"=>$shippingregion,"shippingCity"=>$shippingcity,"shippingPostCode"=>$shippingpostcode,"shippingPhone"=>$shippingphone,"shippingCountry"=>$shippingcountry,"shippingMethod"=>$shippingmethod,"shippingDescription"=>$shippingdesc,"paymentMethod"=>$paymentmethod,"billingFirstName"=>$billingfname,"billingLastName"=>$billinglname,"billingAdress"=>$billingaddres,"billingRegion"=>$billingregion,"billingCity"=>$billingcity,"billingPostCode"=>$billingpostcode,"billingPhone"=>$billingphone,"billingCountry"=>$billingcountry,"itemList"=>$itemdetail,"orderSubTotal"=>$ordersubtotal,"orderShipping"=>$ordershipping,"orderGrandTotal"=>$ordergrandtotal);
}
else
{
$data['responseCode']='0';
$data['msg'] ='Please Select Order Id';

}
}
else
{
 $data['responseCode']='0';
 $data['msg']='Please Login First';
 }


$data2=json_encode($data);
echo $data2;
 ?>

Logged In User Order List in magento programmatically


Get Order List By Customer Id in Magento

<?php
 require_once 'app/Mage.php';
 Mage::app('default');  
 Mage::getSingleton("core/session", array("name" => "frontend"));
 ?>
<?php
 /* create functions */
  function isCustomerHasOrders($customerId, $grandTotal = null)
{
    $orderCollection = $this->getCustomerOrderCollection($customerId, $grandTotal);
    return (bool)$orderCollection->getSize();
}

function getCustomerOrderCollection($customerId, $grandTotal = null)
{  
    $orderCollection = Mage::getResourceModel('sales/order_collection')
        ->addFieldToSelect('*')
        ->addFieldToFilter('customer_id', $customerId)
        ->addFieldToFilter('state', array('in' => Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates()))
        ->setOrder('created_at', 'desc')
    ;
    if ($grandTotal && $grandTotal > 0) {
        $orderCollection->addFieldToFilter('base_grand_total', array ('gteq' => $grandTotal));
    }
    return $orderCollection;
}
/* end function */

// start code here

if (Mage::getSingleton('customer/session')->isLoggedIn()) {
  
$customer = Mage::getSingleton('customer/session')->getCustomer();
$customerId = $customer->getId();
  


$ordercol=getCustomerOrderCollection($customerId, $grandTotal = null);
$countorder= count($ordercol);
if($countorder > 0)
{
$i=0;
foreach($ordercol as $orderdet)
{
$order   = Mage::getModel('sales/order')->load($orderdet->getId());
$orderid=$orderdet->getId();

// get order id or order number
$ordernumber=$order->getIncrementId();

$orderdate1=$order->getCreatedAtStoreDate();

 $orderdate2 = str_replace(",","",$orderdate1);
  $orderdate=trim($orderdate2,'');

//echo date(strtotime($order->getCreatedAtStoreDate());

//get order total value:
 $orderTotalValue = number_format ($order->getGrandTotal(), 2, '.' , $thousands_sep = '');

 $payment_method_code = $order->getPayment()->getMethodInstance()->getCode();

 $status= $order->getStatusLabel();

 $firstname = $order->getCustomerFirstname();

$currency_code = Mage::app()->getStore()->getCurrentCurrencyCode();
 $lastname = $order->getCustomerLastname();


 // item list
 $orderItems = $order->getItemsCollection();
 $j=0;
foreach ($orderItems as $item){
    $productid = $item->product_id;
    $productsku = $item->sku;
     $productprice = $item->getPrice();
     $productname = $item->getName();
     $productqty = $item->getData('qty_ordered');
    //echo $productsubtotal = $item->getSubTotal();
    $productsubtotal = $productqty * $productprice;
  
  
    // get product image
    $productimg2 = Mage::getModel('catalog/product')->load($item->product_id);
    $productMediaConfig = Mage::getModel('catalog/product_media_config');
    $prodimgthumbnailUrl = $productMediaConfig->getMediaUrl($productimg2->getThumbnail());
 
 $itemdetail[$j]=array("productId"=>$productid,"productName"=>$productname,"productSku"=>$productsku,"productQty"=>$productqty,"productPrice"=>$productprice,"productSubTotal"=>$productsubtotal,"prodImgUrl" =>$prodimgthumbnailUrl);

$j++;
}


$orderlist[$i]=array("orderId"=>$orderid,"orderNumber"=>$ordernumber,"orderDate"=>$orderdate,"shipTo"=>$firstname.''.$lastname,"orderTotal"=>$orderTotalValue,"currency"=>$currency_code,"itemList"=>$itemdetail);
$i++;
}
$data['responseCode']='1';
$data['msg']='successfull';
$data['orderListResponse']=$orderlist;
}
else
{
$data['responseCode']='0';
$data['msg']='No Order Found';
}

}
else
{
    $data['responseCode']='0';
    $data['msg']='Please Login First';
    }
$data2=json_encode($data);
echo $data2;
 ?>

Customer Logout in Magento Programmatically




$session = Mage::getSingleton('customer/session'); used for customer Logged Out.
Check Below code
<?php
require_once 'app/Mage.php';
 Mage::app('default');
 Mage::getSingleton("core/session", array("name" => "frontend"));
 // get login customer data
 if(Mage::getSingleton('customer/session')->isLoggedIn()) {
     $customerData = Mage::getSingleton('customer/session')->getCustomer();
      //echo $customerData->getId();
 }


//For Logout Customer
 Mage::getSingleton('customer/session')->logout();

$data['responseCode']='1';
$data['msg']="Logged Out Successfully";

$data2=json_encode($data);
echo $data2;

?>

Get allowed country ,state list in magento programmatically


Get country name by country code


$countryList = Mage::getModel('directory/country')->getResourceCollection()
                                                  ->loadByStore()
                                                  ->toOptionArray(true);

Get Collection Of All Countries
<?php
ini_set('max_execution_time', 6000);
header('Cache-Control: no-cache, must-revalidate');

 require_once '../app/Mage.php';
 Mage::app();
 header("Content-Type: application/json");
 ?> <?php
  function getCountryCollection()
{
 $countryCollection = Mage::getModel('directory/country_api')->items();
 return $countryCollection;
}
  $countryList = getCountryCollection();
              
 //$countryList = Mage::getModel('directory/country')->getResourceCollection()->loadByStore()->toOptionArray(true);             
              //print_r($countryList);


$numcountry= count($countryList);
if($numcountry>0)
{
$i=1;
foreach ($countryList as $item) { 
 $itemDetail[$i]=array("countryId"=>$item['country_id'],"countryCode"=>$item['iso2_code'],"countryName"=>$item['name']);
//print_r($itemDetail);
$i++;  
}
$countryList=$itemDetail;
$data['responseCode']='1';
$data['msg']='successful';
$data['countryResponse']=$itemDetail;
}
else
{
$data['responseCode']='0';
$data['msg']='No Country found';
}
$data2 = json_encode($data);
echo $data2;


?>

Get statelist or region by country code
<?php
/*
created by :Rinky Kandwal
created date : 4/9/2016
Description : Get State List by country code ?countcode='US'

*/
?><?php
ini_set('max_execution_time', 6000);
require_once '../app/Mage.php';
Mage::app();
header("Content-Type: application/json");
?><?php
function getRegionCollection($countryCode)
{
 $regionCollection = Mage::getModel('directory/region_api')->items($countryCode);
 return $regionCollection;
}
if($_REQUEST['countcode']!='')
{
 $countryCode=$_REQUEST['countcode'];
$regionCollection = getRegionCollection($countryCode);
 $numregioncol=count($regionCollection);
if($numregioncol>0)
{
$i=0;
foreach($regionCollection as $regincol)
{
$itemcollection[$i]=array("regionId"=>$regincol['region_id'],"code"=>$regincol['code'],"name"=>$regincol['name']);
$i++;
}
$data['responseCode']='1';
$data['msg']="successful";
$data['regionResponse']=$itemcollection;
}
}
else
{
$data['responseCode']='0';
$data['msg']='No Country Code Selected';
}
$data2=json_encode($data);
echo $data2;
?>

Delete Cart Product by Product Id in magento Programmattically


Magento remove item from cart programmatically : We sometimes need to remove products from the cart on the basis of  id.

<?php
 require_once 'app/Mage.php';
 Mage::app('default');  
 Mage::getSingleton("core/session", array("name" => "frontend"));

  ?>
<?php
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
$productId=$_REQUEST['productId'];
if($_REQUEST['productId']){
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
if(!empty($items))
{

foreach ($items as $item) {
    if ($item->getProduct()->getId() == $productId) {
     $itemId = $item->getItemId();
        $cartHelper->getCart()->removeItem($itemId)->save();
        $data['responseCode']='1';
        $data['msg']='Delete Successfully';  
        break;
    } else {
    $data['responseCode']='0';
    $data['msg']='No Product Found';
    } }
  
}
else
{
$data['responseCode']='0';
    $data['msg']='No Carts Items Found';  
  
    }
    }
else {
$data['responseCode']='0';
$data['msg']="Please Select Product";
}
}
else
{
    $data['responseCode']='0';
    $data['msg']='Please Login First';
    }

$data2=json_encode($data);
echo $data2;
?>

Get All Cart Products with Subtotal & grand Total in Magento Programattically



The best way to access Magento shopping cart data and get items information. Get products id, name, price, quantity, etc. present in your cart. Get number of items in cart and total quantity in cart. Get base total price and grand total price of items in cart.Let see Code

<?php
require_once 'app/Mage.php';
Mage::app('default');   
Mage::getSingleton("core/session", array("name" => "frontend"));
$cartdetails=Mage::getSingleton('checkout/session')->getQuote();
$i=0;
$productMediaConfig = Mage::getModel('catalog/product_media_config');
$numcart= count($cartdetails->getAllItems());
if($numcart>0)
{
//foreach ($cartdetails->getAllItems() as $item) {

foreach ($cartdetails->getAllItems() as $item) {
        //$cartid=$item->getId();
  
        $productid=$item->getProductId();    
     $product2 = Mage::getModel('catalog/product')->load($item->getProductId());  
     $productname=$item->getProduct()->getName(); 
 
     $productsku=$item->getProduct()->getSku();
   
     $productimageurl=$productMediaConfig->getMediaUrl($product2->getThumbnail());
 
     $productqty=Mage::getModel('checkout/cart')->getQuote()->getItemsQty();
 
        $productprice=$item->getProduct()->getPrice();
 
        $currency_code = Mage::app()->getStore()->getCurrentCurrencyCode(); 
    
 
  if (Mage::helper('tax')->displayCartPriceInclTax() || Mage::helper('tax')->displayCartBothPrices()):
    $_incl = $this->helper('checkout')->getPriceInclTax($item);
  
 $specialproductprice=Mage::helper('checkout')->formatPrice($_incl- $item->getWeeeTaxDisposition());
 
else:
    
 $specialproductprice=$final_price= $item->getPrice();
 
endif;

$itemsubtotal=$item->getProduct()->getSubtotal(); 
 $itemDetail[$i]=array("productId"=>$productid,"productName"=>$productname,"productSku"=>$productsku,"productQty"=>$item->getQty(),"productPrice"=>$productprice,"currencyCode"=>$currency_code,"specialProductPrice"=>$specialproductprice,"productImageUrl"=>$productimageurl);
//print_r($itemDetail);
$i++;
  
}

// Total items added in cart

 $totalitems = Mage::getModel('checkout/cart')->getQuote()->getItemsCount(); 

// Total Quantity added in cart

 $totalquantity = Mage::getModel('checkout/cart')->getQuote()->getItemsQty();

// Sub Total for item added in cart
 $subtotal = Mage::getModel('checkout/cart')->getQuote()->getSubtotal();


//grand total for for item added in cart
 $grandtotal = Mage::getModel('checkout/cart')->getQuote()->getGrandTotal();


$data['responseCode']='1';
$data['msg']='successful';
$data['itemResponse']=$itemDetail;
$data['totalItems']=$totalitems;
$data['totalQuantity']=$totalquantity;
$data['subTotal']=$subtotal;
$data['grandTotal']=$grandtotal;
//$data['quoteId']=$quotid;
}
else
{
$data['responseCode']='0';
$data['msg']='No items found';
}
$data2 = json_encode($data);
echo $data2;

?>

Integrate Bulk Sms Gateway API in php


Bulk SMS Gateway can be accessed HTTP by submitting values by GET method with all required message parameters and mobile numbers.
You need to have:
1. Username
2. Password
3. Destination Mobile No.
3. Message Text
4. Sender ID

Sending Messages:
For sending single SMS message, SMS gateway requires various parameters including username, password & apikey for authentication purposes. All the parameters need to be sent via HTTP protocol using the GET method. The following are the parameters required:

Username :- Your registered Username
Password :- Your registered Password
Source :- Sender ID
Dmobile :- Destination mobile number
Message :- Message to be send


suppose you have Api Like that

http://bulksms.sms2india.info/sendsms.php?user=abcd&password=123123&sender=testing&countrycode=91&PhoneNumber=123456&text=This+is+API+Testing+Message&gateway=UES3B2ZX


Use this code to Integrate
<?php
$ch = curl_init('http://bulksms.sms2india.info/sendsms.php?');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,"user=pramod360&password=123123&sender=Snoweb&countrycode=91&PhoneNumber=8802782081&text=This+is+API+Testing+Message&gateway=UES3B2ZX");
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$data = curl_exec($ch);
echo $data;
?>

Add Product to cart without custom option in magento programmatically




Add Product in to cart programmatically. Let see code


<?php
require_once 'app/Mage.php';
Mage::app('default');
Mage::getSingleton("core/session", array("name" => "frontend"));

$productId = $_REQUEST['productId'];
$qty = $_REQUEST['qty'];

if($productId!='' && $qty!='')
{
$_product = Mage::getModel('catalog/product')->load($productId);

if ($_product->getId()):
      try {
                $cart = Mage::getModel('checkout/cart');
                $cart->init();
                $cart->addProduct($_product, array('qty' => $qty));
                $cart->save();
                Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
               //session Not working so we use       
          
            
                $data['responseCode']='1';
                $data['msg']='Product has been added to basket';        

            }
             catch (Exception $exception) {          
$data['responseCode']='0';
$data['msg']="There is an error ".$exception->getMessage();        
}
  
else:
$data['responseCode']='0';
$data['msg']="Product not exist";
endif;
}
else
{
$data['responseCode']='0';
$data['msg']="Please select product & quantity";
}
$data2 = json_encode($data);
echo $data2;

?>
Login by email & password in magento programmattically

Login by email & password in magento programmattically

To login a customer into a given website by email and password we must obtain a session object on which we have to call the login()-method. But before that we have to initialize the correct application object. This means that the first parameter to pass to Mage::app() or Mage::init() is the website ID of the customer to login and the second one is the string "website".

<?php
require_once 'app/Mage.php';
 ?>
 <?php 
    Mage::app('default');    
    Mage::getSingleton("core/session", array("name" => "frontend"));
 $data=array();
 $email = str_replace("'","`",$_REQUEST['emailid']);
    $password = str_replace("'","`",$_REQUEST['password']);   
    $websiteId = Mage::app()->getWebsite()->getId();
    $store = Mage::app()->getStore();
    $customer = Mage::getModel("customer/customer");
    $customer->website_id = $websiteId;
    $customer->setStore($store);
 
//$jSon = ' {"login_data":[ ';

if (!empty($email) && !empty($password )) 
{
    try {
        $customer->loadByEmail($email);
        $session = Mage::getSingleton('customer/session')->setCustomerAsLoggedIn($customer);
        $session->login($email, $password);  
        $data['responseCode']='1';
        $data['msg']='successful';
        $data['result']=array("customerId"=>$session->getCustomer()->getId(),"customerFirstName"=>$session->getCustomer()->getFirstname(),"customerLastName"=>$session->getCustomer()->getLastname(),createdAt=>$session->getCustomer()->getCreatedAt(),"customerEmail"=>$session->getCustomer()->getEmail(),"sessionId"=>$session->getCustomer()->getId());
    } 
 catch(Exception $e){
 $data['responseCode']="0";
 $data['msg']=$e->getMessage();
     // $jSon .= ' {"message":"Email or password Invalid."}'; 
    }

}
else 
{
$data['responseCode']="0";
$data['msg']="Email and password are required";
       
}
$data2 = json_encode($data);
echo $data2;


?>

New Customer Registration in Magento Programmatically

create a new customer through a signup form, in some cases, that might take too long.

For starters, let’s add a customer with some basic information.

<?php 
require_once '../app/Mage.php';
Mage::app();
header("Content-Type: application/json");
?> <?php
if($_POST)
{
$firstname=str_replace("'","`",$_POST['firstname']);
$lastname=str_replace("'","`",$_POST['lastname']);
$emailid=str_replace("'","`",$_POST['emailid']);
$password=$_POST['password'];
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer   ->setWebsiteId($websiteId)
            ->setStore($store)
            ->setFirstname($firstname)
            ->setLastname($lastname)          
            ->setEmail($emailid)
            ->setPassword($password);
try{
    $customer->save();
    $data['responseCode']='1';
    $data['msg']='Registered successful';  
}
catch (Exception $e) {
    Zend_Debug::dump($e->getMessage());
    $data['responseCode']='0';
    $data['msg']='Already Exist';
}
}
else
{
$data['responseCode']='0';
$data['msg']="Enter All Fields";
}
//print_r($data);
$data2 = json_encode($data);
echo $data2;

?>


Solution for Inactive Admin Links in Magento 2

Magento has released the beta version for Magento 2. Magento developers are keenly following these releases and are trying to analyze Magento 2 Upgrades. One of the common issues noted by developers are the broken links in Magento 2 when installed in Windows.
The beta version (Magento ver. 0.74.0-beta13) is working fine when installed in Linux. When the beta version is installed in Windows, the links and CSS are disabled.  The images in the admin panel and front end are not loaded (i.e.) there are inactive admin links in windows.
This has been a common issue faced by many Windows developers (under Xampp) for Magento 2 (Magento ver. 0.74.0-beta13).

SOLUTION: After installing Magento 2 in Windows under Xampp, if your admin and front end link’s are not working, please follow the below steps to fix the same…

1)Remove everything, except .htaccess file from pub/static folder
2)Open up app/etc/di.xml
3) find the path “Magento\Framework\App\View\Asset\MaterializationStrategy\Symlink” and replace to “Magento\Framework\App\View\Asset\MaterializationStrategy\Copy”

Note: Remove entire files and folder under pub/static except .htaccess file.
Now if you refresh the admin panel, the images in the admin panel and the front end will load and be active and functional.
 

Exception printing is disabled by default for security reasons in magento 2.



  I was installing Magento 2 and got the following error.

    There has been an error processing your request
    Exception printing is disabled by default for security reasons.

Solution: It's similar to Magento 1, but local.xml.sample is located in pub/errors.

Just rename local.xml.sample to local.xml within pub/errors directory.

Missing PHP extension .intl during installing Magento 2





I was trying to install Magento 2.0 on my local Xampserver.
The readiness check tells me that the PHP extension intl. is missing but when I look at the installed extensions than intl is installed.

Solution : I solved this issue after enable  extension=php_intl.dll  from php.ini file in xampp.