PHP Code for Sending Simple Events to Meta Conversion API

In the course of working with the Meta (Facebook) Conversion API, I had a need to send my own events to the API which were only available in the professional versions of plugins for WordPress. Some were also not even captured by any plugin due to the nature of the event–Such as a WordPress redirect.

The following code can be modified for your Pixel ID (Dataset ID) and Conversion API access token, and inserted into WordPress files (such as Header.php) or other PHP code files.

A good example of the JSON input (the $data code below) is available in the Meta documentation. I recommend using the JSONEdit free app to allow you to visualize/test the JSON output (the $datastring variable contents).

A big word of thanks to Abraham Garcia, whose instructive page provided the base overall code required to build the JSON via arrays, convert the arrays to JSON, and to execute cURL commands from within PHP (the code that sends the message to Meta).

NOTE: This example is provided with no guarantees of its fitness for use. Use at your own discretion.

//This obtains the referring page info to pass on to Meta, 
//including query string parameters if any
$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$url = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

//Fill these variables in as needed if you have customer email and phone
//NOTE: these must be hashed or they will violate privacy terms of Meta!!!
$email = "";
$phone = "";

//IP and browser of person calling the page
$ip = getenv("REMOTE_ADDR");
$browser = $_SERVER['HTTP_USER_AGENT'];

//Facebook values obtained from facebook cookies which identify visitor.
$fbc = $_COOKIE["_fbc"];
$fbp = $_COOKIE["_fbp"];

//Facebook event name - taken from Meta docs - 
// https://developers.facebook.com/docs/meta-pixel/reference#standard-events
$event_name = "AddToCart";

//This is a single item ID, but with some massaging could probably be used 
//to identify multiple items
$item_ids = "{yourItemID}";
//Order total amount if you like
$order_total = 0;

//Change to Your access token and Pixel/dataset ID
$access_token = "{yourAccessToken}";
$pixel_id = "{yourPixelorDatasetID}";
//Build the data array in PHP
$data = array( // main object
    "data" => array( // data array
        array(
            "event_name" => $event_name,
            "event_time" => time(),
               "user_data" => array(
                "client_ip_address" => $ip,
                "client_user_agent" => $browser,
                "em" => $email,
                "ph" => $phone,
                "fbc" => $fbc,
                "fbp" => $fbp
                ),
                 "custom_data" => array(
                "currency" => "cad",
                "value"    => $order_total
                ,
                "contents" => array(
                array( "id" => $item_ids,
                "quantity" => 1
                ))),
                "action_source" => "website",
                "event_source_url"  => $url
       ),
    ),
       "access_token" => $access_token
    );  
    
    //Convert PHP array structure into JSON
    $dataString = json_encode($data);      
    //URL of meta server -- Ensure you are using a current version of Graph API                                                                                                        
    $ch = curl_init('https://graph.facebook.com/v18.0/' . $pixel_id . '/events');
    //cURL code to send event to Meta server                                                                      
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
    curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);                                                                  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
        'Content-Type: application/json',                                                                                
        'Content-Length: ' . strlen($dataString))                                                                       
    );                                                                                                                                                                       
    $response = curl_exec($ch);
    curl_close($ch);
//Response should be checked before assuming this code is working properly
//response should indicate message received.

I provide the example for general benefit–I am not technical support, so I will not answer questions. I hope this helps you in your journey.

Facebook Comments