Skip to content
Lucas Banegas edited this page Jun 2, 2018 · 7 revisions

Requirements

The following versions of PHP are supported.

  • PHP 5.6
  • PHP 7.0
  • PHP 7.1
  • PHP 7.2
  • HHVM

Install

Via Composer

$ composer require docta/mercadolibre

Configure

The client has four options required and one optional (a token previously granted). Not declaring the required options implies the throwing of an exception.

$authSite     = '{mercadolibre-auth-site}';
$clientId     = '{mercadolibre-client-id}';
$clientSecret = '{mercadolibre-client-secret}';
$redirectUri  = 'https://example.com/oauth';

$client = new \Docta\MercadoLibre\Client($authSite, $clientId, $clientSecret, $redirectUri);
  • authSite corresponds to the country in which you registered your application. Depending on which country you have registered the application, it will also depend on the authorization url that this client will use. For example, if the application was registered for Argentina, the value of authSite must be MLA; and consequently, the client will use the following url: https://auth.mercadolibre.com.ar
/**
 * The keys of the following array are the only values that can be used as an `authSite` value.
 * Example: for an application registered in Argentina you must use `MLA`
 */
$authSites = [
    'MLA' => 'https://auth.mercadolibre.com.ar', // Argentina 
    'MLB' => 'https://auth.mercadolivre.com.br', // Brasil
    'MCO' => 'https://auth.mercadolibre.com.co', // Colombia
    'MCR' => 'https://auth.mercadolibre.com.cr', // Costa Rica
    'MEC' => 'https://auth.mercadolibre.com.ec', // Ecuador
    'MLC' => 'https://auth.mercadolibre.cl',     // Chile
    'MLM' => 'https://auth.mercadolibre.com.mx', // Mexico
    'MLU' => 'https://auth.mercadolibre.com.uy', // Uruguay
    'MLV' => 'https://auth.mercadolibre.com.ve', // Venezuela
    'MPA' => 'https://auth.mercadolibre.com.pa', // Panama
    'MPE' => 'https://auth.mercadolibre.com.pe', // Peru
    'MPT' => 'https://auth.mercadolibre.com.pt', // Portugal
    'MRD' => 'https://auth.mercadolibre.com.do'  // Dominicana
];
  • clientId and clientSecret are two values that you will get when registering your application in MercadoLibre and they appear as App ID and Secret key respectively. To register your application, you must access to http://applications.mercadolibre.com

  • redirectUri is the url to which the user will be redirected after authenticating at MercadoLibre and granting the necessary permissions. In this url we will receive the code that we will then exchange for a token. Below is an example.

Usage

Usage is similar to MercadoLibre Provider, but with substantial differences that simplify the development of an application based on the MercadoLibre API. This client is an extension of the mentioned provider, so it inherits all its properties and methods, but adds other methods that simplify the requests.

$authSite     = '{mercadolibre-auth-site}';
$clientId     = '{mercadolibre-client-id}';
$clientSecret = '{mercadolibre-client-secret}';
$redirectUri  = 'https://example.com/oauth';

$client = new \Docta\MercadoLibre\Client($authSite, $clientId, $clientSecret, $redirectUri);

/**
 * If we do not have an authorization code then get one
 */
if (!isset($_GET['code'])) {

    /**
     * Get the MercadoLibre authorization URL; return the url and also generate
     * and apply other necessary query parameters (for example: state).
     */
    $authUrl = $client->getAuthorizationUrl();

    /**
     * Get the generated state and save in session.
     */
    $_SESSION['state'] = $client->getState();

    /**
     * Redirect the user to the authorization URL
     */
    header('Location: '.$authUrl);
    exit;

/**
 * Check the state returned by MercadoLibre against the state
 * previously stored in session to mitigate the CSRF attack.
 */
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['state'])) {

    unset($_SESSION['state']);
    exit('Invalid state');

/**
 * If the state stored in session and the state returned
 * by MercadoLibre are the same, then continue.
 */
} else {

    try {
        /**
         * Try to exchange the code obtained by an access
         * token (using the authorization code grant).
         */
        $client->setToken($_GET['code']);

        /**
         * Optional: Now that we have a token, we can check
         * the data of the owner of the resources.
         */
        $owner = $client->getOwner();

        /**
         * And from now on to be able to consult the protected resources.
         * The following example makes the same request as the `getOwner()` method.
         */
        $me = $client->get('/users/me');

    /**
     * Failed to get the access token, the owner details or the items request.
     */
    } catch (\Docta\MercadoLibre\Exception\ClientException $e) {

        exit($e->getMessage());

    }
}

Quick reference

Complete and detailed documentation of the client API is available at https://docta.github.io/mercadolibre. However, then explain quickly and briefly the main methods.

Related to authorization

getAuthorizationUrl()

Returns the authorization URL of the MercadoLibre API (remember that the URL depends on the authSite value that you pass to the constructor). The URL includes the following query parameters:

  • response_type: It is always code and indicates to API services the type of authorization to grant.
  • client_id: Necessary for API services to recognize the application to which to grant.
  • redirect_uri: Necessary for API services to know where to return the granted code.
  • state: A random string used to mitigate CSRF attacks (requires a subsequent check).

getState()

Returns the same value of the state query parameter of the authorization URL. For obvious reasons, this method should only be used after generating the authorization URL. The usual use of this value is to store it in a session to then compare with the returned by the API services; and if both are equal, then everything went well.

Related to tokens

setToken($token)

Set a token for the client. The parameter $token passed to the method can be of two types: a string (the client assumes that it is a code) or a token previously granted. A token can also be set by the constructor, passing it as fifth parameter.

getToken()

Returns the current client token. Keep in mind that, if the current token has expired, this method will try to refresh it before returning, so you must remember that the token returned will not necessarily be the same as one previously set.

Related to requests

Keep in mind that, in all these methods:

  • The $path parameter must be relative routes to the API url (ex: /users).

  • The $query parameter must be an array with keys and values that will be added to the URL as query parameters. This parameter is always optional. Remember that the access_token query parameter is added automatically and do not need to include again.

  • The $data parameter must be an array with keys and values that will be sent to the API services through HTTP headers. This parameter is always optional. The value of this parameter, before being sent, will be converted to json. They are used only in post and put methods, for example, to create or edit users, items, etc.

get($path, $query = [])

Execute a GET request.

post($path, $data = [], $query = [])

Execute a POST request.

put($path, $data = [], $query = [])

Execute a PUT request.

delete($path, $query = [])

Execute a DELETE request.

options($path, $query = [])

Execute a OPTIONS request.

execute($method, $path, $query = [], $data = [])

Execute a custom request.

Related to the owner

getOwner()

Returns data from the owner of the token established to the client. It's similar to making the request get('/users/me').

Server side flow

In short, the authentication process of MercadoLibre through OAuth2, is as follows:

Server-Side Flow

Other useful resources