SEO vs. GEO | The Future of Search
Discover why GEO (Generative Engine Optimization) is replacing traditional SEO. Learn how to rank for AI citations with Induji Technologies - Request a Quote today!
Induji Technical Team
Induji Technical Team
Content Strategy
For years, B2B marketers have been told a simple story: run ads, generate leads, and hand them to sales. Success was measured in volume and Cost Per Lead (CPL). But in 2026, this model is fundamentally broken. It operates on lagging indicators, creates massive data silos between marketing and sales, and often sails dangerously close to non-compliance with new data privacy laws like India's Digital Personal Data Protection (DPDP) Act.
The critical question isn't "How many leads did we generate?" but "Which ad campaigns generated the most revenue?" Answering this requires a direct line of sight from the initial ad click to a "Closed-Won" deal in your Enterprise Resource Planning (ERP) system. Without this connection, you're flying blind, optimizing ad spend on campaigns that generate low-quality leads while potentially starving campaigns that attract your most profitable customers.
This is where a closed-loop performance engine comes in. It's not just an integration; it's a strategic architectural shift. This blueprint details how to build a robust, scalable, and DPDP-compliant system connecting Meta's powerful Lead Ads platform directly to your ERPNext instance, using Next.js 15 as the intelligent, server-side glue.
The goal is to create a seamless, automated, and bidirectional data flow. Leads flow in, and high-value conversion signals flow back out, creating a self-optimizing marketing loop.
Here’s a step-by-step breakdown of the data journey:
Lead Capture & DPDP Consent: A user on Facebook or Instagram sees your B2B ad and opens the Lead Ad form. The form must include a link to your privacy policy and custom disclaimer text outlining data processing purposes, forming the basis for explicit consent under the DPDP Act. When the user submits, Meta captures the form data along with critical identifiers like ad_id, form_id, and lead_id.
Real-time Ingestion via Webhooks: Instantly upon submission, Meta's server sends an HTTP POST request (the webhook) to your designated Next.js 15 API Route endpoint. The payload contains all the lead information.
Secure Processing in Next.js: The Next.js API route first validates the webhook's authenticity by checking its X-Hub-Signature. This prevents fraudulent requests. It then parses the lead data, extracts the user-provided information, and constructs an object ready for the ERP. The consent obtained is treated as a first-class piece of data.
ERPNext Lead Creation: The Next.js middleware makes a secure, authenticated REST API call to your ERPNext instance. It creates a new Lead doctype, populating the standard fields (name, email, company). Critically, it also populates custom fields you've created:
meta_lead_id (String)meta_form_id (String)meta_ad_id (String)dpdp_consent_status (Select: Granted)dpdp_consent_timestamp (Datetime)The "Offline" Sales Journey: Your sales team takes over. They engage with the lead entirely within ERPNext. The lead progresses through your defined pipeline stages: Open → Replied → Opportunity → Quotation. Eventually, the opportunity is marked as either Lost or Won. This entire journey is "offline" from Meta's perspective.
Triggering the Conversion Feedback Loop: This is where the magic happens. You configure a webhook in ERPNext to trigger on a specific event, for example, when an Opportunity doctype linked to a Lead from Meta is updated with a status of Won. When this happens, ERPNext fires its own webhook, sending a payload containing details of the deal (including its value) to a second Next.js API Route.
Formatting and Sending Data via Meta CAPI: This second Next.js endpoint receives the ERPNext webhook. It uses the meta_lead_id (which was stored in step 4) to retrieve the original lead's contact information. It then formats a server-side event payload for the Meta Conversions API.
Purchase (or a custom conversion for QualifiedOpportunity)value (the deal amount from ERPNext) and currency.system_generated.Closing the Loop: Meta receives this high-value conversion signal. Its algorithm now knows that the specific combination of audience, creative, and placement that generated this lead resulted in actual revenue. It uses this data to optimize future ad delivery, prioritizing users who resemble your most profitable customers.
Retrofitting compliance is expensive and risky. This architecture integrates the principles of the DPDP Act from the ground up.
Your Meta Lead Ad form is not just a lead capture tool; it's a consent capture mechanism.
dpdp_consent_status field in your ERPNext Lead doctype, you create an auditable record of consent. This is your proof of compliance and a flag for your sales team on how they can interact with the lead.The DPDP Act grants individuals rights over their data. Your architecture must support this.
Lead and associated records in ERPNext. This action can be configured to fire a final webhook to a dedicated Next.js endpoint, which would then call Meta's Marketing API to request the deletion of the user data associated with that lead on their platform, fulfilling your obligation.Let's look at some code concepts for the key middleware components.
This route lives in app/api/meta-webhook/route.ts. It needs to handle both the verification request and the actual lead data.
// app/api/meta-webhook/route.ts
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';
const ERPNEXT_API_URL = process.env.ERNEXT_API_URL!;
const ERPNEXT_API_KEY = process.env.ERNEXT_API_KEY!;
const ERPNEXT_API_SECRET = process.env.ERNEXT_API_SECRET!;
const META_VERIFY_TOKEN = process.env.META_VERIFY_TOKEN!;
const META_APP_SECRET = process.env.META_APP_SECRET!;
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const mode = searchParams.get('hub.mode');
const token = searchParams.get('hub.verify_token');
const challenge = searchParams.get('hub.challenge');
if (mode === 'subscribe' && token === META_VERIFY_TOKEN) {
return new NextResponse(challenge, { status: 200 });
} else {
return new NextResponse('Forbidden', { status: 403 });
}
}
export async function POST(req: NextRequest) {
const signature = req.headers.get('x-hub-signature-256');
const bodyText = await req.text();
if (!signature) {
return new NextResponse('Signature required', { status: 400 });
}
// Validate the payload
const hmac = crypto.createHmac('sha256', META_APP_SECRET);
hmac.update(bodyText);
const expectedSignature = `sha256=${hmac.digest('hex')}`;
if (signature !== expectedSignature) {
console.warn('Invalid signature');
return new NextResponse('Invalid signature', { status: 403 });
}
const body = JSON.parse(bodyText);
const leadgen_data = body.entry[0].changes[0].value;
// Extract lead data
const leadData = {
lead_name: leadgen_data.field_data.find(f => f.name === 'full_name')?.values[0] || 'N/A',
email_id: leadgen_data.field_data.find(f => f.name === 'email')?.values[0],
// ... other fields
meta_lead_id: leadgen_data.leadgen_id,
meta_form_id: leadgen_data.form_id,
dpdp_consent_status: 'Granted', // Assuming form implies consent
dpdp_consent_timestamp: new Date().toISOString(),
};
// POST to ERPNext
try {
const response = await fetch(`${ERPNEXT_API_URL}/api/resource/Lead`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `token ${ERPNEXT_API_KEY}:${ERPNEXT_API_SECRET}`
},
body: JSON.stringify(leadData)
});
if(!response.ok) throw new Error('Failed to create lead in ERPNext');
return new NextResponse('Lead processed successfully', { status: 200 });
} catch (error) {
console.error('ERPNext API Error:', error);
return new NextResponse('Internal Server Error', { status: 500 });
}
}
This second API route (app/api/erpnext-webhook/route.ts) receives data from ERPNext when a deal is won.
// app/api/erpnext-webhook/route.ts
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';
const META_PIXEL_ID = process.env.META_PIXEL_ID!;
const META_CAPI_TOKEN = process.env.META_CAPI_TOKEN!;
// Function to hash data for Meta CAPI
const hash = (data: string) => crypto.createHash('sha256').update(data).digest('hex');
export async function POST(req: NextRequest) {
const dealData = await req.json();
// NOTE: Add validation to ensure the request is from ERPNext
// This can be a simple secret header check.
const eventData = {
event_name: 'Purchase',
event_time: Math.floor(Date.now() / 1000),
action_source: 'system_generated',
user_data: {
em: [hash(dealData.email_id.toLowerCase())], // Hashed Email
// ... other hashed user data if available
},
custom_data: {
value: dealData.opportunity_amount,
currency: 'INR',
},
// Optionally add event_id for deduplication
// event_id: dealData.name // e.g., using the Opportunity ID
};
const payload = {
data: [eventData],
// test_event_code: 'TEST_CODE' // Use for testing
};
try {
await fetch(`https://graph.facebook.com/v19.0/${META_PIXEL_ID}/events?access_token=${META_CAPI_TOKEN}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
return new NextResponse('Conversion event sent', { status: 200 });
} catch (error) {
console.error('Meta CAPI Error:', error);
return new NextResponse('Internal Server Error', { status: 500 });
}
}
This closed-loop system fundamentally changes how you measure success.
Meta's algorithm, now fueled by revenue data, gets smarter. It starts to identify patterns among the users who become high-value customers and actively seeks more of them, dramatically improving the efficiency of your ad budget.
Q1: Why use Next.js as middleware? Why not a simpler serverless function or a no-code tool like Zapier? A: While no-code tools are great for simple integrations, a Next.js application offers superior control, security, and scalability. You can implement robust validation (like HMAC signature checking), complex business logic (data enrichment), custom error handling, and manage secrets securely. It provides a dedicated, version-controlled codebase that is far more maintainable and extensible for enterprise needs than a chain of no-code actions.
Q2: How do I handle lead matching between the event in ERPNext and the original user in Meta? A: The matching is handled by the PII you send in the Conversions API call. When you send the hashed email address and/or phone number, Meta matches this against the user who originally interacted with your ad. This is why it's critical to store the lead's PII accurately in ERPNext and pass it back in the CAPI call.
Q3: What are the security implications of exposing API endpoints for webhooks? A: Security is paramount.
x-hub-signature-256 from Meta) to ensure the request is authentic.Q4: Can this architecture handle high volumes of leads? A: Yes. The architecture is inherently scalable. Meta's webhooks are designed for high throughput. A Next.js application deployed on a modern serverless platform like Vercel or AWS Lambda can scale horizontally to handle virtually any number of incoming requests. ERPNext, when properly configured on robust infrastructure, can also handle a high volume of API writes.
Q5: How does this differ from just uploading a CSV of offline conversions? A: Manual CSV uploads are slow, error-prone, and not real-time. This automated, webhook-driven architecture provides conversion data to Meta in near real-time. This allows Meta's algorithm to optimize your campaigns intra-day, reacting quickly to performance signals rather than waiting for a weekly or monthly manual upload. The feedback loop is faster, leading to much more efficient ad spend.
Stop guessing which marketing efforts drive revenue. By implementing a closed-loop, DPDP-compliant architecture, you transform your B2B marketing from a speculative cost center into a predictable, data-driven revenue engine. This is the future of performance marketing—a fusion of intelligent automation, robust system design, and unwavering respect for data privacy.
Induji Technologies specializes in architecting these complex, high-performance data pipelines. Our expert team of DevOps engineers and developers can build the custom solution that connects your ad platforms to your core business systems, ensuring compliance and maximizing your return on investment.
Ready to build a true B2B performance engine? Request a consultation with our technical architects today.
Discover why GEO (Generative Engine Optimization) is replacing traditional SEO. Learn how to rank for AI citations with Induji Technologies - Request a Quote today!
Induji Technical Team
Learn how to get your brand cited in ChatGPT Search. Follow our 7-step guide to AI Engine Optimization (AIEO) for 31% higher conversion rates.
Induji Technical Team
Discover why AEO is the new SEO. Learn how to optimize for AI answer engines like ChatGPT and Google SGE with Induji - Request a Quote!
Induji Technical Team
Partner with Induji Technologies to leverage cutting-edge solutions tailored to your unique challenges. Let's build something extraordinary together.