SDK-API-Lojista-V2-Java /

Filename Size Date modified Message
src/main/java/com/cnova/api/v2
11.6 KB
4.0 KB

SDK Java para API V2 de Lojistas

Provê os componentes java para uso da API V2 de lojistas, disponibilizada pela CNova.

Vantagens na utilização de SDKs

Criando um API Client

Antes de utilizar as APIs, é necessário a criação de um client com as configurações de base path e também as credenciais para acesso.

Abaixo segue o código de exemplo:

ApiClient apiClient = new ApiClient();
apiClient.setBasePath("https://sandbox.cnova.com/api/v2");

// Alterar a chave informada com o valor de client_id disponível para sua APP
((ApiKeyAuth)apiClient.getAuthentication("client_id")).setApiKey("ll0rQx9SSshr");

// Alterar a chave informada com o valor de access_token disponível para sua APP
((ApiKeyAuth)apiClient.getAuthentication("access_token")).setApiKey("nllKgtXTMv0G");

Operações auxiliares

Tratamento de estruturas de erros recebidas nas chamadas à API:

private Errors deserializeErrors(String errorsJson, ApiClient apiClient) {

    Errors errors = null;
    try {

        errors = (Errors) apiClient.deserialize(errorsJson, "", Errors.class);

    } catch (ApiException e) {
        logger.log(Level.WARNING, "Doesn't containt errors structure.");
    }

    return errors;

}

Formatação de datas para consultas em períodos específicos:

private String formatDateRange(Date initialDate, Date finalDate, ApiClient apiClient) {

    String dtIni = "*";
    String dtEnd = "*";

    if (initialDate != null) {
        dtIni = apiClient.formatDate(initialDate);
    }

    if (finalDate != null) {
        dtEnd = apiClient.formatDate(finalDate);
    }

    return dtIni + "," + dtEnd;

}

APIs Disponíveis

A seguir, são apresentadas as APIs e exemplos com as as principais operações do Marketplace.

Loads API

API utilizada para operações de carga.

Carga de produtos:

LoadsApi loadsApi = new LoadsApi(apiClient);

// Criação de um novo produto
Product product = new Product();

product.setSkuSellerId("CEL_LGG4");
product.setProductSellerId("CEL");
product.setTitle("Produto de testes LG G4");
product.setDescription("<h2>O novo produto de testes</h2>, LG G4");
product.setBrand("LG");
product.getGtin().add("123456ft");
product.getCategories().add("Teste>API");
product.getImages().add("http://img.g.org/img1.jpeg");

ProductLoadPrices prices = new ProductLoadPrices();
prices.setDefault(1999D);
prices.setOffer(1799D);

product.setPrice(prices);

ProductLoadStock stock = new ProductLoadStock();
stock.setQuantity(100);
stock.setCrossDockingTime(0);

product.setStock(stock);

Dimensions dimensions = new Dimensions();
dimensions.setWeight(Double.valueOf(10d));
dimensions.setLength(Double.valueOf(10d));
dimensions.setWidth(Double.valueOf(10d));
dimensions.setHeight(Double.valueOf(10d));

product.setDimensions(dimensions);

ProductAttribute productAttribute = new ProductAttribute();
productAttribute.setName("cor");
productAttribute.setValue("Verde");

product.getAttributes().add(productAttribute);

// Adiciona o novo produto na lista a ser enviada
List<Product> products = new ArrayList<Product>();
products.add(product);

// Envia a carga de produtos
try {

    loadsApi.postProducts(products);

} catch (ApiException e) {

    Errors errors = deserializeErrors(e.getMessage(), apiClient);

    if (errors == null) {
        logger.log(Level.SEVERE, "Error calling LOADS resource.", e);
    } else {
        // TODO: Manage Errors structure.
        System.out.println(errors);
    }

}

Consulta de cargas enviadas:

LoadsApi loadsApi = new LoadsApi(apiClient);

try {

    GetProductsResponse getProductsResponse = loadsApi.getProducts(null, null, 0, 10);
    System.out.println(getProductsResponse);

} catch (ApiException e) {

    Errors errors = deserializeErrors(e.getMessage(), apiClient);

    if (errors == null) {
        logger.log(Level.SEVERE, "Error calling LOADS resource.", e);
    } else {
        // TODO: Manage Errors structure.
        System.out.println(errors);
    }

}

Consulta um produto específico da carga enviada:

LoadsApi loadsApi = new LoadsApi(apiClient);

try {

    GetProductWithErrorsResponse getProductWithErrorsResponse = loadsApi.getProduct("CEL_LGG4");
    System.out.println(getProductWithErrorsResponse);

} catch (ApiException e) {

    Errors errors = deserializeErrors(e.getMessage(), apiClient);

    if (errors == null) {
        logger.log(Level.SEVERE, "Error calling LOADS resource.", e);
    } else {
        // TODO: Manage Errors structure.
        System.out.println(errors);
    }

}

Modificação do tracking de uma ou mais ordens, utilizando a API Loads:

LoadsApi loadsApi = new LoadsApi(apiClient);

OrdersTrackings ordersTrackings = new OrdersTrackings();

OrderTracking orderTracking = new OrderTracking();

OrderId orderId = new OrderId();
orderId.setId(123);
orderTracking.setOrder(orderId);

orderTracking.setControlPoint("ABC");
orderTracking.setCte("123");

OrderItemReference oif = new OrderItemReference();
oif.setSkuSellerId("123456");
oif.setQuantity(1);

orderTracking.getItems().add(oif);

orderTracking.setOccurredAt(new Date());
orderTracking.setSellerDeliveryId("99995439701");
orderTracking.setNumber("01092014");
orderTracking.setUrl("servico envio2");

Carrier carrier = new Carrier();
carrier.setCnpj("72874279234");
carrier.setName("Sedex");

orderTracking.setCarrier(carrier);

Invoice invoice = new Invoice();
invoice.setCnpj("72874279234");
invoice.setNumber("123");
invoice.setSerie("456");
invoice.setIssuedAt(new Date());
invoice.setAccessKey("01091111111111111111111111111111111111101092");
invoice.setLinkXml("link xlm teste5");
invoice.setLinkDanfe("link nfe teste5");

orderTracking.setInvoice(invoice);

ordersTrackings.getTrackings().add(orderTracking);

try {

    loadsApi.postOrdersTrackingSent(ordersTrackings);

} catch (ApiException e1) {
    e1.printStackTrace();
}

Seller Items API

API utilizada para gerenciamento dos recursos enviados pelo lojista.

Consulta de seller items:

SellerItemsApi sellerItemsApi = new SellerItemsApi(apiClient);

try {
    GetSellerItemsResponse getSellerItemsResponse = sellerItemsApi.getSellerItems("EX", 0, 100);
    System.out.println(getSellerItemsResponse);
} catch (ApiException e) {
    e.printStackTrace();
}

Alteração de preço:

SellerItemsApi sellerItemsApi = new SellerItemsApi(apiClient);

try {

    Prices prices = new Prices();
    prices.setDefault(Double.valueOf(100D));
    prices.setOffer(Double.valueOf(100D));

    sellerItemsApi.putSellerItemPrices("31.0019", prices);

} catch (ApiException e) {
    e.printStackTrace();
}

Alteração de estoque:

SellerItemsApi sellerItemsApi = new SellerItemsApi(apiClient);

try {

    Stock stock = new Stock();
    stock.setQuantity(200);
    stock.setCrossDockingTime(0);

    sellerItemsApi.putSellerItemStock("31.0019", stock);

} catch (ApiException e) {
    e.printStackTrace();
}   

Orders API

API utilizada para gerenciamento de pedidos.

Consulta todas as ordens:

OrdersApi ordersApi = new OrdersApi(apiClient);

try {
    GetOrdersResponse getOrdersResponse =  ordersApi.getOrders(0, 100);
    System.out.println(getOrdersResponse);
} catch (ApiException e) {
    e.printStackTrace();
}

Consulta todas as ordens com status "novo":

// Recupera todas as ordens com status novo
OrdersApi ordersApi = new OrdersApi(apiClient);

try {

    String purchasedAt = formatDateRange(null, new Date(), apiClient);

    GetOrdersStatusNewResponse getOrdersStatusNewResponse =  ordersApi.getOrdersByStatusNew(purchasedAt, null, null, 0, 100);
    System.out.println(getOrdersStatusNewResponse);

} catch (ApiException e) {
    e.printStackTrace();
}

Criação de um novo tracking, notificando o envio da ordem:

OrdersApi ordersApi = new OrdersApi(apiClient);

NewTracking newTracking = new NewTracking();

newTracking.getItems().add("23258312-1");
newTracking.getItems().add("23258312-2");

newTracking.setOccurredAt(new Date());

newTracking.setSellerDeliveryId("99995439701");
newTracking.setNumber("01092014");
newTracking.setUrl("servico envio2");

Carrier carrier = new Carrier();
carrier.setCnpj("72874279234");
carrier.setName("Sedex");

newTracking.setCarrier(carrier);

Invoice invoice = new Invoice();
invoice.setCnpj("72874279234");
invoice.setNumber("123");
invoice.setSerie("456");
invoice.setIssuedAt(new Date());
invoice.setAccessKey("01091111111111111111111111111111111111101092");
invoice.setLinkXml("link xlm teste5");
invoice.setLinkDanfe("link nfe teste5");

newTracking.setInvoice(invoice);

try {
    ordersApi.postOrderTrackingSent(newTracking, "1024101");
} catch (ApiException e) {

    Errors errors = deserializeErrors(e.getMessage(), apiClient);

    if (errors == null) {
        logger.log(Level.SEVERE, "Error calling Orders resource.", e);
    } else {
        System.out.println(errors);
        // TODO: Use errors object
    }

}

Consulta de ordens com status "enviado":

OrdersApi ordersApi = new OrdersApi(apiClient);

try {

    GetOrdersResponse getOrdersResponse = ordersApi.getOrdersByStatusSent(null, null, null, 0, 100);
    System.out.println(getOrdersResponse);

} catch (ApiException e) {
    e.printStackTrace();
}

Tickets API

API utilizada para gerenciamento de tickets.

Criação de um novo ticket:

TicketsApi ticketsApi = new TicketsApi(apiClient);

NewTicket newTicket = new NewTicket();
newTicket.setTo("atendimento+OS_706000500000@mktp.extra.com.br");
newTicket.setBody("Corpo da mensagem do ticket");

try {
    ticketsApi.postTicket(newTicket);
} catch (ApiException e) {

    Errors errors = deserializeErrors(e.getMessage(), apiClient);

    if (errors == null) {
        logger.log(Level.SEVERE, "Error calling LOADS resource.", e);
    } else {
        // TODO: Manage Errors structure.
        System.out.println(errors);
    }

}

Consulta ticket com status "Aberto":

TicketsApi ticketsApi = new TicketsApi(apiClient);

try {

    Tickets tickets = ticketsApi.getTickets("opened", "439211092852", null, null, null, 0, 5);
    System.out.println(tickets);

} catch (ApiException e) {
    e.printStackTrace();
}

Alteração do status do ticket:

TicketsApi ticketsApi = new TicketsApi(apiClient);

try {

    TicketStatus ticketStatus = new TicketStatus();
    ticketStatus.setTicketStatus("Em Acompanhamento");

    ticketsApi.putTicketStatus("123123", ticketStatus);

} catch (ApiException e) {
    e.printStackTrace();
}

Categories API

API utilziada na obtenção da árvore de categorias disponível.

Consulta as categorias disponíveis:

CategoriesApi categoriesApi = new CategoriesApi(apiClient);

try {

    GetCategoriesResponse getCategoriesResponse = categoriesApi
            .getCategories(0, 5);

    for (Category category : getCategoriesResponse.getCategories()) {
        System.out.println(category.getId() + " - "
                + category.getName());
    }

} catch (ApiException e) {
    e.printStackTrace();
}

Sites API

API utilizada na obtenção da lista de sites.

Consulta os sites disponíveis:

SitesApi sitesApi = new SitesApi(apiClient);

try {

    GetSitesResponse getSitesResponse = sitesApi.getSites();
    System.out.println(getSitesResponse);

} catch (ApiException e) {
    e.printStackTrace();
}

Warehouses API

API utilizada na obtenção da lista de warehouses (armazéns).

Consulta as warehouses disponíveis:

WarehousesApi warehousesApi = new WarehousesApi(apiClient);

try {

    GetWarehousesResponse getWarehousesResponse = warehousesApi.getWarehouses();
    System.out.println(getWarehousesResponse);

} catch (ApiException e) {
    e.printStackTrace();
}