Last updated: November 2025
Reading time: ~25 minutes
Level: Advanced

Introduction

When implementing Meta (Facebook) tracking for mobile applications, most developers rely on the official Meta SDK to handle event collection and transmission. The SDK automatically collects device information, handles user identification, manages attribution, and sends events to Meta’s servers.

However, there are compelling reasons to implement a CAPI-only approach without integrating the Meta SDK into your mobile application:

But here’s the catch: the Meta SDK does A LOT automatically. When you remove it, you must recreate a large part of its work manually.

This guide provides a complete, technical breakdown of every parameter you need to handle when implementing Meta CAPI for mobile apps without the SDK.

Prerequisites:

Why Go CAPI-Only Without SDK?

The Standard Approach: SDK-Based Tracking

The Meta SDK for mobile apps (iOS and Android) provides automatic event collection including:

The SDK sends events directly from the device to Meta’s servers, handling all the technical complexity of data collection, formatting, and transmission.

The CAPI-Only Alternative

With a CAPI-only implementation:

  1. Your mobile app collects raw event data
  2. The app sends this data to your backend server
  3. Your server processes, enriches, and formats the data
  4. Your server sends events to Meta via the Conversions API

Key advantages:

Key challenges:

What the SDK Does Automatically (That You Must Now Handle)

The Meta SDK automatically collects and sends:

Device Identification

User Identification

Event Context

Attribution Data

Technical Metadata

Without the SDK, you must collect, format, and send ALL of this manually.

Architecture Overview

Here’s the high-level flow for CAPI-only mobile tracking:

┌─────────────────┐
│   Mobile App    │
│  (iOS/Android)  │
└────────┬────────┘
         │ 1. Collect event data
         │    (purchase, install, etc.)
         │
         ▼
┌─────────────────┐
│  Device Data    │
│   Collection    │
│                 │
│ • IDFA/GAID     │
│ • Device info   │
│ • User data     │
└────────┬────────┘
         │ 2. Send to backend
         │    via HTTPS POST
         │
         ▼
┌─────────────────┐
│  Your Backend   │
│    Server       │
│                 │
│ • Validate      │
│ • Hash PII      │
│ • Enrich data   │
└────────┬────────┘
         │ 3. Send to Meta CAPI
         │    POST /events
         │
         ▼
┌─────────────────┐
│   Meta CAPI     │
│   Endpoint      │
│                 │
│ graph.facebook  │
│ .com/v25.0/     │
│ {dataset_id}/   │
│ events          │
└─────────────────┘

Critical decision point: Should your mobile app send PII (emails, phone numbers) to your backend?

Recommendation:

Critical Parameter #1: Device Identifiers (madid & anon_id)

What is MADID?

MADID (Mobile Advertising ID) is the primary identifier for mobile attribution:

The Meta SDK automatically retrieves and sends the MADID. Without the SDK, you must:

iOS: Retrieving IDFA

Since iOS 14.5, you must request permission via Apple’s App Tracking Transparency (ATT) framework.

Swift example:

import AppTrackingTransparency
import AdSupport

func requestIDFA() {
    if #available(iOS 14.5, *) {
        ATTrackingManager.requestTrackingAuthorization { status in
            switch status {
            case .authorized:
                // User granted permission
                let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
                print("IDFA: \(idfa)")
                // Send to your backend
                self.sendToBackend(idfa: idfa)
                
            case .denied, .restricted, .notDetermined:
                // User denied or permission not determined
                // IDFA will be 00000000-0000-0000-0000-000000000000
                // Use anonymous ID instead
                let anonId = self.getOrCreateAnonymousId()
                self.sendToBackend(anonId: anonId)
                
            @unknown default:
                break
            }
        }
    } else {
        // iOS < 14.5: IDFA available without permission
        let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
        self.sendToBackend(idfa: idfa)
    }
}

React Native example:

import { requestTrackingPermission } from 'react-native-tracking-transparency';
import DeviceInfo from 'react-native-device-info';

async function getIDFA() {
    try {
        const trackingStatus = await requestTrackingPermission();
        
        if (trackingStatus === 'authorized' || trackingStatus === 'unavailable') {
            const idfa = await DeviceInfo.getAdvertisingId();
            console.log('IDFA:', idfa);
            return idfa;
        } else {
            // Permission denied
            console.log('ATT denied, using anonymous ID');
            return null; // Use anon_id instead
        }
    } catch (error) {
        console.error('Error getting IDFA:', error);
        return null;
    }
}

Android: Retrieving GAID

Android: no runtime prompt, but apps targeting Android 13+ must declare the AD_ID permission, and a deleted ID comes back as all zeros (filter it like the iOS zero IDFA).

Kotlin example:

import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.google.android.gms.common.GooglePlayServicesNotAvailableException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

suspend fun getGAID(): String? {
    return withContext(Dispatchers.IO) {
        try {
            val adInfo = AdvertisingIdClient.getAdvertisingIdInfo(applicationContext)
            if (!adInfo.isLimitAdTrackingEnabled) {
                adInfo.id?.takeIf { it != "00000000-0000-0000-0000-000000000000" } // GAID, or null if the user deleted it (all zeros)
            } else {
                null // User opted out of ad tracking
            }
        } catch (e: GooglePlayServicesNotAvailableException) {
            null
        } catch (e: Exception) {
            null
        }
    }
}

React Native example:

import { getAdvertisingId } from 'react-native-device-info';

async function getGAID() {
    try {
        const gaid = await getAdvertisingId();
        console.log('GAID:', gaid);
        return gaid;
    } catch (error) {
        console.error('Error getting GAID:', error);
        return null;
    }
}

Formatting MADID for Meta CAPI

Send the MADID in the format Meta’s own examples use:

✅ Correct format:

❌ Incorrect format:

Formatting code:

function formatMADID(madid) {
    if (!madid || madid === '00000000-0000-0000-0000-000000000000') return null;
    return madid.toLowerCase(); // keep the dashes, never hash
}

// Example
const rawIDFA = "38400000-8CF0-11BD-B23E-10B96E40000D";
const formattedMADID = formatMADID(rawIDFA);
// Result: "38400000-8cf0-11bd-b23e-10b96e40000d"

Anonymous ID (anon_id) – Critical Fallback

When IDFA/GAID is unavailable (iOS ATT denied, user opted out, etc.), you must generate and persist an anonymous ID.

Requirements:

iOS Swift example:

import Foundation

func getOrCreateAnonymousId() -> String {
    let key = "anon_id"
    
    if let existingId = UserDefaults.standard.string(forKey: key) {
        return existingId
    }
    
    let newId = UUID().uuidString.lowercased()
    UserDefaults.standard.set(newId, forKey: key)
    return newId
}

React Native example:

import AsyncStorage from '@react-native-async-storage/async-storage';
import uuid from 'react-native-uuid';

async function getOrCreateAnonId() {
    const key = 'anon_id';
    
    try {
        let anonId = await AsyncStorage.getItem(key);
        
        if (!anonId) {
            anonId = uuid.v4().toLowerCase();
            await AsyncStorage.setItem(key, anonId);
        }
        
        return anonId;
    } catch (error) {
        console.error('Error with anon_id:', error);
        return uuid.v4().toLowerCase(); // Fallback to session ID
    }
}

Sending to Meta CAPI

In your CAPI payload:

{
    "user_data": {
        "madid": "38400000-8cf0-11bd-b23e-10b96e40000d",
        "anon_id": "a1b2c3d4-e5f6-7890-1234-567890abcdef"
    }
}

Best practices:

Sources:

Critical Parameter #2: The extinfo Array

What is extinfo?

The extinfo array is a fixed-position array of 16+ values containing device and app metadata. The Meta SDK generates this automatically. Without the SDK, you must construct it manually.

extinfo is required for app events; without it Meta rejects or cannot use the event.

extinfo Structure

The array has a fixed order – each position has a specific meaning:

[
    "i2",              // [0]  extinfo version ("a2" Android, "i2" iOS)
    "com.myapp",       // [1]  App package name / bundle ID
    "1.2.3",           // [2]  Short version
    "456",             // [3]  Long version
    "17.2.1",          // [4]  OS version
    "iPhone14,2",      // [5]  Device model name
    "en_US",           // [6]  Locale
    "CET",             // [7]  Timezone abbreviation
    "Orange",          // [8]  Carrier
    "1170",            // [9]  Screen width
    "2532",            // [10] Screen height
    "3",               // [11] Screen density
    "6",               // [12] CPU cores
    "256",             // [13] External storage size (GB)
    "120",             // [14] Free space on external storage (GB)
    "Europe/Paris"     // [15] Device timezone
]

Collecting extinfo Data

React Native implementation:

import DeviceInfo from 'react-native-device-info';
import { Platform, Dimensions } from 'react-native';

const GB = 1024 * 1024 * 1024;

// All extinfo values are strings; a missing value is an empty string ""
const str = (x) => (x === null || x === undefined ? '' : String(x));

function timezoneAbbreviation() {
    const part = new Intl.DateTimeFormat('en-US', { timeZoneName: 'short' })
        .formatToParts(new Date())
        .find(p => p.type === 'timeZoneName');
    return part ? part.value : '';
}

async function buildExtinfo() {
    try {
        const screen = Dimensions.get('screen');

        const extinfo = [
            Platform.OS === 'ios' ? 'i2' : 'a2',                        // [0]  extinfo version
            str(DeviceInfo.getBundleId()),                               // [1]  com.myapp
            str(DeviceInfo.getVersion()),                                // [2]  1.2.3
            str(DeviceInfo.getBuildNumber()),                            // [3]  456
            str(DeviceInfo.getSystemVersion()),                          // [4]  17.2.1
            str(await DeviceInfo.getDeviceId()),                         // [5]  iPhone14,2
            str(DeviceInfo.getDeviceLocale()),                           // [6]  en_US
            timezoneAbbreviation(),                                      // [7]  CET
            str(await DeviceInfo.getCarrier()),                          // [8]  Orange
            str(Math.round(screen.width * screen.scale)),                // [9]  1170
            str(Math.round(screen.height * screen.scale)),               // [10] 2532
            str(screen.scale),                                           // [11] 3
            str(await DeviceInfo.getProcessorCount()),                   // [12] 6
            str(Math.round(await DeviceInfo.getTotalDiskCapacity() / GB)), // [13] total storage, GB
            str(Math.round(await DeviceInfo.getFreeDiskStorage() / GB)),   // [14] free storage, GB
            Intl.DateTimeFormat().resolvedOptions().timeZone || ''       // [15] Europe/Paris
        ];

        return extinfo;
    } catch (error) {
        console.error('Error building extinfo:', error);
        // Keep all 16 positions: missing values are empty strings
        return [Platform.OS === 'ios' ? 'i2' : 'a2', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''];
    }
}

iOS Swift implementation:

import UIKit
import CoreTelephony

func buildExtinfo() -> [String] {
    let screen = UIScreen.main
    let bundle = Bundle.main
    let device = UIDevice.current
    let fileManager = FileManager.default

    // Get carrier info
    let networkInfo = CTTelephonyNetworkInfo()
    let carrier = networkInfo.serviceSubscriberCellularProviders?.values.first
    let carrierName = carrier?.carrierName ?? ""

    // Disk space in GB (total first, then free)
    let systemAttributes = try? fileManager.attributesOfFileSystem(
        forPath: NSHomeDirectory()
    )
    let freeSpace = (systemAttributes?[.systemFreeSize] as? NSNumber)?.int64Value ?? 0
    let totalSpace = (systemAttributes?[.systemSize] as? NSNumber)?.int64Value ?? 0
    let gb: Int64 = 1024 * 1024 * 1024

    // All values are strings; a missing value is an empty string ""
    let extinfo: [String] = [
        "i2",                                                                    // [0]  extinfo version (iOS)
        bundle.bundleIdentifier ?? "",                                           // [1]  package name
        bundle.infoDictionary?["CFBundleShortVersionString"] as? String ?? "",  // [2]  short version
        bundle.infoDictionary?["CFBundleVersion"] as? String ?? "",              // [3]  long version
        device.systemVersion,                                                    // [4]  OS version
        deviceModelIdentifier(),                                                 // [5]  device model
        Locale.current.identifier,                                               // [6]  locale
        TimeZone.current.abbreviation() ?? "",                                   // [7]  timezone abbreviation
        carrierName,                                                             // [8]  carrier
        String(Int(screen.bounds.width * screen.scale)),                         // [9]  screen width
        String(Int(screen.bounds.height * screen.scale)),                        // [10] screen height
        String(format: "%.0f", screen.scale),                                    // [11] screen density
        String(ProcessInfo.processInfo.processorCount),                          // [12] CPU cores
        String(totalSpace / gb),                                                 // [13] external storage size (GB)
        String(freeSpace / gb),                                                  // [14] free space (GB)
        TimeZone.current.identifier                                              // [15] device timezone
    ]

    return extinfo
}

func deviceModelIdentifier() -> String {
    var systemInfo = utsname()
    uname(&systemInfo)
    let machineMirror = Mirror(reflecting: systemInfo.machine)
    let identifier = machineMirror.children.reduce("") { identifier, element in
        guard let value = element.value as? Int8, value != 0 else { return identifier }
        return identifier + String(UnicodeScalar(UInt8(value)))
    }
    return identifier
}

Android Kotlin implementation:

import android.content.Context
import android.os.Build
import android.os.Environment
import android.os.StatFs
import android.util.DisplayMetrics
import android.view.WindowManager
import android.telephony.TelephonyManager
import java.util.Date
import java.util.TimeZone

fun buildExtinfo(context: Context): List<String> {
    val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
    val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val displayMetrics = DisplayMetrics()
    windowManager.defaultDisplay.getMetrics(displayMetrics)

    // Get carrier
    val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
    val carrierName = telephonyManager.networkOperatorName ?: ""

    // Disk space in GB (total first, then free)
    val statFs = StatFs(Environment.getDataDirectory().path)
    val gb = 1024L * 1024L * 1024L

    val tz = TimeZone.getDefault()

    // All values are strings; a missing value is an empty string ""
    return listOf(
        "a2",                                                    // [0]  extinfo version (Android)
        context.packageName,                                     // [1]  package name
        packageInfo.versionName ?: "",                           // [2]  short version
        packageInfo.versionCode.toString(),                      // [3]  long version
        Build.VERSION.RELEASE,                                   // [4]  OS version
        Build.MODEL,                                             // [5]  device model
        context.resources.configuration.locales[0].toString(),   // [6]  locale
        tz.getDisplayName(tz.inDaylightTime(Date()), TimeZone.SHORT), // [7] timezone abbreviation
        carrierName,                                             // [8]  carrier
        displayMetrics.widthPixels.toString(),                   // [9]  screen width
        displayMetrics.heightPixels.toString(),                  // [10] screen height
        displayMetrics.density.toString(),                       // [11] screen density
        Runtime.getRuntime().availableProcessors().toString(),   // [12] CPU cores
        (statFs.totalBytes / gb).toString(),                     // [13] external storage size (GB)
        (statFs.availableBytes / gb).toString(),                 // [14] free space (GB)
        tz.id                                                    // [15] device timezone
    )
}

Sending extinfo to Meta CAPI

In your CAPI payload:

{
    "app_data": {
        "extinfo": [
            "i2",
            "com.myapp",
            "1.2.3",
            "456",
            "17.2.1",
            "iPhone14,2",
            "en_US",
            "CET",
            "Orange",
            "1170",
            "2532",
            "3",
            "6",
            "256",
            "120",
            "Europe/Paris"
        ]
    }
}

Critical notes:

Sources:

Critical Parameter #3: Advanced Matching (Hashed PII)

What is Advanced Matching?

Advanced Matching allows Meta to match events to users even when device identifiers (IDFA/GAID) are unavailable. This is critical for iOS 14.5+ where most users deny ATT.

The Meta SDK handles Advanced Matching automatically by:

  1. Collecting user data (email, phone, name, etc.)
  2. Normalizing the data
  3. Hashing it with SHA-256
  4. Sending it to Meta

Without the SDK, you must do all of this manually.

Supported PII Fields

Meta accepts the following user data fields (all must be hashed):

FieldParameterDescriptionExample (pre-hash)
EmailemUser’s email addresstest@example.com
PhonephUser’s phone number33612345678
First namefnUser’s first namejohn
Last namelnUser’s last namedoe
CityctUser’s cityparis
State/RegionstUser’s state/provinceiledefrance
Zip codezpPostal code75001
Countrycountry2-letter country codefr
GendergeGender (m/f)m
Date of birthdbBirth date YYYYMMDD19900515

Normalization Rules (CRITICAL)

Meta is extremely strict about normalization. If you don’t normalize correctly before hashing, matching will fail.

Email normalization:

function normalizeEmail(email) {
    if (!email) return null;
    
    // 1. Trim whitespace
    email = email.trim();
    
    // 2. Convert to lowercase
    email = email.toLowerCase();
    
    // 3. No further processing (keep dots, plus signs, etc.)
    
    return email;
}

// Examples
normalizeEmail("  Test@Example.com  ") // → "test@example.com"
normalizeEmail("John.Doe+tag@Gmail.com") // → "john.doe+tag@gmail.com"

Phone normalization:

function normalizePhone(phone, countryCode = '33') {
    if (!phone) return null;

    // 1. Keep digits only (remove symbols and letters; never add "+")
    phone = phone.replace(/[^0-9]/g, '');

    // 2. International prefix "00": drop it
    if (phone.startsWith('00')) {
        return phone.substring(2);
    }

    // 3. National number with a leading 0: replace the 0 by the country code
    if (phone.startsWith('0')) {
        return countryCode + phone.substring(1);
    }

    // 4. Otherwise the number already starts with its country code
    return phone;
}

// Examples
normalizePhone("06 12 34 56 78", "33")  // → "33612345678"
normalizePhone("+33-6-12-34-56-78")      // → "33612345678"
normalizePhone("0033 6 12 34 56 78")     // → "33612345678"

Name normalization:

function normalizeName(name) {
    if (!name) return null;

    // 1. Trim whitespace
    name = name.trim();

    // 2. Convert to lowercase
    name = name.toLowerCase();

    // 3. Remove punctuation; keep letters, including accented letters (UTF-8)
    name = name.replace(/[^\p{L}]/gu, '');

    return name;
}

// Examples
normalizeName("  Jean-Pierre  ")  // → "jeanpierre"
normalizeName("O'Connor")         // → "oconnor"
normalizeName("Valéry")           // → "valéry" (Meta's own example)

City/State normalization:

function normalizeLocation(location) {
    if (!location) return null;

    // 1. Trim whitespace and convert to lowercase
    location = location.trim().toLowerCase();

    // 2. Strip accents ("Î" → "i")
    location = location.normalize('NFD').replace(/[\u0300-\u036f]/g, '');

    // 3. Remove everything that is not a-z (no punctuation, no special characters, no spaces)
    location = location.replace(/[^a-z]/g, '');

    return location;
}

// Examples (US states: use the 2-letter code, e.g. "ca")
normalizeLocation("  Paris  ")       // → "paris"
normalizeLocation("New York")        // → "newyork"
normalizeLocation("Île-de-France")   // → "iledefrance"

Zip code normalization:

function normalizeZipCode(zip, country) {
    if (!zip) return null;

    // 1. Trim whitespace and convert to lowercase
    zip = zip.trim().toLowerCase();

    // 2. Remove spaces and dashes (keep letters: UK, Canada, Netherlands...)
    zip = zip.replace(/[\s-]/g, '');

    // 3. US: first 5 digits only
    if (country === 'us') {
        zip = zip.substring(0, 5);
    }

    return zip;
}

// Examples
normalizeZipCode("75 001")              // → "75001"
normalizeZipCode("M1 1AE")              // → "m11ae" (UK)
normalizeZipCode("94035-1234", "us")    // → "94035"

Date of birth normalization:

function normalizeDateOfBirth(dob) {
    if (!dob) return null;
    
    // Expected format: YYYYMMDD
    // Input can be Date object or string
    
    if (dob instanceof Date) {
        const year = dob.getFullYear();
        const month = String(dob.getMonth() + 1).padStart(2, '0');
        const day = String(dob.getDate()).padStart(2, '0');
        return `${year}${month}${day}`;
    }
    
    // If string, remove all non-digits
    dob = String(dob).replace(/[^0-9]/g, '');
    
    // Should be 8 digits: YYYYMMDD
    if (dob.length === 8) {
        return dob;
    }
    
    return null;
}

// Examples
normalizeDateOfBirth("1990-05-15")      // → "19900515"
normalizeDateOfBirth("15/05/1990")      // → (would need parsing logic)
normalizeDateOfBirth(new Date(1990, 4, 15)) // → "19900515"

Gender normalization:

function normalizeGender(gender) {
    if (!gender) return null;
    
    gender = gender.trim().toLowerCase();
    
    // Meta accepts only 'm' or 'f'
    if (gender === 'm' || gender === 'male' || gender === 'homme') {
        return 'm';
    }
    if (gender === 'f' || gender === 'female' || gender === 'femme') {
        return 'f';
    }
    
    return null; // Don't send if ambiguous
}

Hashing with SHA-256

CRITICAL: Hash on the server, never in the mobile app.

Why?

Node.js example:

const crypto = require('crypto');

function hashSHA256(value) {
    if (!value) return null;
    return crypto.createHash('sha256').update(value).digest('hex');
}

// Example usage
const email = normalizeEmail("Test@Example.com");
const hashedEmail = hashSHA256(email);
// Result: "973dfe463ec85785f5f95af5ba3906eedb2d931c24e69824a89ea65dba4e813b"

Python example:

import hashlib

def hash_sha256(value):
    if not value:
        return None
    return hashlib.sha256(value.encode('utf-8')).hexdigest()

# Example usage
email = normalize_email("Test@Example.com")
hashed_email = hash_sha256(email)
# Result: "973dfe463ec85785f5f95af5ba3906eedb2d931c24e69824a89ea65dba4e813b"

Complete Normalization + Hashing Pipeline

Backend implementation (Node.js):

const crypto = require('crypto');

class AdvancedMatcher {
    
    static normalizeEmail(email) {
        if (!email) return null;
        return email.trim().toLowerCase();
    }
    
    static normalizePhone(phone, countryCode = '1') {
        if (!phone) return null;
        phone = phone.replace(/[^0-9]/g, '');               // digits only, never "+"
        if (phone.startsWith('00')) return phone.substring(2);  // international prefix
        if (phone.startsWith('0')) return countryCode + phone.substring(1); // national number
        return phone;
    }
    
    static normalizeName(name) {
        if (!name) return null;
        return name.trim().toLowerCase().replace(/[^\p{L}]/gu, '');
    }
    
    static normalizeLocation(location) {
        if (!location) return null;
        return location.trim().toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-z]/g, '');
    }
    
    static normalizeZip(zip, country) {
        if (!zip) return null;
        zip = zip.trim().toLowerCase().replace(/[\s-]/g, '');
        return country === 'us' ? zip.substring(0, 5) : zip;
    }
    
    static normalizeGender(gender) {
        if (!gender) return null;
        gender = gender.trim().toLowerCase();
        if (['m', 'male'].includes(gender)) return 'm';
        if (['f', 'female'].includes(gender)) return 'f';
        return null;
    }
    
    static normalizeDOB(dob) {
        if (!dob) return null;
        if (dob instanceof Date) {
            const year = dob.getFullYear();
            const month = String(dob.getMonth() + 1).padStart(2, '0');
            const day = String(dob.getDate()).padStart(2, '0');
            return `${year}${month}${day}`;
        }
        const cleaned = String(dob).replace(/[^0-9]/g, '');
        return cleaned.length === 8 ? cleaned : null;
    }
    
    static hash(value) {
        if (!value) return null;
        return crypto.createHash('sha256').update(value).digest('hex');
    }
    
    static buildUserData(rawUserData, countryCode = '1') {
        const normalized = {
            email: this.normalizeEmail(rawUserData.email),
            phone: this.normalizePhone(rawUserData.phone, countryCode),
            firstName: this.normalizeName(rawUserData.firstName),
            lastName: this.normalizeName(rawUserData.lastName),
            city: this.normalizeLocation(rawUserData.city),
            state: this.normalizeLocation(rawUserData.state),
            zip: this.normalizeZip(rawUserData.zip, rawUserData.country?.trim().toLowerCase()),
            country: rawUserData.country?.trim().toLowerCase() || null,
            gender: this.normalizeGender(rawUserData.gender),
            dob: this.normalizeDOB(rawUserData.dob)
        };
        
        return {
            em: this.hash(normalized.email),
            ph: this.hash(normalized.phone),
            fn: this.hash(normalized.firstName),
            ln: this.hash(normalized.lastName),
            ct: this.hash(normalized.city),
            st: this.hash(normalized.state),
            zp: this.hash(normalized.zip),
            country: this.hash(normalized.country), // country is hashed too
            ge: this.hash(normalized.gender),
            db: this.hash(normalized.dob)
        };
    }
}

// Usage
const rawData = {
    email: "  Test@Example.com  ",
    phone: "06 12 34 56 78",
    firstName: "Jean-Pierre",
    lastName: "Dupont",
    city: "Paris",
    state: "Île-de-France",
    zip: "75 001",
    country: "FR",
    gender: "M",
    dob: "1990-05-15"
};

const hashedUserData = AdvancedMatcher.buildUserData(rawData, '33');

console.log(hashedUserData);
/* Output (SHA-256 of the normalized values):
{
    em: "973dfe463ec85785f5f95af5ba3906eedb2d931c24e69824a89ea65dba4e813b",
    ph: "8a3e7886c9335e82e02299fa3e87b46e2de3b0c63d56003e30a5029394a47661",
    fn: "fbcc8fa66b9a007dc3649ee989950d38f12ed91b9f18a3d215b04ff77546dca0",
    ln: "b043864b7ffb308f63b438a86e60c6d231aae29e020be80c944801e065229e15",
    ct: "1670f2e42fefa5044d59a65349e47c566009488fc57d7b4376dd5787b59e3c57",
    st: "e7a0efad69ad8cd77fcd8218439ad69182b24d819222f038eb166fa4139ef159",
    zp: "3f089dbdff98360a35193e7d401b76b21f5c0d5d6fb76a28660aaaed83a4c3e3",
    country: "67ad8f41a7bb0a18c45f3efd8f6a32bdcd832bcf8f3f2eb44006c03d53076e18",
    ge: "62c66a7a5dd70c3146618063c344e531e6d4b59e379808443ce962b3abd63c5a",
    db: "53058fbd6731774c37a6d838c09d25b337fa7b9b5007f82cc934d857d2596e0c"
}
// em = sha256("test@example.com"), ph = sha256("33612345678"), fn = sha256("jeanpierre"), ln = sha256("dupont"), ct = sha256("paris"), st = sha256("iledefrance"), zp = sha256("75001"), country = sha256("fr"), ge = sha256("m"), db = sha256("19900515")
*/

Sending to Meta CAPI

In your CAPI payload:

{
    "user_data": {
        "em": "973dfe463ec85785f5f95af5ba3906eedb2d931c24e69824a89ea65dba4e813b",
        "ph": "8a3e7886c9335e82e02299fa3e87b46e2de3b0c63d56003e30a5029394a47661",
        "fn": "fbcc8fa66b9a007dc3649ee989950d38f12ed91b9f18a3d215b04ff77546dca0",
        "ln": "b043864b7ffb308f63b438a86e60c6d231aae29e020be80c944801e065229e15",
        "ct": "1670f2e42fefa5044d59a65349e47c566009488fc57d7b4376dd5787b59e3c57",
        "zp": "3f089dbdff98360a35193e7d401b76b21f5c0d5d6fb76a28660aaaed83a4c3e3",
        "country": "67ad8f41a7bb0a18c45f3efd8f6a32bdcd832bcf8f3f2eb44006c03d53076e18",
        "ge": "62c66a7a5dd70c3146618063c344e531e6d4b59e379808443ce962b3abd63c5a"
    }
}

Best practices:

Sources:

Critical Parameter #4: app_data Parameters

What is app_data?

The app_data object contains metadata about your app and the tracking environment. The Meta SDK populates this automatically.

Required app_data Fields

{
    "app_data": {
        "application_tracking_enabled": 1,
        "advertiser_tracking_enabled": 1,
        "extinfo": [ /* array shown in section 2 */ ]
    }
}

Field definitions:

FieldTypeDescriptionValues
application_tracking_enabledintegerWhether app-level tracking is enabled0 or 1
advertiser_tracking_enabledintegerWhether ad tracking is enabled (iOS ATT)0 or 1
extinfoarrayDevice/app metadata arraySee section 2

application_tracking_enabled

This indicates whether your app has permission to track the user at the application level.

When to set to 0:

When to set to 1:

advertiser_tracking_enabled (iOS Specific)

This specifically reflects iOS App Tracking Transparency (ATT) status.

iOS implementation:

import AppTrackingTransparency

func getAdvertiserTrackingEnabled() -> Int {
    if #available(iOS 14.5, *) {
        let status = ATTrackingManager.trackingAuthorizationStatus
        return (status == .authorized) ? 1 : 0
    } else {
        return 1 // Pre-iOS 14.5, always enabled
    }
}

React Native implementation:

import { getTrackingStatus } from 'react-native-tracking-transparency';

async function getAdvertiserTrackingEnabled() {
    const status = await getTrackingStatus();
    return (status === 'authorized' || status === 'unavailable') ? 1 : 0;
}

Optional app_data Fields

{
    "app_data": {
        "installer_package": "com.android.vending",
        "url_schemes": ["myapp://"],
        "consider_views": 1,
        "campaign_ids": "campaign_123"
    }
}
FieldDescriptionExample
installer_packageWhere the app was installed fromcom.android.vending (Google Play). Android only: Meta says it is “used internally by the Android SDKs”
url_schemesDeep link URL schemes your app supports["myapp://", "https://myapp.com"]
consider_viewsWhether to consider view-through attribution1 (yes) or 0 (no)
campaign_idsCampaign identifiers if tracking specific campaigns"campaign_123,campaign_456"

Getting installer_package

Android (Kotlin):

fun getInstallerPackage(context: Context): String? {
    return try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            context.packageManager.getInstallSourceInfo(context.packageName).installingPackageName
        } else {
            @Suppress("DEPRECATION")
            context.packageManager.getInstallerPackageName(context.packageName)
        }
    } catch (e: Exception) {
        null
    }
}

// Common values:
// "com.android.vending" - Google Play Store
// "com.amazon.venezia" - Amazon App Store
// null or "com.google.android.packageinstaller" - Sideloaded

iOS: Meta documents no iOS value for installer_package: leave it out of iOS events.

Complete app_data Example

{
    "app_data": {
        "application_tracking_enabled": 1,
        "advertiser_tracking_enabled": 0,
        "extinfo": [
            "i2",
            "com.myapp",
            "1.2.3",
            "456",
            "17.2.1",
            "iPhone14,2",
            "en_US",
            "CET",
            "Orange",
            "1170",
            "2532",
            "3",
            "6",
            "256",
            "120",
            "Europe/Paris"
        ],
        "url_schemes": ["myapp://", "https://myapp.com"],
        "consider_views": 1
    }
}

Sources:


Critical Parameter #5: action_source

What is action_source?

The action_source parameter tells Meta where the event originated. This is absolutely critical – if you set it wrong, attribution will fail completely.

Valid Values

ValueWhen to UseDescription
appMobile app eventsEvents from your iOS/Android app
websiteWeb eventsEvents from your website
emailEmail eventsConversions from email campaigns
phone_callPhone conversionsConversions from phone calls
chatChat conversionsConversions from chat/messaging
physical_storeIn-store eventsOffline conversions in physical locations
system_generatedSystem eventsEvents generated by automated systems
otherOther sourcesAny other source

For Mobile Apps: ALWAYS Use “app”

{
    "action_source": "app"
}

What happens if you use “website” by mistake?

Complete Event Structure with action_source

{
    "data": [{
        "event_name": "Purchase",
        "event_time": 1701234567,
        "event_id": "purchase_ORDER789_1701234567",
        "action_source": "app",
        "user_data": {
            "madid": "38400000-8cf0-11bd-b23e-10b96e40000d",
            "anon_id": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
            "em": "973dfe463ec85785f5f95af5ba3906eedb2d931c24e69824a89ea65dba4e813b",
            "client_ip_address": "203.0.113.42",
            "client_user_agent": "Mozilla/5.0..."
        },
        "app_data": {
            "application_tracking_enabled": 1,
            "advertiser_tracking_enabled": 1,
            "extinfo": [/* ... */]
        },
        "custom_data": {
            "value": 129.99,
            "currency": "EUR"
        }
    }]
}

Sources:

Additional Important Parameters

event_time

The Unix timestamp (in seconds, not milliseconds) when the event occurred.

const eventTime = Math.floor(Date.now() / 1000);

CRITICAL: Meta expects seconds, not milliseconds. JavaScript’s Date.now() returns milliseconds, so divide by 1000.

❌ Wrong: 1701234567890 (milliseconds)
✅ Correct: 1701234567 (seconds)

event_id

A unique identifier for deduplication. If you’re sending the same event from multiple sources (e.g., both app SDK and CAPI), use the same event_id so Meta can deduplicate.

const eventId = `${eventName}_${orderId}_${timestamp}`;
// Example: "purchase_ORDER789_1701234567"

Best practices:

event_source_url

The deep link or route within your app where the event occurred.

{
    "event_source_url": "myapp://product/12345"
}

This helps Meta understand the user journey within your app.

opt_out

A flag on the event, not a consent mechanism.

{
    "opt_out": false
}

opt_out appears in Meta’s payload examples ("opt_out": false), but its effect is not described on the current Conversions API parameter pages. It does not replace consent: if the user refused, do not send the event.

client_ip_address & client_user_agent

These should be collected by your backend server (not the mobile app) to ensure accuracy.

{
    "user_data": {
        "client_ip_address": "203.0.113.42",
        "client_user_agent": "MyApp/1.2.3 (iPhone; iOS 17.2.1)"
    }
}

Why collect server-side?

Node.js example (Express):

app.post('/api/track-event', (req, res) => {
    const clientIP = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    const userAgent = req.headers['user-agent'];
    
    const eventData = {
        ...req.body,
        client_ip_address: clientIP,
        client_user_agent: userAgent
    };
    
    sendToMetaCAPI(eventData);
    res.sendStatus(200);
});

Complete Implementation Example

Mobile App (React Native)

// EventTracker.js
import AsyncStorage from '@react-native-async-storage/async-storage';
import DeviceInfo from 'react-native-device-info';
import { requestTrackingPermission } from 'react-native-tracking-transparency';
import { Platform, Dimensions } from 'react-native';
import uuid from 'react-native-uuid';

class EventTracker {
    constructor(backendUrl) {
        this.backendUrl = backendUrl;
        this.deviceData = null;
    }
    
    async initialize() {
        // Collect device data once at app start
        this.deviceData = await this.collectDeviceData();
    }
    
    async collectDeviceData() {
        const madid = await this.getMADID();
        const anonId = await this.getOrCreateAnonId();
        const extinfo = await this.buildExtinfo();
        const attEnabled = await this.getATTStatus();
        
        return {
            madid,
            anonId,
            extinfo,
            applicationTrackingEnabled: 1, // Adjust based on app consent
            advertiserTrackingEnabled: attEnabled
        };
    }
    
    async getMADID() {
        try {
            if (Platform.OS === 'ios') {
                const status = await requestTrackingPermission();
                if (status === 'authorized' || status === 'unavailable') {
                    const idfa = await DeviceInfo.getAdvertisingId();
                    return this.formatMADID(idfa);
                }
                return null;
            } else {
                // Android
                const gaid = await DeviceInfo.getAdvertisingId();
                return this.formatMADID(gaid);
            }
        } catch (error) {
            console.error('Error getting MADID:', error);
            return null;
        }
    }
    
    formatMADID(madid) {
        if (!madid || madid === '00000000-0000-0000-0000-000000000000') {
            return null;
        }
        return madid.toLowerCase(); // keep the dashes, never hash
    }
    
    async getOrCreateAnonId() {
        const key = 'anon_id';
        try {
            let anonId = await AsyncStorage.getItem(key);
            if (!anonId) {
                anonId = uuid.v4().toLowerCase();
                await AsyncStorage.setItem(key, anonId);
            }
            return anonId;
        } catch (error) {
            console.error('Error with anon_id:', error);
            return uuid.v4().toLowerCase();
        }
    }
    
    async buildExtinfo() {
        const GB = 1024 * 1024 * 1024;
        const str = (x) => (x === null || x === undefined ? '' : String(x)); // strings only, missing = ""
        try {
            const screen = Dimensions.get('screen');
            const tzPart = new Intl.DateTimeFormat('en-US', { timeZoneName: 'short' })
                .formatToParts(new Date())
                .find(p => p.type === 'timeZoneName');

            return [
                Platform.OS === 'ios' ? 'i2' : 'a2',
                str(DeviceInfo.getBundleId()),
                str(DeviceInfo.getVersion()),
                str(DeviceInfo.getBuildNumber()),
                str(DeviceInfo.getSystemVersion()),
                str(await DeviceInfo.getDeviceId()),
                str(DeviceInfo.getDeviceLocale()),
                tzPart ? tzPart.value : '',
                str(await DeviceInfo.getCarrier()),
                str(Math.round(screen.width * screen.scale)),
                str(Math.round(screen.height * screen.scale)),
                str(screen.scale),
                str(await DeviceInfo.getProcessorCount()),
                str(Math.round(await DeviceInfo.getTotalDiskCapacity() / GB)),
                str(Math.round(await DeviceInfo.getFreeDiskStorage() / GB)),
                Intl.DateTimeFormat().resolvedOptions().timeZone || ''
            ];
        } catch (error) {
            console.error('Error building extinfo:', error);
            return [Platform.OS === 'ios' ? 'i2' : 'a2', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''];
        }
    }
    
    async getATTStatus() {
        if (Platform.OS === 'ios') {
            try {
                const status = await requestTrackingPermission();
                return (status === 'authorized' || status === 'unavailable') ? 1 : 0;
            } catch (error) {
                return 0;
            }
        }
        return 1; // Android doesn't have ATT
    }
    
    async trackEvent(eventName, customData = {}, userData = {}) {
        if (!this.deviceData) {
            await this.initialize();
        }
        
        const eventId = `${eventName}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
        
        const payload = {
            eventName,
            eventId,
            eventTime: Math.floor(Date.now() / 1000),
            deviceData: this.deviceData,
            customData,
            userData: {
                email: userData.email,
                phone: userData.phone,
                firstName: userData.firstName,
                lastName: userData.lastName,
                city: userData.city,
                state: userData.state,
                zip: userData.zip,
                country: userData.country,
                gender: userData.gender,
                dob: userData.dob
            }
        };
        
        try {
            const response = await fetch(`${this.backendUrl}/track-event`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(payload)
            });
            
            if (!response.ok) {
                throw new Error(`Backend error: ${response.status}`);
            }
            
            console.log(`Event ${eventName} tracked successfully`);
        } catch (error) {
            console.error('Error tracking event:', error);
            // Implement retry logic or queue for later
        }
    }
    
    // Convenience methods for common events
    
    async trackPurchase(order) {
        await this.trackEvent('Purchase', {
            value: order.total,
            currency: order.currency,
            content_type: 'product',
            content_ids: order.items.map(i => i.id),
            contents: order.items.map(i => ({
                id: i.id,
                quantity: i.quantity,
                item_price: i.price
            })),
            num_items: order.items.length,
            order_id: order.id
        });
    }
    
    async trackAddToCart(product) {
        await this.trackEvent('AddToCart', {
            value: product.price,
            currency: product.currency,
            content_type: 'product',
            content_ids: [product.id],
            content_name: product.name
        });
    }
    
    async trackRegistration(user) {
        await this.trackEvent('CompleteRegistration', {}, {
            email: user.email,
            phone: user.phone,
            firstName: user.firstName,
            lastName: user.lastName
        });
    }
}

export default EventTracker;

// Usage in your app
// const tracker = new EventTracker('https://your-backend.com/api');
// await tracker.initialize();
// await tracker.trackPurchase(orderData);

Backend Server (Node.js/Express)

// server.js
const express = require('express');
const crypto = require('crypto');
const axios = require('axios');

const app = express();
app.use(express.json());

const DATASET_ID = process.env.META_DATASET_ID; // dataset linked to your app in Events Manager
const API_VERSION = process.env.META_API_VERSION || 'v25.0'; // v18.0 expired in January 2026
const ACCESS_TOKEN = process.env.META_ACCESS_TOKEN;

class AdvancedMatcher {
    static normalizeEmail(email) {
        return email ? email.trim().toLowerCase() : null;
    }
    
    static normalizePhone(phone, countryCode = '1') {
        if (!phone) return null;
        phone = phone.replace(/[^0-9]/g, '');               // digits only, never "+"
        if (phone.startsWith('00')) return phone.substring(2);  // international prefix
        if (phone.startsWith('0')) return countryCode + phone.substring(1); // national number
        return phone;
    }
    
    static normalizeName(name) {
        return name ? name.trim().toLowerCase().replace(/[^\p{L}]/gu, '') : null;
    }
    
    static normalizeLocation(location) {
        return location ? location.trim().toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-z]/g, '') : null;
    }
    
    static normalizeZip(zip, country) {
        if (!zip) return null;
        zip = zip.trim().toLowerCase().replace(/[\s-]/g, '');
        return country === 'us' ? zip.substring(0, 5) : zip;
    }
    
    static normalizeGender(gender) {
        if (!gender) return null;
        gender = gender.trim().toLowerCase();
        if (['m', 'male'].includes(gender)) return 'm';
        if (['f', 'female'].includes(gender)) return 'f';
        return null;
    }
    
    static normalizeDOB(dob) {
        if (!dob) return null;
        if (dob instanceof Date) {
            const year = dob.getFullYear();
            const month = String(dob.getMonth() + 1).padStart(2, '0');
            const day = String(dob.getDate()).padStart(2, '0');
            return `${year}${month}${day}`;
        }
        const cleaned = String(dob).replace(/[^0-9]/g, '');
        return cleaned.length === 8 ? cleaned : null;
    }
    
    static hash(value) {
        return value ? crypto.createHash('sha256').update(value).digest('hex') : null;
    }
    
    static buildUserData(raw, countryCode = '1') {
        const normalized = {
            email: this.normalizeEmail(raw.email),
            phone: this.normalizePhone(raw.phone, countryCode),
            firstName: this.normalizeName(raw.firstName),
            lastName: this.normalizeName(raw.lastName),
            city: this.normalizeLocation(raw.city),
            state: this.normalizeLocation(raw.state),
            zip: this.normalizeZip(raw.zip, raw.country?.trim().toLowerCase()),
            country: raw.country?.trim().toLowerCase() || null,
            gender: this.normalizeGender(raw.gender),
            dob: this.normalizeDOB(raw.dob)
        };
        
        const hashed = {};
        if (normalized.email) hashed.em = this.hash(normalized.email);
        if (normalized.phone) hashed.ph = this.hash(normalized.phone);
        if (normalized.firstName) hashed.fn = this.hash(normalized.firstName);
        if (normalized.lastName) hashed.ln = this.hash(normalized.lastName);
        if (normalized.city) hashed.ct = this.hash(normalized.city);
        if (normalized.state) hashed.st = this.hash(normalized.state);
        if (normalized.zip) hashed.zp = this.hash(normalized.zip);
        if (normalized.country) hashed.country = this.hash(normalized.country); // hashed too
        if (normalized.gender) hashed.ge = this.hash(normalized.gender);
        if (normalized.dob) hashed.db = this.hash(normalized.dob);
        
        return hashed;
    }
}

async function sendToMetaCAPI(eventData, clientIP, userAgent) {
    const { deviceData, userData, customData, eventName, eventId, eventTime } = eventData;
    
    // Build user_data
    const hashedUserData = AdvancedMatcher.buildUserData(userData || {});
    
    const userDataPayload = {
        ...hashedUserData,
        madid: deviceData.madid?.toLowerCase(), // with dashes, unhashed
        anon_id: deviceData.anonId,
        client_ip_address: clientIP,
        client_user_agent: userAgent
    };
    
    // Remove null/undefined values
    Object.keys(userDataPayload).forEach(key => {
        if (userDataPayload[key] == null) delete userDataPayload[key];
    });
    
    // Build app_data
    const appDataPayload = {
        application_tracking_enabled: deviceData.applicationTrackingEnabled,
        advertiser_tracking_enabled: deviceData.advertiserTrackingEnabled,
        extinfo: deviceData.extinfo
    };
    
    // Build complete event
    const event = {
        event_name: eventName,
        event_time: eventTime,
        event_id: eventId,
        action_source: 'app',
        user_data: userDataPayload,
        app_data: appDataPayload,
        custom_data: customData || {}
    };
    
    // Send to Meta
    try {
        const response = await axios.post(
            `https://graph.facebook.com/${API_VERSION}/${DATASET_ID}/events`,
            { data: [event] },
            {
                params: { access_token: ACCESS_TOKEN },
                headers: { 'Content-Type': 'application/json' }
            }
        );
        
        console.log('Meta CAPI response:', response.data);
        return response.data;
    } catch (error) {
        console.error('Error sending to Meta CAPI:', error.response?.data || error.message);
        throw error;
    }
}

app.post('/api/track-event', async (req, res) => {
    try {
        const clientIP = req.headers['x-forwarded-for']?.split(',')[0] || req.connection.remoteAddress;
        const userAgent = req.headers['user-agent'];
        
        await sendToMetaCAPI(req.body, clientIP, userAgent);
        
        res.json({ success: true });
    } catch (error) {
        console.error('Error processing event:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

Testing & Debugging

Use Meta’s Test Events Tool

Meta provides a Test Events tool in Events Manager that lets you send test events and verify they’re formatted correctly.

Step 1: Get a test event code

  1. Go to Meta Events Manager
  2. Select your Pixel/Dataset
  3. Click “Test Events”
  4. Copy the test event code (e.g., TEST12345)

Step 2: Send a test event with the code

const testEvent = {
    // ... your normal event payload
    test_event_code: 'TEST12345'
};

await sendToMetaCAPI(testEvent);

Step 3: Verify in Test Events UI

Check that:

Common Issues & Solutions

Issue: Events not showing in Test Events

Possible causes:

Issue: Poor matching (EMQ is not shown for app events: check delivery and matching in Test Events and the dataset diagnostics instead)

Possible causes:

Issue: Events showing but not in Ads Manager

Possible causes:

Debugging Checklist

Before going to production, verify:

Common Pitfalls & How to Avoid Them

Pitfall #1: MADID Formatting

❌ Wrong:

madid: "384000008cf011bdb23e10b96e40000d" // Dashes removed: not the format Meta documents

✅ Correct:

madid: "38400000-8cf0-11bd-b23e-10b96e40000d" // Lowercase, with dashes, unhashed

Pitfall #2: Hashing Before Normalization

❌ Wrong:

const hashedEmail = hashSHA256("  Test@Example.com  "); // Hashing raw input

✅ Correct:

const normalized = normalizeEmail("  Test@Example.com  "); // → "test@example.com"
const hashedEmail = hashSHA256(normalized);

Pitfall #3: Sending Timestamps in Milliseconds

❌ Wrong:

event_time: Date.now() // 1701234567890 (milliseconds)

✅ Correct:

event_time: Math.floor(Date.now() / 1000) // 1701234567 (seconds)

Pitfall #4: Missing anon_id Fallback

❌ Wrong:

// Only sending MADID, no fallback when ATT denied
user_data: {
    madid: idfa // Will be "00000000..." when ATT denied
}

✅ Correct:

user_data: {
    madid: idfa !== "00000000-0000-0000-0000-000000000000" ? formatMADID(idfa) : null,
    anon_id: anonId // Always include fallback
}

Pitfall #5: Wrong action_source

❌ Wrong:

action_source: "website" // Treating app events as web events

✅ Correct:

action_source: "app"

Pitfall #6: Incomplete extinfo

❌ Wrong:

extinfo: ["a2", "com.myapp", "1.0"] // Only 3 values

✅ Correct:

extinfo: [
    "i2", "com.myapp", "1.2.3", "456", "17.2.1", "iPhone14,2",
    "en_US", "CET", "Orange", "1170", "2532", "3",
    "6", "256", "120", "Europe/Paris"
] // All 16 values, all strings

Pitfall #7: Sending Country Unhashed

❌ Wrong:

country: "fr" // Not hashed: Meta expects the SHA-256 of the code

✅ Correct:

country: hashSHA256("fr") // Lowercase ISO 3166-1 alpha-2 code, then SHA-256

Pitfall #8: Not Handling iOS ATT Properly

❌ Wrong:

// Requesting IDFA without ATT permission
const idfa = await ASIdentifierManager.shared().advertisingIdentifier.uuidString;

✅ Correct:

// Request ATT permission first
const status = await ATTrackingManager.requestTrackingAuthorization();
if (status === 'authorized') {
    const idfa = await ASIdentifierManager.shared().advertisingIdentifier.uuidString;
} else {
    // Use anon_id instead
}

Performance & Scale Considerations

Mobile App Performance

Minimize data collection overhead:

Example optimization:

class EventTracker {
    constructor() {
        this.deviceDataCache = null;
        this.isInitialized = false;
    }
    
    async initialize() {
        if (this.isInitialized) return;
        
        // Collect device data in background
        this.deviceDataCache = await this.collectDeviceData();
        this.isInitialized = true;
    }
    
    async trackEvent(eventName, data) {
        // Use cached device data
        const payload = {
            ...data,
            deviceData: this.deviceDataCache
        };
        
        // Send asynchronously, don't wait
        this.sendToBackend(payload).catch(console.error);
    }
}

Backend Performance

For high-volume apps (>10k events/minute):

  1. Implement batching:
// Send events in batches of up to 1000
const batches = [];
for (let i = 0; i < events.length; i += 1000) {
    batches.push(events.slice(i, i + 1000));
}

for (const batch of batches) {
    await sendToMetaCAPI({ data: batch });
}
  1. Use a queue system (Redis, RabbitMQ):
// Add events to queue
await redisClient.rPush('meta_events_queue', JSON.stringify(event));

// Worker process consumes queue
while (true) {
    const eventJSON = await redisClient.lPop('meta_events_queue');
    if (eventJSON) {
        const event = JSON.parse(eventJSON);
        await sendToMetaCAPI(event);
    }
}
  1. Implement retry logic with exponential backoff:
async function sendWithRetry(event, maxRetries = 3) {
    for (let attempt = 1; attempt <= maxRetries; attempt++) {
        try {
            await sendToMetaCAPI(event);
            return; // Success
        } catch (error) {
            if (attempt === maxRetries) {
                // Final failure, log to dead letter queue
                await logToDeadLetterQueue(event, error);
                throw error;
            }
            // Exponential backoff: 2^attempt seconds
            await sleep(Math.pow(2, attempt) * 1000);
        }
    }
}

Monitoring & Alerting

Key metrics to monitor:

Example monitoring setup (Node.js + Prometheus):

const promClient = require('prom-client');

const eventsSent = new promClient.Counter({
    name: 'meta_capi_events_sent_total',
    help: 'Total number of events sent to Meta CAPI',
    labelNames: ['event_name', 'status']
});

const eventLatency = new promClient.Histogram({
    name: 'meta_capi_event_latency_seconds',
    help: 'Latency of Meta CAPI requests',
    buckets: [0.1, 0.5, 1, 2, 5]
});

async function sendToMetaCAPI(event) {
    const start = Date.now();
    try {
        await axios.post(/* ... */);
        eventsSent.inc({ event_name: event.event_name, status: 'success' });
    } catch (error) {
        eventsSent.inc({ event_name: event.event_name, status: 'error' });
        throw error;
    } finally {
        eventLatency.observe((Date.now() - start) / 1000);
    }
}

Conclusion

Implementing Meta CAPI for mobile apps without the SDK is technically complex but provides significant benefits:

✅ Full control over data collection and transmission
✅ One place to enforce consent (your backend)
✅ Reduced app size and dependencies
✅ Unified tracking architecture (web + mobile)
✅ Server-side validation and data enrichment

But it requires meticulous attention to detail:

❌ A large part of the SDK’s work must be recreated manually
❌ High risk of attribution failure if parameters are incorrect
❌ Additional server infrastructure and maintenance
❌ iOS ATT complexity requires careful handling

Before going to production:

  1. Test thoroughly with Meta’s Test Events tool
  2. Check delivery and matching in Test Events and the dataset diagnostics (EMQ is not shown for app events)
  3. Monitor event delivery and error rates
  4. Implement robust retry and fallback mechanisms
  5. Document your implementation for future maintenance

Key takeaways:

This implementation approach is not for everyone. If you’re just getting started with Meta ads on mobile, use the SDK. But if you need maximum control, privacy compliance, or have specific architectural requirements, the CAPI-only approach is powerful once properly implemented.

Related reading

Sources & References

  1. Meta Conversions API Overview: https://developers.facebook.com/documentation/ads-commerce/conversions-api
  2. CAPI Server Event Parameters: https://developers.facebook.com/documentation/ads-commerce/conversions-api/parameters/server-event
  3. CAPI Customer Information Parameters: https://developers.facebook.com/documentation/ads-commerce/conversions-api/parameters/customer-information-parameters
  4. Meta App Events Parameters: https://developers.facebook.com/documentation/app-events/getting-started-app-events-android
  5. CAPI Best Practices: https://developers.facebook.com/documentation/ads-commerce/conversions-api/best-practices
  6. Advanced Matching: https://developers.facebook.com/documentation/meta-pixel/advanced/advanced-matching
  7. Meta Data Hashing Guide: https://developers.facebook.com/documentation/ads-commerce/conversions-api/parameters/customer-information-parameters
  8. iOS App Tracking Transparency: https://developer.apple.com/documentation/apptrackingtransparency
  9. Android Advertising ID: https://support.google.com/googleplay/android-developer/answer/6048248
  10. Meta CAPI Deduplication: https://developers.facebook.com/documentation/ads-commerce/conversions-api/deduplicate-pixel-and-server-events

Not sure your own tracking is right?

Book a call Or start with the free analytics audit →