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

Monday, July 3, 2017

Magento 1.9 Newsletter Unsubscribe Link Not Working

Yes.... still we are working on Magento 1.9 as Magento 2.0 is bit difficult to work with and there were some bugs in it. So recently we created magento store with Magento 1.9 where we faced an issue of adding unsubscribe link in subscription success email and other newsletter.

Subscriber object is shared with all the newsletter email templates. So to add unsubscribe link you just have to add following code.

<a href="{{var subscriber.getUnsubscriptionLink() }}"> Unsubscribe </a>

 But somehow this was not working. So after checking system log we found following error.

getUnsubscribeUrl function not found for Mage_Newsletter_Helper_Data class.

Now this was a strange issue as this is the basic functionality of Magento 1.9 and it is not working. So I checked the Mage_Newsletter_Helper_Data class in app/code/core/Mage/Newsletter/Helper folder and there was no such function but the function name was different.

Following is the function found in data.php

public function getUnsubscribeLink($subscriber)
    {
        return Mage::getModel('core/url')
            ->setStore($subscriber->getStoreId())
            ->getUrl('newsletter/subscriber/unsubscribe', array(
                'id'     => $subscriber->getId(),
                'code'   => $subscriber->getCode(),
                '_nosid' => true
            ));
    }

And in app/code/core/Mage/Newsletter/Model/Subscriber.php file following is the function.

public function getUnsubscriptionLink() {
        return Mage::helper('newsletter')->getUnsubscribeUrl($this);
    }

Which was used in template. So that was the issue. So to solve this issue replace above function with following function in app/code/core/Mage/Newsletter/Model/Subscriber.php file.

public function getUnsubscriptionLink() {
        return Mage::helper('newsletter')->getUnsubscribeLink($this);
    }

And now it should work. Hope this helps you.

Thursday, January 19, 2017

Magento 1.9 Ajax Login with Social Connectors

We are using Magento 1.9 right now for one the project as Magento 2.0 has certain performance issue and some of the extensions are not yet available for Magento 2.0. In this project we have a requirement to add Ajax Login with Social connector options which includes, login with Facebook and Login with Google. Problem we faced is, there is no free extension available in market which allows both ajax login and give you social connector options. So what I did is I installed two different extensions for Ajax Login and Social Connectors and then merged code from social connector plugin to Ajax Login plugin.

In this blog I am going to explain how you can do this.

First of you have to install following two plugins in Magento.

GoMage Social Connector
Ajax Login

With the first login you will get social login options in admin where you can configure your social networks like Facebook and Google and add necessary information like App id and redirect URL etc.

Once it's configured in admin, you will get Social Connectors option in login page like this.



But we need this options in Ajax Login Popup.




So to do this we will copy code for GoMage Extension to this. To do this go to.

app/design/frontend/base/default/template/digitalpianism/ajaxlogin

And open index.phtml file.

Add following code before buttons code.

<!-- Social Login -->
<a href="#" onclick="gomageSocialFBLogin();return false;" title="<?php echo $this->getText('facebook') ?>">
Login with Facebook
</a>

<a href="<?php echo $this->getUrl('gomage_social/google/login', array('_secure' => true, 'gs_url' => Mage::helper('core')->urlEncode(Mage::helper('core/url')->getCurrentUrl())));  ?>" title="<?php echo $this->getText('google') ?>">
Login with Google
</a>

That's it and now you will have social connector options in Ajax login.




I have just added basic designs, you can change it as per your requirements.

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.

Tuesday, February 9, 2016

Why you should upgrade to Magento 2.0


Magento is the recognized as the leading eCommerce platform for open commerce innovation with over $50B in gross merchandise volume transacted on the platform annually. 

Key features of Magento 2.0


Performance & New Technology:
  • Magento 2.0 is 20% faster than old 1.x versions.
  • A new flexible architecture built on a modern technology stack making it quick to build new sites embracing the latest technology.
Better Security:

  • This latest Magento version supports some steps to deal with server validation. Your online store will get better security.
Improved checkout process:
  • It is no secret that most merchants modify default 6 step checkout to make it easier for the customers. Magento 2.0 addresses this issue with its Shipping & Payment checkout flow. It makes it easy to purchase now and it increases conversation rates.

Improved backend processes:
  • Magento 2.0 makes it easy to add/edit your products, manage orders and customers. You can now change backend grids manually by adding/removing columns. Ajax (without page refresh) requests now all over Magento 2.0 backend. 
 A Countdown for Magento 1.X Support
  • Magento will provide its Magento 1 support until 2018.

Easy to Upgrade
  • Simplified upgrade process our merchants an easier path to the latest version of Magento without costly and complex upgrades. 

Auto-testing 

  •  Automated testing to improve code quality which in itself speeds up time to market for new site builds and changes.

If you planning to upgrade by yourself, Unless you are experienced Magento developer do not do that! You would ruin your online business and would most probably loose some crucial customer data along the way. Migration would involve data, theme, extensions and customizations transfer that require extensive code knowledge to perform bug-free. 
Plan your migration ahead for Magento 2 upgrade at fair price


contact us now at info@thedesignshop.co.in or call on (+919898171728)

Thursday, December 3, 2015

Magento - Multiple Actions for Single Coupon Code

Hello,

Recently in one of my project we had a requirements to supports multiple actions for single coupon code. For example if my my cart total is between 500 to 1000, the coupon should give flat 50 off discount and if total is more than 1000, coupon should give flat 100 off discount. But coupon code should be same.

We all know that magento only allows unique coupon code and each coupon will have only once action. So how to do this? I have explained it in this blog.  Please note that this solution needs changes in magento database. So only use it if you database very well.

So while looking to solve this issue. I found out that, in magento database there is a unique key defined for coupon code. So to solve this problem we have to remove that unique key.

So open your Magento database and run following SQL command.

ALTER TABLE salesrule_coupon DROP INDEX UNQ_SALESRULE_COUPON_CODE;

This will drop unique key index.

Now go back to magento admin panel and clear the cache and create two different shopping cart rules with different discounts and keep the coupon code same and it will work.

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.

Tuesday, May 26, 2015

Create Buy 1 Get 1 Free Promotion in Magento

Recently I was working on Magento admin where we have to create promotions like Buy 1 Get 1 Free. Initially I had a trouble setting it as I don't know much about Magento admin. So In this blog I am going to explain how to do it in 10 simple steps so it can save your time.

Step 1:
First of login to Magento Admin and Go to Promotions -> Shopping Cart Price Rules

Step 2:
Click on Add New Rule. (Button on top right corner)

Step 3:
Add a rule name and descriptions. Select customer groups.

Step 4:
Go to conditions tab.

Step 5:
Click on green + button and select option "Product Attribute Combination"

Step 6:
Now it should show you "If an item is FOUND  in the cart with ALL  of these conditions true:" Now click again on new + button at bottom of this text and select SKU from the drop down.

Step : 7
Now it should show you "SKU  is  ... " Click on three dots and Search the SKU of the product for which you want to set offer.

Step: 8
Now go to actions tab and select option "Percent of product price discount" from the Apply drop down.

Step: 9
Set 50 as value in Discount Amount Textbox.

Step 10:
Set two as value in Maximum Qty Discount is Applied To Textbox and save the rule.

That's it basically we gave 50% discount on total if there are product with 2 quantity in cart. This is how user has to pay for only one item and they get other item as free. Hope this helps you.

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.


Friday, May 22, 2015

Magento API Get All Promotions

Hello,

Recently in one of my project we were building mobile app where we have backend as Magento. In this app we have to show all the promotions added in Magento as shopping cart rules. Also there was a requirement to get all the coupons. There is no API for that in default Magento API so I decided to write an API. Here is how to do this.

Mage::app()->setCurrentStore($_storeId);
   
    $rules = Mage::getResourceModel('salesrule/rule_collection')->load();

$comboOffers = array();
$coupons = array();
foreach ($rules as $rule) {
    if ($rule->getIsActive() && $rule->coupon_type == 1) {//No coupons only offers.
        $rule = Mage::getModel('salesrule/rule')->load($rule->getId());
        $comboOffers[] = array(
        "rule_id" => $rule->getId(),
        "name" => $rule->getName(),
        "description" => $rule->getDescription()
        );
        }else{
        $rule = Mage::getModel('salesrule/rule')->load($rule->getId());
        $coupons[] = array(
        "rule_id" => $rule->getId(),
        "name" => $rule->getName(),
        "description" => $rule->getDescription(),
        "coupon_code"=> $rule->getCouponCode()
        );
        }
    }

As you can see in above code we are first getting collection of all the sales rule and then loop trough it and separate offers and coupon. In case of offers like buy 1 get 1 free and percent discount there is no coupon code so coupon_type is set to 1 which means "No Coupon".  While for others there are coupons. So just checking by that we populated two different arrays and return it in form of JSON.

$MainArray['offers'] = $comboOffers;
$MainArray['coupons'] = $coupons;
$MainArray['success'] = true;
echo json_encode($MainArray);

That's it and you will have all the coupons and array of offers available in response. You can use this JSON data to display on screen.



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, December 31, 2013

Convert your eCommerce Store to Mobile Store and Mobile Application

If you read my earlier blog on eCommerce to mCommerce you will come to know about importance of having mobile commerce, in this blog I am going to explain you mobile commerce solution provided by my company. We have a solution to convert your online store to mobile website or mobile application. If you are using Magento, OpenCart, Big Commerce, Wordpress, Joomla, osCommerce, PrestaShop, osCommerce, Zen Cart, Tomato Cart or any other open source shopping cart, we can convert it to mobile web store or application.


When you need Mobile Website and When you need Mobile Application?

There is a difference between mobile website and mobile application. Mobile website is something which user can directly open in the browser and access data of the website.  Mobile application is something which user has to download from the stores and install it and then they can access it.

Following are some advantages of mobile website.

  • Mobile website is instantly available.
  • It can be viewed on almost all the mobile devices.
  • One can find mobile website easily with search engines.
  • Mobile website can be shared easily.
  • Mobile website can act as mobile application as well.

Following are some advantages of mobile application.

  • One can use mobile application offline.
  • One can personalize application.
  • When you need hardware support.

What we offer?

Our solution converts your online store (your eCommerce website) to mobile website/application by using the facilities and services of your existing eCommerce platform. We build a separate mobile website for your store. That means you can manage your website and mobile website with same admin panel offered by your eCommerce platform. All the changes in your store will be available on both the websites.

Why we give you separate mobile website?

As we know the some of the eCommerce platform gives you mobile or responsive theme. These themes are specially designed for mobile screens. But those themes are not 100% user friendly and touch friendly. Also it just gives good look to your mobile website, but in terms of server communication and data usage, it's not up to mark. As for each request your page is refreshed and it go to server and render new page again. This may be slow in some devices depending your network strength. Also it consumes more bandwidth which may not be good for some users. Sometimes it slow down performance in some of the devices as all the device browsers do not have enough computing power. So with responsive theme your site is not 100% user friendly on mobile devices.

What we offer is site built with JavaScript framework. It's a HTML 5 based framework with advanced layout engines. It has a controls with rich user interface. Site build with this framework works very well on the mobile devices at it has on demand rendering. It will crate layout only when it's required, that improves the performance. Once this site is loaded, it will communicate with server only for data. There is no page refresh. Everything works with Ajax based services and only when it's required. Using this approach your data usage will be reduced and site navigation will be much faster. Application built with this framework has look and feel like native application. This is one more benefit, as normally user likes native designs much. Also with this framework you get offline storage was well your website can work offline as well. Also this website can be converted to mobile application easily and with minimum efforts. So it's very cost effective solution. With one mobile website, you also get mobile application.

How does backend works on your existing store?

For back end we use web services and those web services uses your existing platform data. So whatever your platform is web services fetch data from it and send data back to mobile website or application. Our solution is not like predefined and fully developed product as we understand that each customer have their unique requirements and needs. So what we have is basic product developed and we customize it according to your need. Some of the current eCommerce platform offers mobile website and applications they have predefined products, you can not make much changes in it and you just have to use what they offer. In stead of this we offer you customized solution for your need.

Everything from mobile websites to web services are customized as per your requirements. Designs of mobile websites are built according to your requirements as we know that you want keep your branding as it is in mobile websites.

So with our solution you get mobile website on your existing eCommerce platform as per your requirements and your needs. You can manage both your site from your existing admin panel of eCommerce Platform. Our mobile website is designed to work all the mobile devices. With our solution, you can reach to more customers and increase your business.

Contact me if you need such solution.

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

Monday, December 10, 2012

Magento - Display Custom Option Quantity in Manage Product Grid

Hello,

I am back to blogging after long time. Past few months were really busy for me so did not get enough time for blogging.  So recently I was working on magento project, where we have used MageWrox Advanced Custom Option extension to have quantity and SKU for each custom option.

When you go to Catalog --> Manage Products, in grid only total qty is displayed. Our requirement was to display custom options and it's qty there. So how to do that? Here is the trick.

Copy following file


app/code/core/Mage/Adminhtml/Block/Catalog/Product/Grid.php

Now create following folder structure in side app/code/local 

Mage -->
          Adminhtml -->
                              Block -->
                                         Catalog -->
                                                       Product

And put grid.php file there. Now open grid.php file and find following code.

if (Mage::helper('catalog')->isModuleEnabled('Mage_CatalogInventory')) {
            $this->addColumn('qty',
                array(
                    'header'=> Mage::helper('catalog')->__('Qty'),
                    'width' => '100px',
                    'type'  => 'number',
                    'index' => 'qty',
            ));
        }

This is the qty column which displays total inventory quantity. We don't want this so remove it and put following code instead of it.

$this->addColumn('customqty',
            array(
                'header'=> Mage::helper('catalog')->__('Qty'),
                'width' => '200px',
                'index' => 'entity_id',
            'type' => 'text',
            'renderer' =>  'Mage_Adminhtml_Block_Catalog_Product_Renderer_CO'
        ));

Here we will use renderer to format the data we have to display. Now created Renderer folder in 

app/code/local/Mage/Adminhtml/Block/Catalog/Product/

and create co.php file there and add following code there.


class Mage_Adminhtml_Block_Catalog_Product_Renderer_CO extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
public function render(Varien_Object $row)
{
$value =  $row->getData($this->getColumn()->getIndex());
$product = Mage::getModel('catalog/product');
$product->load($value);
$customOptionHTML = '';
foreach ($product->getOptions() as $opt) {
$values = $opt->getValues();
foreach($values as $v){
$customOptionHTML.=$v['default_title'].' : '.$v['customoptions_qty'].'
';
}
}
return ''.$customOptionHTML.'';
}
}

?>
Here we are using product id to get product model and it's custom options. foreach loop is used to iterate through custom options and get custom option title and qty. Here you can make any change in format if you want. 

Please note that this code is tested in magento community version 1.7.0.2








Saturday, September 24, 2011

Case Study: Connect Magento with ChannelAdvisor

Hello,

This blog is again on different topic. It will not have single line of code. It's a case study on Synchronizing magento with leading eCommerce platforms.

Magento is very popular eCommerce platform widely used across the globe. eBay is acquiring magento and magento framework will be core part of eBay soon. eBay, Magento and Paypal are going to launch new eCommerce platform called xCommerce.

Sometimes it would be difficult to manage everything for those who sell their stuff online and using Magento and other sites like eBay and Amaozn. Because you have magento orders in magento admin. You can view eBay orders in eBay seller account and same way for Amazon orders. So seller have to process all the orders at different place. Same way it would be difficult to manage inventory.

To resolve this problems, magento should be synchronized with other platforms so that all the process like inventory management and order processing can be done at one place. Since last few months, I am working Magento synchronization with those platforms and I would like to share that experience here as a case study.

So this blog is about ChannelAdvisor

ChannelAdvisor provides you multiple channel for eBay and Amazon. ChannelAdvisor provides set of API to access ChhanelAdvisor account from outside. Those API can be used  synchronize it with Magento.

Inventory API

Inventory API is used to manage inventory. It gives various functions like

-Add item
-Delete item
-Update item
-Set quantity
-Set price and much more.

And it provides ability to send set of attributes for products so that all the magento attributes can be sent to CA. So basically on magento we need to set a cron job which runs every specified time interval and send updates in inventory to CA.

Order API


It gives an order api using which we can retrieve order details and using those details we can insert those orders in magento via code and process them in admin. You can retrieve orders based on specific date range. Also various filters can be applied like get all the pending orders, get all unshipped orders etc. We can control detail level of information. If you want all the information about order or only selected information, this can be controlled in API. Same way one can control number of orders returned by API. If you specify 100 orders, it will return information about 100 orders in one API call. It also gives you full details about customer, so that can be used in Magento to create customer and assign that order to him. Orders can be synchronized by setting a cron job in magento which runs on specified time interval and fetch those orders and create them in Magento.

Also after processing orders tracking information can be sent back to ChannelAdvisor using order API.

This makes complete integration of CA with Magento.

I hope this post helps you and if you are looking for such solution let me know.

Thanks,