Giter Club home page Giter Club logo

mercadolibre-net-sdk's Introduction

MercadoLibre's .NET SDK

This is a .NET SDK for MercadoLibre's Platform. Build status

Is this the official Mercado libre SDK for .NET?

No. We forked the .NET SDK a while back and ended up tweaking it to better suits our needs.

How do I install it?

To install the SDK with nuget, run the following command in the Package Manager Console:

PM> Install-Package MercadoLibreSdk -prerelease

How do I start using it?

The first thing to do is to instanciate the MeliApiService class.

You have to obtain an access token after creating your own application. Read the Getting Started guide for more information.

Once you have a client id and client secret for your application, instanciate MeliCredentials and assign it to the MeliApiService.Credentials property.

var m = new MeliApiService 
        {
            Credentials = new MeliCredentials(MeliSite.Argentina, 1234, "a secret")
        };

With this instance you can start working on MercadoLibre's APIs.

There are some design considerations worth mentioning:

  1. This SDK is a thin layer on top of HttpClient to handle the OAuth WebServer flow for you.
  2. Json.NET is used to serialize and deserialising to and from JSON. It's up to you to call the relevant methods with classes that match the expected json format.
  3. http-params library to generate URIs. The HttpParams class is a simple wrapper for System.Collections.Specialized.NameValueCollection with a fluent interface. Values are URL encoded automatically!

How do I redirect users to authorize my application?

This is a 2-step process.

First get the link to redirect the user. This is very easy! Just:

var redirectUrl = m.GetAuthUrl(1234, MeliSite.Argentina, "http://somecallbackurl");

This will give you the url to redirect the user. The callback url must match redirect URI that you specified for your mercado libre application.

Once the user is redirected to your callback url, you'll receive in the query string, a parameter named code. You'll need this for the second part of the process.

m.AuthorizeAsync("the received code", "http://somecallbackurl");

This method will set the AccessToken and RefreshToken properties on the MeliCredentials instance.

An access token represent an authorization for your web application to act on behalf of a mercado libre user.

The refresh token is only set if your application has the offline_access scope enabled.

At this stage your are ready to make call to the API on behalf of the user.

How do I refresh the access token?

Access tokens are only valid for 6 hours. As long as your app has the offline_access scope you will obtain a refresh token along with the access token.

When the refresh token is set, MeliApiService will automatically renew the access token after the first 401 unauthorized answer it receives.

If you need to track access and refresh token changes (for example to store the tokens to use them later) you can subscribe to a TokensChanged event:

var credentials = new MeliCredentials(MeliSite.Argentina, 123456, "clientSecret", "accessToken", "refreshToken");

credentials.TokensChanged += (sender, args) => { doSomethingWithNewTokenValues(args.Info); };

var service = new MeliApiService(new HttpClient()) {Credentials = credentials};

var success = await service.AuthorizeAsync(code, callBackUrl);

Making authenticated calls to the API

As long as the Credentials.AccessToken property is set on the MeliApiService, an Authorization: Bearer YOUR_TOKEN header will be set automatically when making requests.

Read more about authenticating requests on the official API docs.

A handle result policy will automatically refresh the token when it's expired.

Do I always need to include the access_token as a parameter?

Yes. From April 2021 onwawrds, every request API will need an Authorization HTTP header.

Making GET calls

var p = new HttpParams().Add("a param", "a value")
                        .Add("another_param", "another value")
                        .Add("you can chain", "the method calls");

var response = await m.GetAsync("/users/me", p);

if (response.IsSuccessStatusCode)
{
    var json = await r.Content.ReadAsStringAsync();

    // You can then use Json.NET to deserialize the json
}

Making POST calls

var p = new HttpParams().Add("a param", "a value");

var r = await m.PostAsync("/items", p, new { foo = "bar" });

Making PUT calls

var p = new HttpParams().Add("a param", "a value");

var r = await m.PutAsync("/items/123", p, new { foo = "bar" });

Making DELETE calls

var p = new HttpParams().Add("a param", "a value");

var r = await m.DeleteAsync("/items/123", p, new { foo = "bar" });

Strongly typed calls

If you know what JSON you're expecting you can create your own classes decorated with the System.Text.Json attribute.

public class Category
{
    [JsonPropertyName("id")]
    public string Id { get; set; }

    [JsonPropertyName("name")]
    public string Name { get; set; }
}

var categories = await m.GetAsync<Category[]>("/sites/MLB/categories");

Deserializing with an anonymous type

If you just need a few values back from an API call, Json.NET has a really cool DeserializeAnonymousType method:

var json = @"{""refresh_token"":""refresh"",""access_token"":""access"",""user_id"":123456789}";

var token = JsonConvert.DeserializeAnonymousType (json, new {refresh_token="", access_token = ""});

var refreshToken = token.refresh_token;

mercadolibre-net-sdk's People

Contributors

bounav avatar phil-b-higgins avatar puchi84 avatar xetorthio avatar zeusmode avatar tioborracho avatar aleml86 avatar

Stargazers

GW avatar OCTO Tecnologia e Consultoria em Softwares avatar  avatar  avatar Bruno Brigide avatar Jose Carlos Bilhega avatar Edgardo avatar Jonty avatar  avatar  avatar Ernesto Gutiérrez avatar

Watchers

 avatar James Cloos avatar  avatar Diego Ezequiel Guillén avatar  avatar  avatar Jose Carlos Bilhega avatar  avatar

mercadolibre-net-sdk's Issues

Can't install nuget package

When trying to install I get this message "cannot install package MercadoLibreSdk 1.0.8. You´re trying to install the package in a project with .NetFramework 3.5...

I tried with every framework and I still cannot install it. Any solutions?

compatibility issue

PM> Install-Package MercadoLibreSdk -prerelease
Restaurando pacotes para C:\Users\zigui\source\repos\MonteSeuPCML\MonteSeuPCML\MonteSeuPCML.Android\MonteSeuPCML.Android.csproj...
Install-Package : NU1202: O pacote MercadoLibreSdk 1.0.8 não é compatível com monoandroid81 (MonoAndroid,Version=v8.1). O pacote
MercadoLibreSdk 1.0.8 dá suporte a: net451 (.NETFramework,Version=v4.5.1)
No linha:1 caractere:1

  • Install-Package MercadoLibreSdk -prerelease
  •   + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
      + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand
    
    

Install-Package : A restauração do pacote falhou. Revertendo as alterações no pacote para 'MonteSeuPCML.Android'.
No linha:1 caractere:1

  • Install-Package MercadoLibreSdk -prerelease
  •   + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
      + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand
    

Token not refreshed

When making a request with old Token, it returns 401 invalid token.
"{"message":"invalid_token","error":"not_found","status":401,"cause":[]}"
It seem refresh token it isn't refreshed as stated on ducumentation.
Also TokensChanged its not triggered

I do have a refresh token in credentials. If i call the api directly i do get the new token succesfully

AuthorizeAsync not working

I had a code just like the readme example

meliApi = new MeliApiService(new HttpClient())
                {
                    Credentials = new MeliCredentials(MeliSite.Argentina, clientID, secret)
                };
meliApi.Credentials.TokensChanged += (sender, args) => { doSomethingWithNewTokenValues(args.Info); };

var success = await meliApi.AuthorizeAsync(code, callBackUrl);

It was working fine until last update, version 2.0.12
Since then the AuthorizeAsync method is simply returning false, and credential is not getting the access token anymore.
Any idea why it's not working anymore?
Also, the readme is outdated since it doesn't consider the new httpclient parameter, and this line is wrong
var success = await MercadoLibreApiService.AuthorizeAsync(credentials, code, callBackUrl);
MercadoLibreApiService namespace doesn't belong to this project, and MeliApiService AuthorizeAsync method doesn't support a credentials parameter.

Error in the authentication process

When I try to authenticate, I get the following error message ...
I am thankful for any kind of help!

var tokens = await SendAsync(client, HttpMethod.Post, ApiUrl, "/oauth/token", parameters);

--- Error -----
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Transfer-Encoding: chunked
Connection: keep-alive
vary: accept
vary: accept-encoding
X-Content-Type-Options: nosniff
X-Request-Id: fc56abdd-569c-418d-bc47-6214926fa7f9
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS
Access-Control-Max-Age: 86400
Strict-Transport-Security: max-age=15724800
X-Cache: Error from cloudfront
X-Amz-Cf-Pop: EZE51-C1
X-Amz-Cf-Id: 004seDQhEqkyzVVNvb3-f1EzCL5ZHvR_6KlZ7R4zGfvSjuSt9V4sQg==
Cache-Control: max-age=0
Date: Fri, 19 Feb 2021 14:27:14 GMT
Via: 1.1 171d7370ca264be0e555ac6695616d94.cloudfront.net (CloudFront)
Content-Type: application/json; charset=UTF-8
}}

AuthorizeAsync never returns

I get to the point were the app is authorized and i have the code, but AuthorizeAsync never returns.

private async Task authAsync ()
{
     var m = new MeliApiService
     {
          Credentials = new MeliCredentials(MeliSite.Argentina, appID, appSecret)
     };

     var redirectUrl = m.GetAuthUrl(appID, MeliSite.Argentina, callbackURL);
     
     String code = null;

     using (var form = new Form2(redirectUrl))
     {
          var result = form.ShowDialog();
          
          if (result == DialogResult.OK)
          {
               code = form.ReturnValue1.Split('=')[1];
               form.Close();
          }
     }

     await m.AuthorizeAsync(code, callbackURL);
     
     richTextBox2.Text = m.Credentials.AccessToken.ToString();
}

The code contains the correct token.

await m.AuthorizeAsync(code, callbackURL); just never ends. It is also not clear if it wants the redirecturl or the callbackurl since in the example says callback, but in the code it says redirecturl, anyway i tryied them both.

I've just installed the package using nuget in Visual Studio 2017 and nothing more.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.