Connect Magento Store through API for Mobile App

Magento is a widely used and one of the most popular eCommerce platforms that allow users to set up an online store and sell products. Connecting your Magento store through API for the mobile app will enable your orders, messages, and other order information to flow directly into API.

However, all messages will still be delivered to your Magento account, and it will update whenever you send messages from API. This tutorial will learn how to connect the Magento 2 API for mobile apps in simple steps. 

Before you start

  • You’ll need an Admin login to API. 
  • You’ll need a Magento account.

Before we start with the process of connecting your Magento Store through API for mobile apps, let us understand the terms related to it and how things function in Magento 2 API for mobile apps. By the end of this tutorial, you will be able to connect Magento 2 websites to the apps.

What is an API? (Application Programming Interface)

API stands for Application Program Interface. This technology is used to connect different software and set up how their features should interact with each other. In other words, a software intermediary that allows two applications to talk to each other. You actually deal with API almost every day. Each time you use an app like Facebook, send an instant message or Google profile, or if you pay via PayPal, you are using an API.

What Is an Example of an API?

When you use an application on your mobile phone, the application connects to the Internet and sends data to a server. The server then retrieves that data, interprets it, performs the necessary actions, and sends it back to your phone. The application then interprets that data and presents you with the information you want in a readable way. This is what an API is – all of this happens via API.

How Does The API Work?

We will use a simple example to understand how an API works. Imagine you have a pet in your home, and the pet does not understand the human language, but the pet understands you if you use the command it knows. For example, Go, Run, Sit down, and so on. So the pet understands the command. It won’t understand what you want and what you are asking for. Like in the same way API does. You can use some specific commands like getting, Post, Delete, Put, etc., to create the connection between 2 programs or software that knows this language.

In real life, say you want to let your customers log in to their accounts via Google. In this case, you will use Google API Key and API Secret to connect your Magento 2 store with your Google Account. Magento will ask Google about customers’ data and, according to the response given, allow them to access or restrict.

What are the Magento 2 Web APIs?

The Magento web API framework provides integrators and developers a good method to maximize the use of web services that communicate with the Magento system. Amongst the primary key features are support for SOAP (Simple Object Access Protocol) and REST (Representational State Transfer). The coverage is just the same for both SOAP and REST in Magento 2.

Here are three types of authentication available for connecting API for Magento 2 store:

  • Third-party applications authenticate with OAuth 1.0a.
  • Mobile applications authenticate using tokens.
  • Administrators and customers are authenticated with login credentials.

Why Magento 2 API For Mobile App?

Unquestionably, the number of mobile users today is rising dramatically, which is even greater than the number of desktop users in some countries. Most of the Magento store owners have realized this trend and developed mobile apps to attract their customers. In general, it will take months for the app development, regardless of native apps or hybrid apps, in which developing API might consume the most time. By using our ready-to-use Magento 2 API for Mobile App, the developers will save not only significant effort for the development but also be able to deliver the app to the store in the shortest turnaround time.

How to use Magento 2 API For Mobile App?

Magento API is a type of framework that offers developers and integrators a good method to maximize web services that communicate well with the Magneto system. Amongst the primary features are support for SOAP (Simple Object Access Protocol) and REST (Representation State Transfer). The coverage is just the same for both SOAP and REST in Magento 2. 

There are 3 kinds of authentication:

  1. The mobile applications authentication via tokens.
  2. The 3rd party applications authentication via Oath 1.0a.
  3. The authentication of customers and admins via login credentials.

Each account and integration serves as assigned sources which they can access. The API framework monitors the calls to check if the account is authorized to make the request.

In order to configure the web API, you need to define XML attributes and elements in a webapi.xml configuration file. Once the service isn’t defined in a configuration file, it won’t be displayed.

Each Magento or 3rd party service could be configured into a web API via XML.

The framework is anchored upon the CRUD model, which stands for Create, Read, Update, and Delete. The system doesn’t support any webhook

Magento 2 API for Mobile App is the fastest way to reach your product. The Magento APIs could be used to execute tasks like:

  1. Creating a shopping application and the traditional type of application that can be downloaded to a mobile phone or device. This application can be utilized by the employees in a showroom to smoothen the customer’s shopping experience.
  2. Integrating with CRM (Customer Relationship Management) or ERP (Enterprise Resource Planning) backend types systems like Xero or Salesforce.
  3. Integrating CMS (Content Management System). However, content tagging isn’t supported yet.
  4. Creating JavaScript Widgets in the Admin Panel or Magento storefront. The widget creates AJAX calls in order to access services.

SOAP

To connect to Magento SOAP web services, load the WSDL into your SOAP client from either of these URLs:

  • http://magentohost/api/?wsdl
  • http://magentohost/api/soap/?wsdl

Where magentohost is the domain for your Magento host.

As of v1.3, you can also use the following URL to access the Magento API v2, which was added to improve compatibility with Java and.NET:

http://magentohost/api/v2_soap?wsdl=1

The following PHP example shows how to make SOAP calls to the Magento API v1:

$client = new SoapClient('http://magentohost/api/soap/?wsdl');
// If somestuff requires api authentification,
// then get a session token
$session = $client->login('apiUser', 'apiKey');
$result = $client->call($session, 'somestuff.method');
$result = $client->call($session, 'somestuff.method', 'arg1');
$result = $client->call($session, 'somestuff.method', array('arg1', 'arg2', 'arg3'));
$result =$client->multiCall($session,array(array('somestuff.method'), 
array('somestuff.method', 'arg1'),
array('somestuff.method', array('arg1', 'arg2')) ));
// If you don't need the session anymore
$client->endSession($session);

XML-RPC

To use XML-RPC, load the following URL into your XML-RPC client:

http://magentohost/api/xmlrpc/

Where magentohost is the domain for your Magento host.

The following PHP example shows how to make XML-RPC calls:

$client = new Zend_XmlRpc_Client('http://magentohost/api/xmlrpc/');
// If somestuff requires api authentification,
// we should get session token
$session = $client->call('login', array('apiUser', 'apiKey'));
$client->call('call', array($session, 'somestuff.method', array('arg1', 'arg2', 'arg3')));
$client->call('call', array($session, 'somestuff.method', 'arg1'));
$client->call('call', array($session, 'somestuff.method'));
$client->call('multiCall', array($session,
    array(
       array('somestuff.method', 'arg1'),
       array('somestuff.method', array('arg1', 'arg2')),
       array('somestuff.method')
    )
));
// If you don't need the session anymore
$client->call('endSession', array($session));

The XML-RPC only supports version 1 of the Magento API.

SOAP API Version v2

Since Magento 1.3, version v2 of the SOAP API has also been available. The main difference between v1 and v2 is that instead of using the methods call and multiCall, it has separate methods for each of the actions.

For example, consider the following PHP code using SOAP v1.

$params = array(array(
   'status'=>array('eq'=>'pending'),
   'customer_is_guest'=>array('eq'=>'1')) ));
$result = $client->call($sessionId, 'sales_order.list', $params);
With SOAP v2, the following code would be equivalent.
$params = array('filter' => array(
   array('key' => 'status', 'value' => 'pending'),
   array('key' => 'customer_is_guest', 'value' => '1')
));
$result = $client->salesOrderList($sessionId, $params);

Note that the WSDL for SOAP v1 and SOAP v2 is different.

Note that in SOAP v1, customizing the API did not involve changing the WSDL.

In SOAP v2, changes to the WSDL are required.

You can configure the SOAP v2 API to be WS-I compliant in the system configuration menu. To do this, set Services > Magento Core API > WS-I Compliance to Yes.

Note that the WSDL for the SOAP v2 API is different when in WS-I compliant mode.

Using the WS-I compliant SOAP v2 API WSDL, it is easy to automatically generate client classes for Java, .NET, and other languages using the standard libraries.

Using Magento 2 REST API

  1. Magento 2 REST API
  2. Create Web Service Role in Magento 2
  3. Create Web Service User in Magento 2
  4. Magento 2 REST API Authentication
  5. Get Modules Using REST API in Magento 2
  6. Conclusion

Using the REST API in Magento 2 is very easy and simple. But for that, you need to understand the flow to call APIs in PHP. To get started with the REST API in Magento 2 using token-based authentication, you will need to create a web service User Role and register that role to a new Magento 2 Admin User. Keep in mind that creating a new role and user is necessary because it’s not a good practice to use Magento Owner User in a web service.

For the purpose of this tutorial, I will also use this REST API to get all the modules installed on your Magento 2 store.

Create Web Service Role in Magento 2

To create a web service role in Magento 2, follow these steps:

  1. Log in to the Magento 2 Admin Panel.
  2. Go to System >> User Roles and tap the Add New Role
  3. Enter the Role Name.
  4. In the Your Password field, enter the current password of your Magento 2 Admin.
  5. Now, on the left side, click Role Resources.
  6. In Resource Access, select only those that are required for your web service.
  7. Once done, hit the Save Role

Create Web Service User in Magento 2

Now, create a new user for the newly created role through these steps:

  1. Go to System >> All Users and hit the Add New User
  2. Enter the required information, including User Name, First and Last Name, Email, Password, etc.
  3. Now, on the left side, click User Role and select the newly created role.
  4. Once done, click the Save User.

Magento 2 REST API Authentication

As I mentioned earlier, I will authenticate REST API through Token authentication. This means that I will pass a username and password in the initial connection and receive the token. This token will be saved in a variable, which will be passed in the header for further calls.

Here is the code:


<?php
//API URL for authentication
$apiURL="http://magento2.avyatech.com/index.php/rest/V1/integration/admin/token";

//parameters passing with URL
$data = array("username" => "apiaccess", "password" => "[email protected]");
$data_string = json_encode($data);

$ch = curl_init($apiURL);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Content-Length: ".strlen($data_string)));
$token = curl_exec($ch);

//decoding generated token and saving it in a variable
$token=  json_decode($token);

?>

In the above code, I passed the username and password with the API URL to authenticate the REST API and then saved the token in a variable for further use. Remember, you have to use the username password of the new user (created earlier).

Get Modules Using REST API in Magento 2

You can fetch almost everything using Magento 2 REST API. To demonstrate the API, I am going to get all the installed modules on a Magento 2 store. Here is the script:


<?php

//Using above token into header
$headers = array("Authorization: Bearer ".$token);

//API URL to get all Magento 2 modules
$requestUrl='http://magento2.avyatech.com/index.php/rest/V1/modules';

$ch = curl_init($requestUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);

//decoding result
$result=  json_decode($result);

//printing result
print_r($result);

?>

In the above code, I passed the token (fetched earlier) in the header with the API URL to get all the modules installed on Magento 2 store.

Next, I will print the results. Here is the complete code:


<?php

//API URL for authentication
$apiURL="http://magento2.avyatech.com/index.php/rest/V1/integration/admin/token";

//parameters passing with URL
$data = array("username" => "apiaccess", "password" => "[email protected]");
$data_string = json_encode($data);

$ch = curl_init($apiURL);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Content-Length: ".strlen($data_string)));
$token = curl_exec($ch);

//decoding generated token and saving it in a variable
$token=  json_decode($token);

//******************************************//

//Using above token into header
$headers = array("Authorization: Bearer ".$token);

//API URL to get all Magento 2 modules
$requestUrl='http://magento-91647-257956.cloudwaysapps.com/index.php/rest/V1/modules';

$ch = curl_init($requestUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);

//decoding result
$result=  json_decode($result);

//printing result
print_r($result);

?>

All set! You have successfully connected your Magento store through the API for the mobile app. In case you are not able to do so, feel free to reach out to us. We are a trusted Magento web development company with a pool of well-versed Magento experts who have 10+ years of knowledge and expertise working with Magento. 

You can also use our mobile application development services to get a mobile app for your online store. As a well-known mobile application development company, we have experienced mobile app developers who are well-trained in developing every type of mobile application.

Author: Chandan Kumar

Tags: , ,

Recent Posts

Categories

Tags

Leave a Reply

Your email address will not be published. Required fields are marked *