Develop magento mobile app using REST API and OAuth

According to the recent survey conducted by VisionMobile,  most of the developers saying eCommerce is now the best mobile monetization strategy. 40% of US respondents who had downloaded a retailer app said they bought more of that brand’s products. 46% also said the app invite them to visit the physical store more often. For example, Walmart customers who use its app spend 40% more than customers who don’t.

There are many benefits of native apps to improve the customer experience. There is no doubt that mobile payments can be improved in-store by using the smartphone’s inbuilt technology to make the in-store payments experience more friendly. In this blog, we are going to discuss how to get started to develop a mobile app for Magento and implement OAuth  3-legged protocol for authentication for Magento REST API.

Magento REST API

Magento REST API defines a set of functions to which the developers can perform requests and receive responses and these all interaction is performed via the HTTP protocol.

Magento REST API has capabilities to manage a number of features, namely:

  • Managing customers.
  • Managing customer addresses.
  • Managing products.
  • Retrieving sales orders.
  • Managing inventory.

XML and JSON are two formats of response supported by the REST API. Also to manage the state of resources different HTTP verbs are used in Magento REST API, such as to get the contents of the data using HTTP GET, delete the data using HTTP DELETE, and create or update the data using POST/PUT. OAuth 1.0a is the three legged protocol used by Magento REST API  to authenticate the application to access the Magento service.

Develop Magento mobile app using REST API and Authentication Protocol OAuth 1.0

In the traditional client_server authentication model,the client uses its credentials to access its resources hosted by the server. With the increasing use of distributed web services and cloud computing, third-party applications require access to these server-hosted resources.

OAuth introduces a third role to the  traditional client-server authentication model: the resource  owner.In the OAuth model,the client(which is not the resource owner,but is acting on its behalf)requests access to resources controlled by the resource owner  but hosted by the server.In addition,OAuth allows the server to verify not only the resource owner authorization but also the identity of the client making the request.

Preparing REST API for the Third-Party Application

The OAuth process consists of several steps:

  • Getting an Unauthorized Request Token.

The first step to authenticate the user is to retrieve a Request Token from Magento. This is a temporary token that will be exchanged for the Access Token.

  try {
final OAuthHmacSigner signer = new OAuthHmacSigner();

  signer.clientSharedSecret = Constants.CONSUMER_SECRET;

              OAuthGetTemporaryToken temporaryToken = new OAuthGetTemporaryToken(Constants.REQUEST_URL);
                temporaryToken.transport = new ApacheHttpTransport();
                temporaryToken.signer = signer;
                temporaryToken.consumerKey = Constants.CONSUMER_KEY;
                temporaryToken.callback = Constants.OAUTH_CALLBACK_URL;

                OAuthCredentialsResponse tempCredentials = temporaryToken.execute();
                signer.tokenSharedSecret = tempCredentials.tokenSecret;
             OAuthAuthorizeTemporaryTokenUrl authorizeUrl = new OAuthAuthorizeTemporaryTokenUrl(Constants.AUTHORIZE_URL);
                authorizeUrl.temporaryToken = tempCredentials.token;
                authorizationUrl = authorizeUrl.build();
 } catch (Exception ex) {
 ex.printStackTrace();
 }

The OAuthHmacSigner   object is a very important object, responsible for signing requests and plays a very important role in the OAuth flow, as it is required to sign all requests so that they can pass as authorized requests. In the response You will get the Request Token in return.

  • Requesting user authorization

The second step is to request user authorization and for this we need the Request Token  received   from Magento.After that the application provides an authorization page to the user.This object is an OAuth 1.0a URL builder for an authorization web page to allow the end user to authorize the temporary token.

                  try {

                        String requestToken = extractParamFromUrl(url, "oauth_token");
                        String verifier = extractParamFromUrl(url, "oauth_verifier");

                        OAuthGetAccessToken accessToken = getOAuthAccessToken(requestToken);
                        accessToken.verifier = verifier;

                        OAuthCredentialsResponse credentials = accessToken.execute();
                        signer.tokenSharedSecret = credentials.tokenSecret;
                 localCredentialStore.store(new AuthToken(credentials.token, credentials.tokenSecret));

                  } catch (IOException e) {
                    Log.e(TAG, e.getMessage(), e);
                }

Then, the user is asked to enter their credentials and authorize.After the user has granted access, he has authorized our temporary token. After this authorization, we can capturing the following 2 important fields the Request Token value and a verification code that is tied to the Request Token.

  • Getting an Access Token

The final third authentication step. After the application access is authorized, the application needs to exchange the Request Token for an Access Token. For this step, you will need the Request Token (the oauth_token and oauth_token_secret values) and the oauth_verifier value from the previous step.

            signer.clientSharedSecret = Constants.CONSUMER_SECRET;
            OAuthGetAccessToken accessToken = new OAuthGetAccessToken(Constants.ACCESS_URL);
            accessToken.transport = new ApacheHttpTransport();
            accessToken.temporaryToken = requestToken;
            accessToken.signer = signer;
            accessToken.consumerKey = Constants.CONSUMER_KEY;
            return accessToken;

In return,we will get an access token and the corresponding access token secret, URL-encoded.

We store the credentials in our Android Shared Preferences so that we don’t need to force the user to authorize the request again.

	Editor editor = prefs.edit();
        editor.putString(OAUTH_TOKEN, authToken.getAuthToken());
        editor.putString(OAUTH_TOKEN_SECRET, authToken.getAuthTokenSecret());
        editor.commit();

Making API calls

In order to make an authorized API call, we’ll do the following

  • Retrieve the access token and token secret from our shared preferences
  • Create a signer object, containing our token secret
  • Create an authorizer object, containing our signer and access token
  • Tell the authorizer to sign our requests
        OAuthHmacSigner signer = new OAuthHmacSigner();
        signer.clientSharedSecret = Constants.CONSUMER_SECRET;
        signer.tokenSharedSecret = localCredentialStore.getToken().getAuthTokenSecret();
        OAuthParameters authorizer = new OAuthParameters();
        authorizer.consumerKey = Constants.CONSUMER_KEY;
        authorizer.signer = signer;
        authorizer.token = localCredentialStore.getToken().getAuthToken();

Then we initialize the  consumer  during our request call,for e.g.

 new DownloadJson(Constants.PRODUCT_API_REQUEST, getConsumer()).execute();


try{
     GenericUrl requestUrl = new GenericUrl(url);

                HttpRequestFactory requestFactory = HTTP_TRANSPORT
                        .createRequestFactory(new HttpRequestInitializer() {
                            @Override
                            public void initialize(HttpRequest request) {

                                request.getHeaders().setAccept("application/xml");
                            }
                        });

                HttpRequest request = requestFactory.buildGetRequest(requestUrl);
              //Initializing the cosumer
                consumer.initialize(request);
}catch(Exception e){}

 

Summary

In brief, the above points can be explained as following :

  1. The consumer registers his domain with the provider (prerequisite).
  2. The provider accepts the registration and provides a consumer key and a consumer secret.
  3. The consumer requests a request token.
  4. The service provider(Magento in our case) sends the request token.
  5. The consumer sends his request token for authorization.
  6. If the user is not logged into the service provider, he does so now.
  7. User is authenticated by the provider(Magento in our case) . The consumer doesn’t capture the username/password
  8. The provider informs the user that the consumer wants to access his protected resource
  9. The users needs grants access to the consumer
  10. The provider then sends an authorized token to the consumer.
  11. The consumer sends his authorized token
  12. The service provider knows that the user has granted access and sends an access token
OAuth flow for authentication in Magento REST API

OAuth flow for authentication in Magento REST API

Sample Source Code

For complete source code, click here.

References:

Magento API
OAuth in Android
Configure Magento for Rest API

Develop magento mobile app using REST API and OAuth was last modified: September 17th, 2016 by Neha Prakash
  • satish sojitra

    I hope it’s going to be perfect solution for me !. Thanks for nice post.

  • Patel Ajaj

    Although i have provioded oauth_consumer_key
    I am getting an error oauth_problem=parameter_absent&oauth_parameters_absent=oauth_consumer_key
    there is any solution for this.

  • Pradeep Chaubey

    Hi Neha,
    I am developing a mobile application where I need to validate the Client(Mobile Application) with Magento using OAuth1.0. This authentication is needed because we need to call some REST API from Magento.
    I was following the steps mentioned in the blog but not able to proceed after step 1.
    – I am able to generate the URL something like this as per step 1 :
    http://mydomain.com/admin/oauth_authorize?oauth_token=9a101d60ff16cf376ede387a22c47660
    – Next I am pasting this url in browser and generating the oauth_token and oauth_verifier code.
    – To execute the next step I am hard coding the Token and verifier code and calling the next step to get Token.
    – At this step I am getting error
    “com.google.api.client.http.HttpResponseException: 401 Unauthorized”
    oauth_problem=signature_invalid
    Please help me to get rid of this problem as I am unable to move further.

    Also, is there anyway to execute all the steps at the application startup while loading because we don’t want to expose any credentials to our application user i.e. credentials to generate verifier code in step 2.

    Please share your comments, I will be very thankful.

    • Neha Prakash

      Hi Pradeep,
      You don’t need to generate static oauth_token and oauth_verifier code by hitting it on the browser. These keys are generated dynamically by the call provided . Have you gone through our sample code? If not then please try it. The link is provided in the above blog.