Skip to content

StevenCesario/meta-capi-proxy-demo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🔒 Meta CAPI Event Connector

A production-ready FastAPI proxy that securely sends server-side events to Meta's Conversions API. Handles PII hashing, data validation, and payload formatting automatically - saving developers days of implementation time.

Python FastAPI CI/CD

🎯 Problem Solved

Recently, my agency worked with a Swedish Amazon expert whose course business was struggling with inconsistent revenue. One critical issue was poor marketing attribution - they couldn't accurately track which ads drove sales, making optimization nearly impossible. The challenge? Meta's Conversions API (CAPI) is powerful but complex to implement correctly. Most developers struggle with:

Security: Properly hashing PII before transmission
Data Quality: Capturing server-side signals (IP, User Agent) for better event matching
Validation: Ensuring data meets Meta's strict requirements
Infrastructure: Building, deploying, and maintaining server-side infrastructure

I built a complete, end-to-end Meta CAPI solution that solved these problems. The system combines this secure server-side proxy with the custom client-side JavaScript required to accurately capture all user data from the browser.

The result: Accurate server-side event tracking with a 9.3/10 Event Match Quality score, which contributed to taking a client's business from revenue inconsistency to $43k in 45 days at 5.15X ROAS.

Note: This repository contains a generalized, showcase version of the architecture. The same technical patterns demonstrated in both the client-side script and the server-side proxy were used in the production system that helped achieve these results.

This solution eliminates weeks of CAPI implementation complexity in a single, battle-tested service.

✨ Key Features

🔒 Security First

  • Automatic SHA-256 hashing of all Personally Identifiable Information (PII)
  • No raw user data stored or logged
  • Secure credential handling via headers

Production Ready

  • Comprehensive error handling with unique request IDs
  • Detailed logging for debugging and monitoring
  • Input validation and data cleaning
  • Proper HTTP status codes and error responses

🎯 Improved Data Quality

  • Server-side IP extraction (handles proxy headers)
  • User Agent capture and validation
  • Facebook Pixel ID format validation
  • Currency/value relationship validation

🌐 Universal Compatibility

  • Works with any CRM, e-commerce platform, or custom application
  • RESTful API design with clear documentation
  • Comprehensive example payloads

💻 End-to-End Data Flow

  • Includes the custom JavaScript (trackingLead.js) for accurately capturing browser events, cookies (_fbc, _fbp), and user data before they are sent to the server. Specifically for leads but can be rewritten for Purchase

🚀 Quick Start

1. Clone and Install

git clone https://github.com/yourusername/meta-capi-proxy-demo.git
cd meta-capi-proxy-demo
pip install fastapi uvicorn requests pydantic

2. Set Up Environment

# Optional: Set environment variables for default credentials
export META_PIXEL_ID="your_pixel_id"
export META_ACCESS_TOKEN="your_access_token"

3. Run the API

python main.py
# or
uvicorn main:app --reload

4. View Documentation

Open http://localhost:8000 in your browser to see the interactive API documentation.

📋 API Usage

Send a Purchase Event

curl -X POST "http://localhost:8000/v1/process-event" \
  -H "Content-Type: application/json" \
  -H "X-Meta-Pixel-Id: YOUR_PIXEL_ID" \
  -H "X-Meta-Access-Token: YOUR_ACCESS_TOKEN" \
  -d '{
    "event_name": "Purchase",
    "event_time": 1703980800,
    "action_source": "website",
    "event_source_url": "https://example.com/checkout",
    "user_data": {
      "email": "customer@example.com",
      "first_name": "John",
      "last_name": "Doe",
      "phone": "+1234567890",
      "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
    },
    "custom_data": {
      "currency": "USD",
      "value": 99.99,
      "content_ids": ["product_123"],
      "content_type": "product"
    }
  }'

Response

{
  "request_id": "123e4567-e89b-12d3-a456-426614174000",
  "status": "success",
  "message": "Event processed and sent to Meta CAPI successfully",
  "meta_response": {
    "events_received": 1,
    "messages": [],
    "fbtrace_id": "A1B2C3D4E5F6G7H8"
  }
}

🏗️ Architecture

User's Browser (tracking.js)
       ↓ (Data Capture)
Client Application
       ↓ (HTTPS Request)
Meta CAPI Connector (This Project)
       ↓ (Processes & Validates)
   [Hash PII] → [Extract Server Signals] → [Validate Data]
       ↓ (Secure HTTPS)
Meta Conversions API

Data Flow

  1. Capture: The tracking.js script captures user data and browser events.
  2. Input: Receives event data from any system
  3. Security: Hashes all PII using SHA-256
  4. Enhancement: Adds server-side signals (IP, User Agent)
  5. Validation: Ensures data meets Meta's requirements
  6. Transmission: Forwards to Meta CAPI
  7. Response: Returns Meta's response with request tracking

🔧 Technical Details

Dependencies

  • FastAPI: Modern web framework for building APIs
  • Pydantic: Data validation and serialization
  • Requests: HTTP client for Meta API communication
  • Standard Library: hashlib, ipaddress, uuid, re

Security Features

  • PII hashing using SHA-256
  • Input validation and sanitization
  • No data persistence or logging of sensitive information
  • Secure credential handling via headers

Error Handling

  • Comprehensive HTTP error responses
  • Unique request IDs for tracking and support
  • Detailed logging for debugging
  • Graceful handling of Meta API errors

🌟 Production Use

This code powers a live API serving clients globally. The production version includes:

  • Enhanced monitoring and analytics
  • Rate limiting and abuse protection
  • Premium support channels

📊 Business Impact

For marketing agencies and e-commerce businesses, this connector:

  • Saves 2-4 weeks of development time
  • Improves ad performance through better data quality
  • Ensures compliance with privacy regulations
  • Reduces maintenance burden of custom solutions

Typical implementation cost: $5,000-15,000
This solution: Ready in minutes

🤝 Contributing

This is a demonstration repository showcasing production-quality code architecture. For feature requests or questions about custom implementations, please open an issue.

📄 License

MIT License - feel free to use this code as inspiration for your own projects.


Built by Steven Cesario 🌱

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors