### Compra de Fretes API Request Example Source: https://docs.melhorenvio.com.br/reference/compra-de-fretes-1 This example demonstrates the structure of a request to purchase shipping. Ensure all required headers, including Authorization and User-Agent, are correctly set. ```json { "openapi": "3.1.0", "info": { "title": "api-melhor-envio-sandbox", "version": "1.0" }, "servers": [ { "url": "https://sandbox.melhorenvio.com.br/" } ], "security": [ {} ], "paths": { "/api/v2/me/shipment/checkout": { "post": { "summary": "Compra de fretes", "description": "Pagamento de envios (Checkout)", "operationId": "compra-de-fretes-1", "parameters": [ { "name": "Accept", "in": "header", "required": true, "schema": { "type": "string", "default": "application/json" } }, { "name": "Content-Type", "in": "header", "required": true, "schema": { "type": "string", "default": "application/json" } }, { "name": "Authorization", "in": "header", "required": true, "schema": { "type": "string", "default": "Bearer token" } }, { "name": "User-Agent", "in": "header", "description": "É obrigatório que seja adicionado o cabeçalho HTTP User-Agent com o nome da sua aplicação junto a um email de contato/suporte.", "required": true, "schema": { "type": "string", "default": "Aplicação (email para contato técnico" } } ], "requestBody": { "content": { "application/json": { "schema": { "type": "object", "required": [ "orders" ], "properties": { "orders": { "type": "array", "description": "Pedidos", "items": { "type": "string" } } } }, "examples": { "Request Example": { "value": { "orders": [ "{{id}}" ] } } } } } }, "responses": { "200": { "description": "200", "content": { "application/json": { "examples": { "Result": { "value": { "order_id": "{{id}}", "shipping_order_id": "{{id}}", "status": "generated", "tracking_code": "{{tracking_code}}", "payment_url": "{{payment_url}}", "agency": "{{agency}}", "created_at": "{{date}}", "updated_at": "{{date}}", "total_price": "{{price}}", "postage_price": "{{price}}", "custom_price": "{{price}}", "insurance_price": "{{price}}", "label_price": "{{price}}", "collection_price": "{{price}}", "options": { "insurance": "{{price}}", "receipt": true, "own_hand": true, "platform": "{{platform}}", "tags": [ "{{tag}}" ] }, "volumes": [ { "service_code": "{{service_code}}", "code": "{{code}}", "amount": 1, "description": "{{description}}", "weight": 0.5, "volume": { "width": 10, "height": 10, "length": 10 } } ], "buyer": { "name": "{{name}}", "document": "{{document}}", "email": "{{email}}", "phone": "{{phone}}", "country": "{{country}}", "state": "{{state}}", "city": "{{city}}", "street": "{{street}}", "number": "{{number}}", "complement": "{{complement}}", "district": "{{district}}", "postal_code": "{{postal_code}}", "notes": "{{notes}}" }, "recipient": { "name": "{{name}}", "document": "{{document}}", "email": "{{email}}", "phone": "{{phone}}", "country": "{{country}}", "state": "{{state}}", "city": "{{city}}", "street": "{{street}}", "number": "{{number}}", "complement": "{{complement}}", "district": "{{district}}", "postal_code": "{{postal_code}}", "notes": "{{notes}}" }, "sender": { "name": "{{name}}", "document": "{{document}}", "email": "{{email}}", "phone": "{{phone}}", "country": "{{country}}", "state": "{{state}}", "city": "{{city}}", "street": "{{street}}", "number": "{{number}}", "complement": "{{complement}}", "district": "{{district}}", "postal_code": "{{postal_code}}", "notes": "{{notes}}" } } } } } } } } } } } } ``` -------------------------------- ### Example Response for SEDEX with Insurance Source: https://docs.melhorenvio.com.br/discuss/67ae194c9c0e48006fc7cddb This is an example response for a SEDEX quote, showing how insurance values might be reflected. Note that the provided snippet is incomplete. ```json { "id": 2, "name": "SEDEX", "price": "30.70", "custom_price": "30.70", ``` -------------------------------- ### Product Schema Example Source: https://docs.melhorenvio.com.br/reference/calculo-de-fretes-por-produtos Defines the structure for product information, including ID, quantity, and other relevant properties. ```json { "id": "pequeno", "quantity": 1 } ``` -------------------------------- ### OpenAPI Definition - 200 OK Example Source: https://docs.melhorenvio.com.br/reference/inserir-saldo-na-carteira-do-usuario This example shows a successful response (200 OK) for an API operation, including details about the order and shipping information. ```json { "object": { "id": 12345, "order_number": "ABC123456789", "order_id": "12345", "created_at": "2021-06-22 12:17:00", "updated_at": "2021-06-22 12:17:38" }, "redirect": "https://sandbox.melhorenvio.com.br/checkout/notify/2", "message": "", "digitable": {} } ``` -------------------------------- ### Freight Calculation Request - Product Example Source: https://docs.melhorenvio.com.br/reference/calculo-de-fretes-por-produtos An example request body for calculating freight costs based on multiple products. It includes origin and destination postal codes, and a list of products with their respective attributes. ```json { "from": { "postal_code": "96020360" }, "to": { "postal_code": "01018020" }, "products": [ { "id": "x", "width": 11, "height": 17, "length": 11, "weight": 0.3, "insurance_value": 10.1, "quantity": 1 }, { "id": "y", "width": 16, "height": 25, "length": 11, "weight": 0.3, "insurance_value": 55.05, "quantity": 2 }, { "id": "z", "width": 22, "height": 30, "length": 11, "weight": 1, "insurance_value": 30, "quantity": 1 } ] } ``` -------------------------------- ### Curl Request Example Source: https://docs.melhorenvio.com.br/discuss/66855006aa47fd0018911d32 This example demonstrates how to make a POST request to the Melhor Envio API's cart endpoint using curl. It includes headers for authentication and content type, and a JSON payload with shipping details and volume information. ```bash curl --location 'https://sandbox.melhorenvio.com.br/api/v2/me/cart' \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer ...' \ --data-raw '{ "service": 2, "from": { "name": "Fulano de Tal", "phone": "", "email": "", "document": "", "company_document": "", "state_register": "", "address": "Rua Teste", "complement": "SL 1405", "number": "123", "district": "", "city": "São Paulo", "state_abbr": "SP", "country_id": "BR", "postal_code": "", "note": "Pedido: 996003" }, "to": { "name": "Usuário de Teste", "phone": "", "email": "teste@teste.com.br", "document": "", "company_document": "", "state_register": "", "address": "", "complement": "", "number": "150", "district": "", "city": "São Paulo", "state_abbr": "SP", "country_id": "BR", "postal_code": "", "note": "Pedido: 996003" }, "products": [ { "id": "29379", "name": "Teste dimensoes | Cor: Laranja - Tamanho: P", "quantity": "1", "unitary_value": "10.00" } ], "volumes": [ { "width": 11, "height": 2, "length": 18, "weight": 0.01 } ], "options": { "insurance_value": 10.0, "receipt": false, "own_hand": false, "reverse": false, "non_commercial": true, "invoice": { "key": "" } } }' ``` -------------------------------- ### Additional Services Schema Example Source: https://docs.melhorenvio.com.br/reference/calculo-de-fretes-por-produtos Illustrates the schema for configuring additional shipping services such as receipt, own-hand delivery, and collection. ```json { "receipt": true, "own_hand": true, "collect": false } ``` -------------------------------- ### Listar informações de aplicativo (JSON) Source: https://docs.melhorenvio.com.br/reference/listar-informacoes-de-aplicativo Retorna as configurações cadastradas pelo usuário no aplicativo. Inclui detalhes como transportadoras, taxas, dimensões e outras configurações de envio. É necessário incluir os cabeçalhos 'Accept', 'Authorization' e 'User-Agent'. ```json { "settings": { "weight": 0.x, "collect": true, "receipt": false, "own_hand": true, "services": [ 1, 2, 3, 4, 17 ], "addresses": [], "dimensions": { "width": x, "height": x, "length": x }, "jadlog_agency": 9xx, "insurance_value": "all", "jadlog_agencies": null, "delivery_time_extra": 1x, "shipment_modify_type": "add-fixed", "shipment_modify_value": "10.00", "state_register_default": "1xxxxxxxxxxx", "insurance_value_default": "9.xx", "company_document_default": "1xxxxxxxxxxxxx" } } ``` -------------------------------- ### Webhook Request Header Example Source: https://docs.melhorenvio.com.br/docs/webhooks This is an example of the JSON structure for the header of a webhook request. Ensure your server is configured to accept these headers. ```json { "user-agent": "Melhor Envio Webhooks/1.0", "accept": "application/json, text/plain, */*", "accept-encoding": "gzip, compress, deflate, br", "x-me-signature": "eW/6UEmwJ7vH13kMsrhjMVzek3Yg0Oa5TDsUSeLVFoM=", "content-type": "application/json" } ``` -------------------------------- ### Listar informações de aplicativo Source: https://docs.melhorenvio.com.br/reference/listar-informacoes-de-aplicativo Recupere as configurações do seu aplicativo, como transportadoras, taxas e dimensões. ```APIDOC ## GET /api/v2/me/shipment/app-settings ### Description Esta rota retorna as configurações cadastradas pelo usuário no seu aplicativo. Dentre as informações retornadas estão configurações como transportadoras, taxas, dimensões, entre outras. ### Method GET ### Endpoint /api/v2/me/shipment/app-settings ### Parameters #### Header Parameters - **Accept** (string) - Required - Default: application/json - **Authorization** (string) - Required - Default: Bearer token - **User-Agent** (string) - Required - É obritatório que seja adicionado o cabeçalho HTTP User-Agent com o nome da sua aplicação junto a um email de contato/suporte. ### Response #### Success Response (200) - **settings** (object) - Contém as configurações do aplicativo. - **weight** (number) - **collect** (boolean) - **receipt** (boolean) - **own_hand** (boolean) - **services** (array of numbers) - **addresses** (array) - **dimensions** (object) - **width** (number) - **height** (number) - **length** (number) - **jadlog_agency** (number) - **insurance_value** (string) - **jadlog_agencies** (null) - **delivery_time_extra** (number) - **shipment_modify_type** (string) - **shipment_modify_value** (string) - **state_register_default** (string) - **insurance_value_default** (string) - **company_document_default** (string) #### Response Example (200) ```json { "settings": { "weight": 0.x, "collect": true, "receipt": false, "own_hand": true, "services": [ 1, 2, 3, 4, 17 ], "addresses": [], "dimensions": { "width": x, "height": x, "length": x }, "jadlog_agency": 9xx, "insurance_value": "all", "jadlog_agencies": null, "delivery_time_extra": 1x, "shipment_modify_type": "add-fixed", "shipment_modify_value": "10.00", "state_register_default": "1xxxxxxxxxxx", "insurance_value_default": "9.xx", "company_document_default": "1xxxxxxxxxxxxx" } } ``` #### Error Response (404) - **error** (boolean) - Indica se ocorreu um erro. - **message** (string) - Mensagem de erro. #### Response Example (404) ```json { "error": true, "message": "Não há configurações salvas" } ``` ``` -------------------------------- ### Validation Error Example (422) Source: https://docs.melhorenvio.com.br/reference/calculo-de-fretes-por-produtos Provides an example of a 422 Unprocessable Entity response, detailing validation errors for required fields like postal codes. ```json { "message": "The given data was invalid.", "errors": { "from.postal_code": [ "O campo from.postal code é obrigatório." ], "to.postal_code": [ "O campo to.postal code é obrigatório." ] } } ``` -------------------------------- ### Exemplo de Requisição JSON para Cotação por Produto Source: https://docs.melhorenvio.com.br/reference/calculo-de-fretes-por-produtos Utilize este formato para enviar informações unitárias de produtos para cotação de frete. Certifique-se de que as dimensões estejam em cm, peso em kg e o valor segurado em BRL com duas casas decimais. ```json { "from": { "postal_code": "96020360" }, "to": { "postal_code": "01018020" }, "products": [ { "id": "Produto A", "width": 11, //cm "height": 17, //cm "length": 11, //cm "weight": 1, //kg "insurance_value": 10.1, //BRL "quantity": 1 //unidade de produto }, { "id": "Produto B", "width": 10, "height": 10, "length": 12, "weight": 0.2, "insurance_value": 10.1, "quantity": 5 } ], "options": { "receipt": false, "own_hand": false }, "services": "1,2,18" } ``` -------------------------------- ### Exemplo de URL de Autorização Sandbox Simplificada Source: https://docs.melhorenvio.com.br/discuss/675c1f63c0286a00743be1c9 Uma versão simplificada da URL de autorização para o ambiente de sandbox, focando em um escopo menor. Substitua 'x' pelos seus valores. ```URL https://sandbox.melhorenvio.com.br/oauth/authorize?client_id=x&redirect_uri=x&response_type=code&scope=cart-read ``` -------------------------------- ### Example of a 422 Unprocessable Entity Response Source: https://docs.melhorenvio.com.br/reference/compra-de-fretes-1 This example shows the structure of a 422 error response, indicating invalid data was provided. It details the general message and specific errors related to orders. ```json { "message": "The given data was invalid.", "errors": { "orders": [ "Existe uma ou mais orders que já foram pagas." ] } } ``` -------------------------------- ### Freight Calculation Request - Package Example Source: https://docs.melhorenvio.com.br/reference/calculo-de-fretes-por-produtos An example request body for calculating freight costs based on a single package. It includes origin and destination postal codes, and package dimensions and weight. ```json { "from": { "postal_code": "01002001" }, "to": { "postal_code": "90570020" }, "package": { "height": 4, "width": 12, "length": 17, "weight": 0.3 } } ``` -------------------------------- ### Exemplo de URL de Autorização com Parâmetros Source: https://docs.melhorenvio.com.br/discuss/675c1f63c0286a00743be1c9 Modelo genérico para a URL de autorização, onde {{url}}, {{client_id}}, e {{callback}} devem ser substituídos pelos seus dados específicos do ambiente (sandbox ou produção). ```URL {{url}}/oauth/authorize?client_id={{client_id}}&redirect_uri={{callback}}&response_type=code&scope=cart-read cart-write companies-read companies-write coupons-read coupons-write notifications-read orders-read products-read products-write purchases-read shipping-calculate shipping-cancel shipping-checkout shipping-companies shipping-generate shipping-preview shipping-print shipping-share shipping-tracking ecommerce-shipping transactions-read users-read users-write ``` -------------------------------- ### Pré-visualização de Etiquetas Source: https://docs.melhorenvio.com.br/reference/pre-visualizacao-de-etiquetas Este endpoint permite pré-visualizar etiquetas de envio. É necessário ter comprado as etiquetas previamente. O rastreio e a autorização de postagem não estarão disponíveis neste momento. ```APIDOC ## POST /api/v2/me/shipment/preview ### Description Permite pré-visualizar etiquetas de envio antes de gerá-las. ### Method POST ### Endpoint /api/v2/me/shipment/preview ### Parameters #### Header Parameters - **Accept** (string) - Required - Default: application/json - **Content-Type** (string) - Required - Default: application/json - **Authorization** (string) - Required - Default: Bearer token - **User-Agent** (string) - Required - É obrigatório que seja adicionado o cabeçalho HTTP User-Agent com o nome da sua aplicação junto a um email de contato/suporte. Default: Aplicação (email para contato técnico) #### Request Body - **orders** (array) - Required - Lista de IDs das etiquetas a serem pré-visualizadas. - items: (string) ### Request Example ```json { "orders": [ "{{id}}" ] } ``` ### Response #### Success Response (200) - **url** (string) - URL para pré-visualização da etiqueta. #### Response Example ```json { "url": "https://sandbox.melhorenvio.com.br/pre-impressao/Xvi2N2ImijM6" } ``` #### Error Response (404) - **error** (string) - Mensagem de erro. #### Response Example ```json { "error": "Não é possível imprimir etiquetas com o pagamento ainda não processado. Favor aguarde." } ``` ``` -------------------------------- ### Exemplo de Requisição OpenAPI para Pré-visualização de Etiquetas Source: https://docs.melhorenvio.com.br/reference/pre-visualizacao-de-etiquetas Este é um exemplo de como a definição OpenAPI descreve a requisição POST para pré-visualizar etiquetas. Ele especifica os cabeçalhos necessários e o formato do corpo da requisição, que inclui um array de IDs de pedidos. ```json { "openapi": "3.1.0", "info": { "title": "api-melhor-envio-sandbox", "version": "1.0" }, "servers": [ { "url": "https://sandbox.melhorenvio.com.br/" } ], "security": [ {} ], "paths": { "/api/v2/me/shipment/preview": { "post": { "summary": "Pré-visualização de etiquetas", "description": "Etiquetas", "operationId": "pre-visualizacao-de-etiquetas", "parameters": [ { "name": "Accept", "in": "header", "required": true, "schema": { "type": "string", "default": "application/json" } }, { "name": "Content-Type", "in": "header", "required": true, "schema": { "type": "string", "default": "application/json" } }, { "name": "Authorization", "in": "header", "required": true, "schema": { "type": "string", "default": "Bearer token" } }, { "name": "User-Agent", "in": "header", "description": "É obrigatório que seja adicionado o cabeçalho HTTP User-Agent com o nome da sua aplicação junto a um email de contato/suporte.", "required": true, "schema": { "type": "string", "default": "Aplicação (email para contato técnico)" } } ], "requestBody": { "content": { "application/json": { "schema": { "type": "object", "required": [ "orders" ], "properties": { "orders": { "type": "array", "description": "Pedidos", "items": { "type": "string" } } } }, "examples": { "Pré visualização de etiquetas": { "value": { "orders": [ "{{id}}" ] } } } } } }, "responses": { "200": { "description": "200", "content": { "application/json": { "examples": { "Result": { "value": "{\n \"url\": \"https://sandbox.melhorenvio.com.br/pre-impressao/Xvi2N2ImijM6\"\n}" } }, "schema": { "type": "object", "properties": { "url": { "type": "string", "example": "https://sandbox.melhorenvio.com.br/pre-impressao/Xvi2N2ImijM6" } } } } } }, "404": { "description": "404", "content": { "application/json": { "examples": { "Result": { "value": "{\n \"error\": \"Não é possível imprimir etiquetas com o pagamento ainda não processado. Favor aguarde.\"\n}" } }, "schema": { "type": "object", "properties": { "error": { "type": "string", "example": "Não é possível imprimir etiquetas com o pagamento ainda não processado. Favor aguarde." } } } } } } }, "deprecated": false } } }, "x-readme": { "headers": [], "explorer-enabled": true, "proxy-enabled": true }, "x-readme-fauxas": true } ``` -------------------------------- ### Listar Informações de uma Etiqueta (OpenAPI) Source: https://docs.melhorenvio.com.br/reference/listar-informacoes-de-uma-etiqueta Definição OpenAPI para a operação GET /api/v2/me/orders/{id}. Detalha os parâmetros de requisição, incluindo o ID da ordem e cabeçalhos obrigatórios como User-Agent e Authorization. Apresenta um exemplo da estrutura JSON da resposta para um status 'posted'. ```json { "openapi": "3.1.0", "info": { "title": "api-melhor-envio-sandbox", "version": "1.0" }, "servers": [ { "url": "https://sandbox.melhorenvio.com.br/" } ], "security": [ {} ], "paths": { "/api/v2/me/orders/{id}": { "get": { "summary": "Listar informações de uma etiqueta", "description": "", "operationId": "listar-informacoes-de-uma-etiqueta", "parameters": [ { "name": "id", "in": "path", "description": "Id da order correspondente à etiqueta de envio", "schema": { "type": "string" }, "required": true }, { "name": "Accept", "in": "header", "required": true, "schema": { "type": "string", "default": "application/json" } }, { "name": "Authorization", "in": "header", "required": true, "schema": { "type": "string", "default": "Bearer token" } }, { "name": "User-Agent", "in": "header', "description": "É obrigatório que seja adicionado o cabeçalho HTTP User-Agent com o nome da sua aplicação junto a um email de contato/suporte.", "required": true, "schema": { "type": "string", "default": "Aplicação (email para contato técnico)" } } ], "responses": { "200": { "description": "200", "content": { "application/json": { "examples": { "Result": { "value": "{\n \"id\": \"34105e98-bb32-4e85-8b0f-8bd2c888eb31\",\n \"protocol\": \"ORD-20220395517\",\n \"service_id\": 1,\n \"agency_id\": null,\n \"contract\": \"9912415671\",\n \"service_code\": null,\n \"quote\": 31.13,\n \"price\": 31.13,\n \"coupon\": null,\n \"discount\": 4.15,\n \"delivery_min\": 8,\n \"delivery_max\": 9,\n \"status\": \"posted\",\n \"reminder\": null,\n \"insurance_value\": 50,\n \"weight\": null,\n \"width\": null,\n \"height\": null,\n \"length\": null,\n \"diameter\": null,\n \"format\": \"box\",\n \"billed_weight\": 3.5,\n \"receipt\": false,\n \"own_hand\": false,\n \"collect\": false,\n \"collect_scheduled_at\": null,\n \"reverse\": false,\n \"non_commercial\": false,\n \"authorization_code\": \"2022032920\",\n \"tracking\": \"ME220021P96BR\",\n \"self_tracking\": \"ME220021P96BR\",\n \"delivery_receipt\": null,\n \"additional_info\": null,\n \"cte_key\": null,\n \"paid_at\": \"2022-03-29 20:43:37\",\n \"generated_at\": \"2022-03-29 20:43:50\",\n \"posted_at\": \"2022-03-29 21:00:06\",\n \"delivered_at\": null,\n \"canceled_at\": null,\n \"suspended_at\": null,\n \"expired_at\": null,\n \"created_at\": \"2022-03-29 20:24:51\",\n \"updated_at\": \"2022-03-29 21:00:06\",\n \"parse_pi_at\": null,\n \"from\": {\n \"name\": \"Teste ME\",\n \"phone\": \"5598105050\",\n \"email\": \"melhorenvio@teste.com\",\n \"document\": \"16571478358\",\n \"company_document\": \"04517623000197\",\n \"state_register\": \"563025255115\",\n \"postal_code\": \"7110000\",\n \"address\": \"Rua Teste\",\n \"location_number\": \"100\",\n \"complement\": \"CASA\",\n \"district\": \"Bairro Teste\",\n \"city\": \"Guarulhos\",\n \"state_abbr\": \"SP\",\n \"country_id\": \"BR\",\n \"latitude\": null,\n \"longitude\": null,\n \"note\": \"observação\"\n },\n \"to\": {\n \"name\": \"Melhor Envio Teste\",\n \"phone\": \"1999999999\",\n \"email\": \"melhorenvio@teste.com\",\n \"document\": \"73646548010\",\n \"company_document\": \"89794131000100\",\n \"state_register\": \"123456\",\n \"postal_code\": \"26210000\",\n \"address\": \"Avenida Marechal Floriano Peixoto\",\n \"location_number\": \"123\",\n \"complement\": \"Ap 2\",\n \"district\": \"Centro\",\n \"city\": \"Nova Iguacu\",\n \"state_abbr\": \"RJ\",\n \"country_id\": \"BR\",\n \"latitude\": null,\n \"longitude\": null,\n \"note\": \"observação\"\n },\n \"service\": {\n \"id\": 1,\n \"name\": \"PAC\",\n \"status\": \"available\",\n \"type\": \"normal\",\n \"range\": \"interstate\",\n \"restrictions\": \"{\\\"insurance_value\\\":{\\\"min\\\":0,\\\"max\\\":3000},\\\"formats\\\":{\\\"box\\\":{\\\"weight\\\":{\\\"min\\\":0.001,\\\"max\\\":30},\\\"width\\\":{\\\"min\\\":11,\\\"max\\\":105},\\\"height\\\":{\\\"min\\\":2,\\\"max\\\":105},\\\"length\\\":{\\\"min\\\":16,\\\"max\\\":105},\\\"sum\\\":200},\\\"roll\\\":{\\\"weight\\\":{\\\"min\\\":0.001,\\\"max\\\":30},\\\"diameter\\\":{\\\"min\\\":5,\\\"max\\\":91},\\\"length\\\":{\\\"min\\\":18,\\\"max\\\":105},\\\"sum\\\":200},\\\"letter\\\":{\\\"weight\\\":{\\\"min\\\" } } } } } } } } } } ``` -------------------------------- ### OpenAPI Schema for Created/Updated At Source: https://docs.melhorenvio.com.br/reference/inserir-logistica-reversa-no-carrinho This snippet shows the schema definition for 'created_at' and 'updated_at' fields, specifying them as strings with an example format. ```json { "created_at": { "type": "string", "example": "2022-03-29 12:50:19" }, "updated_at": { "type": "string", "example": "2022-03-29 12:50:19" } } ```