Pular para o conteúdo principal

Exemplos de Integração

Este guia fornece exemplos práticos de integração em diferentes linguagens de programação.

Setup Inicial

Antes de começar, você precisará:

  1. Credenciais de acesso (ClientId e ClientSecret)
  2. URL base da API de integração
  3. Webhook configurado para receber notificações

Node.js

Configuração Inicial

const config = {
baseUrl: 'https://api.integration.exemplo.com',
auth: {
clientId: 'seu-client-id',
clientSecret: 'seu-client-secret'
},
contractAccountId: 'seu-contract-account-id',
webhook: {
url: 'https://sua-api.com/webhooks'
}
};

Cliente Base

const axios = require('axios');

class IntegrationClient {
constructor(config) {
this.config = config;
this.client = axios.create({
baseURL: config.baseUrl,
headers: {
'Authorization': `Basic ${this.getAuthToken()}`,
'x-contractAccountId': config.contractAccountId
}
});
}

getAuthToken() {
const credentials = `${this.config.auth.clientId}:${this.config.auth.clientSecret}`;
return Buffer.from(credentials).toString('base64');
}

async createBatch(endpoint, data) {
const response = await this.client.post(`/v1/batch/${endpoint}`, data);
return response.data.operationId;
}

async deleteBatch(endpoint, data) {
const response = await this.client.delete(`/v1/batch/${endpoint}`, { data });
return response.data.operationId;
}
}

Exemplo: Cadastro de Produtos

async function createProducts() {
const client = new IntegrationClient(config);

const products = [
{
externalReference: 'prod-123',
name: 'Refrigerante Cola 2L',
slug: 'refrigerante-cola-2l',
title: 'Refrigerante Cola 2L',
shortDescription: 'Refrigerante de cola 2 litros',
longDescription: 'Refrigerante de cola 2 litros, ideal para toda a família',
brandExternalReference: 'brand-123',
categoryExternalReference: 'cat-123',
commercialPolicyId: '3FA85F64-5717-4562-B3FC-2C963F66AFA6',
displayInSite: true,
displayInSoldOut: false,
fiscalCode: '1111111',
EAN: '7891234567890',
Punctuation: 1,
Active: true,
SKUs: [
{
ExternalReference: 'sku-123',
Name: 'Refrigerante Cola 2L',
EAN: '7891234567890',
Reference: 'REF001',
WeightForFreight: 2.0,
HeightForFreight: 30.0,
WidthForFreight: 10.0,
LengthForFreight: 10.0,
WeightReal: 2.1,
HeightReal: 30.0,
WidthReal: 10.0,
LengthReal: 10.0,
ArrivalDate: '2024-01-01',
ManufacturerCode: 'MFG001',
UnitOfMeasure: 1,
ArithmeticFactor: 1
}
]
}
];

try {
const operationId = await client.createBatch('products', products);
console.log(`Produtos enviados. OperationId: ${operationId}`);
return operationId;
} catch (error) {
console.error('Erro ao criar produtos:', error.response?.data || error);
throw error;
}
}

Exemplo: Webhook Handler

const express = require('express');
const app = express();

app.post('/webhooks', express.json(), async (req, res) => {
const { operationId, relatedEntity, eventType, data, error } = req.body;

console.log(`Notificação: ${relatedEntity} - eventType: ${eventType}`);

try {
switch(eventType) {
case 26: // ProductWithSKUs_Created
await handleProductCreated(data);
break;
case 27: // ProductWithSKUs_Updated
await handleProductUpdated(data);
break;
case 28: // ProductWithSKUs_CreationFailed
case 29: // ProductWithSKUs_UpdateFailed
case 30: // ProductWithSKUs_PartiallyFailed
await handleProductError(data, error);
break;
case 133: // Order_StatusUpdated
await handleOrderStatusUpdated(data);
break;
}

res.status(200).send();
} catch (err) {
console.error(`Erro processando webhook: ${err}`);
res.status(500).send();
}
});

Python

Cliente Base

import base64
import requests
from typing import List, Dict, Any

class IntegrationClient:
def __init__(self, base_url: str, client_id: str, client_secret: str, contract_account_id: str):
self.base_url = base_url
self.contract_account_id = contract_account_id
self.auth_token = self._get_auth_token(client_id, client_secret)

def _get_auth_token(self, client_id: str, client_secret: str) -> str:
credentials = f"{client_id}:{client_secret}"
return base64.b64encode(credentials.encode()).decode()

def _headers(self) -> dict:
return {
"Authorization": f"Basic {self.auth_token}",
"Content-Type": "application/json",
"x-contractAccountId": self.contract_account_id
}

def create_batch(self, endpoint: str, data: List[Dict[str, Any]]) -> str:
response = requests.post(
f"{self.base_url}/v1/batch/{endpoint}",
json=data,
headers=self._headers()
)
response.raise_for_status()
return response.json()["operationId"]

Exemplo: Atualização de Preços

from datetime import datetime, timedelta

def update_prices():
client = IntegrationClient(
base_url="https://api.integration.exemplo.com",
client_id="seu-client-id",
client_secret="seu-client-secret",
contract_account_id="seu-contract-account-id"
)

tomorrow = datetime.now() + timedelta(days=1)
prices = [
{
"skuExternalReference": "sku-123",
"externalReference": "price-123",
"commercialPolicyId": "9f36a666-acd5-4987-a47f-3de247f65d82",
"listPrice": {
"value": 9.99,
"startDateTime": tomorrow.strftime("%Y-%m-%d")
},
"basePrice": {
"value": 10.99
},
"fixedPrice": None
}
]

try:
operation_id = client.create_batch("pricing", prices)
print(f"Preços enviados. OperationId: {operation_id}")
return operation_id
except Exception as e:
print(f"Erro ao atualizar preços: {e}")
raise

C#

Cliente Base

public class IntegrationClient
{
private readonly HttpClient _client;
private readonly string _baseUrl;

public IntegrationClient(string baseUrl, string clientId, string clientSecret, string contractAccountId)
{
_baseUrl = baseUrl;
_client = new HttpClient();

var auth = Convert.ToBase64String(
Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}")
);
_client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", auth);
_client.DefaultRequestHeaders.Add("x-contractAccountId", contractAccountId);
}

public async Task<string> CreateBatchAsync<T>(string endpoint, IEnumerable<T> data)
{
var response = await _client.PostAsJsonAsync(
$"{_baseUrl}/v1/batch/{endpoint}",
data
);

response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<OperationResponse>();
return result.OperationId;
}
}

Exemplo: Gestão de Estoque

public class StockExample
{
private readonly IntegrationClient _client;

public async Task UpdateStock()
{
var stockUpdates = new List<WarehouseSkuUpdate>
{
new()
{
WarehouseExternalReference = "warehouse-001",
Items = new List<WarehouseSkuItem>
{
new()
{
SKUExternalReference = "sku-123",
QuantityAvailable = 100,
QuantityReserved = 5
}
}
}
};

var operationId = await _client.CreateBatchAsync("warehouses/sku", stockUpdates);
Console.WriteLine($"Estoque atualizado. OperationId: {operationId}");
}
}

Casos de Uso Comuns

  1. Criar categorias
  2. Criar marcas
  3. Criar produtos (com SKUs)
  4. Atualizar preços
  5. Configurar estoque
async function syncCatalog() {
const client = new IntegrationClient(config);

const categoryOp = await client.createBatch('categories', categories);
await waitForWebhook(categoryOp);

const brandOp = await client.createBatch('brands', brands);
await waitForWebhook(brandOp);

const productOp = await client.createBatch('products', products);
await waitForWebhook(productOp);

const pricingOp = await client.createBatch('pricing', prices);
await waitForWebhook(pricingOp);

const stockOp = await client.createBatch('warehouses/sku', stock);
await waitForWebhook(stockOp);
}

2. Atualização de Status de Pedido

def update_order_status(order_number: int, new_status: str):
client = IntegrationClient(...)

response = requests.patch(
f"{client.base_url}/v1/orders/{order_number}/status",
json={"status": new_status},
headers=client._headers()
)
response.raise_for_status()
return response.json()["transactionId"]

Boas Práticas

  1. Tratamento de Erros

    • Implemente retry com backoff
    • Armazene operationIds para rastreamento
    • Monitore webhooks de erro
  2. Performance

    • Use lotes apropriados (máximo 1000 itens)
    • Processe webhooks assincronamente
    • Cache tokens de autenticação
  3. Monitoramento

    • Registre todas operações com operationId
    • Monitore taxa de sucesso vs erro
    • Alerte em falhas críticas
  4. Segurança

    • Proteja credenciais (ClientId/ClientSecret)
    • Valide webhooks recebidos
    • Use HTTPS sempre