{"id":12376,"date":"2024-09-03T15:20:18","date_gmt":"2024-09-03T14:20:18","guid":{"rendered":"https:\/\/www.bronco.co.uk\/our-ideas\/?p=12376"},"modified":"2024-09-03T15:20:19","modified_gmt":"2024-09-03T14:20:19","slug":"simplifying-facebook-conversions-api-php-integration-keeping-it-lightweight","status":"publish","type":"post","link":"https:\/\/www.bronco.co.uk\/our-ideas\/simplifying-facebook-conversions-api-php-integration-keeping-it-lightweight\/","title":{"rendered":"Simplifying Facebook Conversions API PHP Integration: Keeping It Lightweight"},"content":{"rendered":"\n<p><a href=\"#code-start\" data-type=\"internal\" data-id=\"#code-start\">Skip to the code<\/a><\/p>\n\n\n\n<p>In today\u2019s web development landscape, there\u2019s an ever-growing reliance on libraries and package managers, often bundled with many dependencies. While these tools speed up development and help solve complex problems, there\u2019s a number of downsides.<\/p>\n\n\n\n<p>When integrating the Facebook Conversion API, you might consider using a prebuilt library like the facebook-php-business-sdk, which requires Composer. Not only does this add extra setup steps, but an SDK like this is packed with features &#8211; most of which are unnecessary for the task at hand \u2013 unless that task is to build a user-friendly interface for the entire Facebook ecosystem.<\/p>\n\n\n\n<p>In our case, we often want to leverage the Facebook Conversions API to send events server-side, rather than relying on the Facebook Pixel, which has become less dependable in the age of cookie banners and privacy regulations.<\/p>\n\n\n\n<p>By building a solution from scratch, we ensured it was lightweight, easily transferrable to other projects, and adaptable for our future needs.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"code-start\">Implementing Facebook Conversions API<\/h2>\n\n\n\n<h4 class=\"wp-block-heading\">Setting up a PHP Class<\/h4>\n\n\n\n<p>We start by defining a simple PHP class <em><strong>FacebookConversionsAPI<\/strong><\/em> to handle our API integration. This class will include methods for sending event data, making HTTP requests, and hashing user data.<\/p>\n\n\n\n<p>In a larger applications, you might wish to split off your cURL code into other classes to avoid repetition.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-php\" data-lang=\"PHP\"><code>&lt;?php\n\nclass FacebookConversionsAPI {\n\n    private $pixel_id;\n    private $access_token;\n    private $api_url;\n\n    \/\/ constructor to set up initial values\n    public function __construct(){\n        $this-&gt;pixel_id = &#39;YOUR_PIXEL_ID_HERE&#39;; \/\/ replace with your actual Pixel ID\n        $this-&gt;access_token = &#39;YOUR_ACCESS_TOKEN_HERE&#39;; \/\/ replace with your actual access token\n        $this-&gt;api_url = &quot;https:\/\/graph.facebook.com\/v18.0\/{$this-&gt;pixel_id}\/events&quot;;\n    }\n\n    \/\/ method to send conversion data to Facebook\n    public function sendEvent($event_name, $user_data = [], $custom_data = []) {\n        \/\/ determine if the request is over HTTPS or HTTP\n        $protocol = ((!empty($_SERVER[&#39;HTTPS&#39;]) && $_SERVER[&#39;HTTPS&#39;] != &#39;off&#39;) || $_SERVER[&#39;SERVER_PORT&#39;] == 443) ? &quot;https:\/\/&quot; : &quot;http:\/\/&quot;;\n        \n        \/\/ build the full URL of the current page\n        $event_source_url = $protocol . $_SERVER[&#39;HTTP_HOST&#39;] . $_SERVER[&#39;REQUEST_URI&#39;];\n        \n        \/\/ collect Facebook cookies that are important for tracking\n        $user_data[&#39;fbc&#39;] = $_COOKIE[&quot;_fbc&quot;];\n        $user_data[&#39;fbp&#39;] = $_COOKIE[&quot;_fbp&quot;];\n        \n        \/\/ collect the client&#39;s IP address and user agent\n        $user_data[&#39;client_ip_address&#39;] = $_SERVER[&#39;REMOTE_ADDR&#39;];\n        $user_data[&#39;client_user_agent&#39;] = $_SERVER[&#39;HTTP_USER_AGENT&#39;];\n\n        \/\/ prepare event data to be sent to Facebook\n        $event_data = [\n            &#39;event_name&#39; =&gt; $event_name, \/\/ name of the event (e.g., &#39;Lead&#39;)\n            &#39;event_time&#39; =&gt; time(), \/\/ current timestamp\n            &#39;event_source_url&#39; =&gt; $event_source_url, \/\/ URL where the event occurred\n            &#39;user_data&#39; =&gt; $user_data, \/\/ hashed and non-hashed user data\n            &#39;custom_data&#39; =&gt; $custom_data, \/\/ any additional custom data for the event\n            &#39;action_source&#39; =&gt; &#39;website&#39; \/\/ specifies that the event came from the website\n        ];\n\n        \/\/ prepare the full payload including the access token\n        $payload = [\n            &#39;data&#39; =&gt; [$event_data],\n            &#39;access_token&#39; =&gt; $this-&gt;access_token\n        ];\n\n        \/\/ send the payload to Facebook using the makeRequest method\n        return $this-&gt;makeRequest($payload);\n    }\n\n    \/\/ private method to handle the CURL request to Facebook\n    private function makeRequest($payload) {\n        $payload_encode = json_encode($payload); \/\/ encode the payload as JSON\n        \n        \/\/ initialize CURL with the API URL\n        $ch = curl_init($this-&gt;api_url);\n        curl_setopt($ch, CURLOPT_POST, true); \/\/ set CURL to use POST method\n        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload_encode); \/\/ attach the payload\n        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); \/\/ return the response as a string\n        curl_setopt($ch, CURLOPT_HTTPHEADER, array(&#39;Content-Type: application\/json&#39;)); \/\/ set the content type to JSON\n\n        \/\/ execute the CURL request and get the response\n        $response = curl_exec($ch);\n        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); \/\/ get the HTTP status code\n        curl_close($ch); \/\/ close the CURL session\n\n        \/\/ check if the response was successful\n        if ($http_code !== 200 || json_decode($response)-&gt;error) {\n            return &#39;Error : &#39; . json_encode($response); \/\/ return error if the response is not OK\n        } else {\n            return true; \/\/ return true if the event was tracked successfully\n        }\n    }\n\n    \/\/ method to hash user data as per Facebook&#39;s requirements\n    public function hashUserData($data) {\n        $hashed_data = [];\n        \n        \/\/ hash each piece of user data using SHA-256\n        foreach ($data as $key =&gt; $value) {\n            $hashed_data[$key] = hash(&#39;sha256&#39;, strtolower(trim($value))); \/\/ trim, lowercase, and hash the data\n        }\n\n        return $hashed_data; \/\/ return the hashed data\n    }\n}\n?&gt;<\/code><\/pre><\/div>\n\n\n\n<h4 class=\"wp-block-heading\">Sending an event to Facebook<\/h4>\n\n\n\n<p>With our class set up, we can now track conversions by invoking the <strong><em>sendEvent<\/em><\/strong> method. Here\u2019s how you can use it in your project.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-php\" data-lang=\"PHP\"><code>&lt;?php\n\n\/\/ include the Facebook Conversions API class\nrequire realpath($_SERVER[&#39;DOCUMENT_ROOT&#39;]) . &#39;\/FOLDER_LOCATION\/fb_conversions_api.php&#39;;\n\n\/\/ create an instance of the FacebookConversionsAPI class\n$fb_api = new FacebookConversionsAPI();\n\n\/\/ prepare the data to be hashed, obtain data from form data as required \n$data_to_hash = [\n    &#39;em&#39; =&gt; $email, \/\/ user&#39;s email\n    &#39;fn&#39; =&gt; $first_name, \/\/ first name\n    &#39;ln&#39; =&gt; $last_name, \/\/ last name\n    &#39;pn&#39; =&gt; $telephone, \/\/ telephone number\n    &#39;zp&#39; =&gt; $postcide \/\/ post\/zip code\n];\n\n\/\/ any custom data you want to send with the event\n$custom_data = [\n    &#39;lead_event_source&#39; =&gt; $form_name \/\/ example custom data\n];\n\n\/\/ hash the user data using the hashUserData method\n$user_data = $fb_api-&gt;hashUserData($data_to_hash);\n\n\/\/ send the &#39;Lead&#39; event to Facebook with the hashed user data and custom data\n$fb_api-&gt;sendEvent(&#39;Lead&#39;, $user_data, $custom_data);\n\n?&gt;<\/code><\/pre><\/div>\n","protected":false},"excerpt":{"rendered":"<p>Skip to the code In today\u2019s web development landscape, there\u2019s an ever-growing reliance on libraries and package managers, often bundled with many dependencies. While these tools speed up development and help solve complex problems, there\u2019s a number of downsides. When integrating the Facebook Conversion API, you might consider using a prebuilt library like the facebook-php-business-sdk, [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":12378,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[2],"class_list":["post-12376","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-web-and-ux"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.bronco.co.uk\/our-ideas\/wp-json\/wp\/v2\/posts\/12376","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.bronco.co.uk\/our-ideas\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bronco.co.uk\/our-ideas\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bronco.co.uk\/our-ideas\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bronco.co.uk\/our-ideas\/wp-json\/wp\/v2\/comments?post=12376"}],"version-history":[{"count":3,"href":"https:\/\/www.bronco.co.uk\/our-ideas\/wp-json\/wp\/v2\/posts\/12376\/revisions"}],"predecessor-version":[{"id":12380,"href":"https:\/\/www.bronco.co.uk\/our-ideas\/wp-json\/wp\/v2\/posts\/12376\/revisions\/12380"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.bronco.co.uk\/our-ideas\/wp-json\/wp\/v2\/media\/12378"}],"wp:attachment":[{"href":"https:\/\/www.bronco.co.uk\/our-ideas\/wp-json\/wp\/v2\/media?parent=12376"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bronco.co.uk\/our-ideas\/wp-json\/wp\/v2\/categories?post=12376"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}