My first application

Before you start working with this tutorial, you will need to install these programs:

We use Git version 2.20.1 and Node.js version 12.3.1, but recommend to use the latest versions. All the online commands launched are generic and will be executed in Unix-based operating systems, such as Windows.

Contents

→Introduction
→Project configuration
→Create an application in Mercado Libre
→Start development
→Deploy for Heroku
→Adjustments in Mercado Libre
→Route configuration
→Updates


Introduction

In this tutorial we will build a Mercado Libre embedded password-protected application so that you can list your items and recover posted items.

For ease of work, Mercado Libre has software development kits (SDKs) in different languages. In this case, we will use Mercado Libre SDK for Node.js. Learn about Mercado Libre tools.

Login screen

Form for item delivery

Items list


Project configuration

To start a project, download files and directories..

Enter the online tool in your project directory and run npm install, command to install project dependencies. We will use the following dependencies:

  • mercadolibre: Mercado Libre SDK to help you develop your integration.
  • express: to ease our application development in Node.js.
  • ejs: for express work and as view engine to create our templates.
  • dotenv: to insert environment variables defined in a .env file in our local code.
  • multer: to help upload files to be used for picture display in Mercado Libre.
  • helmet: to create a protection layer in your Node.js application.
  • cookie-session: to be responsible for session data administration. For example, for logged user validation.

Create an application in Mercado Libre

Once you have a project in Node.js, you will need to create an application in Mercado Libre to work with the integration. So:

  1. Go to our DevCenter.
  2. Click on “Create an application.”
  3. Fill out all mandatory data. In “redirect URI" fill out domain root:
  4. Note:
    It is important that this field is filled with a proper URL, valid and configured to receive notifications.


  5. In "Topics," you can select your interest in receiving notifications and in “Callbacks URL Notifications” we will set up a route to receive notifications on those topics.



  6. Take into account that the notification callback url is filled out with our application base URL (in this case, http://localhost:3000) plus a so called /notifications route. Mercado Libre will make requests for this route whenever something relevant happens with the selected topics. For further information see notification documentation. Save the project and you will be redirected to the homepage where your application will be included. You can see your ID and secret key shown by your application. With these values, we can start integration.
 

Remember that "localhost" is a temporary URL to be replaced as soon as it is implemented.

Start development

Now that the project is installed and you have an application created in Mercado Libre. Create a .env file, to be used to insert our confidential information variables in code without sharing versioning platforms and code collaboration, such as GitHub, GitLab, Bitbucket, etc.

Copy .env.example file content, and paste it in the file you already created and fill out the variables. You will get the following result:

       
  CLIENT_ID={The ID of your application in Mercado Libre}
  CLIENT_SECRET={The key of your application in Mercado Libre}
  REDIRECT_URI=http://localhost:3000
  SYS_PWD={The password that you want to use in your system}
     

Your application is ready for local use! In your command line tool, execute npm start command, access URLhttp://localhost:3000 and go to URL http://localhost:3000. Now that our application is executed, we can continue with the implementation phase.

 

You can stop execution at any time hitting Ctrl+C.

Deploy for Heroku

Heroku is platform as a service (PaaS) that supports different languages and allows developers for cloud-based application creation and upload.

To implement in Heroku, we first need to know Node.js version we are working with. Execute node --version in your online command tool and copy appearing numbers.

Open package.json package and, at the file end, change property "engines" to get your version numbers.

After this, install Heroku CLI. To do this, go to Heroku page and download it.

Git will be used for Herouk project. Execute git init command. Then execute git add command, and finally, git commit -m "first commit" command. You can exchange "first commit" message for any message you want.

To create your application in Heroku, follow these steps:

  1. Log in Heroku with heroku login command.
  2. Once logged in, execute heroku create my-meli-application. You can change "my-meli-application" for any name you want. The application name will define the URL to be used for access to your application. For further information, . Puedes cambiar "my-meli-application" a cualquier nombre que desees. El nombre de la aplicación definirá la URL que usará para acceder a su aplicación. Para obtener más información, go to Heroku documentation.
  3. To upload files to Heroku server, execute git push heroku master command. .env file variables should not go directly to the server. There is a way to create direct configuration variables from command line. Execute commands:
    • heroku config:set CLIENT_ID={APPLICATION ID IN MERCADO LIBRE}
    • heroku config:set CLIENT_SECRET={APPLICATION SECRET KEY IN MERCADO LIBRE}
    • heroku config:set REDIRECT_URI=https://{APPLICATION-NAME}.herokuapp.com
    • heroku config:set SYS_PWD={PASSWORD TO BE USED IN SYSTEM}

Finally, to see your application working, execute heroku open command. A browser window will be opened in Heroku application web site.


Adjustments in Mercado Libre

Now that you posted your first application, the URL will no longer be "localhost." Go back to Mercado Libre DevCenter to make the relevant adjustments.

  1. Go to our DevCenter again.
  2. Click on three dots and then "edit" to edit your application:


  3. Change "redirecting URI" to a new URL provided by Heroku. This URL should be the same as the one in configuration variables, that is, similar to https://{HEROKU-APPLIATION-NAME}.herokuapp.com.


  4. Also change “notification callback URL”:


Route configuration

For better understanding of route system in this small integration, let us prepare a screen with item list.

Open app.js file and add the following code before module.exports = app:


app.get('/posts', validateToken, async (req, res) => {
  try {
    const meliObject = new MeliObject(res.locals.access_token);    
    const user = await meliObject.get('/users/me');
    const items = (await meliObject.get(`/users/${user.id}/items/search`)).results || [];
    if (items.length) {
      const result = [];
      const promises = items.map(item_id => meliObject.get(`/items/${item_id}`));
      for await (item of promises) {
        result.push(item);
      }
      res.render('posts', { items: result });
    } else {
      res.status(404).send('no items were found :(');
    }
  } catch(err) {
    console.log('Something went wrong', err);
    res.status(500).send(`Error! ${err}`);
  }
});
     

res.render('posts', { items: result }) code line refers to page rendering code, called posts.ejs in views directory.

Create this posts.ejs page in views directory and add the following code:

       
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Posts - My Meli Application</title>
  <link rel="stylesheet" type="text/css" href="/css/style.css" />
</head>
<body>
  <div class="container">
    <div class="items-list">
      <% for (item of items) { %>
        <a target="_blank" rel="noopener noreferrer nofollow" href="<%= item.permalink %>">
          <div>
            <img src="<%= item.secure_thumbnail %>" />
            <h3><%= item.title %></h3>
          </div>
        </a>
      <% } %>
    </div>
  </div>
</body>
</html>
     

Updates

As you implement new functionality in your development, consider that you will need to upload these updates to Heroku.

To make this process, repeat the previous steps:

  1. Run git add . command to add files in stage.
  2. Run git commit -m "agrega pantalla de listado de ítems".You can change the message to find it faster but we recommend to always keep a short clear text related to the changes made.
  3. To upload files and server restart, use git push heroku master command.
or register to recieve the latest news about our API