Facebook CAPI
@eladlevy
code:
data:privatelast updated:2 years ago
@eladlevy/
Facebook CAPI

Facebook Conversions API Webhook

This workflow provides a simple alternative to sending your client-side events as Server-Side events.
This is useful in the case your users use ad blockers or pixel blocking browsers and can increase your tracking accuracy by 5-10% on average.

Client-side script

To capture the client-side events, first add this script to all pages:

function CAPI(event, eventData) {
    let fbp = document.cookie.split(';').filter(c => c.includes('_fbp=')).map(c => c.split('_fbp=')[1]);
    let fbc = document.cookie.split(';').filter(c => c.includes('_fbc=')).map(c => c.split('_fbc=')[1]);
    fbp = (fbp.length && fbp[0]) || null;
    fbc = (fbc.length && fbc[0]) || null;

    const headers = new Headers()
    headers.append("Content-Type", "application/json")

    const body = {
        "event": event,
        "event_data": eventData,
        "fbp": fbp,
        "fbclid": fbc,
        "user_agent": navigator.userAgent,
        "url": window.location.origin + window.location.pathname
}

const options = {
    method: "POST",
    headers,
    mode: "cors",
    body: JSON.stringify(body),
}

fetch("MY_PIPEDREAM_URL", options)
}

Make sure you replace MY_PIPEDREAM_URL with the URL from the trigger step in the workflow.

To invoke this script, simply call CAPI(event), with the same event name you would have otherwise sent to Facebook, e.g. CAPI('Lead') or CAPI('Purchase', {currency: "USD", value: 30.00}).

Pipedream setup

Using this ready-made workflow, you can get this API up and running in no time.

This workflow is made of three parts:

  1. The incoming webhook (trigger) which accepts the data sent from the client
  2. The nodejs code, which prepares the data to be sent to Facebook
  3. The send request step which, well, sends the actual request to Facebook

Make sure you replace the ACCESS_TOKEN and PIXEL_ID variables with your values.

Both can be found in your Facebook Business Manager under the Events Manager