Ultimate Magento 1 Developer Guide : How to get product details using rest API in Magento 1.x ?

Future is mobile apps. Especially, eCommerce Mobile Apps. Sooner or later you’ll run into a case where you need REST API for your online store and you found that Magento does not support all Magento REST API. What should you do now? How can you write REST API for your online store as per client need?

The Magento REST API allows you to use various data entities such as customer, catalog and order information to third-party applications. I’d like to share it with you a quick, simple, well written and easy solution which will explain how can you retrieve the product details with the help of REST API.

You are working on a mobile application and want to display product after customer selected a category. You are able to get the list of the product by category in REST API request but that list doesn’t have many details about the product and you want to show more product details to the users. What should you do to get more product information so that you can show the image and other things in a mobile app?

Magento Rest API for Product Details by SKU

Step 1: Get the SKU which you need to get the product details.

      $sku  =  $this->getRequest()->getParam('SKU');

Step 2: Load the product using the product SKU. We can also load product by its attributes, like SKU, Id. Assuming product SKU to be ‘1000’.

       // Mage main object
	$catalogMageObj = Mage::getModel('catalog/product');
	$products = $catalogMageObj->loadByAttribute('sku', $sku);

Step 3: load the product custom attributes details.

	$custom_attributes = array();
	$attributes = $products->getAttributes();
	foreach ($attributes as $attribute) {
		if ($attribute->getAttributeCode() =="category_ids"){
			$custom_attributes[] = array(
				"attribute_code"=> $attribute->getAttributeCode(),
				"value"=> $products->getCategoryIds()
			$custom_attributes[] = array(
				"attribute_code"=> $attribute->getAttributeCode(),
				"value"=> $attribute->getFrontend()->getValue($products)

Step 4: Create and return the full array of the loaded product.

protected function getProductDetailsBySku()
        $sku  =  $this->getRequest()->getParam('sku');	

        // Mage main object
	$catalogMageObj = Mage::getModel('catalog/product');
	$products = $catalogMageObj->loadByAttribute('sku', $sku);

	$custom_attributes = array();
	$attributes = $products->getAttributes();
	foreach ($attributes as $attribute) {
		if ($attribute->getAttributeCode() =="category_ids"){
			$custom_attributes[] = array(
				"attribute_code"=> $attribute->getAttributeCode(),
				"value"=> $products->getCategoryIds()
			$custom_attributes[] = array(
				"attribute_code"=> $attribute->getAttributeCode(),
				"value"=> $attribute->getFrontend()->getValue($products)
	$data = array(
		'id' => $products->getEntityId(),
		'sku' => $products->getSku(),
		'name' => $products->getName(),
		'attribute_set_id' => (int)$products->getAttributeSetId(),
		'price' => $products->getPrice(),
		'status' => $products->getStatus(),
		'visibility' => $products->getVisibility(),
		'type_id' => $products->getTypeId(),
		'created_at' => $products->getCreatedAt(),
		'updated_at' => $products->getUpdatedAt(),
		'product_links' => $productstypes, 
		'custom_attributes'  => $custom_attributes
	//return $products;
	return $data;

How to get Configured Product Extension Attributes

Getting all options of a specific attribute in Magento is fairly easy but sometimes A more challenging task is to get the options and values that are applicable to a particular configurable product. This can solve using the following code:

// get product extension attributes details
	public function getProductExtensionAttributes($productObj){
		if (!is_object($productObj)){
			return false;
		$extensionAttributesFinalArray = array();
		$extensionAttributesArray = array();
		if ($productObj->isConfigurable()){
			$optionsData = $productObj->getTypeInstance(true)->getConfigurableAttributesAsArray($productObj);
			foreach ($optionsData as $option) {
				// get option values
				$values =  $option['values'];
				$tempDataItems = array();
				foreach ($values as $value) {
					$tempData = array(
							"value_index" => $value['value_index'],
							"title" => $value['label']
					$product_super_attribute_id =  $value['product_super_attribute_id'];
					array_push($tempDataItems, $tempData);
				// create temp array for extension_attributes
				$extensionAttributesTempArray = array(
						"id" => $option['id'],
						"label" => $option['label'],
						"position" => $option['position'],
						"attribute_id" => $product_super_attribute_id,
						"values" => $tempDataItems,
						"product_id" => (int)$productObj->getEntityId(),
				array_push($extensionAttributesFinalArray, $extensionAttributesTempArray);
			$extensionAttributesArray['configurable_product_options'] = $extensionAttributesFinalArray;
			$extensionAttributesArray['configurable_product_links'] = [];
		// returning response
		return $extensionAttributesArray;

The resulting array will consist of an associative array, indexed by the attribute label, with nested arrays containing attribute value => attribute label items.


This is the era of eCommerce with the Mobile app as peoples are spending time on their mobile. The user has various choices to purchase an item from the web that’s why your eCommerce website should remain competitive in your business. The mobile app is a new way, which turns your Magento website into a fully functional eCommerce store with everything user needs.

On this tutorial, we have discussed how to get all the product details Magento which you can use to develop your Magento Mobile App.


Further reading

The Death Of Magento Performance: 13 Common Guidelines

The world is moving fast, and people’s attention span is decreasing. Even for online shopping people opt for it because they can save a lot of time and efforts in the process. So, speed and good Magento performance are central to the success of any eCommerce store. A 1-second delay in page response can result in a 7% reduction in conversions. The speed of your business website matters. Fast-loading websites perform better on every front: higher search ranking, excellent user experience, and better user engagement. Most importantly, quick-loading websites deliver higher conversions and higher revenue.

When we are talking about the Magento Performance site, it’s not just about the page load speed, but every function and process a customer has to go through from searching for products to the checkout process. Performance optimization is an integral part of Magento development and cannot be underestimated. Magento 2 has fixed many issues with the previous version, but there is still a lot you can do to improve the performance of your Magento 2 site.

Magento Performance: 13 Common Guidelines

There are many Magento Performance optimization techniques out here. In this post, I am going to share with you some simple tips to speed Magento 2 store.

Server Requirement & configuration optimization

As you may know, the server is the key factor for Magento Performance. If your picked server is not good enough you can’t have a good website. Hence, to have a good website, we suggest you replace it with a dedicated server. Moreover, when you choose a host, please keep these categories in mind.

Code and Database Optimization

Regularly Improve your database performance using query indexing and broad optimization scripts. Use your DB management system to optimize the database on the frequent basis. Let’s me show you little tips to optimize via MySQL configuration. You can try and get the following settings in my.cnf

query_cache_type = 1
query_cache_size = 32M
php_value memory_limit 128M

Optimize Magento database by Cleaning log

If you are wondering when you need to optimize Magento database, you can check your site. In case you have around 200MB, it is time for cleaning.

Enable JS & CSS optimization

CSS and JS file help your front end look better. Yet, they are one of the core factors that slow down your site speed. Luckily you can cut influence in magento 2 by enabling JS & CSS optimization.

To enable JS & CSS optimization: Go to Stores -> “Configuration” in “Settings” Section -> “Developer” in “Advanced” Tab -> Section “JavaScript Settings” (Fields “Enable Javascript Bundling“, “Merge JavaScript Files“, “Minify JavaScript Files” change to “Yes”)

css optimization

Go to Stores -> “Configuration” in “Settings” Section -> “Developer” in “Advanced” Tab ->-> Section “CSS Settings” (Fields “Merge CSS Files“, “Minify CSS Files” change to “Yes“)

css optimization


Implementing a Content Delivery Network (CDN) with Magento is one of the easiest ways to instantly see decreased load times which enables serving your assets from a location geographically closest to your customers and hence reduces latency and increases download speed for those assets. To set up CDN, please go to STORES -> Configuration -> GENERAL -> Web -> Base URLs (Secure) then insert your HTTPS URLs in here and bring your customers fast loading speed.

Images Optimization

You shouldn’t use images that are much larger than necessary. If your site requires a small image, such as 50 x 50, there is no need to upload a much larger file to get the same result.

Enable Cache for Magento Performance

Caching improves load speed response time on your Magento Store. A cached page will be stored after one visit or pre-generated and stored. Magento Enterprise Edition offers full page caching as a default option for the category, product, and CMS pages. To Enable cache Go to Stores -> “Configuration” in “Settings” Section -> “Catalog” in “General” Tab -> Section “Storefront” -> Fields “Use Flat Catalog Category” and “Use Flat Catalog Product” change to “Yes”.

css optimization

Minify CSS, JavaScript, and HTML

Minifying removes all unnecessary characters from source code without changing its functionality. These unnecessary characters usually include white space characters, new line characters, and comments, which are used to add readability to the code but are not required for it to execute.

Enable Flat Categories and Products

One of the main problems that slow down Magento Performance 2 speed is the read speed of database; especially, in case your Magento 2 store has a large number of products. To enable flat-options: Go to Stores -> “Configuration” in “Settings” Section -> “Catalog” in “General” Tab -> Section “Storefront” -> Fields “Use Flat Catalog Category” and “Use Flat Catalog Product” change to “Yes”.

css optimization


Catalog Size

The larger your catalog, the greater the burden on your server(s) to load pages, especially when we’re talking about SKUs tipping over 100K. You can enable Flat Categories and Products to improve load speed.

Check Links

A broken link is a hyperlink to a webpage that doesn’t exist it’s a waste of your page’s load time.

Change to Production Mode

It is recommended to always upgrade your Magento system, your plugins, and other software your website depends on (to the latest version).

Change to Production Mode

Intended for deployment on a production system. Exceptions are not displayed to the user, exceptions are written to logs only, and static view files are served from `pub/static` only. New or updated files are not written to the file system.

php bin/magento deploy:mode:set production


In today’s world increasing page speed performance is getting more and more important for websites, especially for eCommerce stores, because users are becoming more demanding in terms of user experience. I have described how to speed up load times in Magento with recommending a number of solutions. If you are planning to increase Magento Performance and page speed on your website or mobile app then this article gives you the complete guide in less time and effort. You can also join the conversation if you have any other solution or idea which we can use to make it more attractive and easy. That’s all folks and feel free to contact us in case if you have any query.


Further reading

14 features in eCommerce Mobile App to increase your sales

The boom in mobile eCommerce has led to the creation of mobile apps and platforms. Our generation has become a comfortable shopping and paying their mobile devices. Smartphones and eCommerce Mobile App are having a meaningful impact on how we buy. Sales via the eCommerce Mobile App have grown 39% over last year to reach $123.13 billion this year in the United States. This means m-commerce will account for 1/3 of all eCommerce sales. Here is a list of 14 must-have features that attract online shoppers.

eCommerce Mobile App Features

  1. Simple Registration Process: Almost customers will not like to fill the long forms demanding too much information. Make the registration process simple & put smallest required fields for ease operation. People rarely prefer the app which demands too much information for a registration.
  2. All payment options supported: Sometimes it happens that a buyer has a strong wish to buy a product from the specific mobile app. Unfortunately, he doesn’t find the payment option he wants, then it may result in the decreased sale ratio. Put all possible payment options which are used by the most shoppers.
  3. Eye-popping themes: A phone has a limited space and if the design is too cluttered, it would make the user journey complicated. Ensure the app uses space without compromising on design and meets business objectives. Moreover, the visual should be attractive, engaging and must convey to the users. What an app does and why it is better than the competition
  4. A feature of Push Notifications: Some of the most successful eCommerce mobile apps are the ones that have Push Notifications into their list of features. Push notifications tend to inspire immediate action like exclusive promotions, special offers. You can pair up this feature with analytics, and you would see a significant boost in sales in no time.
  5. 100% Custom Branding: Get a custom mobile app with your own logo and color combinations at a nominal cost of development. which will add greatest features to your users like displaying products listing, users account creation, adding into carts, apply coupons, checkout, view order and much more.
  6. Synchronizations: Any changes on the website to the Categories, Catalog or Customers profile get reflected in your mobile phone app. So you don’t have to perform the changes on your app again
  7. Google Analytics: Google Analytics for Mobile Apps measures your app’s full value. See what users love and how to make them happier — and make your app more successful.
  8. Product Review: You might think that having negative reviews is a sale killer. The opposite is actually true. Having negative reviews can often be positive. It’s shown that products without negative reviews are seen as censored.
  9. Wish List Button: E-commerce sites that aren’t using wish lists are leaving revenue on the virtual desktop table. What’s better than having customers bookmark items they want and will most likely buy in the future?
  10. Related Products: People that buy online are impatient and you constantly lose sales as a result. Use Recomatic to display smart Related Products and get those sales back. No time to set it up? No problem! We take care of everything for you.
  11. Quick Checkout: A mobile app should contain Quick Checkout feature. The Quick Checkout feature allows shoppers to complete an order with predefined information from the quick check out profile and automatically sets the shipping and billing addresses for the customer.
  12. Multi-Currency: Build Magento app that can transact in an endless list of international currencies including USD, GBP, EURO, AED, YEN, INR and much more. Offer customers the true experience of international payments, anywhere, anytime.
  13. Multi-Lingual: A mobile app should also contain multiple language support so that customer can convert your store into 30 or more languages of their choice by simply selecting the languages from the drop down menu.
  14. Return Policy: Return policies are an essential feature of any e-commerce website. return policy should be clearly visible and well-written or illustrated.

Above mentioned are just main features that any E-commerce app must have. Excluding these, there are many other features which make the app successful. So, for the extended requirements of your business, you may have other customized app features.


A Good mobile app involves more than technology and the latest tools. An effective mobile app is a platform that requires a solid strategy. These are the very common feature which a mobile app have. If you are planning to create an eCommerce mobile app than the experienced team at Ipragmatech will help you. We will first understand your ideas and then creates an amazing product to you. which is Mobile App Builder for e-commerce Mobile App to you. If you need more help and idea about setting up your mobile app, feel free to contact us.


Magento: A Gift for You

Mobile app builder for your online store based magento2

Further Reading

7 Reasons to choose Magento eCommerce platform for your Online Store

A complete guide to build a native e-commerce mobile app

6 Reasons eCommerce Store Needs Mobile App


Magento salesforce integration with Customers in 3 Creative Steps

If you are running eCommerce website then you always fear to lose your customer accounts one solution is to keep the backup on daily basis but it comes very headache to keep lots of backups also need lots of space. Another solution is Magento 2 customers Salesforce integration.There are two ways for Magento Salesforce Integration for customers. One is to do is manually or another is to do it automatically (Using crone on specific events). We have described the automatically approach to synchronize Magento Salesforce Integration for customers.

Magento Salesforce Integration for Customers

Following are the steps to Magento Salesforce Integration for customers  based upon Magneto 2 customers creation or update

Step 1: Entering Observer event in the XML

This is the important part to handle the event into Magento 2. Go to your module ->etc->frontend and verify that the XML file named as the event.xml exists or not if exist then create. Open event.xml and do the following code inside this


    <event name="customer_save_after">
        <observer name="customer_save_after" instance="Package\Module Name\Observer\CustomerUpdateObserver" />

Step 2: Creating Observer

Now we have to create the observer file to perform Magento Salesforce Integration operations according to our need. In my case my observer name is CustomerUpdateObserver.php . To create the file go to path project/app/code/package/module/Observer/ and create you observer here with following code.

add your needed helper files inside the constructor

 public function __construct(
        \Magento\Framework\ObjectManagerInterface $objectManager, //to performs some operations 
        \Ipragmatech\Msintegration\Helper\Account\Data $helper //we have written our functions inside this helper
    ) {
        $this->_objectManager = $objectManager;
        $this->_helper = $helper;

Add the following line of code inside the execute function of observer

       try {
            $customer = $observer->getEvent()->getCustomer();
            $salesforceId = $this->_helper->getClientSfId($customer->getId());
            if (empty($salesforceId)) {
                $id = $this->_helper->createAccount($customer);
                if (!empty($observer->getCustomerAddress())) {
                   $this->_helper->updateAddress($observer->getCustomerAddress(), $id);
            } else {
                $this->_helper->updateAccount($salesforceId, $customer);
                if (!empty($observer->getCustomerAddress())) {
                    $this->_helper->updateAddress($observer->getCustomerAddress(), $id);

        } catch (\Exception $e) {
            // do what ever you wanna perform based on your exception log or some operation


Step 3: Create Helper file

Go to helper folder create a folder named Account and inside folder create a file named Data.php. Inside the file, we need to write our functions for creating a customer account, updating customer, and updating customer address.

  • Creating customer account on the Salesforce
     public function createAccount($customer)
            $name = $customer->getFirstname() . " " . $customer->getLastname();
            $email = $customer->getEmail();
            $lastUrl = "sobjects/Account/";
            $params = array(
                    "Name" => $name,
            $acountResult = $this->_helper->postAction($params, $lastUrl);
            $response = $acountResult ['response'];
            $status = $acountResult ['status'];
            $id = $response["id"];
            $mappingArray = [
                'customer_id' => $customer->getId(),
                'customer_salesforce_id' => $id,
            try {
                $model = $this->_objectManager->create('Ipragmatech\Msintegration\Model\Customermapping');
            } catch (\Exception $e) {
                // put your own code
            return $id;
  • Updating customer account on Salesforce
     public function updateAccount($salesforceId, $customer)
            $name = $customer->getFirstname() . " " . $customer->getLastname();
            $email = $customer->getEmail();
            $lastUrl = "sobjects/Account/$salesforceId";
            $params = array("Name" => $name);
            $updateAccount = $this->_helper->updateAction($params, $lastUrl);
            $status = $updateAccount ['status'];
            if ($status != 204) {
               // failed with status 
            return true;
  • Updating customer address on the Salesforce
        public function updateAddress($addressObject, $salesforceId)
            $name = $addressObject->getFirstname() . " " . $addressObject->getLastname();
            $streets = $addressObject->getStreet();
            $country = $addressObject->getCountry();
            $city = $addressObject->getCity();
            $postCode = $addressObject->getPostCode();
            $company = $addressObject->getCompany();
            $state = $addressObject->getState();
            $telephone = $addressObject->getTelePhone();
            $strt = "";
            foreach ($streets as $street) {
                $strt .= "," . $street;
            $lastUrl = "sobjects/Account/$salesforceId";
            $params = array(
                    "Name" => $name,
                    "BillingCity" => $city,
                    "BillingStreet" => $strt,
                    "BillingState" => $state,
                    "BillingPostalCode" => $postCode,
                    "BillingCountry" => $country,
                    "ShippingCity" => $city,
                    "ShippingStreet" => $strt,
                    "ShippingState" => $state,
                    "ShippingPostalCode" => $postCode,
                    "ShippingCountry" => $country,
                    "Phone" => $telephone
            try {
                $updateAddress = $this->_helper->updateAction($params, $lastUrl);
                $status = $updateAddress ['status'];
                if ($status != 204) {
                    //your own message call has been failed
                return true;
            } catch (\Exception $e) {
               //handle exception accordingly


The Magento Salesforce Integration for sync customers is an advantageous integration tool for Magento 2 and Salesforce. In this Magento Salesforce Integration you do not encounter any technical difficulties or confusion with it, support for this Magento Salesforce Integration is available, you can ask the question on this blog or you may have a look at a solution which we have already implemented for Magento Salesforce Integration, products and orders to Salesforce on their update/ create in Magento 2. Click here to know about our plugin. So don’t wait any longer, go for it!


Further Reading

7 Easy tips to improve magento store loading speed in 2017

Magento is an open-source eCommerce platform with a large number of active online merchants using it. Magento is very robust with great flexibility, scalability, and customization. Most of the CMS or eCommerce platforms like Magento and WooCommerce are having issues with speed and their performance degrading over time. Why do we need to optimize Magento performance?

    • According to KISSMetrics, 40% of the customer will abandon an eCommerce site if it takes longer than three seconds to load. More noticeable, an ONE-SECOND delay in load time can result in a 7% reduction in conversions.
    • As you know by now, Google is using site speed in web search ranking, and not only for Google but mainly for the User Experience (UX) on your eCommerce store.

In this article, we share some tips and tricks on how you can optimize Magento performance of your Magento based eCommerce store.

Tips to improve Magento store loading

1. Latest Version:

Always upgrade to the latest Magento version. Not only will you get more features and bug- and security fixes, but with every update, Magento performs better. You didn’t check every time to magneto website to for latest release, Magento does a good job of notifying you of important updates that become available within your messages inbox.

2. Enable Flat Catalog:

Magento uses the EAV model (entity attribute value) to store customer and product data. Enabling the flat catalog for categories and products merges product data into one table, thereby improving performance by responding to MySQL queries faster. If your eCommerce store has more than 1000 products, this can very beneficial.

Magento uses the EAV model (entity attribute value) to store customer and product data. Enabling the flat catalog for categories and products merges product data into one table, thereby improving performance by responding to MySQL queries faster. If your eCommerce store has more than 1000 products, this can very beneficial.
1. Login to your Magento Store as admin
2. Navigate to “System” → “Configuration” → “Catalog.”
3. Under “Frontend” change “Use Flat Catalog Category” and “Use Flat Catalog Product” to “Yes.”
4. Click on “Save Config.”
5. Clear the cache. The recommended way to do this is to delete everything from the /var/cache directory. You can also do it by navigating to “System” → “Cache Management” and clicking on “Flush Cache Storage” which is equivalent to deleting all the cache.

3. Cache & Indexers: 

There are many forms of caching that can be implemented with Magento. Combining NGINX + APC + Memcache + Varnish caching is a great way to success. Magento also comes with a built-in caching module as well. One more thing using Magento’s page caching. It reduces the web server processing load is taken off from the web server by serving pages already visited before from a cache which makes it a lot faster. There are lots of pages caching extensions available for Magento you can choose according to your requirement.

Using a PHP accelerator is another form of caching. They increase the performance of PHP scripts by caching them in their compiled state. You can use a PHP accelerator like APCXcacheeAccelerator  etc.

As we know Magento has lots of feature one of them is the indexer. Magento updates indexes on every object store by default, but in some cases, manual updates are required. Basically, indexes are used to speed up Database queries.

4. Code and Database Optimization:

Use a PHP accelerator like Zend and uninstall unnecessary PHP or Apache modules you don’t need or use. Improve your database performance using query indexing and broad optimization scripts. Use your DB management system to optimize the database on the frequent basis.

Magento has a compilation feature which has been reported to sometimes give up to a 50% performance boost. By default, Magento’s application files are searched in a certain order every time the page loads, which results in a lot of filesystem reads. In Magento admin, (top menu) System > Tools > Compilation, click Enable. This will take all the active scripts in Magento’s core structure and bring them to the front for faster website speed. The Magento compiler reduces these reads by copying all of these files into a single include directory and also caches ones that are used more frequently.

Optimizing your product images can dramatically increase the speed of your pages as this decreases their download times. You can compress them before uploading them using a tool like PhotoShop or there are a number of extensions you can use to auto-optimize them like TinyPNG Extension.

5. Merge CSS & JS:

Magento actually has a built in feature to concatenate (merge) your CSS and Javascript files into one file. This will reduce your total number of HTTP requests and in turn help speed up the loading of your pages. By using the advanced configuration in Magento admin, you can merge you JavaScript and CSS files, this reduces the load time. Please be aware that merging your javascript files may cause issues that need to be further resolved, but in the end, it certainly is best for your store.

6. Use CDN:

Implementing a Content Delivery Network (CDN) with Magento is one of the easiest ways to instantly see decreased load times. Using a content delivery network (CDN) such as MetaCDN enables serving your assets from a location geographically closest to your customers and hence reduces latency and increases download speed for those assets. Magento lets you define where certain assets (CSS, javascript, images, etc.) are loaded from such as a URL pointing to a CDN.  Magento CDN integration guide for details how to integrate the MetaCDN Site Accelerator into your Magento installation.

7. Hosting environment:

And last but not least, choosing a reliable and fast web host can be one of the most important decisions you will make when trying to improve Magento performance. We recommend staying away from shared hosting as they tend to overcrowd their servers and you will end up sharing resources between hundreds of website. We suggest going with a VPS like socialfoxhosting.comDigital Ocean, Linode etc. The reason is that you will be in complete control of your resources.


There are many ways to optimize Magento performance for your Magento based eCommerce site. Some of them we have discussed here. If you suffer from slow Magento performance, we can help you with Magento optimization to speed up Magento in no time! Making sure your eCommerce solution is running fast is one of the most important factors to your sales, SEO rankings, and overall best user experience.

For further reading

How to validate payment through PayPal using Magento REST API ?

In this digital age to maintain your business growth, Mobile application for your eCommerce becomes the main key point in short mCommerce. Data researched by Coupofy suggests that between 2013 and 2016 mobile shopping will grow 42% compared to regular eCommerce’s 13%, and mobile users will spend a total of $600 billion in 2018, a 300% growth from 2014’s $200 billion. Business owners are focusing on launching their mobile app to make their exists in this digital age. So the development of mCommerce is in the pick point now. As the mCommerce Mobile application development growing rapidly there are a lot of issues are in the queue related to design, performance, UI, payment gateway, validate PayPal payment etc. In this article, we are going to discuss how to validate PayPal payment through Magento REST API interface?

So what is the actual problem?

We are developing an android app for Magento base eCommerce site. We are using REST API. Payment and order related things integration is challenging for us, since we need more secure and careful module development. We are doing an android app so there is a situation where we have complete the payment process using PayPal express mobile SDK. In return, we get transaction id, according to my understanding we have to save with the created order. In the site, we configured PayPal successfully. So the transaction id passed to Magento, where we need to validate PayPal payment. Now at the end, we want an API from Magento side to save the transaction and complete the checkout process.

In fact lot of people have the same problem:


We have gone through the answer posted in the various community like StackExchange, Magento forum etc. After a little bit research, we have to use the following approach and quite suited well to our requirement.
1. Created a custom payment Method: In the box, Magento rest api does not support place order without the payment method. We have created a custom payment module with a custom method. For More detail how to create a payment module check here. Here is the code sample for our method:

 * Copyright © 2016 iPragmatech. All rights reserved.
namespace Ipragmatech\Paymentapi\Model;

 * Pay In Store payment method model
class Ippaypal extends \Magento\Payment\Model\Method\AbstractMethod

     * Payment code
     * @var string
    protected $_code = 'ippaypal';

     * Availability option
     * @var bool
    protected $_isOffline = true;

2. Enable only for the rest API: The above method enables only for the rest api and not supported on the web app for the payment. Make a new rest api endpoint to receive the transaction id and validate it from PayPal. After successful validation move to the next step.Check out the documentation to validate PayPal payment.
3. Saved transaction id with order: Once all validation are passed save the transaction id return by the PayPal with the order. A transaction is a proof that payment has been done. In Magento transactions are created when the invoice is created, although Magento creates the transaction by itself you don’t need to worry about that but in case you will have to create the transaction manually, here is the code snippet that will create a transaction:

public function createTransaction($order = null, $paymentData = array())
        try {
            //get payment object from order object
            $payment = $order->getPayment();
                [\Magento\Sales\Model\Order\Payment\Transaction::RAW_DETAILS => (array) $paymentData]
            $formatedPrice = $order->getBaseCurrency()->formatTxt(
            $message = __('The authorized amount is %1.', $formatedPrice);
            //get the object of builder class
            $trans = $this->_transactionBuilder;
            $transaction = $trans->setPayment($payment)
                [\Magento\Sales\Model\Order\Payment\Transaction::RAW_DETAILS => (array) $paymentData]
            //build method creates the transaction and returns the object
            return  $transaction->save()->getTransactionId();
        } catch (Exception $e) {
            //log errors here

Click here more detail regarding the transaction.


After all, we have used this approach to validate payment because this is well suited to our requirement. If you have a better idea please fell free to share in the comment. This might help a lot to us as well others.


How to recover images in Magento2 ?

Are you a Magento developer who have accidentally deleted some part of the /media folder Magento installation on the server? So the point is find out the way to recover image without affecting the database.
Is there any probability of deleting media folder ?
Well ….As you get your moves in the new platform, you may be pleasantly surprised to discover how similar the line-by-line code you’ll write really is. Magento2 has completely different architecture. The way Magento2 execute is totally different from Magento1.9x. So the real objective of this article is to give you an overview of the most significant differences from Magento 1 that you’ll encounter, basically digging the media.


Automated code generation and deployment play a huge role in Magento 2, and these can be partially understood with a look at the pub directory. Static view file deployment materializes all necessary static assets from their source in application code into the web-accessible pub directory. This deployment process happens automatically in development mode but requires an explicit action in production. This automatic deployment of assets is what allows all JS/CSS code to live in its appropriate module but still be web-accessible in a centralized location. Code generation doesn’t involve the pub directory, but it’s closely related to the concept of deployment. Certain types of PHP classes are now automatically generated by Magento and facilitate more granular and unobtrusive customization than has been possible in the past.

While developing an online store in Magento2, the developer often needs to clear pre-compiled static data from pub directory. So there is a huge chance to accidently delete media directory from pub folder.
So, the scenario is what should be the next step after deleting the media directory? If the is the backup then great restore from there if not then what? Yeah…you upload one by one for all the product…if products are in big numbers, then how embracing will be upload image one by one?

How to recover image?

So, the problem is media directory is deleted but the path for existing product image are available in the database, now we have to import the image with same name and location. Our approach is to read the image file from your backup (provide image name with product-SKU or any specific pattern) and find the path for you each product and then rename image and insert that specific path.
For example, there is a product with SKU PR10001 have image path like /p/r/test-product.jpg. We search the image in image backup directory and save this file as the specified path for the product.

Basically, we have gone through this situation and we have prepared a Magento script for the same. Here is our  Recover Image  GitHub repository link.


If you accidently delete the media directory in Magento, please don’t be panic use our script to recover image for your Magento products. If you have any custom requirement feel free to contact us. Glad to hear from you.


Magento Image Structure

Tips to build magento2 mobile app using ionic framework

These days, the ways of developing an app have changed, as a result, it provides useful and user-centric apps to businesses and organizations for improving their business presence through a mobile app. These all changes are possible due to the presence of various cutting-edge tools, platforms, and frameworks. These all things have brought ease and convenience for developers and designers to create incredibly potential mobile apps.
The Ionic framework is one of the new entrances in the mobile app development platform. It has a front-end SDK built on AngularJS which is a top popular JavaScript library. Using this popular library Ionic application provides developers and companies a benefit of single development code across multiple mobile platforms. It has many other benefits like:

  1. It provides very beautiful UI. It has many default JS and CSS components which are clean, simple and functional.
  2. It focuses on native apps by running inside PhoneGap or Cordova to deploy an app natively.
  3. It has a most powerful CLI which helps developers to create, built, test and deploy apps onto any platform with just one command.

A few days back we get a chance to develop an app with the ionic framework and the most interesting part was to use Magento2 REST API to retrieve data from the server. Developing an app with the ionic framework and Magento2 Rest API was new to us but yes, it was an amazing thing to learn. We developed the app and it was a great experience to integrate the two amazing platforms in a mobile app. This article will help to learn how to build a Magento2 mobile app using the ionic framework.

Here are some important points to be noticed before starting the development on the front-end.

Magento2 Rest API Configurations: Test accessibility of the mobile API

This is the step which is followed by both the sides i.e. client side as well as server side. On the server side, we need to give permission for webservices and it is done by enabling Web API Security. For more information for server-side implementation please refer the link .

On the client side, you can make a direct call to some of the default Magento API like- product list, product details, product category etc. but for a customer-specific call like- customer authentication, cart, wishlist, checkout etc. needs to be called by passing authentication token in the header. To learn more about authentication token refer the blog.

Magento2 Server-side Configurations(CORS handling):  Setting of Headers in the .htaccess file.

This the most important step while making the call from javascript to Magento rest API.

CORS (Cross-Origin Resource Sharing) is a W3C spec that allows cross-domain communication from the browser. By building on top of the XMLHttpRequest object, CORS allows developers to work with the same idioms as same-domain requests. For CORS you need to add following headers at your server side .htaccess file:

      Access-Control-Allow-Methods: POST, GET, OPTIONS, HEAD...and more
      Header always set Access-Control-Allow-Headers:DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type

Now, here is the detail explanation for developing a Magento2 mobile app using ionic framework

Steps to build Magento2 mobile app using ionic framework

1. Build Iconic project.

Now get ready to start your ionic app. Below are the steps to build an ionic app:

  1. The Ionic framework uses node.js as its utility, so to start first install the node.js utility:
     $ npm install -g ionic
  2.  Then, install the latest Cordova and Ionic command-line tools
    npm install -g cordova ionic
  3. Start a project by:
    ionic start <your app name> blank

Here starter blank means a project with no UI. It will create a blank project. Some of the other named templates starters

  • tabs (Default)
  • side menu
  • maps
  • salesforce
  • complex-list

The above command will create an ionic project with various files including www folder. This folder is the actual folder where your app further implementation resides. The index.html is your app file which runs your app and contains all the js and CSS file declaration.

For more details about ionic framework read its doc.

Now, rest things are to be done for front-end. Below a sample is described to show how to build a Magento2 mobile app using the ionic framework. In this sample, we will have the following functionality:

  1. User signup
  2. User Login
  3. Product Listing from Magento2 website.

Step 2. Create your UI

Create an .html file for Login e.g. login.html in your template folder. Define your view in this layout as your requirement. For more details about defining a layout, you can refer here. TEMPLATES is where your view files go. Your project does have a main index.html file in the WWW directory, but your app likely contains many template views that are added dynamically. Unlike your CSS and JS files, TEMPLATE files do not need to be mentioned in your index.html file.

Step 3. Update the app.js file for app’s states

Now define your app screens state in the app.js file. e.g:

     .config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider,$provide) {

        .state('login', {
             url: "/login",
             templateUrl: "templates/login.html",

Step 4. Define a controller for the state:

controllers.js contains your Angular controllers for the states that require them. Define the logic here to control the state of your app. For example- In our sample, we defined LoginCtrl which defines the method which is to be called when user clicks on submit button.

.controller('LoginCtrl', function($scope, $state) {
   $scope.login = function(data) {
    // do what you want to do

Step 5. Define a service file:

services.js is not always included in the starters, but it contains the custom Angular services your app may use, such as the one that calls out to a 3rd party API to get the information your app uses. So, it the real file from where we call the API for authentication and product listing. For example:

.service('AuthService', function($q, $http) { // call your API here to get informations for the app uses. }

Step 6. update your index.html file

Now, this is the final step to play with your ionic files. Update your index.html file with all the js and CSS file you created in your app. For example:

      <!-- your app's js -->
      <script src="js/app.js"></script>
      <script src="js/controllers.js"></script>
      <script src="js/services.js"></script>

Sample Code

To get a complete code click here.


Above we described the steps to develop a Magento2 mobile app using ionic framework. The process is not only easy and interesting  but also make the  user interface attractive. The Ionic framework entrance in the market has proved to be very helpful for both the developer as well as for the customer because it is focused mainly on the look and feel, and UI interaction of your app. Above is the small sample to demonstrate the basic steps to build a Magento2 mobile app using ionic framework. For more information, you can contact us through our website. Enjoy Coding… 🙂


Ionic framework : Ionic is a powerful HTML5 SDK that helps you build native-feeling mobile apps using web technologies like HTML, CSS, and Javascript.

Magento2 REST API : Magento is an open-source e-commerce platform. Its REST API is used for building an e-commerce mobile apps.

Further Reading


How to add pagination on Magento2 custom collection?

In our recent project, we had a requirement to add pagination facility to custom module collection. It was displaying customer reward history on “My account” as a new tab “My rewards”. Normally Magento provides pagination in default collection like product collection. But here something different. To fulfil the requirement, we have gone through many approaches and found the best solution for pagination on Magento2 custom collection. Here we are going to explain the best approach please follow the steps.

Note: Assuming that You have created a basic module in Magento2. Here Ipragmatech is our package and Ipreward is our module. Please, change your class name accordingly.

Step 1: Create a controller named Myrewad, action Index (Myreward/Index.php)and add the following code to execute method

namespace Ipragmatech\Ipreward\Controller\Myreward;
class Index extends \Magento\Framework\App\Action\Action
   public function execute()

Step 2: Create a block (Assuming that you have already created a model for your table. Here  We have custom table and we have created the model as reward) name Reward.php and add the following code. In this code, we have added the pager in our custom collection.

 * Copyright © 2015 Ipragmatech . All rights reserved.
 * @author Manish Kumar
 * @Date Fri 1 sep
namespace Ipragmatech\Ipreward\Block\Myreward;

use Ipragmatech\Ipreward\Block\BaseBlock;

class Reward extends BaseBlock
     * @var \Ipragmatech\Ipreward\Model\Reward
    protected $_rewardCollection;
     * Reward constructor.
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Ipragmatech\Ipreward\Model\Reward $rewardCollection
    public function __construct(
        \Ipragmatech\Ipreward\Block\Context $context,
        \Ipragmatech\Ipreward\Model\Reward $rewardCollection,
        $this->_rewardCollection = $rewardCollection;

    protected function _prepareLayout()

        $this->pageConfig->getTitle()->set(__('My Reward History'));

        if ($this->getRewardHistory()) {
            $pager = $this->getLayout()->createBlock(
            $this->setChild('pager', $pager);
        return $this;

    public function getPagerHtml()
        return $this->getChildHtml('pager');
     * function to get rewards point transaction of customer
     * @return reward transaction collection
    Public function getRewardHistory()
        //get values of current page
        $page=($this->getRequest()->getParam('p'))? $this->getRequest()->getParam('p') : 1;
        //get values of current limit
        $pageSize=($this->getRequest()->getParam('limit'))? $this->getRequest
        ()->getParam('limit') : 5;

        $collection = $this->_rewardCollection->getCollection();
        $logger->info("Here reward collection: ".$collection->getSelect());
        $logger->info("Here reward collection: Page:".$page." Page size :"
        return $collection;


Step 3: Added/Modify the following code on layout file app/code/Ipragmatech/Ipreward/view/frontend/layout/ipreward_myreward_index.xml


<?xml version="1.0"?>
<page xmlns:xsi="" layout="2columns-left" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <update handle="customer_account"/>
        <referenceContainer name="content">          
         <block class="Ipragmatech\Ipreward\Block\Myreward\Reward" name="myreward_reward" template="myreward/reward.phtml">


Step 4: Add your phtml file as app/code/Ipragmatech/Ipreward/view/frontend/templates/myreward/reward.phtml and add the following code


and the output will be look like this


Sometimes we have faced some CSS issue in which page limit not displayed so use the following CSS if you have the same issue.

.custom-pager .limiter{
    display: block !important;

Hope this will help you a lot. Please let us know if you have any issue regarding Magento customization.

Tips to boost average order value on your eCommerce store

Average Order Value (AOV) is the measure of how much money your customers spend each time they place an order through your online store. It’s a simple calculation (revenue ÷ number of orders = AOV) that can reveal a lot about your customers and your business during a specific time period.
Getting customers to buy multiple items and spend more money on each order is a great way to increase sales and revenue. Thus, online retailers that are able to increase average order value(AOV) should also become more profitable.


This statistic provides information on the average order value of U.S. online shopping orders from the second quarter of 2012 to the first quarter of 2016. During the most recent quarter, online orders which were placed from a desktop device had an average value of 75.9 U.S. dollars.

Why Focus on Increasing AOV?

To increase revenue and cash flow. Improving AOV is a great way to get healthy cash flow back into your store without having to spend a lot of money. In fact, you don’t need to worry if your store gets less traffic, you will have higher revenues due to increased AOV.

Tips to increase average order value

1. Product Bundles: Product bundling makes buying multiple items at once easy. Bundles often group a primary product and its accessories (such as a Mobile Phone that can be matched with Mobile case and a headphone etc); or products that are used for a similar purpose (such as a jacket, scarf and gloves).

2. Up-Sell and Cross-Sell:

  • Up-Sell – Suggest a larger or more expensive version of a product a customer is viewing.up-sell
    For example, If the customer is looking at your shoes, suggest a similarly styled shoes at a higher price point.
  • Cross-Sell – Suggest additional items related to the one your customer is viewing. For example, If the customer is looking at a mobile phone, recommend a matching case or screen guard  of mobile phone.


3. Customer Rewards:

  • Promotions/Discounts – Offer discounts for spending more money or buying additional items.
    Or, offer valuable services such as free shipping when customers spend a certain amount.


  • Rewards Points – Rewarding customers with points for spending more money on your site is a great
    way to increase AOV while at the same time fostering customer loyalty. The more customers buy, the
    more points they earn. Points can later be redeemed for discounts, free gifts, and other incentives.

4. Implement a free shipping: How frequently have you seen offers such as “free shipping when you spend over $49.99” when shopping online? It’s like a game against the total for online shoppers. They will keep throwing products into their cart until they reach the point where they gain free shipping. A win for your customers, and for you!

5. Easy Returns: One of the biggest concerns customers have about shopping online is whether or not they can return the items they purchase. If a customer thinks that returning something will be costly or difficult, he/she will buy fewer items to minimize their return risk. However, research shows that the more items customers buy, the more they actually keep (meaning they don’t return more items when the process is easy, they just want to know that easy returns are an option).


The strategies outlined here are all very different in how they get customers to increase the amount they spend in every order. Implement these strategies to your online and start noticing an increase in the average order value of your store.Thus this is the way to make more revenue with less traffic.