> 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/geofencing-functions.md).

# Geofencing Functions

Functions to watch geographic zones (geofences) from your website and react when the user enters, stays in, or leaves one.

A zone is a circle on the map: a centre point (latitude and longitude) and a radius in metres. Once a zone is registered, the app keeps watching it in the background, even when the app is closed. When the user crosses into a zone, stays inside it for a while, or leaves it, the app can:

* show a local notification, for example "You're near our Downtown store, show this screen for 10% off", which can open a page of your website when tapped, and
* call your webhook, so your backend knows the user arrived or left, for example to check them in, log a visit, or start a delivery.

Typical uses are store-visit offers, attendance and check-in at an office or event, and arrival alerts for pickups and deliveries.

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

> **Platform support:** Android and iOS. Every function works on both platforms unless a platform note says otherwise. `openLocationSettings` is iOS only.

> **Enable it first:** Geofencing must be turned on for your app in the WebToNative dashboard. If it is off, the functions get no reply and their promises never settle.

***

## How Geofencing Works

### Zone sources (modes)

In the WebToNative dashboard you choose where the app gets its zones from. The mode decides which functions you can use from your website.

| Mode          | Where zones come from                                                                                            | Webhook set in                                  |
| ------------- | ---------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- |
| **Dashboard** | The zones you add in the WebToNative dashboard. Every user gets the same zones.                                  | The dashboard                                   |
| **API**       | Your own endpoint, which the app calls to download the zones. Use it to send different zones to different users. | The dashboard                                   |
| **JS Bridge** | Your website, using [`addZone`](#add-zone). Use it when the zones depend on what the user does on your site.     | Your website, with [`setWebhook`](#set-webhook) |

In **Dashboard** and **API** mode the zones and webhook are managed for you, so the functions that change them reply `{ status: "not_allowed" }`. See [Which functions work in which mode](#which-functions-work-in-which-mode).

### Triggers

Each zone can fire on three triggers. For each trigger you choose whether to call the webhook, show a notification, or both.

| Trigger | Fires when                                                      |
| ------- | --------------------------------------------------------------- |
| `enter` | The user crosses into the zone.                                 |
| `dwell` | The user has stayed inside the zone for `dwellMinutes` minutes. |
| `exit`  | The user leaves the zone.                                       |

### Location permission

Geofencing only works when the app may use location **all the time** ("Allow all the time" on Android, "Always" on iOS), because zones are checked in the background. Asking only for "While using the app" is not enough. [`requestPermission`](#request-permission) takes the user through the right steps.

### Where the API mode gets zones

In **API** mode, set your endpoint in the dashboard. The app calls it on launch and when you call [`refreshZones`](#refresh-zones):

* `GET` or `POST` (as set in the dashboard), with the headers you set there. No request body is sent.
* You can put these variables in the URL or header values, and the app fills them in: `{device.platform}` (`android` or `ios`), `{device.appVersion}`, `{device.locale}`, `{device.lat}`, `{device.lng}` (last known location, when available).
* The request times out after 10 seconds.

Your endpoint must reply with a JSON object holding a `zones` array. Each zone uses the same shape as [`addZone`](#the-zone-object). `ttl` (optional) is how many seconds the app may reuse these zones before calling again; the default is 600.

```json
{
  "zones": [
    {
      "_id": "store-1",
      "name": "Downtown store",
      "locationDetails": { "latitude": 28.6139, "longitude": 77.209, "radius": 150 },
      "triggers": {
        "enter": {
          "sendPushNotification": true,
          "pushNotificationConfig": { "title": "You're nearby!", "body": "Show this for 10% off." }
        }
      }
    }
  ],
  "ttl": 600
}
```

If the call fails, the app keeps using the last zones it downloaded. A zone with an error in it is skipped and the others are still used.

***

## How the Functions Reply

Every `WTN.Geofencing` function except `openLocationSettings` returns a Promise. A call ends in one of two ways:

| Outcome  | Where it lands | What it means                                                                                        |
| -------- | -------------- | ---------------------------------------------------------------------------------------------------- |
| Rejected | `.catch`       | The call was invalid (no zone passed, or the page isn't inside a WebToNative app). Nothing was sent. |
| Resolved | `.then`        | The app replied. **Read `status` for the result**: it can still be `"error"` or `"not_allowed"`.     |

```javascript
window.WTN.Geofencing.clearAllZones()
  .then(function (response) {
    if (response.status === "not_allowed") {
      // Your app uses Dashboard or API mode. Zones are managed in the dashboard.
      return;
    }
    if (response.status !== "cleared") {
      // Something went wrong. Try again later.
      return;
    }
    // Done. Use the response here.
  })
  .catch(function (error) {
    // The call was invalid. See "Errors" below.
    console.error(error);
  });
```

### Errors

A promise rejects only in these cases. The rejection value is a plain string.

| When                                                                         | Message                                                                                                            | Fix                                                                                     |
| ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------- |
| Any function is called outside a WebToNative app (e.g. in a desktop browser) | `"This function will work in Native App Powered By WebToNative"`                                                   | Only call these functions inside the app. Use `.catch` to hide geofencing UI elsewhere. |
| The Android app was built before this function was added                     | `"<function> is not supported in this app version"`, e.g. `"addGeofenceZone is not supported in this app version"` | Rebuild the app from the WebToNative dashboard and update it on the device.             |
| `addZone()` is called without `zone`                                         | `"zone is required"`                                                                                               | Pass the zone inside an object: `addZone({ zone: { ... } })`.                           |

```javascript
window.WTN.Geofencing.addZone({ zone: myZone })
  .then(function (response) {
    console.log(response.status);
  })
  .catch(function (error) {
    if (error === "zone is required") {
      // You called addZone() without a zone. Fix the call.
    } else if (error.indexOf("is not supported in this app version") !== -1) {
      // Ask the user to update the app.
    } else {
      // Not inside a WebToNative app: hide your geofencing UI.
    }
  });
```

***

## Request Permission

Asks the user for "all the time" location access, which geofencing needs. Call it from a button such as "Get offers near our stores", so the user knows why you are asking.

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

```javascript
window.WTN.Geofencing.requestPermission()
  .then(function (response) {
    if (response.status === "granted" && response.isAlways !== false) {
      // Ready. Zones are now watched in the background.
    } else {
      // Not allowed. Your code: e.g. show "Turn on location in Settings to get nearby offers."
    }
  })
  .catch(function (error) {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { requestPermission } from "webtonative/Geofencing";

requestPermission()
  .then((response) => {
    if (response.status === "granted" && response.isAlways !== false) {
      // Ready. Zones are now watched in the background.
    } else {
      // Not allowed. Your code: e.g. show "Turn on location in Settings to get nearby offers."
    }
  })
  .catch((error) => {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}
{% endtabs %}

**What the user sees:**

1. If the permission is already granted, nothing is shown and the reply comes at once.
2. Otherwise the app first shows its own explanation screen, with the title, message and buttons you set in the dashboard. If the user taps **Not now**, the reply comes at once with the current status.
3. If the user taps **Allow location**:
   * **Android:** the system asks for location, then for "Allow all the time" in a second dialog. When access is granted, the app also asks to be excluded from battery optimization, so zones keep working in the background. If you turned it on in the dashboard, notification permission is asked first.
   * **iOS:** the first system dialog only offers "While using the app". After that, the app opens its page in Settings so the user can choose **Always**. If the user had already denied location, Settings opens directly.

The reply waits for the user's answer, so it can take a while.

**Response:**

| Key        | Type      | Description                                                                                                           |
| ---------- | --------- | --------------------------------------------------------------------------------------------------------------------- |
| `status`   | `String`  | The location permission after the user's answer. See [Permission status values](#permission-status-values).           |
| `isAlways` | `Boolean` | iOS only. `true` when the user chose **Always**. `false` means only "While using the app", and zones are not watched. |

**Example responses:**

```json
{ "status": "granted" }
{ "status": "granted", "isAlways": false }
{ "status": "denied" }
```

**Notes:**

* On iOS, `status: "granted"` also covers "While using the app". Always check `isAlways` too, as in the example. On Android, `granted` already means "Allow all the time", and `isAlways` is not sent.
* After the permission is granted, call [`refreshZones()`](#refresh-zones) so zones you added before it are registered. Android does this on its own, but iOS doesn't.

***

## Get Permission Status

Reads the location permission without showing anything. Use it on page load to decide whether to show your "Turn on nearby offers" button.

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

```javascript
window.WTN.Geofencing.getPermissionStatus()
  .then(function (response) {
    var ready = response.status === "granted" && response.isAlways !== false;
    // Your code: e.g. show the "Turn on nearby offers" button when !ready.
  })
  .catch(function (error) {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { getPermissionStatus } from "webtonative/Geofencing";

getPermissionStatus()
  .then((response) => {
    const ready = response.status === "granted" && response.isAlways !== false;
    // Your code: e.g. show the "Turn on nearby offers" button when !ready.
  })
  .catch((error) => {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}
{% endtabs %}

**Response:** same keys as [Request Permission](#request-permission): `status`, and `isAlways` on iOS.

### Permission status values

| Status           | Meaning                                                                                                                                                                           |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `granted`        | Location is allowed. On Android this means "Allow all the time". On iOS check `isAlways`.                                                                                         |
| `denied`         | Location is not allowed.                                                                                                                                                          |
| `restricted`     | Blocked for good ("Don't ask again" on Android) or by a system policy on iOS. The user must change it in Settings.                                                                |
| `not_determined` | Not asked yet. On Android, also when location is allowed only while using the app and "all the time" hasn't been asked yet. Only `getPermissionStatus` and `start` reply with it. |

***

## Open Location Settings

**iOS only.** Opens the app's page in iOS Settings, where the user can change location access to **Always**. iOS can't open the Location setting itself, so tell the user to tap **Location** → **Always**.

It returns nothing and **there is no reply**. Call [`getPermissionStatus`](#get-permission-status) again when the user comes back to the app. On Android it does nothing; use [`requestPermission`](#request-permission) instead.

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

```javascript
window.WTN.Geofencing.openLocationSettings();
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { openLocationSettings } from "webtonative/Geofencing";

openLocationSettings();
```

{% endtab %}
{% endtabs %}

***

## Start

**JS Bridge mode only.** Starts watching the zones you added with `addZone`, and replies with the location permission.

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

```javascript
window.WTN.Geofencing.start()
  .then(function (response) {
    if (response.status === "not_allowed") {
      // Your app uses Dashboard or API mode: zones start on their own.
      return;
    }
    if (response.status !== "granted" || response.isAlways === false) {
      // Zones can't be watched yet. Call requestPermission() from a button.
    }
  })
  .catch(function (error) {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { start } from "webtonative/Geofencing";

start()
  .then((response) => {
    if (response.status === "not_allowed") {
      // Your app uses Dashboard or API mode: zones start on their own.
      return;
    }
    if (response.status !== "granted" || response.isAlways === false) {
      // Zones can't be watched yet. Call requestPermission() from a button.
    }
  })
  .catch((error) => {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}
{% endtabs %}

**What it does on each platform:**

* **Android:** never shows a permission dialog. If permission is granted, it registers the saved zones again; if not, it only replies with the status.
* **iOS:** asks for **Always** location access with the system dialog when needed, without the explanation screen. If access is "While using the app" or denied, it opens the app's page in Settings.

**Response:**

| Key        | Type      | Description                                                                                   |
| ---------- | --------- | --------------------------------------------------------------------------------------------- |
| `status`   | `String`  | A [permission status](#permission-status-values), or `not_allowed` in Dashboard and API mode. |
| `isAlways` | `Boolean` | iOS only. `true` when location is allowed **Always**.                                         |

**Notes:**

* Zones are saved on the device and the app watches them again on every launch, so you don't need `start` on every page. Calling it once after sign-in, or when your geofencing page opens, is enough.

***

## Zones

### The zone object

`addZone` takes one zone. The same shape is used by the API mode endpoint and returned by `getActiveZones`.

```javascript
{
  _id: "store-1",                 // required, unique
  name: "Downtown store",         // optional
  enabled: true,                  // optional
  locationDetails: {
    latitude: 28.6139,            // required
    longitude: 77.209,            // required
    radius: 150                   // metres, optional
  },
  triggers: {
    enter: {
      active: true,
      cooldown: 3600,             // seconds
      callWebhook: true,
      sendPushNotification: true,
      pushNotificationConfig: {
        title: "You're near our Downtown store",
        body: "Show this screen at the counter for 10% off.",
        deepLinkUrl: "https://example.com/offers/downtown"
      }
    },
    dwell: {
      active: true,
      dwellMinutes: 10,           // minutes
      callWebhook: true
    },
    exit: {
      active: true,
      callWebhook: true
    }
  }
}
```

**Zone fields:**

| Key                         | Type      | Required | Description                                                                                                    |
| --------------------------- | --------- | -------- | -------------------------------------------------------------------------------------------------------------- |
| `_id`                       | `String`  | Yes      | Unique id of the zone. Adding a zone with an id that already exists replaces that zone. `id` is also accepted. |
| `name`                      | `String`  | No       | Shown as the notification title on iOS when `title` is empty, and sent to your webhook.                        |
| `enabled`                   | `Boolean` | No       | `false` rejects the zone (`status: "error"`). Leave it out or pass `true`.                                     |
| `locationDetails.latitude`  | `Number`  | Yes      | Latitude of the centre.                                                                                        |
| `locationDetails.longitude` | `Number`  | Yes      | Longitude of the centre.                                                                                       |
| `locationDetails.radius`    | `Number`  | No       | Radius in metres, from 100 to 5000. Default 100. Values outside the range are changed to the nearest limit.    |
| `triggers`                  | `Object`  | No       | Holds `enter`, `dwell` and `exit`. Each is optional. A zone with no triggers is saved but never fires.         |

**Trigger fields** (inside `enter`, `dwell` or `exit`):

| Key                                  | Type      | Default | Description                                                                                                                           |
| ------------------------------------ | --------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `active`                             | `Boolean` | `true`  | `false` turns this trigger off.                                                                                                       |
| `callWebhook`                        | `Boolean` | `false` | Calls your [webhook](#webhook) when the trigger fires.                                                                                |
| `sendPushNotification`               | `Boolean` | `false` | Shows a local notification when the trigger fires. Needs `pushNotificationConfig`.                                                    |
| `pushNotificationConfig.title`       | `String`  |         | Notification title.                                                                                                                   |
| `pushNotificationConfig.body`        | `String`  |         | Notification text.                                                                                                                    |
| `pushNotificationConfig.deepLinkUrl` | `String`  |         | Page opened in the app when the user taps the notification. Leave it out to just open the app.                                        |
| `cooldown`                           | `Number`  | `0`     | Seconds to wait before this trigger can fire again for this zone. `0` fires every time. Covers both the webhook and the notification. |
| `dwellMinutes`                       | `Number`  | `1`     | `dwell` only. Minutes the user must stay inside before `dwell` fires.                                                                 |

### Add Zone

**JS Bridge mode only.** Adds one zone and starts watching it. If a zone with the same `_id` exists, it is replaced.

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

```javascript
window.WTN.Geofencing.addZone({
  zone: {
    _id: "store-1",
    name: "Downtown store",
    locationDetails: { latitude: 28.6139, longitude: 77.209, radius: 150 },
    triggers: {
      enter: {
        cooldown: 3600,
        callWebhook: true,
        sendPushNotification: true,
        pushNotificationConfig: {
          title: "You're near our Downtown store",
          body: "Show this screen at the counter for 10% off.",
          deepLinkUrl: "https://example.com/offers/downtown",
        },
      },
      exit: { callWebhook: true },
    },
  },
})
  .then(function (response) {
    if (response.status === "added" || response.status === "updated") {
      // The zone is saved and watched.
    } else if (response.status === "not_allowed") {
      // Your app uses Dashboard or API mode. Add zones there instead.
    } else {
      // "error": the zone is invalid, or location "all the time" isn't allowed yet.
    }
  })
  .catch(function (error) {
    console.error(error); // e.g. "zone is required"
  });
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { addZone } from "webtonative/Geofencing";

addZone({
  zone: {
    _id: "store-1",
    name: "Downtown store",
    locationDetails: { latitude: 28.6139, longitude: 77.209, radius: 150 },
    triggers: {
      enter: {
        cooldown: 3600,
        callWebhook: true,
        sendPushNotification: true,
        pushNotificationConfig: {
          title: "You're near our Downtown store",
          body: "Show this screen at the counter for 10% off.",
          deepLinkUrl: "https://example.com/offers/downtown",
        },
      },
      exit: { callWebhook: true },
    },
  },
})
  .then((response) => {
    if (response.status === "added" || response.status === "updated") {
      // The zone is saved and watched.
    } else if (response.status === "not_allowed") {
      // Your app uses Dashboard or API mode. Add zones there instead.
    } else {
      // "error": the zone is invalid, or location "all the time" isn't allowed yet.
    }
  })
  .catch((error) => {
    console.error(error); // e.g. "zone is required"
  });
```

{% endtab %}
{% endtabs %}

**Response:**

| Key      | Type     | Description                                                  |
| -------- | -------- | ------------------------------------------------------------ |
| `status` | `String` | The result. See the values below.                            |
| `zoneId` | `String` | The zone's id. Missing on Android when the zone was invalid. |

**`status` values:**

| Value         | Meaning                                                                                                                                                                                                                                                                                                          |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `added`       | New zone saved and watched.                                                                                                                                                                                                                                                                                      |
| `updated`     | A zone with this id already existed and was replaced.                                                                                                                                                                                                                                                            |
| `error`       | Either the zone is invalid (missing `_id`, `latitude` or `longitude`, or `enabled: false`) and nothing was saved, **or** the zone was saved but can't be watched yet because location "all the time" isn't allowed. In the second case, call [`refreshZones()`](#refresh-zones) after the permission is granted. |
| `not_allowed` | Your app uses Dashboard or API mode.                                                                                                                                                                                                                                                                             |

**Add several zones one after another.** Each `addZone` call must finish before the next one starts (see [Notes](#notes)):

```javascript
var zones = [/* your zone objects */];

zones
  .reduce(function (chain, zone) {
    return chain.then(function () {
      return window.WTN.Geofencing.addZone({ zone: zone });
    });
  }, Promise.resolve())
  .then(function () {
    // All zones added.
  })
  .catch(function (error) {
    console.error(error);
  });
```

### Remove Zone

**JS Bridge mode only.** Stops watching one zone and deletes it. Pass the zone's id as `id`.

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

```javascript
window.WTN.Geofencing.removeZone({ id: "store-1" })
  .then(function (response) {
    // response.status: "removed", "not_found", "error" or "not_allowed"
  })
  .catch(function (error) {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { removeZone } from "webtonative/Geofencing";

removeZone({ id: "store-1" })
  .then((response) => {
    // response.status: "removed", "not_found", "error" or "not_allowed"
  })
  .catch((error) => {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}
{% endtabs %}

**`status` values:**

| Value         | Meaning                                                     |
| ------------- | ----------------------------------------------------------- |
| `removed`     | The zone was removed.                                       |
| `not_found`   | No zone has this id.                                        |
| `error`       | `id` was missing or empty, or the zone couldn't be removed. |
| `not_allowed` | Your app uses Dashboard or API mode.                        |

### Get Active Zones

Returns the zones the app is watching, in every mode. Use it to show the user which places they get alerts for, or to check what your API returned.

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

```javascript
window.WTN.Geofencing.getActiveZones()
  .then(function (response) {
    response.zones.forEach(function (zone) {
      console.log(zone._id, zone.name);
    });
  })
  .catch(function (error) {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { getActiveZones } from "webtonative/Geofencing";

getActiveZones()
  .then((response) => {
    response.zones.forEach((zone) => {
      console.log(zone._id, zone.name);
    });
  })
  .catch((error) => {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}
{% endtabs %}

**Response:**

| Key     | Type    | Description                                                                   |
| ------- | ------- | ----------------------------------------------------------------------------- |
| `zones` | `Array` | Zones in the [zone object](#the-zone-object) shape. `[]` when there are none. |

**Notes:**

* Zones come back as the app uses them: `radius` is within 100–5000, triggers with `active: false` are left out, and `dwellMinutes` is a whole number.
* **iOS** lists only the zones registered with the system right now. **Android** lists every saved zone, including ones not watched yet because permission is missing. When you have more zones than the [limit](#zone-limits), both list only the nearest ones being watched.

### Clear All Zones

**JS Bridge mode only.** Stops watching every zone and deletes them all. Use it when the user signs out. The webhook is kept; call [`removeWebhook`](#remove-webhook) to remove it too.

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

```javascript
window.WTN.Geofencing.clearAllZones()
  .then(function (response) {
    // response.status: "cleared", "error" or "not_allowed"
  })
  .catch(function (error) {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { clearAllZones } from "webtonative/Geofencing";

clearAllZones()
  .then((response) => {
    // response.status: "cleared", "error" or "not_allowed"
  })
  .catch((error) => {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}
{% endtabs %}

### Refresh Zones

Registers the zones again, in every mode. In API mode it also downloads them from your endpoint right away, even if the `ttl` hasn't passed. Call it after your backend changes a user's zones.

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

```javascript
window.WTN.Geofencing.refreshZones()
  .then(function (response) {
    if (response.status !== "refreshed") {
      // Couldn't refresh: e.g. location "all the time" isn't allowed, or your API endpoint failed.
    }
  })
  .catch(function (error) {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { refreshZones } from "webtonative/Geofencing";

refreshZones()
  .then((response) => {
    if (response.status !== "refreshed") {
      // Couldn't refresh: e.g. location "all the time" isn't allowed, or your API endpoint failed.
    }
  })
  .catch((error) => {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}
{% endtabs %}

**What it does in each mode:**

| Mode      | What it does                                               |
| --------- | ---------------------------------------------------------- |
| Dashboard | Registers the zones you added in the dashboard again.      |
| API       | Downloads the zones from your endpoint and registers them. |
| JS Bridge | Registers the zones you added with `addZone()` again.      |

**`status` values:** `refreshed`, or `error` when the zones couldn't be registered (usually because location "all the time" isn't allowed).

### Zone limits

The system limits how many zones one app can watch at once: **100 on Android** and **20 on iOS**.

***

## Webhook

When a trigger with `callWebhook: true` fires, the app sends a `POST` request to your webhook URL. Your backend can then react, for example mark the user as checked in.

In **Dashboard** and **API** mode, set the webhook in the dashboard. In **JS Bridge** mode, set it from your website with `setWebhook`.

### Set Webhook

**JS Bridge mode only.** Sets the URL the app calls when a trigger fires.

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

```javascript
window.WTN.Geofencing.setWebhook({
  url: "https://example.com/geofence-hook",
  headers: {
    Authorization: "Bearer YOUR_API_KEY",
    "X-User-Id": "u123",
  },
})
  .then(function (response) {
    if (response.status === "set") {
      // Webhook saved.
    } else if (response.status === "not_allowed") {
      // Your app uses Dashboard or API mode. Set the webhook in the dashboard.
    } else {
      // "error": url was missing or empty.
    }
  })
  .catch(function (error) {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { setWebhook } from "webtonative/Geofencing";

setWebhook({
  url: "https://example.com/geofence-hook",
  headers: {
    Authorization: "Bearer YOUR_API_KEY",
    "X-User-Id": "u123",
  },
})
  .then((response) => {
    if (response.status === "set") {
      // Webhook saved.
    } else if (response.status === "not_allowed") {
      // Your app uses Dashboard or API mode. Set the webhook in the dashboard.
    } else {
      // "error": url was missing or empty.
    }
  })
  .catch((error) => {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}
{% endtabs %}

**Parameters:**

| Key       | Type     | Required | Description                                                                                                     |
| --------- | -------- | -------- | --------------------------------------------------------------------------------------------------------------- |
| `url`     | `String` | Yes      | Your webhook URL. **Must start with `https://`**. An `http://` URL is saved, but the app never calls it.        |
| `headers` | `Object` | No       | Headers sent with every webhook request, e.g. an API key. Leave it out to keep the headers from your last call. |

**`status` values:** `set`, `error` (`url` missing or empty) or `not_allowed`.

**Notes:**

* Header values must be plain ASCII text. A header with other characters is not sent.
* Since nothing in the payload identifies your user in JS Bridge mode, send your user id in a header, as in the example, and call `setWebhook` again after sign-in.

### Remove Webhook

**JS Bridge mode only.** Deletes the webhook. Triggers still show notifications, but no request is sent.

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

```javascript
window.WTN.Geofencing.removeWebhook()
  .then(function (response) {
    // response.status: "removed", "error" or "not_allowed"
  })
  .catch(function (error) {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}

{% tab title="npm" %}

```javascript
import { removeWebhook } from "webtonative/Geofencing";

removeWebhook()
  .then((response) => {
    // response.status: "removed", "error" or "not_allowed"
  })
  .catch((error) => {
    console.error(error); // not inside a WebToNative app
  });
```

{% endtab %}
{% endtabs %}

### Webhook request

* Method `POST`, header `Content-Type: application/json`, plus your headers.
* The app tries **once** and waits up to 3 seconds. A failed request is not sent again, so reply quickly with a `2xx` and do slow work afterwards.

**Payload:**

```json
{
  "id": "evt_3f9a1c2b7d4e",
  "event": "zone.enter",
  "timestamp": "2026-10-28T09:41:12Z",
  "zone": {
    "id": "store-1",
    "name": "Downtown store",
    "latitude": 28.6139,
    "longitude": 77.209,
    "radius": 150
  },
  "deviceInfo": {
    "id": "a1b2c3d4e5f6",
    "platform": "android",
    "accuracy_m": 18
  }
}
```

| Key                     | Type     | Description                                                                   |
| ----------------------- | -------- | ----------------------------------------------------------------------------- |
| `id`                    | `String` | Unique id of this event. Use it to ignore duplicates.                         |
| `event`                 | `String` | `zone.enter`, `zone.dwell` or `zone.exit`.                                    |
| `timestamp`             | `String` | When the trigger fired, in ISO 8601 UTC.                                      |
| `zone`                  | `Object` | The zone's `id`, `name` (`""` if none), `latitude`, `longitude` and `radius`. |
| `deviceInfo.id`         | `String` | An id for this device and app.                                                |
| `deviceInfo.platform`   | `String` | `android` or `ios`.                                                           |
| `deviceInfo.accuracy_m` | `Number` | Accuracy of the location fix in metres. Can be missing on Android.            |

**Dashboard and API mode only:** the webhook settings in the dashboard can add more to the request:

* **Signing secret:** the app adds an `X-W2N-Signature` header, the HMAC-SHA256 of the raw request body as lowercase hex. Check it to make sure the request came from your app (see the examples below).
* **Custom fields:** adds a `custom` object. Values can use `{user.externalUserId}`, `{user.name}`, `{user.email}`, `{user.phone}`, `{user.meta.<key>}`, `{device.id}`, `{device.platform}`, `{event.type}`, `{event.timestamp}`, `{zone.id}` and `{zone.name}`. A field whose variables can't be filled in is left out.

### Receiving the webhook

{% tabs %}
{% tab title="Node (Express)" %}

```javascript
const express = require("express");
const crypto = require("crypto");

const app = express();
const SIGNING_SECRET = process.env.W2N_GEOFENCE_SECRET; // Dashboard/API mode, if set
const seen = new Set(); // use your database in production

// Keep the raw body: the signature is calculated on it.
app.post("/geofence-hook", express.raw({ type: "application/json" }), (req, res) => {
  if (SIGNING_SECRET) {
    const expected = crypto.createHmac("sha256", SIGNING_SECRET).update(req.body).digest("hex");
    const received = req.get("X-W2N-Signature") || "";
    if (
      received.length !== expected.length ||
      !crypto.timingSafeEqual(Buffer.from(received), Buffer.from(expected))
    ) {
      return res.status(401).end();
    }
  }

  const event = JSON.parse(req.body.toString("utf8"));
  res.status(200).end(); // reply first: the app waits only 3 seconds

  if (seen.has(event.id)) return;
  seen.add(event.id);

  const userId = req.get("X-User-Id"); // from setWebhook headers (JS Bridge mode)

  switch (event.event) {
    case "zone.enter":
      // Your code: e.g. check the user in at event.zone.id
      break;
    case "zone.dwell":
      // Your code
      break;
    case "zone.exit":
      // Your code: e.g. check the user out
      break;
  }
});

app.listen(3000);
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
$signingSecret = getenv('W2N_GEOFENCE_SECRET'); // Dashboard/API mode, if set
$rawBody = file_get_contents('php://input');

if ($signingSecret) {
    $expected = hash_hmac('sha256', $rawBody, $signingSecret);
    $received = $_SERVER['HTTP_X_W2N_SIGNATURE'] ?? '';
    if (!hash_equals($expected, $received)) {
        http_response_code(401);
        exit;
    }
}

$event = json_decode($rawBody, true);
http_response_code(200); // reply quickly: the app waits only 3 seconds

$userId = $_SERVER['HTTP_X_USER_ID'] ?? null; // from setWebhook headers (JS Bridge mode)

// Ignore duplicates: store $event['id'] in your database and skip ids you've seen.

switch ($event['event']) {
    case 'zone.enter':
        // Your code: e.g. check the user in at $event['zone']['id']
        break;
    case 'zone.dwell':
        // Your code
        break;
    case 'zone.exit':
        // Your code: e.g. check the user out
        break;
}
```

{% endtab %}
{% endtabs %}

***

## Notifications on a Trigger

When a trigger has `sendPushNotification: true` and a `pushNotificationConfig`, the app shows a local notification. No push service is needed.

* **Title** is `title`. On iOS, if `title` is empty, the zone's `name` is used, then "Geofence Alert".
* **Text** is `body`.
* **Tapping it** opens `deepLinkUrl` in the app, or just opens the app when there is no `deepLinkUrl`.
* On Android, a new notification for the same zone and trigger replaces the previous one.

The user must allow notifications, or nothing is shown. Ask for it with [`WTN.Permission.request({ permission: "notification" })`](broken://pages/e8075f81cade857119750df8628ec05c66acaeef), or turn on the notification request for the geofencing explanation screen in the dashboard.

***

## Complete Example

A JS Bridge mode page that turns on nearby-store offers for a signed-in user: it checks the permission, asks for it from a button, sets the webhook, and adds the store zones.

```html
<button id="nearby-btn" style="display: none">Get offers near our stores</button>

<script>
  var STORES = [
    { id: "store-1", name: "Downtown store", lat: 28.6139, lng: 77.209 },
    { id: "store-2", name: "Airport store", lat: 28.5562, lng: 77.1 },
  ];

  function isReady(response) {
    return response.status === "granted" && response.isAlways !== false;
  }

  function storeToZone(store) {
    return {
      _id: store.id,
      name: store.name,
      locationDetails: { latitude: store.lat, longitude: store.lng, radius: 200 },
      triggers: {
        enter: {
          cooldown: 86400, // at most once a day
          callWebhook: true,
          sendPushNotification: true,
          pushNotificationConfig: {
            title: "You're near our " + store.name,
            body: "Show this screen at the counter for 10% off.",
            deepLinkUrl: "https://example.com/offers/" + store.id,
          },
        },
        exit: { callWebhook: true },
      },
    };
  }

  function setUpZones(userId) {
    return window.WTN.Geofencing.setWebhook({
      url: "https://example.com/geofence-hook",
      headers: { "X-User-Id": userId },
    }).then(function () {
      // Add the zones one at a time.
      return STORES.reduce(function (chain, store) {
        return chain.then(function () {
          return window.WTN.Geofencing.addZone({ zone: storeToZone(store) });
        });
      }, Promise.resolve());
    });
  }

  function init(userId) {
    var button = document.getElementById("nearby-btn");

    window.WTN.Geofencing.getPermissionStatus()
      .then(function (response) {
        // Add the zones now. They are saved even before the permission is granted.
        return setUpZones(userId).then(function () {
          if (!isReady(response)) button.style.display = "block";
        });
      })
      .catch(function (error) {
        console.error(error); // not inside a WebToNative app: keep the button hidden
      });

    button.addEventListener("click", function () {
      window.WTN.Geofencing.requestPermission().then(function (response) {
        if (isReady(response)) {
          button.style.display = "none";
          window.WTN.Geofencing.refreshZones(); // register the zones saved before the permission
        } else {
          // Your code: e.g. "Turn on location 'Always' in Settings to get nearby offers."
        }
      });
    });
  }

  init("u123"); // your signed-in user's id
</script>
```

When the user signs out, call `clearAllZones()` and `removeWebhook()`.

***

## Which Functions Work in Which Mode

| Function                                                       | Dashboard     | API           | JS Bridge |
| -------------------------------------------------------------- | ------------- | ------------- | --------- |
| [`requestPermission()`](#request-permission)                   | ✅             | ✅             | ✅         |
| [`getPermissionStatus()`](#get-permission-status)              | ✅             | ✅             | ✅         |
| [`openLocationSettings()`](#open-location-settings) (iOS only) | ✅             | ✅             | ✅         |
| [`start()`](#start)                                            | `not_allowed` | `not_allowed` | ✅         |
| [`addZone()`](#add-zone)                                       | `not_allowed` | `not_allowed` | ✅         |
| [`removeZone()`](#remove-zone)                                 | `not_allowed` | `not_allowed` | ✅         |
| [`getActiveZones()`](#get-active-zones)                        | ✅             | ✅             | ✅         |
| [`clearAllZones()`](#clear-all-zones)                          | `not_allowed` | `not_allowed` | ✅         |
| [`refreshZones()`](#refresh-zones)                             | ✅             | ✅             | ✅         |
| [`setWebhook()`](#set-webhook)                                 | `not_allowed` | `not_allowed` | ✅         |
| [`removeWebhook()`](#remove-webhook)                           | `not_allowed` | `not_allowed` | ✅         |

***

## Notes

* **Don't call the same function again before the previous call replies.** Only the latest call's promise settles; the earlier one never does. For several zones, chain the calls as shown in [Add Zone](#add-zone).
* If geofencing is turned off in the dashboard, the functions get no reply and their promises never settle.
* Switching your app to JS Bridge mode from another mode deletes the old zones once, on the next launch.
* On Android, if the device is already inside a zone when you add it, `enter` doesn't fire until the user leaves and comes back.
* Every function also accepts a `callback` instead of `.then()`, e.g. `WTN.Geofencing.start({ callback: function (response) { ... } })`. Use one or the other.
