Hivestr Logo
Hivestr
Documentación Oficial

Documentación de la API Hivestr

Guía completa para integrar tu aplicación con la plataforma Hivestr

Ver Planes

API Pública - Hivestr

Documentación completa de la API pública para integración con sistemas externos.

Escritura en el CRM: además de consultar inventario, clientes y propuestas, la API permite crear y actualizar datos — clientes, propuestas, notas del cliente y tarjetas del pipeline de ventas.

Última actualización: 02/06/2026
Versión de la API: v1
Base URL Producción: https://www.hivestr.com/api/v1



🔐 1. AUTENTICACIÓN

POST /api/v1/auth/token

Genera un Access Token JWT válido por 1 hora.

Headers: Ninguno
Body:

{ "api_key": "hvstr_abc123...", // ✅ OBLIGATORIO "api_secret": "secret456..." // ✅ OBLIGATORIO }

Respuesta:

{ "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "token_type": "Bearer", "expires_in": 3600 }

Uso: Use el access_token en todas las solicitudes posteriores en el header:
Authorization: Bearer {access_token}


📦 2. INVENTARIO

GET /api/v1/public/inventory/list

Lista el inventario de medios out-of-home del media owner.

Query Params (todos opcionales):

?media_type=DOOH          // OOH, DOOH, TV, RADIO, all
&city=Brasília            // Nome da cidade
&state=DF                 // UF (DF, SP, RJ, etc)
&is_active=true           // true, false, all
&page=1                   // Número da página (default: 1)
&limit=50                 // Itens por página (default: 50, máx: 100)

Respuesta:

{ "success": true, "data": [ { "id": "uuid", "name": "Painel Digital Shopping", "media_type": "DOOH", "city": "Brasília", "state": "DF", "address": "SCS Quadra 1", "bairro": "Asa Sul", "latitude": -15.7942, "longitude": -47.8822, "base_price": 500000, // En centavos "unit_price": 16667, // Precio diario (centavos) "audience": 50000, "format": "LED 3x2m", "dimensions": "3x2", "description": "Painel no corredor principal", "photo_url": "https://...", "is_active": true, "is_occupied": false, "screen_quantity": 2, "environment": "Shopping Center", "insertions_per_day": 50, "total_daily_insertions": 100, "discounted_price": null, "discount_percentage": 0, "negotiation_margin_percentage": 15, "created_at": "2024-01-01T00:00:00Z", "updated_at": "2024-01-05T10:30:00Z" } ], "pagination": { "page": 1, "limit": 50, "total": 45, "total_pages": 1 } }

GET /api/v1/public/inventory/{id}

Consulta un ítem específico del inventario con programación (TV/Radio).

Respuesta:

{ "success": true, "data": { "id": "uuid", "name": "Rádio CBN Brasília - Manhã", "media_type": "RADIO", // ... todos los campos del list "media_schedules": [ { "id": "uuid-schedule", "run_days": [1, 2, 3, 4, 5], // Lun-Vie (0=Dom, 1=Lun, ..., 6=Sáb) "start_time": "07:00:00", "end_time": "09:00:00", "price_per_slot": 150000, // R$ 1.500,00 en centavos "available_slots": 10, "program_name": "Jornal da Manhã", "social_class": "A,B", "audience": 100000, "is_active": true } ] } }

👥 3. CLIENTES

GET /api/v1/public/clients

Lista los clientes del media owner.

Query Params (todos opcionales):

?search=João              // Busca em name, email, company_name, cnpj, cpf
&status=lead              // lead, prospect, client, inactive, all
&page=1                   // Número da página
&limit=50                 // Itens por página (default: 50)

Respuesta:

{ "success": true, "data": [ { "id": "uuid", "name": "João Silva", "email": "joao@empresa.com", "phone": "(61) 99999-9999", "company_name": "Empresa XYZ Ltda", "cnpj": "12.345.678/0001-99", "cpf": null, "address": "Rua Exemplo, 123", "city": "Brasília", "state": "DF", "zip_code": "70000-000", "contact_person": "João Silva", "position": "Diretor", "notes": "Cliente VIP", "status": "client", "source": "Website", "created_at": "2024-01-01T00:00:00Z", "updated_at": "2024-01-05T10:00:00Z" } ], "pagination": { "page": 1, "limit": 50, "total": 150, "total_pages": 3 } }

POST /api/v1/public/clients

Crea un nuevo cliente.

Body:

{ "name": "João Silva", // ✅ OBLIGATORIO "email": "joao@empresa.com", // ⚪ Opcional "phone": "(61) 99999-9999", // ⚪ Opcional "company_name": "Empresa XYZ", // ⚪ Opcional "cnpj": "12.345.678/0001-99", // ⚪ Opcional "cpf": "123.456.789-00", // ⚪ Opcional "address": "Rua Exemplo, 123", // ⚪ Opcional "city": "Brasília", // ⚪ Opcional "state": "DF", // ⚪ Opcional "zip_code": "70000-000", // ⚪ Opcional "contact_person": "João Silva", // ⚪ Opcional "position": "Diretor", // ⚪ Opcional "notes": "Cliente indicado", // ⚪ Opcional "status": "lead", // ⚪ Opcional (default: "lead") "source": "Website" // ⚪ Opcional (default: "API") }

Respuesta:

{ "success": true, "data": { "id": "uuid-gerado", "name": "João Silva", "email": "joao@empresa.com", "status": "lead", "created_at": "2024-01-06T16:00:00Z" }, "pipeline_deal": { "id": "uuid-do-card", "title": "João Silva — Empresa XYZ", "pipeline_stage": "Prospecção", "estimated_value": null, "notes": "Cliente indicado" }, "message": "Cliente criado com sucesso" }

Use pipeline_deal.id para actualizar título, valor y observaciones de la tarjeta vía PATCH /pipeline/deals/{id}.


GET /api/v1/public/clients/{id}

Consulta un cliente específico con todas las propuestas.

Respuesta:

{ "success": true, "data": { "id": "uuid", "name": "João Silva", // ... todos los campos del cliente "proposals": [ { "id": "uuid-proposta", "proposal_number": "P0123", "title": "Campanha Verão 2025", "status": "approved", "total_value": 50000, "final_value": 40000, "discount_percentage": 20, "campaign_start_date": "2025-01-15", "campaign_end_date": "2025-01-29", "created_at": "2024-12-15T10:00:00Z" } ], "proposal_stats": { "total": 5, "approved": 2, "pending": 2, "rejected": 1, "total_value": 250000, "approved_value": 150000 } } }

PUT /api/v1/public/clients/{id}

Edita un cliente existente.

Body (todos los campos opcionales):

{ "name": "João Silva Santos", // ⚪ Opcional "email": "novo@email.com", // ⚪ Opcional "phone": "(61) 98888-8888", // ⚪ Opcional "company_name": "Empresa XYZ", // ⚪ Opcional "cnpj": "12.345.678/0001-99", // ⚪ Opcional "cpf": "123.456.789-00", // ⚪ Opcional "address": "Rua Nova, 456", // ⚪ Opcional "city": "São Paulo", // ⚪ Opcional "state": "SP", // ⚪ Opcional "zip_code": "01234-567", // ⚪ Opcional "contact_person": "Maria", // ⚪ Opcional "position": "Gerente", // ⚪ Opcional "notes": "Cliente VIP", // ⚪ Opcional "status": "client" // ⚪ Opcional (lead, prospect, client, inactive) }

Respuesta:

{ "success": true, "data": { "id": "uuid", "name": "João Silva Santos", "email": "novo@email.com", "status": "client", "updated_at": "2024-01-06T16:30:00Z" }, "message": "Cliente atualizado com sucesso" }

📋 4. PROPUESTAS

POST /api/v1/public/proposals/calculate

Calcula valores de propuesta automáticamente (DOOH, OOH, TV/Radio).

Body:

{ "campaign_start_date": "2024-01-15", // ✅ OBLIGATORIO (YYYY-MM-DD) "campaign_end_date": "2024-01-29", // ✅ OBLIGATORIO (YYYY-MM-DD) "bonus_days": 2, // ⚪ Opcional (default: 0) "discount_percentage": 10, // ⚪ Opcional (default: 0) "sell_by_insertions": false, // ⚪ Opcional (default: false) - solo DOOH "daily_insertions_per_screen": 50, // ⚪ Opcional (default: 50) - Si sell_by_insertions=true "items": [ // ✅ OBLIGATORIO (min: 1 item) { "vehicle_id": "uuid-dooh-1", // ✅ OBLIGATORIO "is_bonus": false // ⚪ Opcional (default: false) }, { "vehicle_id": "uuid-ooh-1", // ✅ OBLIGATORIO "face_orientation": "Fluxo", // ⚪ Opcional (OOH) - Fluxo o Contra-Fluxo "is_bonus": false }, { "vehicle_id": "uuid-tv-1", // ✅ OBLIGATORIO "schedule_id": "uuid-schedule", // ✅ OBLIGATORIO (TV/Radio) "quantity": 10, // ⚪ Opcional (default: 1) - Cantidad de inserciones "is_bonus": false } ] }

Respuesta:

{ "success": true, "data": { "campaign_period": { "start_date": "2024-01-15", "end_date": "2024-01-29", "campaign_days": 15, "is_bi_semana": false, "bonus_days": 2, "total_days": 17 }, "items": [ { "vehicle_id": "uuid-dooh-1", "vehicle_name": "Painel Digital Shopping", "media_type": "DOOH", "is_bonus": false, "screen_quantity": 2, "pricing_mode": "daily", "daily_price": 16667, "campaign_days": 15, "unit_price": 500000, "quantity": 15, "discount_percentage": 0, "discount_value": 0, "final_price": 250005 } ], "summary": { "campaign_days": 15, "is_bi_semana": false, "subtotal": 250005, "discount_percentage": 10, "discount_value": 25000, "final_value": 225005, "total_screens": 2 } } }

GET /api/v1/public/proposals

Lista las propuestas del media owner.

Query Params (todos opcionales):

?client_id=uuid           // Filtrar por cliente
&status=draft             // draft, sent, viewed, approved, rejected, all
&start_date=2024-01-01    // Filtro por data de criação (YYYY-MM-DD)
&end_date=2024-12-31      // Filtro por data de criação
&page=1                   // Número da página
&limit=50                 // Itens por página

Respuesta:

{ "success": true, "data": [ { "id": "uuid", "proposal_number": "PROP-0123-24", "title": "Campanha Verão 2024", "description": "Campanha de mídia exterior", "status": "approved", "total_value": 500000, "discount_percentage": 10, "discount_value": 50000, "final_value": 450000, "valid_until": "2024-01-10T23:59:59Z", "campaign_start_date": "2024-01-15", "campaign_end_date": "2024-01-29", "bonus_days": 0, "created_at": "2024-01-05T10:00:00Z", "created_via": "api", "client": { "id": "uuid", "name": "João Silva", "email": "joao@empresa.com", "company_name": "Empresa XYZ" } } ], "pagination": { "page": 1, "limit": 50, "total": 25, "total_pages": 1 } }

POST /api/v1/public/proposals

Crea una nueva propuesta (use los valores calculados de /calculate).

Body:

{ "client_id": "uuid-cliente", // ✅ OBLIGATORIO "title": "Campanha Verão 2024", // ✅ OBLIGATORIO "description": "Campanha de mídia exterior", // ⚪ Opcional "campaign_start_date": "2024-01-15", // ✅ OBLIGATORIO (YYYY-MM-DD) "campaign_end_date": "2024-01-29", // ✅ OBLIGATORIO (YYYY-MM-DD) "bonus_days": 0, // ⚪ Opcional (default: 0) "discount_percentage": 0, // ⚪ Opcional (default: 0) "discount_value": 0, // ⚪ Opcional (default: 0) - En centavos "valid_until": "2024-01-10", // ⚪ Opcional (YYYY-MM-DD) "commercial_notes": "Obs para cliente", // ⚪ Opcional "notes": "Obs internas", // ⚪ Opcional "advertising_agency": "Agência ABC", // ⚪ Opcional "agency_commission_percentage": 15, // ⚪ Opcional (default: 0) "has_volume_commission": false, // ⚪ Opcional (default: false) "volume_commission_percentage": 0, // ⚪ Opcional (default: 0) "sell_by_insertions": false, // ⚪ Opcional (default: false) "daily_insertions_per_screen": null, // ⚪ Opcional (si sell_by_insertions=true) "items": [ // ✅ OBLIGATORIO (min: 1 item) { "vehicle_id": "uuid-dooh-1", // ✅ OBLIGATORIO "schedule_id": null, // ⚪ Opcional (obligatorio para TV/Radio) "quantity": 1, // ✅ OBLIGATORIO "unit_price": 500000, // ✅ OBLIGATORIO (centavos) "discount_percentage": 0, // ⚪ Opcional (default: 0) "discount_value": 0, // ⚪ Opcional (default: 0) - En centavos "final_price": 250005, // ✅ OBLIGATORIO (centavos) "is_bonus": false, // ⚪ Opcional (default: false) "notes": "Observação do item", // ⚪ Opcional "screen_quantity": 2, // ⚪ Opcional (DOOH) "face_details": null // ⚪ Opcional (OOH) - JSON con detalles de la cara } ] }

Respuesta:

{ "success": true, "data": { "id": "uuid-proposta", "proposal_number": "PROP-0124-24", "title": "Campanha Verão 2024", "status": "draft", "final_value": 250005, "items_count": 1, "created_at": "2024-01-06T16:00:00Z", "created_via": "api" }, "message": "Proposta criada com sucesso" }

GET /api/v1/public/proposals/{id}

Consulta una propuesta específica con todos los detalles.

Respuesta:

{ "success": true, "data": { "id": "uuid", "proposal_number": "PROP-0123-24", "title": "Campanha Verão 2024", "description": "Campanha de mídia exterior", "status": "approved", "total_value": 500000, "discount_percentage": 10, "discount_value": 50000, "final_value": 450000, "campaign_start_date": "2024-01-15", "campaign_end_date": "2024-01-29", "bonus_days": 0, "valid_until": "2024-01-10T23:59:59Z", "notes": "Observações internas", "commercial_notes": "Observações para cliente", "created_at": "2024-01-05T10:00:00Z", "updated_at": "2024-01-06T15:00:00Z", "created_via": "api", "client": { "id": "uuid", "name": "João Silva", "email": "joao@empresa.com", "company_name": "Empresa XYZ" }, "proposal_items": [ { "id": "uuid-item", "vehicle_id": "uuid", "quantity": 1, "unit_price": 500000, "final_price": 250005, "is_bonus": false, "screen_quantity": 2, "media_vehicle": { "id": "uuid", "name": "Painel Digital Shopping", "media_type": "DOOH", "city": "Brasília", "state": "DF" } } ] } }

PUT /api/v1/public/proposals/{id}

Edita una propuesta existente.

⚠️ Restricción: No se pueden editar propuestas con status approved o rejected.

Body (todos los campos opcionales):

{ "title": "Novo Título", // ⚪ Opcional "description": "Nova descrição", // ⚪ Opcional "status": "sent", // ⚪ Opcional (draft, sent, viewed, approved, rejected) "discount_percentage": 15, // ⚪ Opcional "discount_value": 0, // ⚪ Opcional (centavos) "valid_until": "2024-02-10", // ⚪ Opcional (YYYY-MM-DD) "notes": "Novas observações", // ⚪ Opcional "commercial_notes": "Obs para cliente", // ⚪ Opcional "items": [ // ⚪ Opcional (si se envía, REEMPLAZA todos) { "vehicle_id": "uuid", // ✅ OBLIGATORIO (si se envían items) "quantity": 1, // ✅ OBLIGATORIO (si se envían items) "unit_price": 500000, // ✅ OBLIGATORIO (si se envían items) "final_price": 250005, // ✅ OBLIGATORIO (si se envían items) "is_bonus": false, // ⚪ Opcional "screen_quantity": 2 // ⚪ Opcional (DOOH) } ] }

Comportamiento:

  • Si envía items: TODOS los ítems actuales son ELIMINADOS y reemplazados por los nuevos
  • Si NO envía items: Los ítems actuales se MANTIENEN
  • Los totales se recalculan automáticamente si cambian items o descuentos

Respuesta:

{ "success": true, "data": { "id": "uuid", "proposal_number": "PROP-0123-24", "title": "Novo Título", "status": "sent", "final_value": 200004, "updated_at": "2024-01-06T16:45:00Z" }, "message": "Proposta atualizada com sucesso" }

🧩 5. CRM (NOTAS Y PIPELINE)

Endpoints para grabar datos en el CRM externamente: notas del cliente, tarjetas del pipeline y movimiento de etapas.

Permiso necesario en la API Key: clients: true

Al crear un cliente vía POST /clients, se crea automáticamente una tarjeta en el pipeline (etapa Prospecção).

Etapas del pipeline (pipeline_stage)

Valores exactos aceptados por la API (siempre en portugués, case-sensitive):

ValorDescripciónStatus de la propuesta vinculada*
ProspecçãoContacto inicial; aún sin propuesta formaldraft
DegustaçãoCliente conociendo producto/servicio (demo/prueba)draft
PropostaPropuesta enviada, en espera de análisissent
NegociaçãoCliente evaluando valores y condicionesviewed
AprovaçãoInterés confirmado; aprobación internapre_approved
GanhoNegocio cerradoapproved
PerdidoCliente rechazó o el deal no avanzórejected

* Cuando la tarjeta tiene propuesta vinculada, mover la etapa vía PATCH /pipeline/deals/{id}/stage sincroniza el status de la propuesta automáticamente.

Reglas importantes:

  • Default al crear cliente o tarjeta: Prospecção
  • No use PATCH .../stage para Perdido — use POST .../mark-lost con el campo reason
  • Las tarjetas en Perdido no pueden moverse ni editarse
  • Las tarjetas en Ganho o Perdido no entran en el valor total activo del pipeline

Ejemplo de filtro:

GET /api/v1/public/pipeline/deals?pipeline_stage=Negociação

Ejemplo de movimiento:

PATCH /api/v1/public/pipeline/deals/{id}/stage { "pipeline_stage": "Aprovação" }

GET /api/v1/public/clients/{id}/notes

Lista notas/interacciones del cliente.

Query Params (opcionales):

?note_type=follow_up    // note, task, reminder, follow_up, all
&page=1
&limit=50

Respuesta:

{ "success": true, "data": [ { "id": "uuid", "client_id": "uuid", "content": "Cliente pediu retorno na sexta", "note_type": "follow_up", "is_completed": false, "created_at": "2026-06-02T10:00:00Z", "user": { "id": "uuid", "full_name": "Maria Silva" } } ], "pagination": { "page": 1, "limit": 50, "total": 3, "total_pages": 1 } }

POST /api/v1/public/clients/{id}/notes

Registra una nota en el historial del cliente.

Body:

{ "content": "Cliente recusou proposta por budget", // ✅ OBLIGATORIO "note_type": "follow_up" // ⚪ Opcional (default: note) }

Tipos válidos: note, task, reminder, follow_up


GET /api/v1/public/pipeline/deals

Lista tarjetas del pipeline de ventas.

Query Params (opcionales):

?client_id=uuid
&pipeline_stage=Negociação    // Ver tabela de estágios acima
&page=1
&limit=50

Cada tarjeta incluye tasks_summary:

{ "tasks_summary": { "pending": 2, "total": 3, "overdue": 1, "due_soon": 2, "next_due_at": "2026-06-02T14:30:00Z" } }

GET /api/v1/public/pipeline/reminders

Lista tareas con plazo vencido o en las próximas 24 horas (equivalente al icono de notificaciones del pipeline).

Query Params (opcionales):

?user_id=uuid-vendedor    // Filtra por responsável da tarefa ou do deal

Respuesta:

{ "success": true, "count": 2, "overdue_count": 1, "data": [ { "id": "uuid-tarefa", "title": "Ligar para o cliente", "due_at": "2026-06-02T10:00:00Z", "urgency": "overdue", "deal_id": "uuid-deal", "deal_title": "Campanha verão", "pipeline_stage": "Negociação", "client_name": "João Silva", "assignee_name": "Maria Vendedora" } ] }

Valores de urgency: overdue (atrasada), due_today (hoy), due_soon (próximas 24h)


POST /api/v1/public/pipeline/deals

Crea una tarjeta manual en el pipeline.

Body:

{ "client_id": "uuid", // ✅ OBLIGATORIO "title": "Follow-up campanha verão", // ✅ OBLIGATORIO "pipeline_stage": "Prospecção", // ⚪ Opcional — ver tabla de etapas "estimated_value": 500000, // ⚪ Opcional (centavos) "notes": "Lead vindo do RD Station", // ⚪ Opcional "user_id": "uuid-vendedor" // ⚪ Opcional (default: creador de la API Key) }

GET /api/v1/public/pipeline/deals/{id}

Consulta una tarjeta específica del pipeline.


PATCH /api/v1/public/pipeline/deals/{id}

Actualiza información de la tarjeta (título, valor, observaciones, responsable).

Body (todos opcionales, envíe al menos uno):

{ "title": "Campanha verão 2026", "estimated_value": 500000, "notes": "Budget aprovado pelo marketing", "user_id": "uuid-vendedor" }

Restricciones:

  • Las tarjetas en Perdido no pueden editarse
  • Para mover de etapa, use PATCH /pipeline/deals/{id}/stage
  • Valores monetarios en centavos

PATCH /api/v1/public/pipeline/deals/{id}/stage

Mueve una tarjeta a otra etapa del pipeline.

Body:

{ "pipeline_stage": "Negociação" // ✅ OBLIGATORIO }

Restricciones:

  • No use este endpoint para Perdido — use mark-lost con motivo
  • Las tarjetas ya en Perdido no pueden moverse

Si la tarjeta tiene propuesta vinculada, el status de la propuesta se sincroniza automáticamente.


POST /api/v1/public/pipeline/deals/{id}/mark-lost

Marca el deal como perdido y registra nota en el cliente.

Body:

{ "reason": "Cliente escolheu concorrente" // ✅ OBLIGATORIO }

Comportamiento:

  • Mueve la tarjeta a etapa Perdido
  • Si hay propuesta vinculada, la marca como rejected
  • Crea nota automática en client_notes con el motivo

GET /api/v1/public/pipeline/deals/{id}/tasks

Lista tareas de una tarjeta del pipeline.


POST /api/v1/public/pipeline/deals/{id}/tasks

Crea tarea con plazo opcional.

Body:

{ "title": "Ligar para o cliente", // ✅ OBLIGATORIO "due_at": "2026-06-02T14:30:00Z", // ⚪ Opcional (ISO 8601) "user_id": "uuid-vendedor" // ⚪ Opcional (default: creador de la API Key) }

PATCH /api/v1/public/pipeline/deals/{id}/tasks/{taskId}

Actualiza tarea (marcar concluida, alterar plazo, etc.).

Body (envíe al menos uno):

{ "title": "Retornar ligação", "due_at": "2026-06-03T09:00:00Z", "is_completed": true, "user_id": "uuid-vendedor" }

DELETE /api/v1/public/pipeline/deals/{id}/tasks/{taskId}

Elimina una tarea.


📊 RESUMEN DE TODOS LOS ENDPOINTS

MétodoEndpointDescripciónCampos Obligatorios
POST/auth/tokenGenerar access tokenapi_key, api_secret
GET/inventory/listListar inventario-
GET/inventory/{id}Consultar ítem-
GET/clientsListar clientes-
POST/clientsCrear clientename
GET/clients/{id}Consultar cliente + propuestas-
PUT/clients/{id}Editar cliente- (todos opcionales)
GET/clients/{id}/notesListar notas del cliente-
POST/clients/{id}/notesCrear nota en el clientecontent
GET/pipeline/dealsListar tarjetas del pipeline-
POST/pipeline/dealsCrear tarjeta en el pipelineclient_id, title
GET/pipeline/deals/{id}Consultar tarjeta del pipeline-
PATCH/pipeline/deals/{id}Editar tarjeta del pipeline- (title, notes, estimated_value, user_id)
PATCH/pipeline/deals/{id}/stageMover tarjeta de etapapipeline_stage
POST/pipeline/deals/{id}/mark-lostMarcar deal como perdidoreason
GET/pipeline/remindersRecordatorios de tareas (24h)-
GET/pipeline/deals/{id}/tasksListar tareas de la tarjeta-
POST/pipeline/deals/{id}/tasksCrear tarea con plazotitle
PATCH/pipeline/deals/{id}/tasks/{taskId}Actualizar tarea-
DELETE/pipeline/deals/{id}/tasks/{taskId}Eliminar tarea-
POST/proposals/calculateCalcular valorescampaign_start_date, campaign_end_date, items
GET/proposalsListar propuestas-
POST/proposalsCrear propuestaclient_id, title, campaign_start_date, campaign_end_date, items
GET/proposals/{id}Consultar propuesta-
PUT/proposals/{id}Editar propuesta- (todos opcionales)

🎯 FLUJO COMPLETO DE INTEGRACIÓN

// 1. AUTENTICAÇÃO (1x por hora) const tokenRes = await fetch('https://www.hivestr.com/api/v1/auth/token', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ api_key: process.env.API_KEY, api_secret: process.env.API_SECRET }) }); const { access_token } = await tokenRes.json(); // 2. BUSCAR/CRIAR CLIENTE const clientRes = await fetch('https://www.hivestr.com/api/v1/public/clients?search=joao@empresa.com', { headers: { 'Authorization': `Bearer ${access_token}` } }); const clientData = await clientRes.json(); let clientId; let dealId; if (clientData.data.length > 0) { clientId = clientData.data[0].id; } else { const createRes = await fetch('https://www.hivestr.com/api/v1/public/clients', { method: 'POST', headers: { 'Authorization': `Bearer ${access_token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ name: "João Silva", email: "joao@empresa.com" }) }); const newClient = await createRes.json(); clientId = newClient.data.id; dealId = newClient.pipeline_deal?.id; } // 2b. ATUALIZAR CARD DO PIPELINE (opcional) if (dealId) { await fetch(`https://www.hivestr.com/api/v1/public/pipeline/deals/${dealId}`, { method: 'PATCH', headers: { 'Authorization': `Bearer ${access_token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'Campanha verão — João Silva', estimated_value: 500000, notes: 'Lead captado via integração externa' }) }); } // 2c. REGISTRAR NOTA NO CRM (opcional) await fetch(`https://www.hivestr.com/api/v1/public/clients/${clientId}/notes`, { method: 'POST', headers: { 'Authorization': `Bearer ${access_token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ content: 'Lead captado via integração externa', note_type: 'follow_up' }) }); // 2d. CRIAR CARD NO PIPELINE (opcional — POST /clients já cria card em Prospecção) await fetch('https://www.hivestr.com/api/v1/public/pipeline/deals', { method: 'POST', headers: { 'Authorization': `Bearer ${access_token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ client_id: clientId, title: 'Follow-up integração', pipeline_stage: 'Degustação' }) }); // 2e. CRIAR TAREFA COM PRAZO (opcional) await fetch(`https://www.hivestr.com/api/v1/public/pipeline/deals/${dealId}/tasks`, { method: 'POST', headers: { 'Authorization': `Bearer ${access_token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'Ligar para confirmar interesse', due_at: new Date(Date.now() + 3600000).toISOString() }) }); // 2f. CONSULTAR LEMBRETES (sininho) const remindersRes = await fetch('https://www.hivestr.com/api/v1/public/pipeline/reminders', { headers: { 'Authorization': `Bearer ${access_token}` } }); const reminders = await remindersRes.json(); // 3. CALCULAR PROPOSTA const calcRes = await fetch('https://www.hivestr.com/api/v1/public/proposals/calculate', { method: 'POST', headers: { 'Authorization': `Bearer ${access_token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ campaign_start_date: "2024-01-15", campaign_end_date: "2024-01-29", items: [{ vehicle_id: "uuid-vehicle" }] }) }); const calcData = await calcRes.json(); // 4. CRIAR PROPOSTA const proposalRes = await fetch('https://www.hivestr.com/api/v1/public/proposals', { method: 'POST', headers: { 'Authorization': `Bearer ${access_token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ client_id: clientId, title: "Campanha Verão 2024", campaign_start_date: "2024-01-15", campaign_end_date: "2024-01-29", items: calcData.data.items }) }); const proposal = await proposalRes.json(); const proposalId = proposal.data.id; // 5. ENVIAR PROPOSTA (mudar status) await fetch(`https://www.hivestr.com/api/v1/public/proposals/${proposalId}`, { method: 'PUT', headers: { 'Authorization': `Bearer ${access_token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ status: "sent" }) }); // 6. CONSULTAR PROPOSTA const getRes = await fetch(`https://www.hivestr.com/api/v1/public/proposals/${proposalId}`, { headers: { 'Authorization': `Bearer ${access_token}` } }); const fullProposal = await getRes.json();

📌 OBSERVACIONES IMPORTANTES

Valores Monetarios

Todos los valores están en centavos:

  • R$ 500,00 = 50000
  • R$ 1.234,56 = 123456

Fechas

Formato ISO 8601: YYYY-MM-DD

  • Fecha: 2024-01-15
  • Fecha/Hora: 2024-01-15T10:30:00Z

created_via

Las propuestas creadas vía API tienen created_via: "api" automáticamente.

Rate Limiting

  • Básico: 1.000 req/hora
  • Professional: 5.000 req/hora
  • Enterprise: Ilimitado

Errores Comunes

  • 401: Token expirado → Generar nuevo en /auth/token
  • 403: Sin permiso → Verificar permisos de la API Key
  • 404: Recurso no encontrado → Verificar ID
  • 429: Rate limit excedido → Esperar reset (1 hora)
  • 500: Error interno → Verificar logs/campos enviados

🔄 RENOVACIÓN AUTOMÁTICA DE TOKEN

let currentToken = null; let tokenExpiry = null; async function getValidToken() { const now = Date.now(); // Se token não existe ou expira em menos de 10min, renova if (!currentToken || !tokenExpiry || now >= tokenExpiry - (10 * 60 * 1000)) { const res = await fetch('https://www.hivestr.com/api/v1/auth/token', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ api_key: process.env.API_KEY, api_secret: process.env.API_SECRET }) }); const data = await res.json(); currentToken = data.access_token; tokenExpiry = now + (50 * 60 * 1000); // Renova a cada 50min } return currentToken; }

¡Documentación completa de todos los endpoints! 📚

¿Dudas? Habla con nuestro soporte (suporte@hivestr.com)