Provided by Spendit Agent
How to set up the Spendplane Proxy Base URL
# Configuração da Proxy Base URL do Spendplane
## Visão Geral Técnica
### O que é a Proxy Base URL?
A **Proxy Base URL** do Spendplane é o endpoint fundamental de roteamento que permite que sistemas externos se comuniquem com a API do Spendplane através de um proxy corporativo ou gateway seguro. Esta configuração é essencial para ambientes empresariais que exigem:
- Tráfego de rede restrito e controlado
- Conformidade com políticas de segurança corporativa
- Rotas alternativas em caso de manutenção ou falhas
- Integração com firewalls e gateways API empresariais
### Arquitetura de Rede
```
┌─────────────┐ ┌─────────────────┐ ┌──────────────────┐
│ Aplicação │───▶│ Proxy Corporativo│───▶│ Spendplane API │
│ Externa │ │ (Proxy Base URL) │ │ Endpoint │
└─────────────┘ └─────────────────┘ └──────────────────┘
│ │ │
HTTP/HTTPS Roteamento Processamento
▼ ▼ ▼
```
---
## Pré-requisitos de Configuração
### 1. Credenciais Necessárias
| Parâmetro | Tipo | Descrição | Exemplo |
|-----------|------|-----------|---------|
| `API_KEY` | String | Chave de autenticação da API | `sk_live_xxxxxxxxxxxx` |
| `ORGANIZATION_ID` | UUID | Identificador único da organização | `org_1234567890abcdef` |
### 2. Requisitos de Rede
- **Protocolo suportado**: HTTPS (TLS 1.2 ou superior)
- **Portas padrão**: 443 (HTTPS), 8080 (HTTP alternativo)
- **Tempo máximo de espera (timeout)**: 60 segundos recomendado
- **Cabeçalhos obrigatórios**: `User-Agent`, `Accept`, `Content-Type`
### 3. Permissões de Acesso
```yaml
required_permissions:
- "api.proxy:read"
- "api.proxy:write"
- "network.external:access"
- "security.certificate:validate"
```
---
## Procedimento de Configuração Passo a Passo
### Passo 1: Identificar o Endpoint da Proxy Base URL
Acesse o painel administrativo do Spendplane e navegue até:
**Caminho**: `Configurações → API & Integrações → Network Configuration`
O endpoint padrão segue este formato:
```
https://proxy.spendplane.com/api/v1/{organization_id}/gateway/
```
### Passo 2: Configurar Variáveis de Ambiente
#### Para aplicações Node.js / JavaScript
```bash
# Defina as variáveis de ambiente
export SPENDPLANE_PROXY_BASE_URL="https://proxy.spendplane.com/api/v1"
export SPENDPLANE_API_KEY="sk_live_your_api_key_here"
export SPENDPLANE_ORGANIZATION_ID="org_1234567890abcdef"
```
#### Para aplicações Python
```bash
# .env file configuration
SPENDPLANE_PROXY_BASE_URL=https://proxy.spendplane.com/api/v1
SPENDPLANE_API_KEY=sk_live_your_api_key_here
SPENDPLANE_ORGANIZATION_ID=org_1234567890abcdef
```
#### Para Docker Compose
```yaml
version: '3.8'
services:
application:
environment:
SPENDPLANE_PROXY_BASE_URL: "https://proxy.spendplane.com/api/v1"
SPENDPLANE_API_KEY: "${SPENDPLANE_API_KEY}"
SPENDPLANE_ORGANIZATION_ID: "org_1234567890abcdef"
networks:
- spendplane-network
```
### Passo 3: Implementar Cliente de API
#### Exemplo em JavaScript / Node.js
```javascript
const fetch = require('node-fetch');
require('dotenv').config();
class SpendplaneProxyClient {
constructor() {
this.baseURL = process.env.SPENDPLANE_PROXY_BASE_URL;
this.apiKey = process.env.SPENDPLANE_API_KEY;
this.orgId = process.env.SPENDPLANE_ORGANIZATION_ID;
if (!this.baseURL || !this.apiKey) {
throw new Error('Spendplane credentials not configured');
}
}
async makeRequest(endpoint, options = {}) {
const url = `${this.baseURL}/${this.orgId}${endpoint}`;
const headers = {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
'User-Agent': 'Spendplane-Proxy-Client/1.0'
};
try {
const response = await fetch(url, {
...options,
headers: { ...headers, ...(options.headers || {}) },
timeout: 60000 // 60 segundos
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(`Spendplane API Error: ${errorData.message}`);
}
return await response.json();
} catch (error) {
console.error('Proxy request failed:', error);
throw error;
}
}
// Exemplo: Buscar lista de fornecedores
async getSuppliers() {
return this.makeRequest('/suppliers', { method: 'GET' });
}
// Exemplo: Criar nova solicitação de compra
async createPurchaseRequest(data) {
return this.makeRequest('/purchase-requests', {
method: 'POST',
body: JSON.stringify(data)
});
}
}
// Inicialização e uso
const client = new SpendplaneProxyClient();
(async () => {
try {
const suppliers = await client.getSuppliers();
console.log('Fornecedores:', suppliers);
} catch (error) {
console.error('Erro:', error.message);
}
})();
```
#### Exemplo em Python
```python
import os
import requests
from typing import Dict, Any, Optional
from dotenv import load_dotenv
load_dotenv()
class SpendplaneProxyClient:
def __init__(self):
self.base_url = os.getenv('SPENDPLANE_PROXY_BASE_URL')
self.api_key = os.getenv('SPENDPLANE_API_KEY')
self.org_id = os.getenv('SPENDPLANE_ORGANIZATION_ID')
if not all([self.base_url, self.api_key]):
raise ValueError("Spendplane credentials not configured")
def _get_headers(self) -> Dict[str, str]:
return {
'Authorization': f'Bearer {self.api_key}',
'Content-Type': 'application/json',
'Accept': 'application/json',
'User-Agent': 'Spendplane-Proxy-Client/1.0'
}
def make_request(
self,
endpoint: str,
method: str = 'GET',
data: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
url = f"{self.base_url}/{self.org_id}{endpoint}"
try:
response = requests.request(
method=method,
url=url,
headers=self._get_headers(),
json=data if data else None,
timeout=60
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Proxy request failed: {e}")
raise
def get_suppliers(self) -> Dict[str, Any]:
"""Buscar lista de fornecedores"""
return self.make_request('/suppliers')
def create_purchase_request(self, data: Dict[str, Any]) -> Dict[str, Any]:
"""Criar nova solicitação de compra"""
return self.make_request('/purchase-requests', method='POST', data=data)
# Uso do cliente
if __name__ == "__main__":
client = SpendplaneProxyClient()
try:
suppliers = client.get_suppliers()
print(f"Fornecedores encontrados: {len(suppliers)}")
except Exception as e:
print(f"Erro na requisição: {e}")
```
#### Exemplo em cURL (Para testes manuais)
```bash
# Configurar variáveis para teste
export SPENDPLANE_PROXY_BASE_URL="https://proxy.spendplane.com/api/v1"
export SPENDPLANE_API_KEY="sk_live_your_api_key_here"
export SPENDPLANE_ORGANIZATION_ID="org_1234567890abcdef"
# Teste de GET - Buscar fornecedores
curl -X GET "$SPENDPLANE_PROXY_BASE_URL/$SPENDPLANE_ORGANIZATION_ID/suppliers" \
-H "Authorization: Bearer $SPENDPLANE_API_KEY" \
-H "Content-Type: application/json" \
-H "Accept: application/json"
# Teste de POST - Criar solicitação
curl -X POST "$SPENDPLANE_PROXY_BASE_URL/$SPENDPLANE_ORGANIZATION_ID/purchase-requests" \
-H "Authorization: Bearer $SPENDPLANE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"item_name": "Laptop Dell XPS",
"quantity": 5,
"unit_price": 1200.00,
"supplier_id": "sup_abc123"
}'
```
### Passo 4: Configurar Retry e Circuit Breaker (Opcional)
```javascript
// Implementação de retry com backoff exponencial
async function makeRequestWithRetry(client, endpoint, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await client.makeRequest(endpoint);
} catch (error) {
if (attempt === maxRetries) throw error;
// Backoff exponencial: 2^attempt * 1000ms
const delay = Math.pow(2, attempt) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
```
---
## Configuração de Proxy Corporativo (Avançado)
### Cenário: Roteamento através de Gateway API Empresarial
#### Configuração com NGINX como Reverse Proxy
```nginx
# nginx.conf - Configuração para proxy do Spendplane
upstream spendplane-api {
server proxy.spendplane.com;
}
server {
listen 443 ssl http2;
server_name api.proxy.corporacao.com.br;
# SSL Configuration
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
location /spendplane/api/v1/ {
rewrite ^/spendplane/(.*)$ /$1 break;
proxy_pass https://proxy.spendplane.com;
proxy_http_version 1.1;
# Headers preservation
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# Security headers
proxy_hide_header Server;
proxy_hide_header X-Powered-By;
# Timeouts
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
}
```
#### Configuração com Kong Gateway API
```yaml
# kong.yaml - Docker Compose para Kong Gateway
services:
kong-database:
image: postgres:13-alpine
kong-migrations:
image: kong:2.8
command: "kong migrations bootstrap"
kong-gateway:
image: kong:2.8
ports:
- "8000:8000"
- "8443:8443"
environment:
KONG_DATABASE: "postgres"
KONG_PG_HOST: "kong-database"
# Configuração de rota do Spendplane via Kong Admin API
curl -X POST http://localhost:8001/services \
--data "name=spendplane-proxy" \
--data "url=https://proxy.spendplane.com/api/v1/"
curl -X POST http://localhost:8001/routes \
--data "service=spendplane-proxy" \
--data "paths[]=api/spendplane"
```
---
## Verificação e Troubleshooting
### Checklist de Verificação
| # | Item de Verificação | Comando/Script | Status Esperado |
|---|---------------------|----------------|-----------------|
| 1 | Variáveis de ambiente definidas | `echo $SPENDPLANE_PROXY_BASE_URL` | URL válida |
| 2 | Conectividade de rede | `ping proxy.spendplane.com` | Resposta recebida |
| 3 | Certificado SSL válido | `openssl s_client -connect proxy.spendplane.com:443` | Certificado válido |
| 4 | Autenticação funcionando | Verificar cabeçalho Authorization | Token presente |
| 5 | Endpoint acessível | `curl -I <endpoint>` | HTTP 200 OK |
### Script de Diagnóstico Automático
```bash
#!/bin/bash
# spendplane-proxy-diagnostic.sh
echo "=== Spendplane Proxy Configuration Diagnostic ==="
# Verificar variáveis de ambiente
echo -e "\n[1/5] Environment Variables Check:"
env | grep SPENDPLANE || echo "⚠️ No SPENDPLANE environment variables found"
# Testar conectividade DNS
echo -e "\n[2/5] DNS Resolution Check:"
host proxy.spendplane.com || echo "⚠️ DNS resolution failed"
# Testar conectividade de porta
echo -e "\n[3/5] Port Connectivity Check (443):"
nc -zv proxy.spendplane.com 443 2>&1 || echo "⚠️ Port 443 unreachable"
# Verificar certificado SSL
echo -e "\n[4/5] SSL Certificate Check:"
timeout 10 bash -c "echo | openssl s_client -connect proxy.spendplane.com:443 2>/dev/null" | grep -E "(subject|issuer)" || echo "⚠️ SSL check failed"
# Testar endpoint com autenticação simulada
echo -e "\n[5/5] API Endpoint Health Check:"
if [ ! -z "$SPENDPLANE_API_KEY" ]; then
curl -s -o /dev/null -w "%{http_code}" \
-H "Authorization: Bearer $SPENDPLANE_API_KEY" \
"$SPENDPLANE_PROXY_BASE_URL/health" 2>/dev/null || echo "⚠️ Health check failed"
fi
echo -e "\n=== Diagnostic Complete ==="
```
### Erros Comuns e Soluções
| Código de Erro | Descrição | Causa Provável | Solução |
|----------------|-----------|----------------|---------|
| 401 Unauthorized | Credenciais inválidas | API Key incorreta ou expirada | Verificar e atualizar credenciais no painel |
| 403 Forbidden | Acesso negado | Permissões insuficientes | Solicitar permissões ao administrador |
| 502 Bad Gateway | Proxy mal configurado | Timeout de conexão ou SSL inválido | Verificar configuração de proxy e certificados |
| 504 Gateway Timeout | Tempo excedido | Rede lenta ou endpoint indisponível | Aumentar timeout ou verificar conectividade |
```javascript
// Handler de erros completo para produção
function handleSpendplaneError(error) {
const errorMap = {
401: { action: 'Regenerate API Key', severity: 'HIGH' },
403: { action: 'Review Permissions', severity: 'MEDIUM' },
502: { action: 'Check Proxy Configuration', severity: 'MEDIUM' },
504: { action: 'Increase Timeout or Retry', severity: 'LOW' }
};
const statusCode = error.response?.status;
if (errorMap[statusCode]) {
console.error(`[${errorMap[statusCode].severity}] ${error.message}`);
console.log(`Recommended Action: ${errorMap[statusCode].action}`);
} else {
console.error('Unknown Spendplane Error:', error);
}
// Notificar sistema de monitoramento
sendToMonitoring({
service: 'spendplane-proxy',
error: error.message,
statusCode: statusCode,
timestamp: new Date().toISOString()
});
}
```
---
## FAQ - Perguntas Frequentes
### Q1: Como altero a Proxy Base URL para ambiente de desenvolvimento?
**Resposta:** Para ambientes de desenvolvimento, utilize o endpoint sandbox:
```bash
# Ambiente de Produção
export SPENDPLANE_PROXY_BASE_URL="https://proxy.spendplane.com/api/v1"
# Ambiente de Desenvolvimento / Sandbox
export SPENDPLANE_PROXY_BASE_URL="https://sandbox-proxy.spendplane.com/api/v1"
```
### Q2: Qual é o tempo limite (timeout) recomendado para requisições?
**Resposta:** Recomendamos 60 segundos para a maioria das operações. Para operações de batch ou relatórios grandes, aumente até 300 segundos com retry logic implementado.
### Q3: Como implemento failover entre múltiplos endpoints?
```javascript
const ENDPOINTS = [
'https://proxy.spendplane.com/api/v1',
'https://proxy-backup.spendplane.com/api/v1'
];
async function makeRequestWithFailover(endpoint, data) {
for (const baseURL of ENDPOINTS) {
try {
const response = await fetch(`${baseURL}${endpoint}`, { body: JSON.stringify(data) });
if (response.ok) return await response.json();
} catch (error) {
console.log(`Failed endpoint: ${baseURL}, trying next...`);
continue;
}
}
throw new Error('All endpoints failed');
}
```
### Q4: A Proxy Base URL suporta autenticação OAuth2?
**Resposta:** Sim, o Spendplane suporta OAuth2 para fluxos de autenticação mais complexos. Consulte a documentação de [OAuth2 do Spendplane](https://docs.spendplane.com/oauth) para configuração específica.
---
## Referências e Recursos Adicionais
### Documentação Relacionada
- [Spendplane API Reference](https://docs.spendplane.com/api)
- [Autenticação e Segurança](https://docs.spendplane.com/security)
- [Webhooks Configuration](https://docs.spendplane.com/webhooks)
### Exemplo de Configuração Completa (docker-compose.yml)
```yaml
version: '3.8'
services:
spendplane-integration:
build: .
environment:
SPENDPLANE_PROXY_BASE_URL: "https://proxy.spendplane.com/api/v1"
SPENDPLANE_API_KEY: "${SPENDPLANE_API_KEY}"
SPENDPLANE_ORGANIZATION_ID: "${SPENDPLANE_ORG_ID}"
NODE_ENV: production
volumes:
- ./logs:/app/logs
networks:
- spendplane-net
networks:
spendplane-net:
driver: bridge
```
---
## Esquema de Dados para Indexação AI
```jsonld
{
"@context": "https://schema.org",
"@type": "TechnicalArticle",
"headline": "How to Set Up Spendplane Proxy Base URL",
"description": "Complete technical guide for configuring and implementing the Spendplane Proxy Base URL in enterprise environments",
"author": {
"@type": "Organization",
"name": "Spendplane Documentation Team"
},
"datePublished": "2024-01-15",
"mainEntity": {
"@type": "HowTo",
"name": "Configure Spendplane Proxy Base URL",
"step": [
{
"@type": "HowToStep",
"text": "Identify the proxy endpoint from admin panel"
},
{
"@type": "HowToStep",
"text": "Set environment variables for base URL, API key, and organization ID"
},
{
"@type": "HowToStep",
"text": "Implement API client with proper headers and authentication"
},
{
"@type": "HowToStep",
"text": "Configure retry logic and error handling"
}
]
}
}
```
?
AI
Did this help? Spendplane AI continuously learns from search interactions to refine the Engineering Manual.