> For the complete documentation index, see [llms.txt](https://docs.webtonative.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.webtonative.com/javascript-apis/facebook-app-events-api.md).

# Facebook App Events API

Track user actions with the WebToNative Facebook App Events API. Integrate event logging to measure app engagement and conversions.

Use the Facebook App Events API to log what users do in your app, such as sign-ups, add-to-carts and purchases, so you can measure engagement and conversions and optimise your ads in Facebook Events Manager. You can also turn the Facebook SDK's automatic event logging on or off at runtime, for example to respect a user's consent choice.

> You'll need to import the javascript file in your website before starting from this [link](https://docs.webtonative.com/javascript-apis/getting-started).

This page covers:

| Function                                                                       | What it does                                               |
| ------------------------------------------------------------------------------ | ---------------------------------------------------------- |
| [`events.send`](#send-a-custom-event)                                          | Logs a custom or standard event.                           |
| [`events.sendPurchase`](#send-a-purchase-event)                                | Logs a purchase with an amount and currency.               |
| [`setFacebookAnalyticsCollection`](#enable-or-disable-automatic-event-logging) | Turns automatic event logging on or off.                   |
| [`getFacebookAnalyticsCollectionStatus`](#get-automatic-event-logging-status)  | Tells you whether automatic event logging is currently on. |

***

## Automatically Logged Events

When the Facebook SDK is active, it logs certain events (such as app installs and app launches) automatically and sends them to Facebook Events Manager. These events are used for targeting, measurement and optimisation.

Learn more about automatically logged events:

* **Android:** <https://developers.facebook.com/docs/app-events/getting-started-app-events-android#auto-events>
* **iOS:** <https://developers.facebook.com/docs/app-events/getting-started-app-events-ios#auto-events>

You can turn this automatic logging on or off from your website with [`setFacebookAnalyticsCollection`](#enable-or-disable-automatic-event-logging), and check its current state with [`getFacebookAnalyticsCollectionStatus`](#get-automatic-event-logging-status).

***

## Manually Log Events (Custom Events)

Besides the automatic events, you can log your own events whenever something meaningful happens on your website, such as a completed registration or a viewed product.

> Facebook Analytics must be enabled in your app configuration. If it is not, `send` and `sendPurchase` do nothing on both Android and iOS, and no error is reported.

### Send a custom event

Sends a custom or standard event to Facebook.

{% tabs %}
{% tab title="Plain Javascript" %}

```javascript
const { events: FacebookEvents } = window.WTN.facebook;

FacebookEvents.send({
  event: "MY_EVENT",
  valueToSum: 10, // optional
  parameters: {   // optional
    name: "webtonative",
  },
});
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { send } from "webtonative/Facebook/events";

send({
  event: "MY_EVENT",
  valueToSum: 10, // optional
  parameters: {   // optional
    name: "webtonative",
  },
});
```

{% endtab %}
{% endtabs %}

**Parameters:**

| Key          | Type     | Required | Description                                                                                                                                            |
| ------------ | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `event`      | `String` | Yes      | Name of the event. Use a Facebook standard event name (see [Event names and parameter keys](#event-names-and-parameter-keys)) or your own custom name. |
| `valueToSum` | `Number` | No       | A numeric value Facebook adds up across events, for example an order value.                                                                            |
| `parameters` | `Object` | No       | Extra key-value data to attach to the event.                                                                                                           |

This function does not take a callback.

### Send a purchase event

Purchases have their own function. Facebook's SDK sends purchase events more quickly than regular events.

{% tabs %}
{% tab title="Plain Javascript" %}

```javascript
const { events: FacebookEvents } = window.WTN.facebook;

FacebookEvents.sendPurchase({
  amount: 3.14,
  currency: "INR",
  parameters: { // optional
    name: "webtonative",
  },
});
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { sendPurchase } from "webtonative/Facebook/events";

sendPurchase({
  amount: 3.14,
  currency: "INR",
  parameters: { // optional
    name: "webtonative",
  },
});
```

{% endtab %}
{% endtabs %}

**Parameters:**

| Key          | Type     | Required | Description                                                                  |
| ------------ | -------- | -------- | ---------------------------------------------------------------------------- |
| `amount`     | `Number` | Yes      | The purchase amount.                                                         |
| `currency`   | `String` | Yes      | A valid ISO 4217 currency code in uppercase, for example `"USD"` or `"INR"`. |
| `parameters` | `Object` | No       | Extra key-value data to attach to the event.                                 |

This function does not take a callback.

### Event names and parameter keys

The list of standard event names and parameter keys is available here:

* **Android:** <https://developers.facebook.com/docs/app-events/reference#standard-events>
* **iOS:** <https://developers.facebook.com/docs/app-events/reference#standard-events-2>

***

## Enable or Disable Automatic Event Logging

Turns the Facebook SDK's automatic event logging on or off. Use this to stop sending data to Facebook until the user gives consent, and to turn it back on once they do.

The choice is saved on the device and is applied again every time the app starts. Until it is set, the app uses the automatic logging default from your app configuration.

> This setting only controls **automatically logged events**. Events you send with `events.send` and `events.sendPurchase` are still sent while it is off, so check the user's consent in your own code before calling them (see the [example](#example-consent-toggle) below).

{% tabs %}
{% tab title="Plain Javascript" %}

```javascript
window.WTN.facebook.setFacebookAnalyticsCollection({
  enabled: true, // true = enable, false = disable
  callback: function (data) {
    console.log(data);
  },
});
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { setFacebookAnalyticsCollection } from "webtonative/Facebook";

setFacebookAnalyticsCollection({
  enabled: true, // true = enable, false = disable
  callback: function (data) {
    console.log(data);
  },
});
```

{% endtab %}
{% endtabs %}

**Parameters:**

| Key        | Type       | Required | Description                                                                                                |
| ---------- | ---------- | -------- | ---------------------------------------------------------------------------------------------------------- |
| `enabled`  | `Boolean`  | Yes      | `true` to enable automatic event logging, `false` to disable it. Pass a real boolean, not `"true"` or `1`. |
| `callback` | `Function` | No       | Receives the response object.                                                                              |

**Callback responses:**

Success (Android and iOS):

```json
{ "type": "setFacebookAnalyticsCollection", "success": true }
```

Invalid `enabled` value (Android only):

```json
{ "type": "setFacebookAnalyticsCollection", "success": false, "error": "Invalid data: 'enabled' must be a boolean" }
```

Save or apply failed (Android only):

```json
{ "type": "setFacebookAnalyticsCollection", "success": false, "error": "<exception message>" }
```

If the exception has no message, `error` is `"Failed to update Facebook Analytics collection"`.

***

## Get Automatic Event Logging Status

Tells you whether automatic event logging is currently on. Use it to show the right state in a privacy or consent setting.

{% tabs %}
{% tab title="Plain Javascript" %}

```javascript
window.WTN.facebook.getFacebookAnalyticsCollectionStatus({
  callback: function (data) {
    console.log(data.enabled);
  },
});
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { getFacebookAnalyticsCollectionStatus } from "webtonative/Facebook";

getFacebookAnalyticsCollectionStatus({
  callback: function (data) {
    console.log(data.enabled);
  },
});
```

{% endtab %}
{% endtabs %}

**Parameters:**

| Key        | Type       | Required | Description                   |
| ---------- | ---------- | -------- | ----------------------------- |
| `callback` | `Function` | No       | Receives the response object. |

**Callback response:**

```json
{ "type": "getFacebookAnalyticsCollectionStatus", "enabled": true }
```

`enabled` is `true` when automatic event logging is on and `false` when it is off.

***

## Example: Consent Toggle

A privacy setting that shows the current state when the page loads and turns automatic event logging on or off when the user changes it. A purchase event is only sent while logging is enabled.

{% tabs %}
{% tab title="Plain Javascript" %}

```html
<label>
  <input type="checkbox" id="fb-consent" disabled />
  Share app usage with Facebook
</label>

<script>
  const consentToggle = document.getElementById("fb-consent");
  let facebookLoggingEnabled = false;

  // Show the current state
  window.WTN.facebook.getFacebookAnalyticsCollectionStatus({
    callback: function (data) {
      facebookLoggingEnabled = data.enabled === true;
      consentToggle.checked = facebookLoggingEnabled;
      consentToggle.disabled = false;
    },
  });

  // Save the user's choice
  consentToggle.addEventListener("change", function () {
    const enabled = consentToggle.checked;
    consentToggle.disabled = true;

    window.WTN.facebook.setFacebookAnalyticsCollection({
      enabled: enabled, // real boolean
      callback: function (data) {
        consentToggle.disabled = false;

        if (data.success) {
          facebookLoggingEnabled = enabled;
          // Your code: e.g. show "Preference saved"
        } else {
          consentToggle.checked = !enabled; // revert the toggle
          // Your code: e.g. show data.error
        }
      },
    });
  });

  // Call this after a successful checkout
  function onPurchaseComplete(order) {
    if (!facebookLoggingEnabled) return;

    window.WTN.facebook.events.sendPurchase({
      amount: order.total,
      currency: order.currency,
      parameters: { order_id: order.id },
    });
  }
</script>
```

{% endtab %}

{% tab title="npm" %}

```javascript
import {
  setFacebookAnalyticsCollection,
  getFacebookAnalyticsCollectionStatus,
} from "webtonative/Facebook";
import { sendPurchase } from "webtonative/Facebook/events";

// <input type="checkbox" id="fb-consent" disabled />
const consentToggle = document.getElementById("fb-consent");
let facebookLoggingEnabled = false;

// Show the current state
getFacebookAnalyticsCollectionStatus({
  callback: (data) => {
    facebookLoggingEnabled = data.enabled === true;
    consentToggle.checked = facebookLoggingEnabled;
    consentToggle.disabled = false;
  },
});

// Save the user's choice
consentToggle.addEventListener("change", () => {
  const enabled = consentToggle.checked;
  consentToggle.disabled = true;

  setFacebookAnalyticsCollection({
    enabled, // real boolean
    callback: (data) => {
      consentToggle.disabled = false;

      if (data.success) {
        facebookLoggingEnabled = enabled;
        // Your code: e.g. show "Preference saved"
      } else {
        consentToggle.checked = !enabled; // revert the toggle
        // Your code: e.g. show data.error
      }
    },
  });
});

// Call this after a successful checkout
export function onPurchaseComplete(order) {
  if (!facebookLoggingEnabled) return;

  sendPurchase({
    amount: order.total,
    currency: order.currency,
    parameters: { order_id: order.id },
  });
}
```

{% endtab %}
{% endtabs %}

***
