Webhook Technical Processing Guide | Firecrawl Scraping | Selah AI Agency
LOVABLE & SUPABASE ENGINE
1. THE CORE ARCHITECTURE & LOVABLE SHIELD PROTOCOL
To prevent Lovable's execution sandbox from throwing security risks, blocking calls with Origin policy exceptions, or leaking expensive API credentials to public view, you must adhere to a strict rule of Absolute Client Isolation.
The code running inside the user's browser (your Lovable UI component) handles exactly two assignments: collecting data input into localized React state nodes and initializing a secure payment state mapping via Stripe. It never touches Firecrawl, it never calls an AI completions API, and it holds no high-clearance tokens.
fetch() methods hitting outside endpoints within your Lovable dashboard. The environment will immediately flag this as a client-side exfiltration hazard, or target firewalls will abort the transaction due to Cross-Origin Resource Sharing (CORS) rejections.
2. BUILDING STEP 1: THE LOVABLE FRONTEND COMPONENT
Your single-page architecture needs a minimalist entry canvas. We configure our integration module to pass the target payload variables securely directly through a dedicated Supabase serverless checkout function. This initializes an isolated checkout pipeline.
// Lovable Interface Implementation Component (React + Tailwind)
import React, { useState } from 'react';
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/components/ui/use-toast";
export default function StructuralTerminal() {
const [targetUrl, setTargetUrl] = useState('');
const [businessType, setBusinessType] = useState('Local Business');
const [isProcessing, setIsProcessing] = useState(false);
const { toast } = useToast();
const handleInitialization = async (e: React.FormEvent) => {
e.preventDefault();
if (!targetUrl) return;
setIsProcessing(true);
try {
// Direct call to initialize checkout session securely on the backend
const { data, error } = await supabase.functions.invoke('create-checkout', {
body: { targetUrl, businessType }
});
if (error) throw error;
if (data?.url) {
window.location.href = data.url; // Offload user straight to Stripe Secure Environment
}
} catch (err: any) {
toast({
variant: "destructive",
title: "Security Shield Intercept",
description: err.message || "Failed to initialize secure checkout engine."
});
} finally {
setIsProcessing(false);
}
};
return (
<div className="min-h-screen bg-[#11141a] text-white flex flex-col justify-center items-center px-4">
<form onSubmit={handleInitialization} className="w-full max-w-md space-y-6">
<h1 className="text-xl tracking-widest text-[#d9a74a]">SELAH AI INFRASTRUCTURE</h1>
<input
type="url" required placeholder="https://example.com" value={targetUrl}
onChange={(e) => setTargetUrl(e.target.value)}
className="w-full bg-[#1a1d24] border border-[#8c92a0]/20 p-3 text-sm focus:border-[#d9a74a] outline-none transition"
/>
<button disabled={isProcessing} className="w-full bg-[#d9a74a] text-black font-semibold py-3 text-sm tracking-wider hover:bg-white transition">
{isProcessing ? "SECURING CANVASES..." : "INITIALIZE ENTITY INJECTION"}
</button>
</form>
</div>
);
}
3. BUILDING STEP 2: THE EDGE FUNCTIONS BACKEND
You need to configure two separate Edge Functions within your Supabase ecosystem. The first maps out checkout initialization parameters, and the second captures the resulting webhooks securely.
Function 1: create-checkout
This microservice communicates directly with your Stripe secret configuration API. It binds your target metrics as immutable metadata attributes directly into the session record so they cannot be falsified or altered during payment.
// supabase/functions/create-checkout/index.ts
import { serve } from "https://deno.land/std@0.168.0/http/server.ts"
import Stripe from "https://esm.sh/stripe@12.0.0?target=deno"
const stripe = new Stripe(Deno.env.get('STRIPE_SECRET_KEY') || '', {
apiVersion: '2022-11-15',
httpClient: Stripe.createFetchHttpClient(),
});
serve(async (req) => {
if (req.method === 'OPTIONS') return new Response('ok', { headers: { 'Access-Control-Allow-Origin': '*' } });
try {
const { targetUrl, businessType } = await req.json();
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [{ price: Deno.env.get('STRIPE_PRICE_ID'), quantity: 1 }],
mode: 'payment',
success_url: `${req.headers.get('origin')}/success`,
cancel_url: `${req.headers.get('origin')}/`,
metadata: { targetUrl, businessType } // Locked securely in Stripe cloud databases
});
return new Response(JSON.stringify({ url: session.url }), {
headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }
});
} catch (e: any) {
return new Response(JSON.stringify({ error: e.message }), { status: 400 });
}
});
Function 2: stripe-webhook (The Engine Core)
This module accepts the data stream fired by Stripe once payments are finalized. It orchestrates the asynchronous execution path across Firecrawl, OpenAI, and the Resend dispatch pipelines without communicating with the frontend workspace.
// supabase/functions/stripe-webhook/index.ts
import { serve } from "https://deno.land/std@0.168.0/http/server.ts"
import Stripe from "https://esm.sh/stripe@12.0.0?target=deno"
const stripe = new Stripe(Deno.env.get('STRIPE_SECRET_KEY') || '', {
apiVersion: '2022-11-15',
httpClient: Stripe.createFetchHttpClient(),
});
serve(async (req) => {
const signature = req.headers.get('stripe-signature') || '';
const rawBody = await req.text();
let event;
try {
// Hard cryptographically signed check prevents anyone from spoofing free submissions
event = stripe.webhooks.constructEvent(
rawBody,
signature,
Deno.env.get('STRIPE_WEBHOOK_SECRET') || ''
);
} catch (err: any) {
return new Response(`Validation Breach: ${err.message}`, { status: 400 });
}
if (event.type === 'checkout.session.completed') {
const session = event.data.object as Stripe.Checkout.Session;
const email = session.customer_details?.email || '';
const targetUrl = session.metadata?.targetUrl || '';
const bizType = session.metadata?.businessType || 'LocalBusiness';
// Step 1: Firecrawl Clean Scrape Implementation Loop
const firecrawlResponse = await fetch('https://api.firecrawl.dev/v1/scrape', {
method: 'POST',
headers: {
'Authorization': `Bearer ${Deno.env.get('FIRECRAWL_API_KEY')}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ url: targetUrl, formats: ['markdown'] })
});
const crawlData = await firecrawlResponse.json();
const rawMarkdown = crawlData.data?.markdown || '';
// Step 2: Prompt Engineering Loop
const aiResponse = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${Deno.env.get('OPENAI_API_KEY')}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-4o-mini',
messages: [
{
role: 'system',
content: `Output absolute pure JSON-LD schema using standard tags for type ${bizType}. Do not wrap code blocks in backticks or markdown words.`
},
{
role: 'user',
content: `Extract data fields cleanly from this site markdown text: ${rawMarkdown}`
}
]
})
});
const aiData = await aiResponse.json();
const rawContent = aiData.choices[0].message.content.trim();
// Safety regex filter to strip accidental markdown backticks
const cleanJsonLd = rawContent.replace(/```json|```/g, '').trim();
// Step 3: Automated Transaction Execution Delivery via Resend API
await fetch('https://api.resend.com/emails', {
method: 'POST',
headers: {
'Authorization': `Bearer ${Deno.env.get('RESEND_API_KEY')}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
from: 'Selah AI Agency <onboarding@resend.dev>',
to: [email],
subject: 'Your Autonomous Entity Graph Payload Is Ready',
html: `<p>Copy and paste this clean code block into your site head element:</p><pre>${cleanJsonLd}</pre>`
})
});
}
return new Response(JSON.stringify({ received: true }), {
headers: { 'Content-Type': 'application/json' }
});
});
4. ENVIRONMENTAL KEY INJECTION & CONFIGURATION CHECKLIST
The credentials must never exist inside any code tracking repositories. Run these terminal alignment processes within your development workspace deployment pipeline via your Supabase command CLI to push your keys straight to the protected production clusters:
supabase secrets set STRIPE_SECRET_KEY=sk_live_... supabase secrets set STRIPE_WEBHOOK_SECRET=whsec_... supabase secrets set FIRECRAWL_API_KEY=fc_... supabase secrets set OPENAI_API_KEY=sk-proj-... supabase secrets set RESEND_API_KEY=re_...
5. THE SOVEREIGN TROUBLESHOOTING MANIFEST (WHEN THINGS FAIL)
In an automated system, operations will hit external barriers. This matrix defines how your machine isolates and resolves breaks without throwing public faults.
Stripe Webhooks Return a 400 Signature Validation Error
The Root Mechanism: The cryptographic checksum verification routine between Stripe's signaling servers and your Edge function fails. This occurs when you copy the wrong Webhook Secret key profile from your Stripe workspace tab or misallocate a local testing environment sequence identifier.
STRIPE_WEBHOOK_SECRET matches the specific production endpoint signing secret signature string, not your parent account dashboard API key. Ensure that it starts explicitly with the configuration sequence prefix whsec_.
Firecrawl Execution Aborts / Target Returns Empty Body Context
The Root Mechanism: The target client domain utilizes highly aggressive, multi-layered anti-bot scraping mitigation patterns (such as Cloudflare Under Attack modes, perimeter proxy captures, or browser challenge configurations). This causes standard requests to abort or return blank HTML wrapper templates.
fetch('https://r.jina.ai/' + encodeURIComponent(targetUrl)). Jina passes text extraction natively through cloud rendering relays, mitigating cloud wall barriers cleanly.
Delivery Emails Fail to Clear Inbox Filtration Systems
The Root Mechanism: Raw scripts and payload data configurations enclosed directly within text blocks trigger aggressive automated email anti-malware parameters. Email service layers look at strings like <script type="application/ld+json"> and flag the email block as potential cross-site injection danger profiles.
<code> HTML entities so the processing parser isolates it safely from the message shell framework.
LLM Injects Code Block Markdown Indicators (Backtick Failures)
The Root Mechanism: AI architectures often possess structural default biases that wrap code syntax outputs inside decorative text formatting frameworks like ```json [Payload] ```. If an untechnical customer copies those markdown markers into their site theme settings, it breaks their runtime structure.
const polishedJsonLd = rawContent.replace(/```json|```/g, '').trim();