- Implemented a bash script to test n8n API and retrieve credential schemas. - Added types for API responses, Google Calendar, and WhatsApp instances. - Configured Vitest for testing with React and added setup for testing-library.
5.2 KiB
5.2 KiB
Setup Google OAuth - Guia Rápido
1. Variáveis de Ambiente (.env.local)
# Google OAuth (copie do n8n)
NEXT_PUBLIC_GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=your-client-secret
# n8n
N8N_BASE_URL=https://n8n.automatizase.com.br
N8N_OAUTH_URL_WEBHOOK=https://n8n.automatizase.com.br/webhook/google-calendar-oauth-url
NEXT_PUBLIC_N8N_CREDENTIAL_ID=ccTThTS9TKsejR7W
# Site (localhost em dev, domínio em prod)
NEXT_PUBLIC_SITE_URL=http://localhost:3000
# Supabase
NEXT_PUBLIC_SUPABASE_URL=your-supabase-url
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
2. Google Cloud Console - Redirect URIs
Desenvolvimento
http://localhost:3000/api/google-calendar/callback
https://n8n.automatizase.com.br/rest/oauth2-credential/callback
Produção
https://dashboard.automatizase.com.br/api/google-calendar/callback
https://n8n.automatizase.com.br/rest/oauth2-credential/callback
3. Onde Encontrar as Credenciais
Client ID e Client Secret (Google)
- Acesse n8n → Credentials
- Abra a credencial "Google Calendar OAuth2"
- Copie
Client IDeClient Secret
N8N Webhook (OAuth URL Generator)
Você precisa criar um workflow no n8n que gera a oauth_url.
Documentação completa: docs/n8n-webhook-oauth-url.md
Resumo rápido:
- Crie um workflow no n8n
- Adicione um Webhook trigger com path
/webhook/google-calendar-oauth-url - Adicione um Code node que gera o state + oauth_url (veja doc)
- Adicione um Respond to Webhook que retorna
{ oauthUrl: "..." } - Ative o workflow
Credential ID (n8n)
Via URL:
- No n8n, abra a credencial Google Calendar OAuth2
- URL será:
https://n8n.automatizase.com.br/credentials/ccTThTS9TKsejR7W - O ID é:
ccTThTS9TKsejR7W
Via curl:
# Listar credenciais usando API Key
curl https://n8n.automatizase.com.br/api/v1/credentials \
-H "X-N8N-API-KEY: n8n_api_xxxxx"
# Procurar pelo type: "googleCalendarOAuth2Api"
# Copiar o "id" da credencial
4. Tabela Supabase
-- Criar schema (se não existir)
CREATE SCHEMA IF NOT EXISTS portal;
-- Criar tabela
CREATE TABLE IF NOT EXISTS portal.integrations (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
provider VARCHAR(50) NOT NULL,
status VARCHAR(20) NOT NULL,
connected_at TIMESTAMPTZ,
updated_at TIMESTAMPTZ DEFAULT NOW(),
metadata JSONB,
UNIQUE(user_id, provider)
);
-- Criar índice
CREATE INDEX IF NOT EXISTS idx_integrations_user_provider
ON portal.integrations(user_id, provider);
5. Testar o Fluxo
- Inicie o servidor:
npm run dev - Acesse:
http://localhost:3000/dashboard - Clique em "Conectar Google Calendar"
- Autorize no Google
- Verifique no Supabase:
SELECT * FROM portal.integrations WHERE provider = 'google_calendar';
6. Troubleshooting
Erro: redirect_uri_mismatch
- Verifique se adicionou AMBAS as URIs no Google Cloud Console
- Use
http(não https) para localhost
Erro: Invalid state format
- Certifique-se que o
NEXT_PUBLIC_N8N_CREDENTIAL_IDestá correto - Verifique os logs no console do navegador
Erro: Missing environment variables
- Verifique se todas as variáveis do
.env.localestão configuradas - Reinicie o servidor após alterar
.env.local
Erro: Unauthorized ou Failed to generate OAuth URL (n8n)
- Verifique se o workflow do n8n está ativo
- Teste o webhook manualmente:
curl https://n8n.automatizase.com.br/webhook/google-calendar-oauth-url?callbackUrl=http://localhost:3000/api/google-calendar/callback - Veja: docs/n8n-webhook-oauth-url.md
Erro: Failed to save in Supabase
- Verifique se a tabela
portal.integrationsexiste - Verifique as permissões do usuário no Supabase
7. Fluxo Completo
Dashboard → GET /api/google-calendar/auth
↓
n8n gera oauth_url com state criptografado
↓
Dashboard modifica redirect_uri e redireciona
↓
Usuário autoriza no Google
↓
Google → http://localhost:3000/api/google-calendar/callback
↓
Dashboard salva no Supabase
↓
Dashboard → https://n8n.automatizase.com.br/rest/oauth2-credential/callback
↓
n8n processa OAuth e salva tokens
↓
Sucesso! ✅
8. Documentação Completa
- Fluxo detalhado: docs/qa/fluxo-final-google-oauth.md
- Configuração redirect URIs: docs/qa/google-oauth-redirect-uris.md
- Erro Invalid state format: docs/qa/erro-invalid-state-format.md
9. Checklist
- Criar workflow no n8n para gerar oauth_url (veja docs/n8n-webhook-oauth-url.md)
- Ativar workflow no n8n
- Testar webhook:
curl https://n8n.automatizase.com.br/webhook/google-calendar-oauth-url?callbackUrl=test - Configurar
.env.localcom todas as variáveis (incluindoN8N_OAUTH_URL_WEBHOOK) - Adicionar redirect URIs no Google Cloud Console
- Criar tabela
portal.integrationsno Supabase - Reiniciar servidor Next.js (
npm run dev) - Testar fluxo OAuth completo
- Verificar se dados são salvos no Supabase
- Verificar se credencial é atualizada no n8n