Pular para o conteúdo

Serviços Externos e Integrações

Database, autenticação, storage, e edge functions.

ComponenteUso
PostgreSQLBanco de dados principal (66+ migrations)
RLSIsolamento multi-tenant
AuthEmail/password authentication
StorageMedia de templates (bucket template-media)
pg_cronJobs agendados (segments, campaigns)
  • Project ref: osytjlchrelbuphsvfax
  • Regiao: sa-east-1 (Sao Paulo)
  • Plano: Pro
ClientEnv VarsUso
BrowserNEXT_PUBLIC_SUPABASE_URL, NEXT_PUBLIC_SUPABASE_ANON_KEYClient components
ServerNEXT_PUBLIC_SUPABASE_URL, NEXT_PUBLIC_SUPABASE_ANON_KEY + cookiesAPI routes, server components
AdminNEXT_PUBLIC_SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEYWebhooks, cron, automações (bypass RLS)
JobIntervaloFunção
recalculate_all_segments5 minutosRecalcula membros de segmentos dinâmicos
execute-scheduled-campaigns1 minutoExecuta campanhas agendadas
  • Bucket: template-media (público)
  • Limite: 100MB por arquivo
  • Tipos: JPEG, PNG, WebP, MP4, PDF
  • Path: {accountId}/{uuid}.{ext}
  • URL pública: supabase.storage.from("template-media").getPublicUrl(path)
ArquivoDescrição
src/lib/supabase/client.tsBrowser client
src/lib/supabase/server.tsServer client
src/lib/supabase/admin.tsAdmin client (service role)
src/lib/supabase/middleware.tsSession management

Rate limiting e controle de concorrência (execution limiter).

  • Regiao: sa-east-1 (mesmo que Supabase para latencia mínima)
  • Protocolo: REST API (não TCP — funciona em serverless)
  • Prefix: x17:rl (rate limiting), x17:exec:active (execution limiter)

Sliding window rate limiter via @upstash/ratelimit.

Presets:

PresetLimiteJanela
webhook100 req1 min
api30 req1 min
auth5 req1 min
callback20 req1 min
ai20 req1 hora
send60 req1 min

Funcoes:

rateLimit(key, limit, windowMs) // Custom
rateLimitByPreset(key, preset) // Preset
rateLimitResponse(remaining, limit) // 429 response
rateLimitHeaders(limit, remaining, reset) // X-RateLimit-* headers

Fallback: Se Redis não configurado, permite todas as requests (não bloqueia).

Uso 2: Execution Limiter (src/lib/automations/execution-limiter.ts)

Seção intitulada “Uso 2: Execution Limiter (src/lib/automations/execution-limiter.ts)”

Controla execuções concorrentes de automações por account.

  • Key: x17:exec:active:{accountId}
  • Max: 10 execuções concorrentes
  • TTL: 300 segundos (auto-cleanup)
UPSTASH_REDIS_REST_URL # URL da REST API
UPSTASH_REDIS_REST_TOKEN # Token de autenticação

API oficial do WhatsApp para envio/recebimento de mensagens.

  • Graph API: v23.0
  • Base URL: https://graph.facebook.com/v23.0
FeatureEndpoint
Enviar mensagemPOST /{phoneNumberId}/messages
Submeter templatePOST /{wabaId}/message_templates
Listar templatesGET /{wabaId}/message_templates
Deletar templateDELETE /{wabaId}/message_templates
Registrar phonePOST /{phoneNumberId}/register
Subscribé webhooksPOST /{wabaId}/subscribed_apps
Embedded SignupOAuth flow + debug_token
  • Endpoint: /api/whatsapp/webhook
  • Verificação: HMAC-SHA256 com FACEBOOK_APP_SECRET
  • Rate limit: 100 req/min por IP
  • Eventos processados: messages (inbound), statuses (delivered/read/failed), message_template_status_update
FACEBOOK_APP_ID # App ID
FACEBOOK_APP_SECRET # App Secret (HMAC + OAuth)
FACEBOOK_CONFIG_ID # Embedded Signup Config ID
WHATSAPP_VERIFY_TOKEN # Webhook verification token
ENCRYPTION_KEY # AES-256 para tokens
ArquivoDescrição
src/lib/whatsapp/meta-api.tsMetaWhatsAppApi client
src/lib/whatsapp/facebook-sdk.tsOAuth + Embedded Signup
src/lib/whatsapp/encryption.tsToken encryption
src/app/api/whatsapp/webhook/route.tsWebhook handler

Documentação detalhada: whatsapp-integration


Proxy para a API da Anthropic (Claude). Permite usar o Claude Opus sem expor a API key no frontend.

  • Servidor: VPS dedicado com FastAPI (Python)
  • Endpoint: {VPS_API_URL}/v1/messages
  • Modelo padrão: claude-opus-4-6
  • Timeout: 30 segundos
  • Retries: 2
chatWithClaude(messages, systemPrompt?, model?) // Chat genérico
generateCopy(prompt, context?) // Copywriting WhatsApp
suggestReply(history, personality?) // Sugestao de resposta
analyzeBrand(html, url) // Análise de marca (scraping)
VPS_API_URL # URL base da VPS
VPS_API_KEY # API key (enviado como X-Api-Key header)
ArquivoDescrição
src/lib/vps/client.tsVPS client com retry logic
src/lib/constants.tsVPS_CONFIG (endpoint, model, timeout)

Gateway de pagamento brasileiro para assinaturas.

  • PIX (QR code)
  • Boleto bancário
  • Cartão de crédito
interface Subscription {
asaas_customer_id: string // ID do cliente no ASAAS
asaas_subscription_id: string // ID da assinatura
plan: "free" | "starter" | "pro" | "enterprise"
billing_type: "CREDIT_CARD" | "PIX" | "BOLETO"
cycle: "MONTHLY" | "YEARLY"
value_cents: number
status: "pending" | "active" | "past_due" | "suspended" | "cancelled"
}
interface BillingHistory {
asaas_payment_id: string
pix_qr_code: string | null
pix_payload: string | null
invoice_url: string | null
}
  • Endpoint: /api/cron/billing-suspension (cron de verificação)
  • Processa notificações de pagamento do ASAAS
  • Suspende contas com pagamento atrasado

PlataformaAuthArquivos
ShopifyOAuth 2.0src/lib/integrations/shopify/ (client, oauth, normalizer, webhooks)
YampiOAuth 2.0 + Token Managersrc/lib/integrations/yampi/ (client, oauth, token-manager, normalizer, webhooks)
NuvemshopOAuth 2.0src/lib/integrations/nuvemshop/ (client, oauth, normalizer, webhooks)
WooCommerceAPI Keysrc/lib/integrations/woocommerce/ (client, normalizer, webhooks)
HotmartWebhooksrc/lib/integrations/hotmart/ (client, normalizer, webhooks)
KiwifyWebhooksrc/lib/integrations/kiwify/ (client, normalizer, webhooks)

Cada integração segue o padrão:

src/lib/integrations/{platform}/
client.ts # Client HTTP para a API da plataforma
oauth.ts # (se OAuth) Fluxo de autorização
normalizer.ts # Normaliza dados para formato x17
webhooks.ts # Processa webhooks da plataforma

Arquivo compartilhado:

  • src/lib/integrations/trigger-data-builder.ts - Constroi triggerData padronizado para automações
  • src/lib/integrations/recovery-tracker.ts - Rastreamento de recuperação de carrinhos
1. Plataforma envia webhook -> /api/integrations/{platform}/webhook
2. Verificação de assinatura (HMAC ou token)
3. Normalizar dados (normalizer.ts)
4. Upsert contato + pedido/carrinho no banco
5. emitEvent() com métrica aprópriada
6. dispatchTrigger() ou dispatchEventToAutomations()
7. Automações com trigger correspondente são executadas
  • Shopify: OAuth 2.0, token longo prazo (offline access)
  • Yampi: OAuth 2.0, token com expiração (refresh automático via token-manager.ts)
  • Nuvemshop: OAuth 2.0
  • WooCommerce: API Key (consumer_key + consumer_secret)
  • Hotmart: Webhook-only (sem API client com token)
  • Kiwify: Webhook-only (sem API client com token)

Todos os tokens são criptografados com a mesma função encrypt() de src/lib/whatsapp/encryption.ts.


API de rastreamento de envios para acompanhar pedidos em transito.

interface ShipmentTracking {
tracking_number: string
carrier_code: number | null
carrier_name: string | null
status: "not_found" | "info_received" | "in_transit" | "expired" |
"available_for_pickup" | "out_for_delivery" | "delivery_failure" |
"delivered" | "exception" | "pending"
tracking_url: string | null
estimated_delivery: string | null
}
interface TrackingSettings {
api_key_encrypted: string | null // AES-256-GCM
webhook_secret: string | null
is_active: boolean
auto_register: boolean
quota_total: number
quota_used: number
}
  • Shipment Created
  • Shipment In Transit
  • Shipment Out For Delivery
  • Shipment Delivered
  • Shipment Exception

Registrar ações de usuários para compliance e debugging.

function logAudit(params: {
accountId: string
userId?: string
action: "create" | "update" | "delete" | "restore" | "login" | "export"
entityType: string
entityId?: string
changes?: Record<string, unknown>
ip?: string
})
  • Fire-and-forget: Usa createAdminClient() + .then() internamente
  • Nunca bloqueia: Chamado SEM await — não afeta latencia da response
  • Tabela: audit_logs (account_id, user_id, action, entity_type, entity_id, changes, ip_address)

Error
+-- AppError (code, statusCode, details)
|-- AuthError (401)
|-- NotFoundError (404)
|-- ValidationError (422)
|-- WhatsAppError (502)
+-- VPSError (502)
formatApiError(error)
-> AppError: { code, message, details }, status
-> ZodError: { code: "VALIDATION_ERROR", message, details: flatten() }, 422
-> Unknown: { code: "INTERNAL_ERROR", message: "Erro interno" }, 500
success<T>(data, status=200) // { data: T }
created<T>(data) // { data: T }, 201
noContent() // null, 204
error(err) // { error: { code, message } }, status
withErrorHandling(handler) // try/catch wrapper

NEXT_PUBLIC_SUPABASE_URL
NEXT_PUBLIC_SUPABASE_ANON_KEY
SUPABASE_SERVICE_ROLE_KEY
FACEBOOK_APP_ID
FACEBOOK_APP_SECRET
FACEBOOK_CONFIG_ID
WHATSAPP_VERIFY_TOKEN
ENCRYPTION_KEY
UPSTASH_REDIS_REST_URL
UPSTASH_REDIS_REST_TOKEN
VPS_API_URL
VPS_API_KEY
CRON_SECRET
PLATFORM_ADMIN_EMAILS
SHOPIFY_API_KEY
SHOPIFY_API_SECRET
NUVEMSHOP_APP_ID
NUVEMSHOP_APP_SECRET
YAMPI_CLIENT_ID
YAMPI_CLIENT_SECRET
# (Hotmart e Kiwify: webhook-only, sem keys de API)