Developer notes
Technical reference for developers who customize Melhor Envio Shipping & Labels.
Add-on identity
Section titled “Add-on identity”| Item | Value |
|---|---|
| Add-on id | kv_melhor_envio |
| Function prefix | fn_kv_melhor_envio_ |
| Language variables | kv_melhor_envio.* |
| CSS scope | .kv-melhor-envio |
| PHP namespace | Tygh\Addons\KvMelhorEnvio |
| Shipping service module | kv_melhor_envio (class Tygh\Shippings\Services\KvMelhorEnvio); service code = Melhor Envio service id |
Structure
Section titled “Structure”| Class | Role |
|---|---|
Client\BaseClient |
HTTP (cURL, TLS verification, timeouts), JSON, OAuth2 authorization code with a rotating refresh token renewed under a lock, error mapping, masked logging |
Client\Api |
The Melhor Envio calls (one method per reference page, see the table below) |
Client |
Client per company, the connection test |
Accounts, Secret |
Application credentials per mode and the OAuth tokens, sealed with AES-256-GCM; one account per store owner or per vendor |
RateCalculator |
Checkout quote: package set to one request, memory + time cache, short timeout, negative cache, BRL conversion, price rules |
Labels |
The label flow (cart, pay, generate, print, cancel) under a per-order lock, with reconcile after an unclear answer |
Shipments |
Label rows, status mapping, tracking, webhook events, side effects claimed once (order status, core shipment) |
Doc |
CPF, CNPJ (also the alphanumeric one), NF-e key, CEP and UF checks |
Config, Access |
Settings, owner mode, who may see and manage what (Access::moneyDenied(): vendor in owner mode) |
Queue, Jobs, JobException, Idempotency |
Job queue, back-off 5 min / 15 min / 1 h / 3 h / 12 h, locks and atomic claims |
Log |
Event log with masking of secrets and personal data, filters, CSV, retention |
Webhook |
Signature check; the controller kv_melhor_envio.webhook?c=<account> stores the event as a job |
Database tables
Section titled “Database tables”| Table | Purpose |
|---|---|
?:kv_melhor_envio_accounts |
Application credentials per company and mode (secrets sealed), sealed OAuth tokens and the one-time authorization state, sender data (non-secret), last connection check |
?:kv_melhor_envio_shipments |
One row per Melhor Envio label: id, protocol, service, price, status, tracking, print link; written BEFORE the cart request (status I) |
?:kv_melhor_envio_log |
Log |
?:kv_melhor_envio_jobs |
Queue |
Hooks used
Section titled “Hooks used”| Hook | Use |
|---|---|
change_order_status_post (PHP) |
Puts the label in the Melhor Envio cart at the status of the setting (never pays; skipped for a vendor in owner mode) |
init_templater_post (PHP) |
Upgrade synchronizer (only while an upgrade is pending) |
orders:tabs_extra (admin template) |
The label and tracking tab of the order page |
addons:manage, addons:tabs_content (admin template) |
License badge and card |
Shipping service kv_melhor_envio |
Realtime rates (getSimpleRates) |
Melhor Envio API conformance
Section titled “Melhor Envio API conformance”Source: the official reference at docs.melhorenvio.com.br, read on 2026-11-25; hosts and OAuth parameters cross-checked in the official PHP SDK (melhorenvio/auth-sdk-php, src/OAuth2.php: sandbox https://sandbox.melhorenvio.com.br, production https://melhorenvio.com.br, /oauth/authorize, /oauth/token). Every API request sends Accept: application/json, Content-Type: application/json, Authorization: Bearer <token> and the User-Agent header (application name and the contact e-mail the merchant enters). Mocks and test fixtures are pasted from the examples of these pages (tests/fixtures/SOURCES.md).
| Step | Endpoint | Page (https://docs.melhorenvio.com.br…) | Fields used |
|---|---|---|---|
| Authorize | GET /oauth/authorize (browser) |
/reference/fluxo-de-autorização |
client_id, redirect_uri (static, exact match), response_type=code, state, scope (space separated) |
| Token | POST /oauth/token JSON |
/reference/solicitacao-do-token |
grant_type (authorization_code or refresh_token), client_id (integer), client_secret, redirect_uri, code, refresh_token; answer expires_in, access_token, refresh_token (a new one every time) |
| Quote | POST /api/v2/me/shipment/calculate |
/reference/calculo-de-fretes-por-produtos |
from.postal_code, to.postal_code, products[] (id, width, height, length integer cm, weight kg, insurance_value, quantity), options.receipt, options.own_hand; answer: id, name, price, custom_price, custom_delivery_time, custom_delivery_range, company, error; the custom fields win |
| Services | GET /api/v2/me/shipment/services |
/reference/listar-servicos |
id, name, company{id,name}; services are matched by id (the page warns against names) |
| Cart | POST /api/v2/me/cart |
/reference/inserir-fretes-no-carrinho |
service, from, to (name, document or company_document, state_register, address, complement, number, district, city, country_id, postal_code, state_abbr), products[] (name, quantity, unitary_value strings), volumes[], options (insurance_value, receipt, own_hand, reverse, non_commercial, platform, tags[], invoice.key) |
| Remove from cart | DELETE /api/v2/me/cart/{id} |
/reference/remocao-de-itens-do-carrinho |
204 without a body; 400 message when the id is not in the cart. Used for a label that is still unpaid (cart items are not shipments: cancellable / cancel do not apply) |
| Pay | POST /api/v2/me/shipment/checkout |
/reference/compra-de-fretes-1 |
orders[]; answer purchase.orders[].status |
| Generate | POST /api/v2/me/shipment/generate |
/reference/geracao-de-etiquetas |
orders[]; answer {id: {status, message}} |
POST /api/v2/me/shipment/print |
/reference/impressao-de-etiquetas |
orders[], mode (private default, public); answer url |
|
| Can cancel | POST /api/v2/me/shipment/cancellable |
/reference/verificar-se-etiqueta-pode-ser-cancelada |
orders[]; answer {id: {cancellable, time}} |
| Cancel | POST /api/v2/me/shipment/cancel |
/reference/cancelamento-de-etiquetas |
order.id, order.reason_id = "2", order.description |
| Tracking | POST /api/v2/me/shipment/tracking |
/reference/rastreio-de-envios |
orders[] (20 per request); answer status, tracking, melhorenvio_tracking, *_at |
| One label | GET /api/v2/me/orders/{id} |
/reference/listar-informacoes-de-uma-etiqueta |
the real state before any payment is repeated |
| Label list | GET /api/v2/me/orders?status=pending&page= |
/reference/listar-etiquetas |
every page (last_page); finds a cart item whose creation answer was lost, matched by the order tag, the service and the destination CEP |
| Webhook | POST to our URL |
/docs/webhooks |
event, data{id, status, tracking, ..._at}, header x-me-signature (HMAC-SHA256 of the raw body keyed with the application secret; base64 and hex accepted) |
Scopes requested (names from /reference/fluxo-de-autorização, only what the calls need): shipping-calculate cart-write shipping-checkout shipping-generate shipping-print shipping-cancel shipping-tracking shipping-companies orders-read.
Rules from the documentation and how they are handled
Section titled “Rules from the documentation and how they are handled”| Rule | Handling |
|---|---|
| Sizes in whole centimetres, weight in kg, values in reais | sizes rounded up to integers, weight from the store weight unit (weight_symbol_grams), values converted to BRL with the store’s BRL rate; no BRL currency = nothing is quoted |
Individuals send document (CPF), companies company_document (CNPJ) |
chosen by the length (11 or 14), check digits verified before the call; the alphanumeric CNPJ (IN RFB 2.229/2024) and the NF-e key are supported |
Content declaration: non_commercial true, from.state_register empty |
the default; commercial shipments need the sender CNPJ, state registration and a valid 44 character invoice key, else nothing is sent |
| Correios, J&T and Loggi take one volume | one volume per label; more packages = more labels |
| Access token 30 days, refresh token 45 days, rotating | renewed under a lock one time after a 401 (Unauthenticated); renewed daily when idle 15 days; a rejected renewal marks the connection “authorization rejected” and pauses it |
| Webhook: 6 s, retried 5 times 15 minutes apart | the controller stores the event and answers at once; handled by the queue, idempotent by the body hash |
| Generated labels print for 20 days | a fresh print link is requested on demand |
| Tracking link | the link https://www.melhorrastreio.com.br/rastreio/<code> is the tracking_url of the webhook example on /docs/webhooks; the tracking_url of a webhook payload is used when it is present |
User-Agent with application name and e-mail |
KavioLabs-MelhorEnvio-CS-Cart/1.0 (<contact e-mail of the merchant>); without the e-mail no request is sent |
Money safety
Section titled “Money safety”Labels::createandLabels::advancerun under the database locklabel:<order>and re-read the row inside the lock; a double click pays once.- The row is written (status
I) before the cart request. After a timeout or a 5xx the cart list is searched (all pages) for the order tag; if the lookup also fails the row stays “creating (unclear)” and nothing more is sent until an administrator removes it. - Before a payment the label is read back (
GET /me/orders/{id}); a payment or generate request whose answer was lost is followed by a read of the real state, and the flow continues from what Melhor Envio says. - Vendors in marketplace owner mode are denied on create, pay, cancel and remove (server side) and the status automation does not run for them.
- A late status answer never takes a delivered or cancelled label back; order status changes and the core shipment are claimed once with a conditional update.
Flagged: not verifiable from the documentation
Section titled “Flagged: not verifiable from the documentation”| Item | Situation |
|---|---|
| Rate limits | no number is published on the pages read; HTTP 429 and Retry-After are treated as retryable and never looped |
| Wallet balance endpoint | not documented in the pages read; the payment answer of Melhor Envio is shown as it comes |
| Webhook signature encoding | the page does not state it; both base64 and hex are accepted |
volumes in the quote |
the schema spells heigth and lenght; the add-on quotes with products only |
Services with an error in the quote |
the page shows no example; a service with an error field is not offered |
| Status values | pages show example values; unknown values are stored and treated as “Problem” |
| Brand rules | no rule for third-party use of the Melhor Envio logo is published on the pages read; only the text “Works with Melhor Envio” is used |
Test the HTTP layer without Melhor Envio
Section titled “Test the HTTP layer without Melhor Envio”The base URL can be overridden for tests in config.local.php (development only; the add-on never calls a real host in a test):
$config['kv_melhor_envio_base_url'] = 'http://127.0.0.1:11830';node tests/mock-server/server.js 11830 starts a local stand-in built from the reference pages; node tests/e2e/e2e.mjs runs the HTTP end-to-end test against it (it refuses to run unless the store points at the mock); php tests/unit.php runs the unit tests.
Template overrides
Section titled “Template overrides”Admin templates live in design/backend/templates/addons/kv_melhor_envio/. Do not edit them in a store; they are replaced on update.