Skip to content

REF-701-01: API Response Contract

ADR: ADR-701 — API & AuthenticationEscopo: Estrutura JSON do envelope, campos meta, 7 error codes, exemplos, headers obrigatórios, paginação


1. Envelope de Resposta

Todos os endpoints retornam:

json
{
  "success": true,
  "data": { },
  "meta": {
    "page": 1,
    "per_page": 20,
    "total": 100,
    "pages": 5
  },
  "message": null,
  "errors": null
}
CampoTipoSempre presenteDescrição
successbooleanSimtrue para 2xx, false para erros
dataobject / arraySimPayload (null em erros)
metaobject / nullSimPaginação (null se N/A)
messagestring / nullSimMensagem humanizada (null se N/A)
errorsobject / nullSimDetalhes de erro (null em sucesso)

2. Campos Meta (Paginação)

Presente em endpoints de lista:

CampoTipoDescrição
pageintPágina atual
per_pageintItens por página
totalintTotal de itens
pagesintTotal de páginas

Query params: ?page=1&per_page=20 (defaults).


3. 7 Error Codes

CodeHTTPQuandoExemplo errors
VALIDATION_ERROR422Input inválido{"fields": {"email": ["Email is required"]}}
AUTHENTICATION_ERROR401Sem token, expirado, inválido{"code": "AUTHENTICATION_ERROR", "detail": "Token expired"}
AUTHORIZATION_ERROR403Sem permissão{"code": "AUTHORIZATION_ERROR", "detail": "Scope 'finances' required"}
NOT_FOUND404Recurso não existe{"code": "NOT_FOUND", "detail": "Organization 42 not found"}
CONFLICT409Estado conflitante{"code": "CONFLICT", "detail": "Entitlement already cancelled"}
RATE_LIMIT429Excedeu limite{"code": "RATE_LIMIT", "detail": "5 requests/min exceeded"}
INTERNAL_ERROR500Erro interno{"code": "INTERNAL_ERROR", "detail": "Unexpected error"}

4. Exemplos

Sucesso (item único)

json
{
  "success": true,
  "data": {
    "id": 42,
    "name": "Acme Corp",
    "tax_id": "XX.XXX.XXX/XXXX-XX",
    "status": "verified"
  },
  "meta": null,
  "message": null,
  "errors": null
}

Sucesso (lista paginada)

json
{
  "success": true,
  "data": [
    { "id": 1, "code": "PLG-2026040001" },
    { "id": 2, "code": "ENV-2026040002" }
  ],
  "meta": { "page": 1, "per_page": 20, "total": 2, "pages": 1 },
  "message": null,
  "errors": null
}

Erro (validação)

json
{
  "success": false,
  "data": null,
  "meta": null,
  "message": "Validation failed",
  "errors": {
    "code": "VALIDATION_ERROR",
    "fields": {
      "email": ["Email is required"],
      "name": ["Name must be at least 2 characters"]
    }
  }
}

5. Headers Obrigatórios

HeaderDireçãoObrigatórioValor
AuthorizationRequestSim *Bearer {jwt_token}
X-Middag-OrganizationRequestSim **ID da organization
X-Middag-CompanyRequestNãomiddag_br / middag_global
Content-TypeRequestSim (POST/PUT)application/json
Content-TypeResponseSempreapplication/json

* Exceto /auth/login e endpoints públicos ** Exceto endpoints que não operam sobre dados de organization


6. HTTP Status Codes

CodeMeaningContext
200OKSuccessful request
201CreatedResource created successfully
400Bad RequestInvalid or missing parameters
401UnauthorizedToken absent, invalid, or expired
403ForbiddenNo permission for resource/action
404Not FoundResource not found
409ConflictState conflict (e.g., email already exists)
422Unprocessable EntityBusiness validation failed
429Too Many RequestsRate limit exceeded
500Internal Server ErrorInternal server error

7. Pagination Parameters

List endpoints accept:

ParameterTypeDefaultDescription
pageint1Current page
per_pageint20Items per page (max: 100)
orderstringdescDirection: asc or desc
orderbystringcreated_atSort field
searchstringText search (when supported)

8. Authentication Types

TypeDescriptionUsed by
JWT RS256 BearerJWT signed with RS256 in Authorization: Bearer {token} headerMost protected endpoints
Refresh TokenOpaque token used exclusively to renew expired JWT/auth/refresh
Stripe SignatureValidation via Stripe-Signature header with webhook secretStripe webhooks
HubSpot SignatureValidation via X-HubSpot-Signature header with client secretHubSpot webhooks
Invite TokenUnique token sent by email for invite operationsCollaborator invite endpoints
PublicNo authenticationRegister, login, password reset

9. Endpoint Catalog

Base URL: https://account.middag.com.br/wp-json/middag-account/v1

9.1 Auth Endpoints (/auth/*)

#MethodEndpointAuthDescription
1POST/auth/loginPublicLogin with email/password, returns JWT
2POST/auth/registerPublicFull registration with all fields
3POST/auth/register-emailPublicEmail-only registration (OAuth flow)
4POST/auth/refreshRefresh TokenRenew JWT using refresh token
5GET/auth/userJWTAuthenticated user data
6POST/auth/update-profileJWTUpdate profile data
7POST/auth/forgot-passwordPublicRequest password reset token
8POST/auth/validate-reset-tokenPublicValidate reset token validity
9POST/auth/reset-passwordPublicReset password with valid token
10POST/auth/check-userPublicCheck if email is already registered
11POST/auth/resend-verificationPublicResend account verification email
12POST/auth/verify-accountPublicVerify account using email token

POST /auth/login — Request/Response:

json
// Request
{
    "email": "user@example.com",
    "password": "securePassword123"
}

// Response (200)
{
    "success": true,
    "data": {
        "user": {
            "id": 123,
            "email": "user@example.com",
            "display_name": "User Name",
            "roles": [
                "subscriber"
            ],
            "email_verified": true
        },
        "access_token": "eyJhbGciOiJSUzI1NiIs...",
        "refresh_token": "rt_abc123def456...",
        "expires_in": 86400
    }
}

POST /auth/refresh — Request/Response:

json
// Request
{
    "refresh_token": "rt_abc123def456..."
}

// Response (200)
{
    "success": true,
    "data": {
        "access_token": "eyJhbGciOiJSUzI1NiIs...",
        "refresh_token": "rt_newtoken789...",
        "expires_in": 86400
    }
}

Rate limits: /auth/login 5/min/IP, /auth/register 3/min/IP, /auth/forgot-password 3/5min/IP.

9.2 Organization Endpoints (/organizations/*)

#MethodEndpointAuthScopeDescription
13GET/organizationsJWTList user's organizations
14POST/organizationsJWTCreate new organization
15GET/organizations/{id}JWT + OrgorganizationOrganization details
16PUT/organizations/{id}JWT + OrgorganizationUpdate organization data
17DELETE/organizations/{id}JWT + Orgorganization (owner)Delete organization
18POST/organizations/cnpj-checkJWTValidate CNPJ with federal API
19GET/organizations/{id}/collaboratorsJWT + OrgorganizationList organization members

9.3 Collaborator Endpoints (/collaborators/*)

#MethodEndpointAuthScopeDescription
20POST/collaboratorsJWT + OrgorganizationInvite new collaborator
21GET/collaborators/{id}JWT + OrgorganizationCollaborator details
22PUT/collaborators/{id}JWT + OrgorganizationUpdate role/permissions
23DELETE/collaborators/{id}JWT + OrgorganizationRemove collaborator
24POST/collaborators/check-inviteTokenVerify invite validity
25POST/collaborators/accept-inviteTokenAccept invite
26POST/collaborators/reject-inviteTokenReject invite
27POST/collaborators/{id}/resend-inviteJWT + OrgorganizationResend invite email

Roles: owner (full access), admin (manage members), member (scoped access), guest (restricted read), pending (invite not accepted).

Scopes: organization, orders, finances, quotes, contracts, documents, licenses, downloads, entitlements, admin.

9.4 Order Endpoints (/orders/*)

#MethodEndpointAuthScopeDescription
28GET/ordersJWT + OrgordersList organization orders
29GET/orders/{id}JWT + OrgordersFull order details
30POST/orders/{id}/cancelJWT + OrgordersCancel pending order
31POST/orders/{id}/refundJWT + Orgorders + financesRequest refund

Query filters: status (pending/processing/completed/cancelled/refunded), date_from, date_to.

9.5 Invoice Endpoints (/invoices/*)

#MethodEndpointAuthScopeDescription
32GET/invoicesJWT + OrgfinancesList invoices
33GET/invoices/{id}JWT + OrgfinancesInvoice details
34GET/invoices/{id}/pdfJWT + OrgfinancesDownload invoice PDF
35GET/invoices/order/{order_id}JWT + OrgfinancesInvoices linked to an order

9.6 Tax Invoice Endpoints (/tax-invoices/*)

#MethodEndpointAuthScopeDescription
36GET/tax-invoicesJWT + OrgfinancesList NFSe
37GET/tax-invoices/{id}JWT + OrgfinancesNFSe details
38GET/tax-invoices/{id}/pdfJWT + OrgfinancesDownload NFSe PDF
39GET/tax-invoices/order/{order_id}JWT + OrgfinancesNFSe linked to an order

9.7 Quote Endpoints (/quotes/*)

#MethodEndpointAuthScopeDescription
40GET/quotesJWT + OrgquotesList quotes
41GET/quotes/{id}JWT + OrgquotesQuote details
42POST/quotes/{id}/acceptJWT + OrgquotesAccept quote
43POST/quotes/{id}/rejectJWT + OrgquotesReject quote
44GET/quotes/{id}/paymentJWT + Orgquotes + financesPayment status

Query filters: status (draft/sent/accepted/rejected/expired).

9.8 Contract Endpoints (/contracts/*)

#MethodEndpointAuthScopeDescription
45GET/contractsJWT + OrgcontractsList contracts
46GET/contracts/{id}JWT + OrgcontractsContract details
47GET/contracts/{id}/pdfJWT + OrgcontractsDownload contract PDF

9.9 Document Endpoints (/documents/*)

#MethodEndpointAuthScopeDescription
48GET/documentsJWT + OrgdocumentsList documents
49GET/documents/{id}JWT + OrgdocumentsDocument details
50GET/documents/{id}/downloadJWT + OrgdocumentsDownload file

9.10 License Endpoints (/licenses/*)

#MethodEndpointAuthScopeDescription
51GET/licensesJWT + OrglicensesList licenses
52GET/licenses/{id}JWT + OrglicensesLicense details
53POST/licenses/{id}/activateJWT + OrglicensesActivate license on domain
54POST/licenses/{id}/deactivateJWT + OrglicensesDeactivate from domain

9.11 Download Endpoints (/downloads/*)

#MethodEndpointAuthScopeDescription
55GET/downloadsJWT + OrgdownloadsList available downloads
56GET/downloads/{id}JWT + OrgdownloadsGet signed download URL

9.12 Entitlement Endpoints (/entitlements/*)

#MethodEndpointAuthScopeDescription
57GET/entitlementsJWT + OrgentitlementsList organization entitlements
58GET/entitlements/{id}JWT + OrgentitlementsEntitlement details
59GET/entitlements/code/{code}JWT + OrgentitlementsLookup by code (e.g., PLG-2026040142)
60GET/entitlements/{id}/ordersJWT + OrgentitlementsLinked orders
61GET/entitlements/{id}/licensesJWT + OrgentitlementsLinked licenses
62GET/entitlements/{id}/contractsJWT + OrgentitlementsLinked contracts

Query filters: class (PLG/ENV/SVC/ORD/AFL/EDU), status (active/suspended/expired/cancelled).

9.13 Environment Endpoints (/environments/*)

#MethodEndpointAuthScopeDescription
63GET/environmentsJWT + OrgentitlementsList managed environments
64GET/environments/{id}JWT + OrgentitlementsEnvironment details
65GET/environments/{id}/service-requestsJWT + OrgentitlementsService requests linked to env
66POST/environments/{id}/service-requestsJWT + OrgentitlementsCreate service request for env

Query filters: status (provisioning/active/maintenance/suspended/decommissioned), platform (moodle/wordpress/custom), environment_type (production/staging/development/sandbox).

9.14 Service Endpoints (/services/*)

#MethodEndpointAuthScopeDescription
67GET/servicesJWT + OrgentitlementsList organization services
68GET/services/{id}JWT + OrgentitlementsService details
69GET/services/{id}/service-requestsJWT + OrgentitlementsService requests for service

Query filters: status (proposal/approved/in_progress/on_hold/delivered/closed/cancelled), lifecycle (ongoing/project) + type (a definir).

9.15 ServiceRequest Endpoints (/service-requests/*)

#MethodEndpointAuthScopeDescription
70GET/service-requestsJWT + OrgentitlementsList organization SRs
71GET/service-requests/{id}JWT + OrgentitlementsSR details
72POST/service-requestsJWT + OrgentitlementsCreate service request
73GET/service-requests/{id}/historyJWT + OrgentitlementsStatus transition history

Number format: SR-{YEAR}{SEQ:4d}. Clients can only create SRs for ENV-class entitlements (standalone). Admin can create for any entitlement/service.

9.16 Affiliate Endpoints (/affiliates/*)

#MethodEndpointAuthScopeDescription
74GET/affiliates/meJWTLogged-in affiliate data
75POST/affiliates/registerJWTRegister as affiliate

9.17 Admin Endpoints (/admin/*)

#MethodEndpointAuthScopeDescription
76GET/admin/usersJWT (admin)adminList all users
77GET/admin/organizationsJWT (admin)adminList all organizations

9.18 Webhook Endpoints (/webhooks/*)

No JWT auth — validated by service-specific signatures.

#MethodEndpointAuthDescription
78POST/webhooks/stripeStripe SignatureStripe events (company via header)
79POST/webhooks/hubspotHubSpot SignatureHubSpot events (company via header)

Stripe events processed: checkout.session.completed, invoice.paid, invoice.payment_failed, customer.subscription.updated, customer.subscription.deleted, charge.refunded.

HubSpot events processed: Contact create/update, deal stage changes, form submissions.

Company routing uses X-Middag-Company header (unified endpoint, not split by path).


10. Summary and Counts

By Group

GroupEndpointsMethods
Auth122 GET, 10 POST
Organizations73 GET, 2 POST, 1 PUT, 1 DELETE
Collaborators81 GET, 6 POST, 1 PUT, 1 DELETE
Orders42 GET, 2 POST
Invoices44 GET
Tax Invoices44 GET
Quotes53 GET, 2 POST
Contracts33 GET
Documents33 GET
Licenses42 GET, 2 POST
Downloads22 GET
Entitlements66 GET
Environments43 GET, 1 POST
Services33 GET
ServiceRequests43 GET, 1 POST
Affiliates21 GET, 1 POST
Admin22 GET
Webhooks22 POST
Total79(ver tabela completa acima)

By Auth Type

Auth TypeCount
Public8
JWT5
JWT + Org58
Token (invite)3
Webhook Signature2
JWT (admin)2