Pular para o conteúdo principal

Exemplos de Integração

Este guia fornece exemplos práticos de integração com o Grocers 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
  3. Webhook configurado para receber notificações

Node.js

Configuração Inicial

// config.js
const config = {
baseUrl: 'https://api.grocers.com',
auth: {
clientId: 'seu-client-id',
clientSecret: 'seu-client-secret'
},
webhook: {
url: 'https://sua-api.com/webhooks/grocers'
}
};

module.exports = config;

Cliente Base

// grocersClient.js
const axios = require('axios');

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

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;
}
}

module.exports = GrocersClient;

Exemplo: Cadastro de Produtos

// products.js
const GrocersClient = require('./grocersClient');
const config = require('./config');

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

const products = [
{
externalReference: 'prod-123',
name: 'Refrigerante Cola 2L',
description: 'Refrigerante de cola 2 litros',
brand: 'brand-123',
categories: ['cat-123']
},
{
externalReference: 'prod-124',
name: 'Biscoito Cream Cracker',
description: 'Biscoito cream cracker 400g',
brand: 'brand-124',
categories: ['cat-124']
}
];

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

// webhook.js
const express = require('express');
const app = express();

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

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

try {
// Processa a notificação de acordo com o tipo
switch(eventType) {
case 1: // Product_Created
await handleProductCreated(data);
break;
case 2: // Product_Updated
await handleProductUpdated(data);
break;
// ... outros casos
}

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

Python

Cliente Base

# grocers_client.py
import base64
import requests
from typing import List, Dict, Any

class GrocersClient:
def __init__(self, base_url: str, client_id: str, client_secret: str):
self.base_url = base_url
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 create_batch(self, endpoint: str, data: List[Dict[str, Any]]) -> str:
response = requests.post(
f"{self.base_url}/v1/batch/{endpoint}",
json=data,
headers={
"Authorization": f"Basic {self.auth_token}",
"Content-Type": "application/json"
}
)
response.raise_for_status()
return response.json()["operationId"]

Exemplo: Atualização de Preços

# pricing_example.py
from grocers_client import GrocersClient
from datetime import datetime, timedelta

def update_prices():
client = GrocersClient(
base_url="https://api.grocers.com",
client_id="seu-client-id",
client_secret="seu-client-secret"
)

# Define preços com vigência futura
tomorrow = datetime.now() + timedelta(days=1)
prices = [
{
"skuExternalReference": "sku-123",
"basePrice": 10.99,
"listPrice": 9.99,
"startDate": tomorrow.isoformat(),
"endDate": None
},
{
"skuExternalReference": "sku-124",
"basePrice": 15.99,
"listPrice": 13.99,
"startDate": tomorrow.isoformat(),
"endDate": 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

// GrocersClient.cs
public class GrocersClient
{
private readonly HttpClient _client;
private readonly string _baseUrl;

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

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

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

// StockExample.cs
public class StockExample
{
private readonly GrocersClient _client;

public StockExample(GrocersClient client)
{
_client = client;
}

public async Task UpdateStock()
{
var stockUpdates = new List<WarehouseSkuUpdate>
{
new()
{
WarehouseExternalReference = "wh-123",
SkuExternalReference = "sku-123",
Quantity = 100,
UpdateType = "Increment"
},
new()
{
WarehouseExternalReference = "wh-124",
SkuExternalReference = "sku-124",
Quantity = 50,
UpdateType = "Set"
}
};

try
{
var operationId = await _client.CreateBatchAsync(
"warehouse-skus",
stockUpdates
);

Console.WriteLine($"Estoque atualizado. OperationId: {operationId}");
return operationId;
}
catch (Exception ex)
{
Console.WriteLine($"Erro ao atualizar estoque: {ex.Message}");
throw;
}
}
}

Casos de Uso Comuns

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

// 1. Criar categorias
const categoryOp = await client.createBatch('categories', categories);
await waitForOperation(categoryOp);

// 2. Criar marcas
const brandOp = await client.createBatch('brands', brands);
await waitForOperation(brandOp);

// 3. Criar produtos
const productOp = await client.createBatch('products', products);
await waitForOperation(productOp);

// 4. Atualizar preços
const pricingOp = await client.createBatch('pricing', prices);
await waitForOperation(pricingOp);

// 5. Configurar estoque
const stockOp = await client.createBatch('warehouse-skus', stock);
await waitForOperation(stockOp);
}

2. Atualização de Pedidos

# order_tracking.py
def update_order_status(order_id: str, new_status: int):
client = GrocersClient(...)

update = {
"orderId": order_id,
"status": new_status,
"updateDate": datetime.now().isoformat()
}

operation_id = client.create_batch("orders", [update])
return operation_id

Boas Práticas

  1. Tratamento de Erros

    • Implemente retry com backoff
    • Armazene operationIds
    • Monitore webhooks
  2. Performance

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

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

    • Proteja credenciais
    • Valide webhooks
    • Use HTTPS sempre