Skip to main content

⚡ Guia Rápido - API Krayin CRM

Implementação Finalizada - Pronto para Usar!

Status:IMPLEMENTADO E FUNCIONANDO URL: https://crm.memudecore.com.br/api/v1/ Documentação: https://crm.memudecore.com.br/api/documentation


🚀 ACESSO IMEDIATO

🔑 Credenciais Prontas

URL Base: https://crm.memudecore.com.br/api/v1
Email:    accounts@memudecore.com.br
Senha:    Memude@2025

📝 Obter Token (1 Passo)

curl -X POST "https://crm.memudecore.com.br/api/v1/login" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "email=accounts@memudecore.com.br&password=Memude@2025&device_name=MeuApp"

Resposta: Copie o token do retorno para usar em todas as requisições.


COMANDOS ESSENCIAIS

🎯 1. Criar Lead (Mais Usado)

curl -X POST "https://crm.memudecore.com.br/api/v1/leads" \
  -H "Authorization: Bearer SEU_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Cliente Potencial - Empresa ABC",
    "description": "Interesse em nossos produtos",
    "lead_value": 5000,
    "person": {
      "name": "João Silva",
      "emails": [{"value": "joao@empresa.com", "label": "work"}],
      "contact_numbers": [{"value": "11999999999", "label": "mobile"}]
    }
  }'

📋 2. Listar Leads

curl -X GET "https://crm.memudecore.com.br/api/v1/leads" \
  -H "Authorization: Bearer SEU_TOKEN"

📞 3. Criar Atividade

curl -X POST "https://crm.memudecore.com.br/api/v1/activities" \
  -H "Authorization: Bearer SEU_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Ligar para cliente",
    "type": "call",
    "comment": "Follow-up da proposta",
    "schedule_from": "2026-01-20T14:00:00Z",
    "schedule_to": "2026-01-20T14:30:00Z",
    "lead_id": 1,
    "user_id": 1
  }'

👥 4. Criar Contato

curl -X POST "https://crm.memudecore.com.br/api/v1/contacts/persons" \
  -H "Authorization: Bearer SEU_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Maria Santos",
    "emails": [{"value": "maria@empresa.com", "label": "work"}],
    "contact_numbers": [{"value": "11888888888", "label": "mobile"}],
    "job_title": "Gerente de Compras"
  }'

🔧 INTEGRAÇÃO RÁPIDA

📱 JavaScript (Frontend)

// Configuração básica
const API_BASE = 'https://crm.memudecore.com.br/api/v1';
const TOKEN = 'seu_token_aqui';

const headers = {
  'Authorization': `Bearer ${TOKEN}`,
  'Content-Type': 'application/json'
};

// Criar lead
async function criarLead(dados) {
  const response = await fetch(`${API_BASE}/leads`, {
    method: 'POST',
    headers,
    body: JSON.stringify(dados)
  });
  return response.json();
}

// Usar
criarLead({
  title: 'Lead do Site',
  description: 'Formulário de contato',
  lead_value: 3000,
  person: {
    name: 'Cliente Exemplo',
    emails: [{value: 'cliente@email.com', label: 'work'}]
  }
});

🐍 Python (Backend)

import requests

class KrayinAPI:
    def __init__(self, token):
        self.base_url = 'https://crm.memudecore.com.br/api/v1'
        self.headers = {
            'Authorization': f'Bearer {token}',
            'Content-Type': 'application/json'
        }

    def criar_lead(self, dados):
        response = requests.post(
            f'{self.base_url}/leads',
            json=dados,
            headers=self.headers
        )
        return response.json()

# Usar
api = KrayinAPI('seu_token')
lead = api.criar_lead({
    'title': 'Lead Python',
    'lead_value': 2500,
    'person': {'name': 'Cliente Python'}
})

🟨 Node.js (Server)

const axios = require('axios');

const krayin = axios.create({
  baseURL: 'https://crm.memudecore.com.br/api/v1',
  headers: {
    'Authorization': 'Bearer seu_token',
    'Content-Type': 'application/json'
  }
});

// Endpoint para receber webhook
app.post('/novo-lead', async (req, res) => {
  const leadData = {
    title: `Lead - ${req.body.nome}`,
    description: req.body.mensagem,
    lead_value: req.body.valor || 1000,
    person: {
      name: req.body.nome,
      emails: [{value: req.body.email, label: 'work'}]
    }
  };

  const response = await krayin.post('/leads', leadData);
  res.json({success: true, leadId: response.data.data.id});
});

📊 ENDPOINTS PRINCIPAIS

Funcionalidade Método Endpoint
Login POST /login
Leads GET/POST /leads
Lead Específico GET/PUT/DELETE /leads/{id}
Atividades GET/POST /activities
Contatos GET/POST /contacts/persons
Organizações GET/POST /contacts/organizations

🎯 CASOS DE USO PRONTOS

1. Formulário Web → Lead

<form id="contato">
  <input name="nome" placeholder="Nome" required>
  <input name="email" type="email" placeholder="Email" required>
  <input name="empresa" placeholder="Empresa">
  <button type="submit">Enviar</button>
</form>

<script>
document.getElementById('contato').onsubmit = async (e) => {
  e.preventDefault();
  const dados = new FormData(e.target);

  await fetch('/api/criar-lead', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
      nome: dados.get('nome'),
      email: dados.get('email'),
      empresa: dados.get('empresa')
    })
  });

  alert('Obrigado! Entraremos em contato.');
};
</script>

2. WhatsApp → Lead Automático

// Webhook WhatsApp
app.post('/whatsapp', async (req, res) => {
  const message = req.body.entry[0].changes[0].value.messages[0];
  const contact = req.body.entry[0].changes[0].value.contacts[0];

  if (message.text.body.includes('orçamento')) {
    await krayin.post('/leads', {
      title: `WhatsApp - ${contact.profile.name}`,
      description: `Mensagem: ${message.text.body}`,
      lead_source_id: 3, // WhatsApp
      person: {
        name: contact.profile.name,
        contact_numbers: [{
          value: message.from,
          label: 'whatsapp'
        }]
      }
    });
  }

  res.sendStatus(200);
});

3. E-commerce → Lead

// WordPress/WooCommerce Hook
add_action('woocommerce_new_order', function($order_id) {
    $order = wc_get_order($order_id);

    $lead_data = [
        'title' => "Pedido #{$order_id} - {$order->get_billing_first_name()}",
        'lead_value' => floatval($order->get_total()),
        'person' => [
            'name' => $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),
            'emails' => [
                ['value' => $order->get_billing_email(), 'label' => 'billing']
            ]
        ]
    ];

    wp_remote_post('https://crm.memudecore.com.br/api/v1/leads', [
        'headers' => [
            'Authorization' => 'Bearer ' . get_option('krayin_token'),
            'Content-Type' => 'application/json'
        ],
        'body' => json_encode($lead_data)
    ]);
});

⚠️ PONTOS IMPORTANTES

🔐 Segurança

  • Sempre usar HTTPS
  • Token no header Authorization: Bearer {token}
  • Não expor token no frontend
  • Renovar tokens periodicamente

📝 Campos Obrigatórios

  • Lead: title (título)
  • Person: name (nome)
  • Activity: title, type, lead_id, user_id

🚫 Erros Comuns

  • 401: Token inválido ou expirado
  • 422: Dados inválidos (verificar campos obrigatórios)
  • 429: Muitas requisições (aguardar)

🛠️ FERRAMENTAS DE TESTE

🌐 Swagger UI

Acesse: https://crm.memudecore.com.br/api/documentation

  • Interface visual para testar todos os endpoints
  • Documentação completa
  • Teste direto no navegador

📮 Postman Collection

{
  "info": {"name": "Krayin CRM API"},
  "variable": [
    {"key": "base_url", "value": "https://crm.memudecore.com.br/api/v1"},
    {"key": "token", "value": "{{seu_token}}"}
  ],
  "request": [
    {
      "name": "Login",
      "method": "POST",
      "url": "{{base_url}}/login",
      "body": {
        "mode": "urlencoded",
        "urlencoded": [
          {"key": "email", "value": "accounts@memudecore.com.br"},
          {"key": "password", "value": "Memude@2025"},
          {"key": "device_name", "value": "Postman"}
        ]
      }
    },
    {
      "name": "Criar Lead",
      "method": "POST",
      "url": "{{base_url}}/leads",
      "header": [{"key": "Authorization", "value": "Bearer {{token}}"}],
      "body": {
        "mode": "raw",
        "raw": "{\n  \"title\": \"Lead Teste\",\n  \"lead_value\": 1500,\n  \"person\": {\n    \"name\": \"João Teste\"\n  }\n}"
      }
    }
  ]
}

🧪 Script de Teste Rápido

#!/bin/bash
# Salvar como test.sh

API="https://crm.memudecore.com.br/api/v1"

# 1. Login
TOKEN=$(curl -s -X POST "$API/login" \
  -d "email=accounts@memudecore.com.br&password=Memude@2025&device_name=Test" \
  | jq -r '.token')

echo "Token: $TOKEN"

# 2. Criar lead
LEAD_ID=$(curl -s -X POST "$API/leads" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"title":"Lead Teste","person":{"name":"João Teste"}}' \
  | jq -r '.data.id')

echo "Lead criado: $LEAD_ID"

# 3. Listar leads
curl -s -X GET "$API/leads" \
  -H "Authorization: Bearer $TOKEN" \
  | jq '.data[] | {id, title, person: .person.name}'

📞 SUPORTE RÁPIDO

Problemas Comuns

❌ "Unauthenticated"

# Solução: Renovar token
curl -X POST "https://crm.memudecore.com.br/api/v1/login" \
  -d "email=accounts@memudecore.com.br&password=Memude@2025&device_name=NovoApp"

❌ "The title field is required"

// Solução: Sempre incluir campos obrigatórios
{
  "title": "Título obrigatório do lead",
  "person": {
    "name": "Nome obrigatório da pessoa"
  }
}

❌ Rate limit atingido

// Solução: Implementar delay entre requests
await new Promise(resolve => setTimeout(resolve, 1000)); // 1s delay

🔍 Debug Rápido

# Verificar se API está online
curl -I https://crm.memudecore.com.br/api/v1/

# Verificar token
curl -H "Authorization: Bearer SEU_TOKEN" \
  https://crm.memudecore.com.br/api/v1/leads?limit=1

# Verificar últimos logs
docker exec krayin_container tail -f storage/logs/laravel.log

🎉 PRÓXIMOS PASSOS

Implementação Básica (Hoje)

  1. Testar endpoints com Postman/curl
  2. Implementar criação de leads
  3. Configurar autenticação

🚀 Expansão (Próximas semanas)

  1. Integrar formulários web
  2. Conectar WhatsApp/email
  3. Automatizar relatórios
  4. Implementar webhooks

📈 Otimização (Futuro)

  1. Cache inteligente
  2. Batch operations
  3. Monitoramento avançado
  4. Integração BI

📋 CHECKLIST DE VALIDAÇÃO

  • ✅ API respondendo (https://crm.memudecore.com.br/api/v1/)
  • ✅ Login funcionando (accounts@memudecore.com.br / Memude@2025)
  • ✅ Token sendo gerado
  • ✅ Leads sendo criados
  • ✅ Atividades sendo agendadas
  • ✅ Contatos sendo adicionados
  • ✅ Documentação acessível (Swagger)

🎯 RESULTADO: API Krayin CRM 100% operacional e pronta para integração imediata!

Guia atualizado: Janeiro 2026 | Status: ✅ IMPLEMENTADO