import { NextRequest, NextResponse } from 'next/server'; import { handleGHLWebhook, GHLWebhookPayload } from '@/lib/ghl/webhook-handler'; import { settingsService } from '@/lib/settings'; import crypto from 'crypto'; // Verify webhook signature from GHL async function verifyWebhookSignature( body: string, signature: string | null, secret: string ): Promise { if (!signature || !secret) return false; const expectedSignature = crypto .createHmac('sha256', secret) .update(body) .digest('hex'); return crypto.timingSafeEqual( Buffer.from(signature), Buffer.from(expectedSignature) ); } export async function POST(request: NextRequest) { try { const body = await request.text(); const signature = request.headers.get('x-ghl-signature'); // Optional: Verify signature if webhook secret is configured const ghlWebhookSecret = await settingsService.get('ghlWebhookSecret'); if (ghlWebhookSecret) { const isValid = await verifyWebhookSignature(body, signature, ghlWebhookSecret); if (!isValid) { console.error('[Webhook] Invalid signature'); return NextResponse.json({ error: 'Invalid signature' }, { status: 401 }); } } const payload: GHLWebhookPayload = JSON.parse(body); const result = await handleGHLWebhook(payload); return NextResponse.json(result); } catch (error) { console.error('[Webhook] Error:', error); return NextResponse.json({ error: 'Webhook processing failed' }, { status: 500 }); } } // GHL may send GET requests to verify webhook URL export async function GET(request: NextRequest) { return NextResponse.json({ status: 'ok', message: 'Webhook endpoint active' }); }