Showing posts with label Magento API. Show all posts
Showing posts with label Magento API. Show all posts

Monday, December 5, 2016

Magento 2.0 Missing Write Permissions in Directory var When Run bin/magento setup:upgrade

Hello,

Recently in of our Magento product we installed a Payment Gateway module on our Magento for that we have to run following command.

php bin/magento setup:upgrade php

But every time we run this command we end with following exception.

Missing write permissions to the following directories: public_html/var

so at first it looks like write permission issue in directory, so we gave write permission to directory

chmod 777 ./var

And command run successfully but still we were getting same error while running

php bin/magento setup:upgrade php

That was little wired as we have all the necessary permission but still command was not working. So I decided to get error location and found out following file from where this error is thrown.

setup/src/Magento/Setup/Model/Installer.php

Open this and find following function.

/**
     * Check permissions of directories that are expected to be writable for installation
     *
     * @return void
     * @throws \Exception
     */
    public function checkInstallationFilePermissions()
    {
        $results = $this->filePermissions->getMissingWritableDirectoriesForInstallation();
        if ($results) {
            $errorMsg = "Missing write permissions to the following directories: '" . implode("' '", $results) . "'";
            throw new \Exception($errorMsg);
        }
    }

This is the function which throws an error so what I did is I commented all the code in this function and run the command again

php bin/magento setup:upgrade php

and it worked, it updated properly and after that I again uncommented this code and upload file back to server.

PLEASE NOTE THIS IS A HACK, AS A MAGENTO DEVELOPER I DO NOT SUGGEST TO UPDATE SOURCE FILE BUT THERE WAS NO OTHER OPTION SO I TRIED IT. IF YOU ARE TRYING THIS ON YOUR SIDE, PLEASE BE CAREFUL.

Wednesday, June 15, 2016

Magento 2.0 Products API Get all the Details Of Products.

Hello,

It's been long since I have worked on Magento and published a blog on it. But recently my team was stuck in Magento REST Products API so I have to look into it. Basically the problem was

V1/categories/:categoryId/products API.

This API gives following result in an array.

{
     "sku": "Cotton"
     "position": 10001
     "category_id": "2"
}

Now that's little bit weird as there are no other info of products like product name, description etc. So to get this info we have to use other API which is.


V1/products/:sku

But practically that is not a solution. As we may have n number of products so we can call details API n number of times. So what to do in this case. I have spent almost couple of hours on this but could not get any solution so finally this is what I did.


I used SOAP V1/categories/:categoryId/products API in other PHP file go get array of SKUs and loop through an array and formed following strings of SKUs.

sku1,sku2,sku3,sku4,sku5

Now I used SOAP V1/products API will following search criteria.

V1/products?searchCriteria[filter_groups][0][filters][0][field]=sku&searchCriteria[filter_groups][0][filters][0][value]=sku1,sku2, sku3,sku4,sku5&searchCriteria[filter_groups][0][filters][0][condition_type]=in

As you can see above I used filed SKU in search criteria , passed all the SKU I need in comma separated format and used condition IN.

But wait there was another problem,  After calling above API, I did not get any result. I used few different tricks like

[sku1,sku2,sku3,sku4,sku5]

['sku1','sku2','sku3','sku4','sku5']

'sku1','sku2','sku3','sku4','sku5'

But nothing worked. Again I tried to find solution for sometime ad found solution in Magento 2 GitHub repo.

Please check this link.

https://github.com/magento/magento2/commit/65819d2f61a63e4fa9fc978220f8662ee5472791

This problem is going to be fixed in next release but we could not wait so here I updated Magento code myself.

Open the following file.

lib/internal/Magento/Framework/DB/Adapter/Pdo/Mysql.php

Go to line no 2792

and add following code.

if (($key == 'in' || $key == 'nin') && is_string($value)) {
$value = explode(',', $value);
}

That's it and now run following API.

V1/products?searchCriteria[filter_groups][0][filters][0][field]=sku&searchCriteria[filter_groups][0][filters][0][value]=sku1,sku2, sku3,sku4,sku5&searchCriteria[filter_groups][0][filters][0][condition_type]=in


It should give all the details of mentioned SKU. Hope this helps you.

Sunday, April 24, 2016

Solve Magento Error MySQL: Can't create/write to file '/tmp/#sql_3c6_0.MYI'

Recently one our client called me and said Magento Site is not working so I checked the site and found following error.

MySQL: Can't create/write to file '/tmp/#sql_3c6_0.MYI'

So what's the meaning of this error. At first it looks like a permission issue that tmp folder does not have necessary permissions. I checked through SSH and permission was ok. But still it's not working. 

Second issues could be tmp folder owner is not web root, hence it's not allowing to create files from web users. I checked that also and owner was correct. 

After few checks through SSH, I found out that it was actually an issue of Inodes on server. Disk was almost full and there were no enough space to create new files. So have to delete some files to create space. 

This you can do through SSH, but make sure you what are the files you are deleting and will that create any issues. If you don't know much about magento files and folders, PLEASE CONTACT YOUR HOSTING PROVIDER to delete it for you.

In my case I deleted old backups of database and deleted magento caches and sessions files from /var folder and then my site was up and working normally. 

Hope this helps you.

Saturday, June 20, 2015

Magento Get All Products With Special Prices

Hello,

Recently in one of my projects we were working with Magento APIs. Where we have to fetch a list of all products with special prices to display hot deals on site. There are no APIs for this in Magento so I decided to write custom logic for that.

Here is how you can fetch it.

First get product collections.

$productCollection = Mage::getModel('catalog/product')->getCollection();
$productCollection->addAttributeToSelect(array(
        'image',
        'name',
        'price',
        'short_description'
 ))
 ->addFieldToFilter('visibility', array(
        Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
        Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG
 ));

Then apply filter on product collection to get products with only special prices.

$productCollection->addAttributeToFilter('special_from_date', array('date' => true, 'to' => $todayDate))
                        ->addAttributeToFilter('special_to_date', array('or'=> array(
                        0 => array('date' => true, 'from' => $tomorrowDate),
                        1 => array('is' => new Zend_Db_Expr('null')))
                        ), 'left');

That's it and now it will give you collections of only those products for which there is a special price set.

Now just loop through it and add to array.

$hotDeals = array();
foreach ($productCollection as $product){
        $product = Mage::getModel('catalog/product')->load($product->getId());
$name = $product->getName();
$productPrice = number_format($product->getPrice(), 2, '.', ',');
$specialPrice = number_format($product->getSpecialPrice(), 2, '.', ',');

        $hotDeals[] = array(
"product_id" => $product->getId(),
"product_name" => $name,
"product_image" =>  ($product['image'] == 'no_selection') ? $skinUrl.'frontend/default/default/images/catalog/product/placeholder/thumbnail.jpg' : (string)Mage::helper('catalog/image')->init($product, 'image')->resize(60),
"product_price" => $productPrice,
"special_price" => $specialPrice
);
}

And return it as JSON array.

$resultArray['success'] = true;
$resultArray['hot_deals'] = $hotDeals;

echo json_encode($resultArray);

Hope this helps you.

Friday, June 19, 2015

Magento Load Quote Generated By API on Frontend

Hello,

Recently in one of my project we were using magento to implement checkout process for third party website. Basically we were using Magento APIs to create quote. Now for the paypal payment we were redirecting users to magento url and start checkout process by redirecting them to paypal and on successful payment redirect back to magento site, place and order and redirect them back to their site. Now the problem is when we redirect user to magento site to start checkout process there is no customer or checkout session hence checkout can not be started as shopping cart was empty. In this blog I am going to explain how to load quote generated by API on frontend and start checkout process.

First of all let me explain why we have to this changes. Magento has its own session management on front end. It will not load cart of there is no checkout session found on front end. So we have to store everything in frontend session so magento can remember it.

First of all you have to pass three params when user is redirecting to magento site. Following are three params required.

customer_id
quote_id
store_id

As on front end we have to set specific store and create customer session with customer_id and load shopping cart. I was using following URL for redirection.

http://yourmagento/paypal/express/start/button/1/?customer_id=1&store_id=3&quote_id=146

As you can see above we are directly starting checkout process and redirecting user to paypal. But before that we have to set store and generate customer session and load quote. So lets go step by step. First of all open following file.


app/code/core/Mage/Core/Controller/Varien/Front.php

and find following function.

/**
     * Init Front Controller
     *
     * @return Mage_Core_Controller_Varien_Front
     */
    public function init()
    {
    }

This function is called first for any magento URL request. So here are going to do some initialization steps.

First let's set up the store for which quote id was generated. Add following code to start of init function.

$storeId = '';
//////////////////////////////////////Setting up store id///////////////////////////
if(isset($_REQUEST['store_id'])){
        $storeId = $_REQUEST['store_id'];
    Mage::getSingleton('core/session')->setStoreId($_REQUEST['store_id']); 
}

if( Mage::getSingleton('core/session')->getStoreId()){
$storeId = Mage::getSingleton('core/session')->getStoreId();
}
switch($storeId){
case "1" : Mage::app()->setCurrentStore('store1');break;
case "2" : Mage::app()->setCurrentStore('store2');break;
default: Mage::app()->setCurrentStore('store1');break;
}
//////////////////////////////////////////////////////////////////////////////////////


First we are checking if there is store id in request then first we are storing it to magento core session. Later we are getting it from session and storing respective store. Please note this is required if you have multiple stores, else you can avoid this. In my case there were multiple stores. 

Now next step is to create customer session. Add following code after above code.

////////////////////////////////////////Setting up customer id////////////////////////
if(isset($_REQUEST['customer_id'])){
Mage::getSingleton('core/session')->setCustomerId($_REQUEST['customer_id']); 
}
        
if( Mage::getSingleton('core/session')->getCustomerId()){
Mage::getSingleton('customer/session')->loginById(Mage::getSingleton('core/session')->getCustomerId());
}
//////////////////////////////////////////////////////////////////////////////////////

Now next step is to store quote id in session so it can be used later.

/////////////////////////////////////////Saving Quote Id//////////////////////////////
if(isset($_REQUEST['quote_id'])){
Mage::getSingleton('core/session')->setQuoteId($_REQUEST['quote_id']); 
}
//////////////////////////////////////////////////////////////////////////////////////

Now open following file.

/app/code/core/Mage/Checkout/Model/Session.php

And check following function.

/**
     * Get checkout quote instance by current session
     *
     * @return Mage_Sales_Model_Quote
     */
    public function getQuote()
    {
    }

Add below code to the function after following line.

Mage::dispatchEvent('custom_quote_process', array('checkout_session' => $this));

//////////////////////////////////////////Returning quote stored in session////////////////////////
if(Mage::getSingleton('core/session')->getQuoteId()){
    $this->_quote = Mage::getModel('sales/quote')->setStore(Mage::app()->getStore())->load(Mage::getSingleton('core/session')->getQuoteId());
return $this->_quote;
}
///////////////////////////////////////////////////////////////////////////////////////////////////

That's it and now you can start checkout process with this quote. Hope this helps you. 

Thursday, June 18, 2015

Magento Cart Payment List API, Paypal Not Available

Hello,

Recently we were working on Magento API. Where we were implementing checkout process for a website using Magento platforms. Since we were integrating in third party website which was built on ASP.NET, we were using Magento API. Here we have faced an issue on Select Payment Method step, that Paypal was not coming in list. In this blog I am going to explain how to solve this issue.

Magento API cart_payment.list is the API we were using for this and Paypal was enabled but still were not getting it. The reason was because we were using Paypal Standard Checkout where user is redirected to Paypal website for Payment. Since API is called on backend and there is no UI for that, so there is no point of redirecting to site. Hence this Payment method was ignored in API. Check the following function in app/code/core/Mage/Checkout/Model/Cart/Payment/Api.php file.

/**
     * @param  $method
     * @param  $quote
     * @return bool
     */
    protected function _canUsePaymentMethod($method, $quote)
    {
        if (!($method->isGateway() || $method->canUseInternal())) {
            return false;
        }

        if (!$method->canUseForCountry($quote->getBillingAddress()->getCountry())) {
            return false;
        }

        if (!$method->canUseForCurrency(Mage::app()->getStore($quote->getStoreId())->getBaseCurrencyCode())) {
            return false;
        }

        /**
         * Checking for min/max order total for assigned payment method
         */
        $total = $quote->getBaseGrandTotal();
        $minTotal = $method->getConfigData('min_order_total');
        $maxTotal = $method->getConfigData('max_order_total');

        if ((!empty($minTotal) && ($total < $minTotal)) || (!empty($maxTotal) && ($total > $maxTotal))) {
            return false;
        }

        return true;
    }


Here as you can see It's checking if Payment method is Gateway or can be used internally. Since Paypal standard checkout can not be used in internally as user is redirected to Paypal site. So to solve this issue just comment following code in _canUsePaymentMethod function.

/*if (!($method->isGateway() || $method->canUseInternal())) {
            return false;
}*/

That's it and now cart_payment.list will return you Paypal in list. Please note ideally you have to override this code and should not change in core code.

Monday, May 25, 2015

Magento API Add Promo Item To Cart

Hello,

Recently I was working on a project where we were working with MAgento API. There was a requirement to show promotions to user. I have published a post on this. You can check it from here

Now we had another requirement to add items of promo to cart when user purchase an item. Here in this blog I will explain how to do this. Please note this logic will work for Buy X and get Y product free and Buy X and get Y Free logic.

So in API we were passing rule_id. First we will get rule information.

Mage::app()->setCurrentStore($_storeId);
$rule = Mage::getModel('salesrule/rule')->load($_POST['rule_id']);

Now we will get all the rules conditions.

$conditions = $rule->getConditions()
$conditions = $rule->getConditions()->asArray();

Now we will get all the product SKUs  and qty involved in condition.

$conditionSkus = array();
$conditionQty = array();

foreach( $conditions['conditions'] as $_conditions ){
foreach( $_conditions['conditions'] as $_condition ){
if($_condition['attribute'] == 'sku'){
$string = explode(',', $_condition['value']);
for ($i=0; $i $conditionSkus[] = trim($string[$i]);
}
}else if($_condition['attribute'] == 'quote_item_qty'){
$string = explode(',', $_condition['value']);
for ($i=0; $i $conditionQty[] = trim($string[$i]);
}
}
}
}

As you can see above we have conditions as array and we get sku and number of qty. Number of qty will be useful if you have promos like Buy 2 get 1 Free.

$actions = $rule->getActions();
$actions = $rule->getActions()->asArray();
$actionSkus = array();
$actionQty = null;
if(isset($actions['conditions'])){
foreach( $actions['conditions'] as $_actions ){
$string = explode(',', $_actions['value']);
for ($i=0; $i $actionSkus[] = trim($string[$i]);
}
}
}
else{
$actionQty = $rule->discount_step;
}

In above code as you can see we are checking if there are any skus specified as free products. If there are not skus then it's buy x and get y offers so we are getting free qty from discount_step.

That's it now we just have to loop through array and add item to cart.

$arrProducts= array();
foreach($conditionSkus as $sku){
//load product from sku and get id
$qty = 1;
if(count($conditionQty) != 0){
$qty= $conditionQty[0];
}else if(isset($actionQty)){
$qty = $actionQty;
}
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);
$product = Mage::getModel('catalog/product')->load($product->getId());
$arrProducts[] =  array(
"product_id" => $product->getId(),
"qty" => $qty
);
}

foreach($actionSkus as $sku){
//load product from sku and get id
$qty = 1;
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);
$product = Mage::getModel('catalog/product')->load($product->getId());
$arrProducts[] =  array(
"product_id" => $product->getId(),
"qty" => $qty
);
}

$resultCartProductAdd = $client->call(
$session,
"cart_product.add",
array(
$quote_id,
$arrProducts
)
);

That's it and now promot items will be added to cart.


Wednesday, April 22, 2015

Mageto Cart API - Add Simple Product with Custom Options and Configurable Products

Hello,

Recently I was working with Magento SOAP API and I was using cart_product.add API of Magento. I had to support three types of products.

1) Simple Products
2) Simple Product with Custom Options
3) Configurable Products

If you try to add simple products with custom options without specifying options it will give you error. Same thing for configurable products. You have to specify product options. If you check their documentation, there is no information about adding options and attributes.  So here in this blog I am going to explain how to do that. check following code.


$client = new SoapClient($baseurl.'/api/soap/?wsdl');
        $session = $client->login(USER,PASS);
        $quote_id = $_POST['quote_id'];
        $arrProducts = null;
        if($_POST['has_options'] == "false"){
        $arrProducts = array(
array(
"product_id" => $_POST['product_id'],
"qty" => $_POST['qty']
)
);
        }else{
        $jsondata = $_POST['product_options'];
        $allOptions = json_decode($jsondata,true);
        $productType = $_POST['product_type'];
       
        if($productType == 'simple'){
        $arrProducts = array(
array(
"product_id" => $_POST['product_id'],
"qty" => $_POST['qty'],
'options' => $allOptions
                                               //array("option1"=>"value1","option2"=>"value2")
)
);
        }else if($productType == 'configurable'){
        $arrProducts = array(
array(
"product_id" => $_POST['product_id'],
"qty" => $_POST['qty'],
'super_attribute' => $allOptions
                                               //array("option1"=>"value1","option2"=>"value2")
)
);
        }
        }

As you can see above first we creating SOAP client and then creating $arrProducts. As you can see in above code we are passing product options as JSON encoded data and passing type of product. If product is simple product we set key as "options" and if product type is configurable product we need key as "super_attribute". I hope this helps you.

Wednesday, February 4, 2015

Solution for - Magento cart.totals API Returns Zero After Adding Product

Hello,

Recently in one of my project I was working with Magento SOAP APIs. Where we have used Magento cart.create API to create Magento cart and adding items to it. Now every time I add items I want to refresh totals. So I used cart_product.add API and after that used cart.totals API to get totals. But strangely it was always returning zero, no matter how many products are there. I tried to find out a solutions for it and did some tests and in one of the test I found out that if after creating a cart if I do operations like setting shipping address or add coupons, it was giving accurate totals.  That's really strange. I tried to find out issue for it but I am not magento expert to finally I came up with following solution. After creating  cart, I set dummy billing and shipping address immediately. And then when I add a product and get totals, it was giving me accurate result.

Please note this is not the best solution, but if you want to use you can use this. This will solve your problem. If any magento expert can debug API code and resolve this issue please post solution.

So here is what you have to do.

//Create a Quote

$client = new SoapClient($baseurl.'/api/soap/?wsdl');
$session = $client->login(USER,PASS);
$quote_id = $client->call( $session, 'cart.create', array($_storeId) );

//Add dummy shipping and billing address

$arrAddresses = array(
array(
"mode" => "shipping",
"firstname" => "testFirstname",
"lastname" => "testLastname",
"company" => "testCompany",
"street" => "testStreet",
"city" => "testCity",
"region" => "testRegion",
"postcode" => "testPostcode",
"country_id" => "id",
"telephone" => "0123456789",
"fax" => "0123456789",
"is_default_shipping" => 0,
"is_default_billing" => 0
),
array(
"mode" => "billing",
"firstname" => "testFirstname",
"lastname" => "testLastname",
"company" => "testCompany",
"street" => "testStreet",
"city" => "testCity",
"region" => "testRegion",
"postcode" => "testPostcode",
"country_id" => "id",
"telephone" => "0123456789",
"fax" => "0123456789",
"is_default_shipping" => 0,
"is_default_billing" => 0
)
);
$resultCustomerAddresses = $client->call($session, "cart_customer.addresses", array($quote_id, $arrAddresses));


//Now add a product to cart

$resultCartProductAdd = $client->call(
$session,
"cart_product.add",
array(
$quote_id,
$arrProducts
)
);

//Now get the cart info

$result = $client->call($session, 'cart.totals', $quote_id);
echo json_encode($result);

Hope this helps you and solve your problem.

Wednesday, February 5, 2014

Magento Get Cart Items - How to get the correct list?

Recently we were working on Magento project where we were building custom APIs for the Magento. One such API was to return the current items in current cart session. Now we know that Magento has various type of the products like simple product, Simple product with custom options, configurable product, bundle product etc and in our API we have to add support for all. Now here we have faced the issue with bundle products. As when we add a bundle product with cart, magento also adds selected simple products in cart session.

For example , you have a bundle product called A and it has associated product X, Y and Z. Customer has selected bundle product A and selected options X and Y. Magento will add three product in cart. One is A and other two are Y, Z.  So in our API when we were trying to get items in cart we were getting three items. That is wrong as user has only selected parent bundle product so we should only display it with the options selected. We used following code to get items.

$quote_id = $_REQUEST['quote_id'];
$cartsession = Mage::getSingleton('checkout/session')->getQuote();
foreach ($cartsession->getAllItems() as $item) {

}

So it was returning three items that is wrong. So initially we thought of removing those items from the collections. But then we may have this scenario. User has added bundle product A with X and Y. X product is also sellable independently. So if user has added it, we should display product A and product X in cart. So it was difficult to identify in collections. So what is the solution? After checking class definition of Mage_Sales_Model_Quote in app/code/core/Mage/Sales/Model/Quote.php , we found following two functions.

/**
     * Retrieve quote items array
     *
     * @return array
     */
    public function getAllItems()
    {
        $items = array();
        foreach ($this->getItemsCollection() as $item) {
            if (!$item->isDeleted()) {
                $items[] =  $item;
            }
        }
        return $items;
    }

    /**
     * Get array of all items what can be display directly
     *
     * @return array
     */
    public function getAllVisibleItems()
    {
        $items = array();
        foreach ($this->getItemsCollection() as $item) {
            if (!$item->isDeleted() && !$item->getParentItemId()) {
                $items[] =  $item;
            }
        }
        return $items;
    }

So there is only once difference here in both the function and that is the condition !$item->isDeleted() && !$item->getParentItemId() in second function. It filters the product based in parent id. So in our case product X and Y has parent id product A so that products were avoided. in list and we get only single bundle product. If the product X is added separately, it does not have any parent so it will be still visible in list.

So in short, to get the correct list of items in cart use getAllVisibleItems function if you have to support bundle products and configurable products. If you have only simple products and custom options you can use getAllItems function.

Friday, January 31, 2014

Convert your Magento Store to Mobile Store and Mobile Web Application (Magento Mobile)

Do you have a Magento store and you want to reach to maximum number customers? Then read this blog.

As we know that mobile revolution has changed the world. Number of people are using smart phones and tablets now a days for day to day work. They use mobile internet for almost everything. So your customers may browse your magento store from mobile devices and if your store is not optimized for mobile, it may not load on mobile, or have some issue. Hence users may not be able to buy products on your store and eventually you lost your customer. Now lets see in details, why you need separate mobile web app for your store.

1) Limited Screen Size

On mobile devices screen size is limited so we don't get much space like desktop computers to show data. In very small space you have to effectively show the content to user so user can easily read it and see it. Many magento stores have this issues. As the site is optimized for desktop only, so the content is not visible properly.

2) Limited BandWidth

Generally mobile networks are slow you your magento store may take time to load. As we know that for each magento page there are some CSS some JS files. There are plenty of images, banners etc. Every time when user navigate on your magento store there is considerable delay in loading resources of the page. This may slow down performance on the mobile devices. Some of the users don't like slow websites.  If we use responsive mobile theme, we can improve the layout performance but still we have delay in page refresh

3) Different Resolutions

As we know that there are mobile devices with different screen resolutions. For example iPhone has high resolution retina display. Some of the android phones also support HD graphics. While some mobiles does not support HD graphics. In this scenario your assets like images, CSS should support high resolution and normal resolution. So if you don't support high graphics, your website does not look good on high resolution devices.

So how to solve all above problems and optimize your magento store for all the mobile devices? We have a solution for that. We have built an JavaScript/HTML 5 /CSS 3 based application for magento stores. This application has following features. With our solution your magento store is easily converted to Magento Mobile Store.

1) Responsive layout to fit all the devices.
2) Support all types of touch gestures
3) Show resources based on resolution
4) Rendering engine to support landscape and portrait orientation
5) Have services to load data instead of page refreshes.
6) Supports private browsing
7) Slide navigation for menus
8) Support for local storage of data
9) Supports all types of magento products
10) Customized from same magento admin
11) Optimized for best speed and performance.
12) Rich user interface

Our solution is completely build in HTML and JavaScript. So once the application is loaded. There is no page refresh. All the navigation is local navigation. Data is coming via Ajax request with JSON format. It drastically reduces the network usage. It uses space such a way that you will see the clear information about products and content.

Don't believe it? See the difference
This is our recent implementation in one of the biggest magento store. Following is the regular desktop site in iPhone.

As you see that it looks bit cluttered in iPhone. None of the content is visible unless you zoom in. So to read the content properly, you have to zoom in and zoom out. After zoom in you have to scroll left and right to see the content properly.Now lets how our mobile web app for magento looks in mobile browser.


Pretty cool right? With our application your magento store look like mobile web application in mobile phones and users have easy to use navigation, clear content, rich media, high resolution graphics, high performance. When you implement our solution, your users will still see the desktop site when they view it on desktop browsers. But they will see above mobile app when they visit your store from mobile browser.

Want this app for your magento store? Contact me right away.

Email : hdave10@gmail.com
Skype: hiren.dave
Phone: +91-9327452580

Tuesday, June 28, 2011

Replicate Category Tree from one Magento to Other Magento (Import category in Magento)

Recently I was working on Magento migration where I have to migrate magento shop from one server to other and create an identical shop on other server. Here time was the concern. So instead of creating categories manually I decided to create to replicate whole category tree with same category ids on other server. As next turn was to import product and keep in the same category. I used Magento API to get category tree from old Magento and traversed through it to create categories in new Magento. Check the following code.

I used recursive function to traverse the whole tree.


$flag = 1;
$client=new SoapClient('http://www.oldmagentodomain.com/api/soap/?wsdl');
$sessionId = $client->login('myAPIUserName','myApiKey');

$categoryTree= $client->call($sessionId, 'category.tree');

$currentCategory = $categoryTree['children'];


importCategory($currentCategory,$client); //This starts the import.



function importCategory($currentCategory,$client)
{

      $count= count($currentCategory);
      for($i=0; $i<$count; $i++)
      {
           $categoryId = $currentCategory[$i]['category_id'];
           $categoryInfo = $client->call($sessionId, 'category.info',$id);
   
           if($flag == 1)
           {
               $rootParentCategory = 1;
               $flag = 0;
           }
           else
           {
                $rootCategory = $categoryInfo ['parent_id'];
           }

                             
           $newCategory = new Mage_Catalog_Model_Category();                      
           $newCategory ->setName($categoryInfo ['name']);
           $newCategory ->setUrlKey($categoryInfo ['url_key']);
           $newCategory ->setLevel($categoryInfo ['level']);
           $newCategory ->setIsActive($categoryInfo ['is_active']);
           $newCategory ->setIsAnchor($categoryInfo ['is_anchor']);
           $newCategory ->setId($categoryInfo ['category_id']);

                               
           $parentCategory = Mage::getModel('catalog/category')->load($rootCategory);
           if($parentCategory)
           {
                $newCategory ->setPath($parentCategory->getPath()."/");                              
           }
            else
           {      
                 $newCategory ->setPath('');                                
            }

           $newCategory ->save(); 

           $childCategories = $currentCategory[$i]['children'];

           if($childCategories)
           {
               importCategory($childCategories,$client);
           }



     }
}

I hope this will help you. Now next post would be about importing products via Magento API. Stay tuned.

Thanks.