API do Libax Business

Modificado em Wed, 10 May 2023 às 06:54 PM

Aqui poderá encontrar toda a documentação relacionada com a API do Libax Business para o ajudar a ligar a sua aplicação com o seu software de faturação. Com esta integração poderá facilmente:

  • Criar clientes
  • Emitir faturas ou outro tipo de documentos
  • Realizar impressão de documentos
  • e muito mais...


É uma excelente solução para adicionar as funcionalidade de faturação à sua loja on-line ou a outra aplicação que necessite de ter um suporte de faturação associado.


Obter o ClientID

Para utilizar a API é preciso criar um clientID para utilizar na fase de autenticação.

Esta funcionalidade está disponível Business -> Configurações (roda dentada em cima à direita) -> Cliente API

Após entrar nesta opção, pressione o botão Criar conforme imagem seguinte:


Após criação do ID de cliente, será mostrado o ID e o seacret conforme imagem seguinte:


O secret não será mostrado novamente. Assim, guarde esta informação num local seguro e partilhe apenas com que vai utilizar a API. Caso perca informação terá de gerar novo secret.


A qualquer momento poderá voltar a esta configuração se pretender remover esta funcionalidade.


Utilizar a API

A API está disponível no endereço https://api.libax.com/business/v1/


Neste endereço está também disponível a documentação Swagger onde pode também autenticar-se e invocar os métodos de forma a facilitar o desenvolvimento.

Para a autenticação ser completa é necessário escolher o scope business_public_api conforme imagem seguinte:


Exemplos em C# de como utilizar a API

Para utilizar os exemplos seguintes é preciso referênciar as libraries seguintes:

using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

Exemplo para obter o token de autenticação

Utilize o código seguinte como exemplo para obter o token de autenticação

using HttpClient client = new HttpClient();
string url = "https://id.libax.com/api/connect/token";
string clientId = "YOUR-CLIENTID";
string clientSecret = "YOUR-SECRET";

string encodedCredentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(clientId + ":" + clientSecret));
client.DefaultRequestHeaders.Add("Authorization", "Basic " + encodedCredentials);

var content = new StringContent("grant_type=client_credentials&scope=business_public_api", Encoding.UTF8, "application/x-www-form-urlencoded");

using HttpResponseMessage response = await client.PostAsync(url, content);

if (response.IsSuccessStatusCode)
{
    string responseData = await response.Content.ReadAsStringAsync();
    dynamic t = Newtonsoft.Json.JsonConvert.DeserializeObject(responseData);

    string accessToken = t.access_token;
    int expiresIn = t.expires_in;
    string tokenType = t.token_type;
    string scope = t.scope;

    Console.WriteLine($"Access Token: {accessToken}, Expires in {expiresIn}, type {tokenType}, scope {scope}");
}
else
{
    Console.WriteLine($"Error: {response.StatusCode}");
}

Exemplo para obter lista de 10 produtos

Utilização do método em https://api.libax.com/business/v1/index.html#/Products/get_Products

using HttpClient client = new HttpClient();
string url = "https://api.libax.com/business/v1/products";

client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "YOUR-ACCESS-TOKEN");

var queryParams = new System.Collections.Generic.Dictionary<string, string> { { "take", "10" } };

using FormUrlEncodedContent formContent = new FormUrlEncodedContent(queryParams);
string queryString = await formContent.ReadAsStringAsync();

using HttpResponseMessage response = await client.GetAsync($"{url}?{queryString}");

if (response.IsSuccessStatusCode)
{
    string data = await response.Content.ReadAsStringAsync();
    Console.WriteLine(data);
}
else
{
    Console.WriteLine($"Error: {response.StatusCode}");
}


Exemplo para inserir uma entidade

Utilização do método em https://api.libax.com/business/v1/index.html#/Entities/post_Entities

using HttpClient client = new HttpClient();
string url = "https://api.libax.com/business/v1/entities";

client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "YOUR-ACCESS-TOKEN");

var data = new
{
    name = "Ana Ferreira",
    city = "Lisboa"
};
using StringContent content = new StringContent(JsonSerializer.Serialize(data), Encoding.UTF8, "application/json");

using HttpResponseMessage response = await client.PostAsync(url, content);

if (response.IsSuccessStatusCode)
{
    string newEntityId = await response.Content.ReadAsStringAsync();
    Console.WriteLine(newEntityId);
}
else
{
    Console.WriteLine($"Error: {response.StatusCode}");
}


Exemplo para procurar 5 entidades registadas em 2022

Utilização do método em https://api.libax.com/business/v1/index.html#/Entities/post_Entities_search

using HttpClient client = new HttpClient();
string url = "https://api.libax.com/business/v1/Entities/search";

client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "YOUR-ACCESS-TOKEN");

var data = new
{
    take = 5,
    filters = new[]
    {
        new { propertyName = "creationdate", @operator = "GTE", value = "2022-01-01" },
        new { propertyName = "creationdate", @operator = "LT", value = "2023-01-01" }
    }
};

using StringContent content = new StringContent(JsonSerializer.Serialize(data), Encoding.UTF8, "application/json");

using HttpResponseMessage response = await client.PostAsync(url, content);

if (response.IsSuccessStatusCode)
{
    string newEntityId = await response.Content.ReadAsStringAsync();
    Console.WriteLine(newEntityId);
}
else
{
    Console.WriteLine($"Error: {response.StatusCode}");
}


Filtros

É possível aplicar filtros nos pedidos da API no sentido de obter apenas a informação que pretende.

Considere os seguintes operators disponíveis:


OperadorSignificadoTipo de campo
EQIgualNumber,Date,String
LTMenorNumber,Date
LTEMenor ou igualNumber,Date
GTMaiorNumber,Date
GTEMaior ou igualNumber,Date
CONTAINS_TOKENContemString

Nota: em Enums e Booleans o operator é ignorado e é sempre feita uma igualdade


Campos possível para filtrar

Nota: São todos case insensitive


Entities

    Number

    Name

    ContactID

    AddressID

    VatNumber

    BirthDate

    Type

    OccupationID

    Observation

    Status

    Balance

    CreationDate

    LibaxUserID

    ViewActivityEnabled

    RegisterDate

    Iban

    ChildrenCount

    CivilState

    Rating

    ModifiedDate

    Email

    Phone

    Mobile

    City

    OfficeId

    SellerId


Liquidations

    SerieID

    DocumentType

    Number

    LiquidationDate

    EntityID

    ReceivedAmount

    DiscountAmount

    CashFlowID

    BankNoteID

    Observation

    CreatorUserID

    CreationDate

    SaleId


Series

    DisplayCode

    Name

    StartDate

    EndDate

    IsActive

    IsDeviceOnly

    Type

    VatNumber


SerieSequeces

    SerieID

    DocumentType

    LastNumber

    LastDate

    DisplayCode



Sales

    EntityId

    SerieID

    DocumentType

    Number

    SaleDate

    DueDate

    SubTotal

    DiscountAmount

    GrossAmount

    RetentionRate

    RetentionAmount

    SealAmount

    TaxAmount

    TotalDue

    PendingAmount

    Reference

    Observation

    Hash

    HashControl

    CreditReference

    Reason

    CreatorUserID

    CreationDate

    Status

    VerificationCode

    StatusDate

    StatusUserID

    RetentionIRC

    Adjustment


Products

    ProductType

    StandardCost

    TaxID

    DiscontinuedDate

    DiscountRate

    ApplyRetention

    StockQty

    StockAlertQty

    AutoStockHistory

    ProductDetail

    UnitID

    SellPrice

    StockCategory

    Reference

    Name




Exemplos de utilização de filtros


Dica: quando pretende considerar uma condição "ou", coloque os filters dentro de uma lista de filterGroups.


Procura por entidades com "ana" no nome e ordena por data de criação 

{
  "take": 50,
  "skip": 0,
  "filters": [
    {
      "propertyName": "name",
      "operator": "CONTAINS_TOKEN",
      "value": "Ana"
    }
  ],
  "sort": {
    "propertyName": "creationDate",
    "direction": 1
  }
}

Procura por entidades criadas no ano 2022

{
  "take": 50,
  "skip": 0,
  "filters": [
    {
      "propertyName": "creationdate",
      "operator": "GTE",
      "value": "2022-01-01"
    },
    {
      "propertyName": "creationdate",
      "operator": "LT",
      "value": "2023-01-01"
    }
  ]
}


Procura por entidades com a cidade igual a "Lisboa" ou "Porto"

{
  "take": 50,
  "skip": 0,
  "filterGroups": [
    {
      "filters": [
        {
          "propertyName": "city",
          "operator": "EQ",
          "value": "Lisboa"
        }
      ]
    },
    {
      "filters": [
        {
          "propertyName": "city",
          "operator": "EQ",
          "value": "Porto"
        }
      ]
    }
  ]
}


Procura por entidades com cidade "Lisboa" ou "Porto" e criadas apartir de 2023

{
  "take": 50,
  "skip": 0,
  "filterGroups": [
    {
      "filters": [
        {
          "propertyName": "city",
          "operator": "EQ",
          "value": "Lisboa"
        }
      ]
    },
    {
      "filters": [
        {
          "propertyName": "city",
          "operator": "EQ",
          "value": "Porto"
        }
      ]
    }
  ],
  "filters": [
    {
      "propertyName": "creationdate",
      "operator": "GTE",
      "value": "2023-01-01"
    }
  ]
}

Limites de utilização

A API está protegida com um número de requests por minuto:

  • 100 requests por minuto todos os dias entre as 9h e as 19h (hora de Portugal continental)
  • 200 requests por minuto todos os dias entre as 19h e as 9h (hora de Portugal continental)


Em todos os responses, irá obter os seguintes headers:

  • X-Rate-Limit - indica quantos requests já fez desde que o contador voltou a zero
  • X-Rate-Limit-Remaining - indica quantos requests ainda pode fazer dentro do minuto a decorrer

Dica: Utilize estes headers para não exceder o número de requests permitidos por minuto.


Se exceder o limite de requests por minuto, irá obter um erro 429 com o header Retry-After que indica o tempo no formato delta-seconds que tem de esperar para que possa fazer um novo request.


Dúvidas e apoio ao desenvolvimento

Se durante o desenvolvimento surgirem dúvidas ou pretende ajudar no desenvolvimento, não hesite em contactar-nos pelo e-mail support@libax.com

Este artigo foi útil?

Isso é ótimo!

Obrigado pelo seu feedback

Lamentamos por não termos podido ajudá-lo(a)

Obrigado pelo seu feedback

Diga-nos como podemos melhorar este artigo!

Selecione pelo menos um motivo

Comentário enviado

Agradecemos o seu esforço e iremos tentar corrigir o artigo