Meta Ads Conversions API (CAPI) Server-Side Tracking Webhook
Overview
This workflow provides a complete server-side endpoint for sending conversion events to the Meta (Facebook) Conversions API (CAPI). It solves the critical problem of ad tracking accuracy in an era where browser-based tracking is increasingly blocked by ad blockers, iOS privacy changes (ATT), and browser cookie restrictions. By sending conversion data directly from your server to Meta's servers, you bypass these client-side limitations and ensure your ad performance data remains reliable and complete.
The workflow receives incoming webhook data (typically from a website form submission or backend system), normalizes and hashes personally identifiable information (PII) using SHA-256 as required by Meta, structures the payload according to Meta's CAPI specifications, and sends it to the Graph API endpoint. It also returns a 200 response to the caller to confirm successful processing.
Workflow Steps
-
Webhook (No auth) — This is the trigger node that receives incoming HTTP POST requests. It listens on the path
/meta-conversion-apiand expects a JSON body with user data includingemail,phone,firstName,lastName,fbc, andfbp. The node is configured to respond using a separate "Respond to Webhook" node rather than automatically. -
Edit Normalize PII (No auth) — A Set node that cleans and normalizes incoming PII data. It trims whitespace, converts email and names to lowercase, and strips all non-digit characters from the phone number. This creates standardized fields (
normalized_email,normalized_phone,firstName,lastName) for consistent hashing. -
Crypto - Hash Email (No auth) — Uses SHA-256 hashing on the normalized email address. The result is stored in a field called
hashed_em, which is the format Meta expects for email identifiers. -
Crypto - Hash Phone (No auth) — Uses SHA-256 hashing on the normalized phone number. The result is stored in
hashed_ph, matching Meta's expected phone identifier format. -
Crypto - First Name (No auth) — Uses SHA-256 hashing on the normalized first name. The result is stored in
hashed_firstName, which will be mapped to Meta'sfnfield. -
Crypto - Last Name (No auth) — Uses SHA-256 hashing on the normalized last name. The result is stored in
hashed_lastName, which will be mapped to Meta'slnfield. -
Set - Compute Timestamps & Map Fields (No auth) — A Set node that assembles all the processed data into a unified object. It computes a Unix timestamp for the current time, hardcodes the event name as
SubmitApplication(configurable), and pulls together all hashed fields plus the originalfbc,fbp, IP address (fromx-forwarded-forheader), and user agent from the webhook headers. -
Preparing for HTTP Request Payload (No auth) — A Code node that transforms the flat data into Meta's required CAPI payload structure. It creates a
dataarray with an object containingevent_name,event_time,action_source(set towebsite), and auser_dataobject mapping the hashed fields to Meta's field names (fn,ln,em,ph,fbc,fbp,client_ip_address,client_user_agent). -
Sending Events To Facebook Pixel (Bearer Token auth) — An HTTP Request node that sends the final payload to Meta's Graph API endpoint at
https://graph.facebook.com/v24.0/PIXEL_ID_HERE/events. It uses Bearer Token authentication with a CAPI access token. The URL contains a placeholderPIXEL_ID_HEREthat must be replaced with the user's actual Meta Pixel ID. -
Respond to Webhook (No auth) — Returns a 200 HTTP response to the original webhook caller with the processed data, confirming successful delivery to Meta.
Setup Instructions
Prerequisites
- A Meta (Facebook) Pixel with Conversions API access
- A Meta CAPI Access Token generated from Events Manager
- An n8n instance (self-hosted or cloud) with webhook capability
- A website or backend system that can send HTTP POST requests
Configuration Steps
-
Copy the Webhook URL: Open the "Webhook" node and copy the Test URL (for testing) or Production URL (for live use). Configure your website form or backend to send a POST request to this URL with a JSON body containing the required fields.
-
Customize Event Name (Optional): In the "Set - Compute Timestamps & Map Fields" node, change the
event_namevalue fromSubmitApplicationto your desired event type (e.g.,Purchase,Lead,CompleteRegistration,AddToCart). -
Add Your Pixel ID: In the "Sending Events To Facebook Pixel" node, replace
PIXEL_ID_HEREin the URL with your actual Meta Pixel ID (a numeric string found in Meta Events Manager). -
Add Your Access Token: In the same node, go to the Authentication tab and create a new Bearer Token credential. Paste your CAPI Access Token (generated from Meta Events Manager > Settings > Conversions API > Generate Access Token).
-
Test the Workflow: Use a tool like Postman or curl to send a test POST request with sample data matching the pinned data structure on the Webhook node. Activate the workflow and verify you receive a 200 response with
events_received: 1.
Use Cases and Variations
Primary Use Cases
- Lead Generation Forms: Send lead form submissions from your website directly to Meta for better conversion attribution
- Purchase Tracking: Change the event name to
Purchaseand includevalueandcurrencyfields for revenue tracking - Add to Cart / Initiate Checkout: Track micro-conversions that indicate purchase intent
- Complete Registration: Track user signups that happen on your platform
Adaptation Ideas
- Add Value Tracking: Modify the Code node to include
event_source_url,value, andcurrencyfields for purchase events - Multiple Event Types: Add conditional logic to route different webhook payloads to different event names based on a field in the incoming data
- Error Handling: Add an error workflow or notification node (e.g., Slack, email) if the Meta API returns an error
- Data Enrichment: Add an HTTP Request node to look up additional user data from your CRM before sending to Meta
- Batch Events: Modify the Code node to accept an array of events in the webhook payload for batch processing
- Custom Action Sources: Change
action_sourcefromwebsitetoemail,app, orphone_calldepending on your conversion source
Workflow JSON
{
"id": "mXgQJT7qXMEFQAow",
"meta": {},
"name": "Server-Side Meta Ads Tracking Template [PUBLIC]",
"tags": [],
"nodes": [
{
"id": "de88e89c-acfd-4592-8f73-0f1b56dba93b",
"name": "Edit Normalize PII",
"type": "n8n-nodes-base.set",
"position": [
-752,
0
],
"parameters": {
"options": {},
"assignments": {
"assignments": [
{
"id": "9545094c-a24a-4689-b212-4bc351f8f08b",
"name": "normalized_email",
"type": "string",
"value": "={{ $json.body.email.trim().toLowerCase() }}"
},
{
"id": "fe26118b-5e9e-4c3f-acf0-e995a32779d1",
"name": "normalized_phone",
"type": "string",
"value": "={{ $json.body.phone.replace(/\\D/g, '') }}"
},
{
"id": "59a2b784-44c4-44c4-bf28-2e8a27cc8975",
"name": "firstName",
"type": "string",
"value": "={{ $json.body.firstName.trim().toLowerCase() }}"
},
{
"id": "72ada7ed-e895-445e-ac4f-f5d8102ba46a",
"name": "lastName",
"type": "string",
"value": "={{ $json.body.lastName.trim().toLowerCase() }}"
}
]
}
},
"typeVersion": 3.4
},
{
"id": "cf2debc3-7cc0-450f-9e58-9b981333c537",
"name": "Crypto - Hash Email",
// ... truncated (copy to see full JSON)How to Import This Workflow
- 1Copy the workflow JSON above using the Copy Workflow JSON button.
- 2Open your n8n instance and go to Workflows.
- 3Click Import from JSON and paste the copied workflow.
Don't have an n8n instance? Start your free trial at n8nautomation.cloud
Related Templates
Product Video Generator using AI
Overview This workflow automatically generates personalized, cinematic-quality product videos by combining competitor ad intelligence from Foreplay, creative prompt generation with Google Gemini AI, and text-to-video generation via Kie.ai (Sora 2). It's designed for marketers, brand managers, and content creators who want to produce high-quality video ads quickly without manual scripting or editing. The workflow fetches product images from Google Drive, analyzes competitor video ads from Foreplay, uses Gemini to craft optimized video prompts, generates videos through Kie.ai, and automatically saves the finished videos back to Google Drive. Workflow Steps Manual Trigger (No auth) — Starts the workflow manually for testing or on-demand video generation. Set Workflow Credentials (No auth) — Configures environment variables including Google Drive folder IDs, Foreplay API base URL, API key, and brand ID. These values are referenced throughout the workflow. Set Product Information (No auth) — Defines the product details: name (e.g., "Homyped"), niche (e.g., "fashion"), category (e.g., "shoes"), and target market (e.g., "b2c"). These parameters drive the entire video generation process. Fetch Product Image from Google Drive (OAuth2) — Retrieves the first image file from a specified Google Drive folder. Uses the folder ID set in step 2. Fetch Competitor Video Data (Foreplay API) (Bearer Token auth) — Calls the Foreplay API to get competitor ad data filtered by brand ID, date range (last month), niche, target market, language (English), video duration (5-30 seconds), and platform (Instagram). Returns the top 5 longest-running video ads. Split Foreplay Response (No auth) — Splits the Foreplay API response array into individual items for processing each competitor ad example. Assemble Video Input Data (No auth) — Combines competitor ad data (description, transcript, emotional drivers, duration) with the product image URL into a structured format for prompt generation. Iterate Over Ad Examples (No auth) — Processes each competitor ad example one at a time in batches, allowing the workflow to generate multiple video prompts and videos sequentially. Generate Video Prompt (No auth) — Uses Google Gemini AI (connected via the Google Gemini LLM node) to generate a personalized, cinematic-quality text prompt for video generation. The prompt incorporates product information, competitor ad details, emotional tone, and target duration. Google Gemini LLM (API Key auth) — The language model connection that powers the prompt generation. Requires a Google Gemini API key. Create Video Task (Kie.ai) (Bearer Token auth) — Sends the generated prompt and product image URL to Kie.ai's Sora 2 image-to-video model. Configures portrait aspect ratio, removes watermark, and includes a callback URL. Check Video Generation Status (Bearer Token auth) — Polls Kie.ai's API to check the status of the video generation task using the task ID returned from step 11. Video Generation Status (No auth) — A switch node that evaluates the video generation status: - Success — Proceeds to download the finished video - Failed — Returns to the iteration loop to try the next ad example - Processing — Waits and checks again Wait Before Checking Again (No auth) — Pauses execution for 1 minute before re-checking the video generation status. Download Finished Video (No auth) — Downloads the completed video file from the URL provided by Kie.ai's success response. Upload Generated Video to Google Drive (OAuth2) — Saves the downloaded video to a specified Google Drive folder, named with the current date and time. Setup Instructions Required Accounts & Services Google Account — For Google Drive access (store product images and save generated videos) - Create a Google Cloud Project and enable the Google Drive API - Set up OAuth 2.0 credentials in n8n Foreplay Account — For competitor ad intelligence - Sign up at Foreplay - Get your API key and brand ID from your Foreplay dashboard Google Gemini API Key — For AI prompt generation - Get an API key from Google AI Studio Kie.ai Account — For video generation (Sora 2 model) - Sign up at Kie.ai and obtain API credentials - Configure Bearer Token authentication in n8n Configuration Steps Add all API keys and credentials in the n8n credentials manager Update the Set Workflow Credentials node with your: - Google Drive folder IDs (for product images and generated videos) - Foreplay API key and brand ID - Kie.ai callback URL (optional) Update the Set Product Information node with your product details Ensure your product image folder in Google Drive is set to public access Run the workflow manually to test Use Cases & Variations Primary Use Cases E-commerce product videos — Generate video ads for new product launches Competitor analysis — Create videos inspired by successful competitor ad formats Social media content — Produce Instagram-ready video ads A/B testing — Generate multiple video variations from different competitor examples Adaptation Ideas Change video model — Replace Kie.ai with another video generation service (e.g., Runway, Pika) Add scheduling — Replace Manual Trigger with a Cron trigger for automated daily video generation Multi-product support — Modify the workflow to iterate over a list of products from a Google Sheet Add review step — Insert a human approval node before uploading to Google Drive Different platforms — Change the Foreplay API parameters to target TikTok, Facebook, or YouTube ads Custom branding — Modify the Gemini prompt to include specific brand guidelines or tone of voice
Auto-Generate Platform-Specific Posts from YouTube Videos with Dumpling AI
Overview This workflow automatically generates platform-specific social media posts (Instagram, Facebook, LinkedIn) from YouTube videos. It reads a topic from a Google Sheet, searches YouTube via Dumpling AI, selects the best matching video using GPT-4o, fetches its transcript, and creates tailored posts with AI-generated images. The final output is saved back to Google Sheets, making it ideal for content creators and marketers who want to repurpose video content across social media platforms efficiently. Workflow Steps Trigger Search Schedule — Schedule Trigger (No auth) — Runs the workflow on a schedule. Configured to run at regular intervals (default: every hour) but you can customize the cron or interval in the node settings. Get Unsearched Topic from Google Sheet — Google Sheets (OAuth2) — Reads a topic from the "YouTube Topics" sheet. Uses a filter to find rows where the "Searched?" column is empty, returning the first match. Requires Google Sheets OAuth2 credentials. Search YouTube via Dumpling AI — HTTP Request (Header Auth) — Sends a POST request to Dumpling AI's YouTube search endpoint. The query is dynamically populated from the Google Sheets topic. Requires a Dumpling AI API key configured as HTTP Header Auth. Filter + Sort YouTube Videos — Code (No auth) — Custom JavaScript code that extracts video data from the search results, filters for video types, sorts by published time (newest first), and returns the 3 most recent videos. Prepare Video List for AI — Aggregate (No auth) — Combines all video items into a single array, preparing the data for the AI node to process. Select Best Video with GPT-4o — OpenAI (API Key auth) — Uses GPT-4.1 to analyze the search results and pick the most relevant video based on the original topic and current date. Returns a JSON structure with the selected video details. Requires an OpenAI API key. Get Transcript (Dumpling AI) — HTTP Request (Header Auth) — Fetches the YouTube video transcript via Dumpling AI's transcript endpoint. Requires the same Dumpling AI credentials as node 3. Generate Posts with GPT-4o — OpenAI (API Key auth) — Takes the transcript and generates three platform-specific posts (Instagram, Facebook, LinkedIn) with matching image prompts. Each post is tailored to the platform's tone and format. Uses the same OpenAI credentials as node 6. Generate Instagram Image (Dumpling AI) — HTTP Request (Header Auth) — Generates an AI image for the Instagram post using FLUX.1-pro model. Prompt comes from the GPT-4o output. Generate Facebook Image (Dumpling AI) — HTTP Request (Header Auth) — Same as node 9 but for Facebook post image. Generate LinkedIn Image (Dumpling AI) — HTTP Request (Header Auth) — Same as node 9 but for LinkedIn post image. Format Instagram Post — Set (No auth) — Combines the Instagram post text, platform name, and image URL into a structured format for saving. Format Facebook Post — Set (No auth) — Same as node 12 but for Facebook. Format LinkedIn Post — Set (No auth) — Same as node 12 but for LinkedIn. Save Instagram Post to Sheet — Google Sheets (OAuth2) — Appends the formatted Instagram post (platform, content, image URL) to the "Social Media Post" sheet. Save Facebook Post to Sheet — Google Sheets (OAuth2) — Same as node 15 but for Facebook. Save LinkedIn Post to Sheet — Google Sheets (OAuth2) — Same as node 15 but for LinkedIn. Merge Post Results — Merge (No auth) — Combines all three saved post results into a single output. Update Topic Status in Sheet — Google Sheets (OAuth2) — Updates the original topic row in "YouTube Topics" sheet, setting "Searched?" to "Yes" to prevent reprocessing. Setup Instructions Required Accounts & Credentials Google Account — For Google Sheets access. Create OAuth2 credentials in n8n for Google Sheets. OpenAI Account — For GPT-4.1 access. Create an API key from platform.openai.com. Dumpling AI Account — For YouTube search, transcript, and image generation. Sign up at dumplingai.com and get an API key. Google Sheets Setup Create a Google Sheet with two sheets: YouTube Topics (columns: , ) — Add your topics with "Searched?" column empty for unprocessed items. Social Media Post (columns: , , ) — Will store generated posts. Configuring Credentials In n8n, go to Credentials → Add Credential. Add Google Sheets OAuth2 credentials. Add OpenAI credentials with your API key. Add Header Auth credentials with your Dumpling AI API key. Node Configuration Update the in all Google Sheets nodes to your sheet's ID. Verify the values match your sheet tab names. Adjust the schedule trigger interval as needed. Use Cases & Variations Content Repurposing — Automatically turn YouTube videos into social media posts for multiple platforms. Batch Processing — Add multiple topics to the sheet; the workflow processes one per run. Custom Platforms — Modify GPT-4o prompts to add Twitter, TikTok, or other platforms. Brand Voice Customization — Update the system prompt to match your brand's tone. Manual Trigger — Replace the schedule trigger with a webhook for on-demand processing. Review Before Posting — Add a manual approval step before saving to sheets. This workflow saves hours of manual content creation and ensures consistent, platform-optimized posts.
Auto-Generate Social Posts from YouTube via Dumpling AI
🧠 Automate Social Media Content Creation from YouTube Videos This powerful workflow automatically generates platform-specific social media posts (Instagram, Facebook, LinkedIn) from YouTube videos. It takes a topic from a Google Sheet, searches for relevant YouTube videos using Dumpling AI, selects the best match with GPT-4o, fetches the transcript, and creates tailored posts with matching AI-generated images — all saved back to your Google Sheet. Perfect for content creators, social media managers, and marketers who want to repurpose YouTube content efficiently. The workflow runs on a schedule, processes one topic at a time, and marks topics as completed to avoid duplication. It combines the power of Dumpling AI for YouTube search and image generation, OpenAI's GPT-4o for intelligent content selection and copywriting, and Google Sheets for data management. 📋 Node-by-Node Breakdown Trigger Search Schedule (Schedule Trigger) — No auth required. Runs the workflow on a configurable interval (default: every hour). You can adjust the schedule in the node settings. Get Unsearched Topic from Google Sheet (Google Sheets) — OAuth2 (Google Sheets). Reads the first unsearched topic from the "YouTube Topics" sheet. Uses a filter to find rows where "Searched?" column is empty, and returns only the first match. Search YouTube via Dumpling AI (HTTP Request) — Header Auth (Dumpling AI API key). Sends a POST request to Dumpling AI's YouTube search endpoint with the topic as query. Returns video results matching the search term. Filter + Sort YouTube Videos (Code) — No auth. Custom JavaScript that extracts video data from the API response, filters for video type, sorts by published date (newest first), and returns the 3 most recent videos. Prepare Video List for AI (Aggregate) — No auth. Combines all video items into a single array for processing by the AI node. Select Best Video with GPT-4o (OpenAI) — API Key auth (OpenAI). Uses GPT-4o to analyze the search results and select the most relevant video based on the original topic and current date. Returns the best match in structured JSON format. Get Transcript (Dumpling AI) (HTTP Request) — Header Auth (Dumpling AI API key). Fetches the YouTube transcript for the selected video using Dumpling AI's transcript endpoint. Generate Posts with GPT-4o (OpenAI) — API Key auth (OpenAI). Takes the transcript and generates three platform-specific posts (Instagram, Facebook, LinkedIn) with matching image prompts. Each post is tailored to the platform's style and audience. Generate Instagram Image (Dumpling AI) (HTTP Request) — Header Auth (Dumpling AI API key). Creates an AI-generated image for the Instagram post using FLUX.1-pro model. Generate Facebook Image (Dumpling AI) (HTTP Request) — Header Auth (Dumpling AI API key). Creates an AI-generated image for the Facebook post. Generate LinkedIn Image (Dumpling AI) (HTTP Request) — Header Auth (Dumpling AI API key). Creates an AI-generated image for the LinkedIn post. Format Instagram Post (Set) — No auth. Structures the Instagram post data with platform name, content text, and image URL. Format Facebook Post (Set) — No auth. Structures the Facebook post data similarly. Format LinkedIn Post (Set) — No auth. Structures the LinkedIn post data similarly. Save Instagram Post to Sheet (Google Sheets) — OAuth2 (Google Sheets). Appends the formatted Instagram post to the "Social Media Post" sheet. Save Facebook Post to Sheet (Google Sheets) — OAuth2 (Google Sheets). Appends the formatted Facebook post to the same sheet. Save LinkedIn Post to Sheet (Google Sheets) — OAuth2 (Google Sheets). Appends the formatted LinkedIn post to the same sheet. Merge Post Results (Merge) — No auth. Combines the three post results into a single output for the final update step. Update Topic Status in Sheet (Google Sheets) — OAuth2 (Google Sheets). Marks the original topic as "Searched?" = "Yes" in the YouTube Topics sheet to prevent reprocessing. 🔧 Setup Instructions Required Accounts & Credentials: Google Account — For Google Sheets access. Create OAuth2 credentials in n8n for Google Sheets. Dumpling AI Account — Sign up at app.dumplingai.com and get your API key. Add as Header Auth credential in n8n. OpenAI Account — Get your API key from platform.openai.com. Add as API Key credential in n8n. Required Google Sheets: YouTube Topics sheet with columns: , Social Media Post sheet with columns: , , 💡 Use Cases & Variations Primary Use Cases: Content repurposing for social media managers Automated content calendar creation YouTube-to-social-media content pipeline Brand consistency across platforms Adaptation Ideas: Add more platforms (Twitter/X, TikTok, Pinterest) Schedule posts directly to social media using n8n integrations Add human review step before posting Use different AI models for image generation Add email newsletter content generation Include video thumbnail generation Add analytics tracking for post performance