# MoEngage Destination

## Destination Info

* Accepts [Identify](/docs/segment/connections/spec/identify), [Track](/docs/segment/connections/spec/track) calls.
* Refer to it as **MoEngage** in the [Integrations object.](/docs/segment/guides/filtering-data/#filtering-with-the-integrations-object)

### Components

* [Browser](https://github.com/segment-integrations/analytics.js-integration-moengage)
* [iOS](https://github.com/moengage/MoEngage-Segment-iOS)
* [Android](https://github.com/moengage/Segment-Integration)

## Connection Modes

[Learn more about connection modes.](/docs/segment/connections/destinations/#connection-modes)

### Device-Mode

* web: yes
* mobile: yes
* server: yes

### Cloud-Mode

* web: yes
* mobile: yes
* server: yes

[MoEngage](https://www.moengage.com/) is an intelligent customer engagement platform. MoEngage allows brands to personalize every customer interaction and drive better engagement, retention, loyalty and lifetime value.

The MoEngage and Segment integration allows you to send the users you have tracked on Segment, along with their route data, to MoEngage for further targeting and campaigning. This destination enables you to:

* **Import data from Segment to MoEngage**: Moengage offers a side-by-side (device-mode) SDK integration for your Android, iOS, and web applications and a server-to-server integration for your backend services.
* **Sync [Twilio Engage](https://segment.com/product/twilio-engage) (cohorts)**: Send Segment Cohorts to MoEngage for use in MoEngage Segments and campaigns.

The MoEngage Destination source code for the iOS, Android, and Web connection modes is open-sourced and freely available on GitHub for anyone to view:

| Connection Mode | Maintained by | GitHub Link                                                                                                           |
| --------------- | ------------- | --------------------------------------------------------------------------------------------------------------------- |
| iOS             | MoEngage      | [MoEngage-Segment-Swift](https://github.com/moengage/MoEngage-Segment-Swift)                                          |
| Android         | MoEngage      | [moengage-segment-integration](https://github.com/moengage/moengage-segment-integration)                              |
| Web             | Segment       | [analytics.js-integrations](https://github.com/segmentio/analytics.js-integrations/tree/master/integrations/moengage) |
| Server          | MoEngage      | Private repository                                                                                                    |

## Getting started

Once you add the Segment-MoEngage library to your app, you can enable MoEngage from the Segment App. These new settings can take up to an hour to propagate to your existing users. For new users, the settings are propagated instantly.

The Segment-MoEngage Integration is a bundled integration, meaning it requires that you add a client-side integration to your app.

## Setup MoEngage in your Segment workspace

To setup MoEngage, complete the following:

1. First get your key(AppID) from the MoEngage dashboard. Navigate to **Dashboard > Settings > App > General**.
2. In your Segment workspace, go to **Destinations** and select **MoEngage**.
3. Enable the MoEngage Destination.
4. Go to the MoEngage Settings and enter the MoEngage AppID, obtained in Step 1.
5. Save the changes.
6. Make sure you set the **Connection Mode**  to `Device Mode`. MoEngage requires this setting to use of features like push notifications and any in-app features of the MoEngage SDK.

Segment-MoEngage Integration is a bundled integration and requires client-side integration.

![MoEngage settings with options for APP ID, debug logging, and connection mode.](https://docs-resources.prod.twilio.com/9d14652b82392bc1723b32b864e871c29b48be397c062154919f43ec2bae1ae1.png)

## Identify

Use [Identify](/docs/segment/connections/sources/catalog/libraries/mobile/android/#identify) to track user-specific attributes. This is the same as tracking [user attributes](https://help.moengage.com/hc/en-us/articles/360044285511-User-Profile) on MoEngage. MoEngage supports traits supported by Segment as well as custom traits. If you set `traits.id`, MoEngage sets that as the Unique ID for that user.

> \[!NOTE]
>
> MoEngage supports anonymous identifiers in device-mode only. If you use the MoEngage destination in cloud-mode, use a known user identifier.

The Identify method follows the format below:

```javascript
analytics.identify('12090000-00001992', {
  name: 'John Doe',
  email: 'john.doe@example.com'
});
```

## Track

Use [Track](/docs/segment/connections/sources/catalog/libraries/mobile/android/#track) to track events and user behavior in your app.

```javascript
analytics.track('Article Completed', {
  title: 'How to Create a Tracking Plan',
  course: 'Intro to Analytics',
});
```

This sends the event to MoEngage with the associated properties. Tracking events is essential and helps you create segments for engaging users.

## Reset

If your app or website supports the ability for a user to logout and login with a new identity, then you need to call the [Reset](/docs/segment/connections/sources/catalog/libraries/website/javascript#reset-logout) method in `analytics.js`.

```javascript
analytics.reset();
```

## iOS

To get started with MoEngage on iOS, first integrate your app with the [MoEngage-Segment-Swift](https://github.com/moengage/MoEngage-Segment-Swift) library. You can integrate MoEngage and Segment with Swift Package Manager.

> \[!NOTE]
>
> This document covers the integration with [analytics-swift](https://github.com/segmentio/analytics-swift). If you've integrated with [analytics-ios](https://github.com/segmentio/analytics-ios) refer [MoEngage's documentation](https://partners.moengage.com/hc/en-us/articles/4409143473172-iOS-device-mode-) for details on how to integrate.

To install with SPM use the [MoEngage-Segment-Swift](https://github.com/moengage/MoEngage-Segment-Swift.git) library and set the branch as master or version as 1.0.0 and above.

### Configure the Segment SDK:

Head to the App Delegate file, and setup the Segment SDK by:

1. Importing `Segment`, `Segment_MoEngage` and `MoEngageSDK`.
2. Initialize `MoEngageSDKConfig` object and call `initializeDefaultInstance` method of `MoEngageInitializer`.
3. Initialize `MoEngageDestination`:

Under your Analytics-Swift library setup, add the MoEngage plugin using the `analytics.add(plugin: ...)` method. The MoEngage dashboard now tracks all of your events.

```text
let analytics = Analytics(configuration: Configuration(writeKey: "<YOUR WRITE KEY>")
                    .flushAt(3)
                    .trackApplicationLifecycleEvents(true))
analytics.add(plugin: MoEngageDestination())
```

### Configure the MoEngage SDK:

```swift
 import Segment_MoEngage
 import MoEngageSDK
 ...
 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey:  Any]?) -> Bool {
 ...
 
     let sdkConfig = MoEngageSDKConfig(withAppID: "YOUR APP ID")
     MoEngageInitializer.shared.initializeDefaultInstance(sdkConfig: sdkConfig)
 ...
 }
```

### Tracking user attribute

[User attributes](https://developers.moengage.com/hc/en-us/articles/4403905883796-Tracking-user-attributes) are specific traits of a user, like email, username, mobile, gender, and more. Identify lets you tie a user to their actions and record traits about them. It includes a unique User ID and any optional traits you know about them.

```swift
Analytics.main.identify("a user's id", traits: @["email":"a user's email address"])
```

Read more about [Identify calls](/docs/segment/connections/sources/catalog/libraries/mobile/ios/#identify) for further detail.

### Tracking events

Segment uses event tracking to track user behavior in an app. Track calls let you record the actions your users perform. Every action triggers an "event", which can also have associated attributes.

```swift
Analytics.main.track("Item Purchased", properties: @["item":"Sword of Heracles"])
```

Read more about [Track calls](/docs/segment/connections/sources/catalog/libraries/mobile/ios/#track) for further detail.

### Reset users

The Reset method clears the SDK's internal stores for the current user. This is useful for apps where users can log in and out with different identities over time.

```swift
Analytics.main.reset()
```

Read more about the [Reset method](/docs/segment/connections/sources/catalog/libraries/mobile/ios/#reset) for further detail.

### Install or update differentiation

Since your app might already be on the App Store, you must specify whether your app update would be an `UPDATE` or an `INSTALL`.
To differentiate between those, use one of the following methods:

```swift
//For new Install call following
MoEngageSDKAnalytics.sharedInstance.appStatus(.install)

//For an app update call following
MoEngageSDKAnalytics.sharedInstance.appStatus(.update)
```

Read more on [Install/Update differentiation](https://developers.moengage.com/hc/en-us/articles/4403910297620) on MoEngage website.

### Set the data center

By default, the data center setting in the SDK is set to `data_center_01`. Follow the steps in the [MoEngage - Data Center](https://developers.moengage.com/hc/en-us/articles/4403910162452-Data-Center) to update the data center value. If not set correctly, several features of the MoEngage SDK won't function.

## MoEngage iOS SDK features

Along with tracking your user's activities, you can use the MoEngage iOS SDK for more effective user engagement:

### Push notifications:

Push notifications are a useful way to keep your users engaged and informed about your app. You have following options while implementing push notifications in your app:

**Segment push implementation:**

1. In your application's application:didRegisterForRemoteNotificationsWithDeviceToken: method, add the following:

```swift
 Analytics.main.registeredForRemoteNotifications(deviceToken: deviceToken)
```

2. In your application's application:didReceiveRemoteNotification: method, add the following:

```swift
Analytics.main.receivedRemoteNotification(userInfo: userInfo)
```

3. If you integrated the application:didReceiveRemoteNotification:fetchCompletionHandler: in your app, add the following to that method:

```swift
Analytics.main.receivedRemoteNotification(userInfo: userInfo)
```

4. If you implemented handleActionWithIdentifier:forRemoteNotification:, add the following to that method:

```swift
Analytics.main.handleAction(identifier: identifier, userInfo: userInfo)
```

**MoEngage push implementation:**
For information about the MoEngage push implementation, see [**Push Notifications**](https://developers.moengage.com/hc/en-us/articles/4403943988756) in the MoEngage documentation.

### In-app messaging

In-app messages are custom views which you can send to a set of users to show custom messages, give new offers, or direct to a specific page. For more information about in-app messaging, see [MoEngage - In-App NATIV](https://developers.moengage.com/hc/en-us/articles/4404155127828-In-App-Nativ).

### Cards

Create targeted or automated App Inbox/NewsFeed messages that can be grouped into various categories, and target your users with different updates or offers that can stay in the Inbox/Feed over a designated period of time. For more information about cards, see [MoEngage - Cards](https://developers.moengage.com/hc/en-us/articles/4404058438676-Cards-in-iOS).

### Compliance

To make the app compliant with policies (such as GDPR) while using MoEngage's SDK, follow the instructions in [MoEngage's documentation](https://developers.moengage.com/hc/en-us/articles/4403905438228-SDK-initialisation).

### Segment for iOS

For more info on using Segment for iOS, refer to the [Developer docs](/docs/segment/connections/sources/catalog/libraries/mobile/ios/) provided by Segment.

## Android

To use MoEngage in an Android app, you must perform the following steps to set up your environment.

![MavenBadge](https://maven-badges.herokuapp.com/maven-central/com.moengage/moengage-segment-kotlin-destination/badge.svg)

To enable the full functionality of MoEngage (like push notifications, in-app messaging), complete the following steps in your Android app.

> \[!NOTE]
>
> This document covers the integration with [analytics-kotlin](https://github.com/segmentio/analytics-kotlin). If you have integrated with [analytics-android](https://github.com/segmentio/analytics-android) refer [MoEngage's documentation](https://partners.moengage.com/hc/en-us/articles/4409143473172-iOS-device-mode-) for details on how to integrate.

### Adding the MoEngage dependency

Along with the Segment dependency, add the following dependency in your `build.gradle` file.

```groovy
implementation("com.moengage:moengage-segment-kotlin-destination:$sdkVersion") {
        transitive = true
    }
```

with `$sdkVersion` replaced by the latest version of the MoEngage SDK.

The MoEngage SDK depends on the following Jetpack libraries provided by Google for its functioning, make sure you add them if not done already.

```groovy
    implementation("androidx.core:core:1.6.0")
    implementation("androidx.appcompat:appcompat:1.3.1")
    implementation("androidx.lifecycle:lifecycle-process:2.4.0")
```

Refer to the [SDK Configuration](https://developers.moengage.com/hc/en-us/articles/4401984733972-Android-SDK-Configuration) documentation to learn more about the build config and other libraries used by the SDK.

### Register MoEngage with Segment SDK

After adding the dependency, you must register the integration with Segment SDK. To do this, import the MoEngage integration:

```kotlin
import com.segment.analytics.kotlin.destinations.moengage.MoEngageDestination
```

Add the following line:

```kotlin
Analytics("<YOUR WRITE KEY>", context)
  .add(MoEngageDestination(application))
```

### Initialize the MoEngage SDK

Copy the APP ID from the Settings page **Dashboard > Settings > App > General** and initialize the MoEngage SDK in the onCreate method of the `Application` class

> \[!NOTE]
>
> MoEngage recommends that you initialize the SDK on the main thread inside `onCreate()` and not create a worker thread and initialize the SDK on that thread.

```kotlin
// This is the instance of the application class and "YOUR_APP_ID" is the APP ID from the dashboard.
      val moEngage = MoEngage.Builder(this, "YOUR_APP_ID")
          .enablePartnerIntegration(IntegrationPartner.SEGMENT)
          .build()
      MoEngage.initialiseDefaultInstance(moEngage)
```

### Exclude MoEngage storage file from auto-backup

The auto-backup service of Android periodically backs up the Shared Preference file, Database files, and so on.

For more information, refer to the [Auto-Backup](https://developer.android.com/guide/topics/data/autobackup) documentation.

As a result of the backup, MoEngage SDK identifiers are backed up and restored after re-install. The restoration of the identifier results in your data being corrupted and the user not being reachable using push notifications.

To ensure data isn't corrupted after a backup is restored, opt-out of MoEngage SDK storage files.

Refer to the [MoEngage documentation](https://developers.moengage.com/hc/en-us/articles/4401999257236-Exclude-MoEngage-Storage-File-from-Auto-Backup) for further details.

### Install or update differentiation

This is required for migrations to the MoEngage Platform so the SDK can determine whether the user is a new user on your app, or an existing user who updated to the latest version.

If the user was already using your application and has just updated to a new version which has the MoEngage SDK. An example call:

```kotlin
 MoEAnalyticsHelper.setAppStatus(context, AppStatus.UPDATE)
```

If this is a fresh install:

```kotlin
MoEAnalyticsHelper.setAppStatus(context, AppStatus.INSTALL)
```

## MoEngage Android SDK features

### Configure push notifications

Copy the Server Key from the FCM console and add it to the MoEngage Dashboard. To upload it, go to the Settings page, **Dashboard > Settings > Channel > Push > Mobile Push > Android** and add the Server Key and package name. Ensure that you add the keys both in Test and Live environment.

#### Add meta information for push notification

To display push notifications, some metadata regarding the notification is required. For example, the small icon and large icon drawables are mandatory.

Refer to the [MoEngage - NotificationConfig](https://moengage.github.io/android-api-reference-v11/core/com.moengage.core.config/-notification-config/index.html) API reference for all the possible options.

Use the `configureNotificationMetaData()` to pass on the configuration to the SDK.

```kotlin
      val moEngage = MoEngage.Builder(this, "YOUR_APP_ID")
          .enablePartnerIntegration(IntegrationPartner.SEGMENT)
          .configureNotificationMetaData(NotificationConfig(
              smallIcon = R.drawable.small_icon,
              largeIcon = R.drawable.large_icon
          ))
          .build()
      MoEngage.initialiseDefaultInstance(moEngage)
```

#### Configuring Firebase cloud messaging

To show push notifications there are two important steps:

1. Registration for Push, for example generating push token.
2. Receiving the Push payload from Firebase Cloud Messaging(FCM) service and showing the notification on the device.

##### Push registration and receiving handled by the application

###### Opt-out of MoEngage registration

To opt-out of MoEngage token registration mechanism disable token registration while configuring FCM in the `MoEngage.Builder`:

```kotlin
      val moEngage = MoEngage.Builder(this, "YOUR_APP_ID")
          .enablePartnerIntegration(IntegrationPartner.SEGMENT)
          .configureNotificationMetaData(NotificationConfig(
              smallIcon = R.drawable.small_icon,
              largeIcon = R.drawable.large_icon
          ))
          .configureFcm(FcmConfig(false))
          .build()
      MoEngage.initialiseDefaultInstance(moEngage)
```

###### Pass the push token to the MoEngage SDK

The application must pass the Push Token received from FCM to the MoEngage SDK for the MoEngage platform to send out push notifications to the device.
Use the following API to pass the push token to the MoEngage SDK.

```kotlin
MoEFireBaseHelper.getInstance().passPushToken(applicationContext,token)
```

Ensure that the token is passed to MoEngage SDK whenever push token is refreshed and on application update. Passing token on application update is important for migration to the MoEngage Platform.

###### Passing the push payload to the MoEngage SDK

To pass the push payload to the MoEngage SDK call the MoEngage API from the `onMessageReceived()` from the Firebase receiver. Before passing the payload to the MoEngage SDK, check if the payload is from the MoEngage platform using the helper API provided by the SDK.

```kotlin
if (MoEPushHelper.getInstance().isFromMoEngagePlatform(remoteMessage.data)) {
    MoEFireBaseHelper.getInstance().passPushPayload(applicationContext, remoteMessage.data)
 } else {
    // your app's business logic to show notification
 }
```

##### Push registration and receiving handled by SDK

Add the following code in your manifest file:

```xml
<service android:name="com.moengage.firebase.MoEFireBaseMessagingService">
 	<intent-filter>
		<action android:name="com.google.firebase.MESSAGING_EVENT" />
 	</intent-filter>
</service>
```

When the MoEngage SDK handles push registration, it optionally provides a callback to the Application whenever a new token is registered or the token is refreshed.

An application can get this callback by implementing `FirebaseEventListener` and registering for a callback in the Application class `onCreate()` using `MoEFireBaseHelper.getInstance().addEventListener()`.

Refer to the [MoEngage - API reference](https://moengage.github.io/android-api-reference-v11/moe-push-firebase/com.moengage.firebase.listener/-firebase-event-listener/index.html?query=open%20class%20FirebaseEventListener) for more details on the listener.

##### Callbacks

Segment recommends that you add the callbacks in the `onCreate()` of the application class since these callbacks can be triggered even when the application is in the background.

###### Token callback

When MoEngage SDK handles push registration, it optionally provides a callback to the application whenever a new token is registered or the token is refreshed. To get the token callback implement the [TokenAvailableListener](https://moengage.github.io/android-api-reference/pushbase/com.moengage.pushbase.listener/-token-available-listener/index.html) and register for the callback using [MoEFireBaseHelper.getInstance().addTokenListener()](https://moengage.github.io/android-api-reference/moe-push-firebase/com.moengage.firebase/-mo-e-fire-base-helper/add-token-listener.html).

###### Non-MoEngage payload

If you're using the receiver provided by the SDK in your application's manifest file, SDK provides a callback in case a push payload is received for any other server apart from MoEngage Platform. To get a callback implement the [NonMoEngagePushListener](https://moengage.github.io/android-api-reference/moe-push-firebase/com.moengage.firebase.listener/-non-mo-engage-push-listener/index.html) and register for the callback using [MoEFireBaseHelper.getInstance().addNonMoEngagePushListener()](https://moengage.github.io/android-api-reference/moe-push-firebase/com.moengage.firebase/-mo-e-fire-base-helper/add-non-mo-engage-push-listener.html).

#### Declare and configure rich landing activity:

A rich landing page can be used to open a web URL inside the app through a push campaign.

The following configuration is only required if you want to add a parent activity to the Rich landing page. If not, you can move to the next section.
To use a rich landing page you need to add the below code in the AndroidManifest.xml

Add the following snippet and replace `[PARENT_ACTIVITY_NAME]` with the name of the parent
activity; `[ACTIVITY_NAME]` with the activity name which should be the parent of the Rich Landing Page

```xml
<activity
  android:name="com.moe.pushlibrary.activities.MoEActivity"
  android:label="[ACTIVITY_NAME]"
  android:parentActivityName="[PARENT_ACTIVITY_NAME]" >
</activity>
```

You are now all set up to receive push notifications from MoEngage. For more information on features provided in MoEngage Android SDK refer to the following links:

* [Push Notifications](https://developers.moengage.com/hc/en-us/sections/360013606771-Push)
* [Location Triggered](https://developers.moengage.com/hc/en-us/articles/4403443036564-Location-Triggered)
* [In-App messaging](https://developers.moengage.com/hc/en-us/sections/360013831431-In-App-Messages)
* [Notification Center](https://developers.moengage.com/hc/en-us/articles/4403878923284-Notification-Center)
* [API Reference](https://moengage.github.io/android-api-reference/index.html)
* [Compliance](https://developers.moengage.com/hc/en-us/sections/4403894212116-Compliance)
* [Release Notes](https://developers.moengage.com/hc/en-us/articles/4403896795540-Changelog)

### Identify

Use [Identify](/docs/segment/connections/sources/catalog/libraries/mobile/android/#identify) to track user-specific attributes. This is the same as tracking [user attributes](https://developers.moengage.com/hc/en-us/articles/4402050979860-Track-User-Attributes) on MoEngage. MoEngage supports traits supported by Segment as well as custom traits. If you set `traits.id`, MoEngage sets that as the Unique ID for that user.

> \[!NOTE]
>
> MoEngage supports anonymous identifiers in Device-mode only. If you use the MoEngage destination in Cloud-mode, use a known user identifier.

### Track

Use [Track](/docs/segment/connections/sources/catalog/libraries/mobile/android/#track) to track events and user behavior in your app. This sends the event to MoEngage with the associated properties. Tracking events is essential and helps you create segments for engaging users.

### Reset

If your app supports the ability for a user to logout and login with a new identity, then you need to call reset for the Analytics client.

### Sample Implementation

Refer to [MoEngage's](https://github.com/moengage/moengage-segment-integration) GitHub repository for sample implementation.

## Web

The MoEngage WebSDK offers the ability to send push notifications to Google Chrome, Opera and Firefox browsers. Complete the following steps after you've configured Segment's `analytics.js.`

### Integration

#### 1. Setup your MoEngage Web SDK settings at MoEngage Dashboard

Configure the [web settings](https://help.moengage.com/hc/en-us/articles/210224063) on the MoEngage dashboard to start using MoEngage \<> Segment integration.

If you have selected `HTTPS` mode of integration in the settings, complete the following steps:

#### 2 Set up for HTTPS websites

#### 2.a Download the required files (HTTPS)

For HTTPS Web Push to work, you need to host two files in the `root` directory of your web server. These two files are available for you to download at the [web settings page](https://app.moengage.com/v3/#/settings/push/web).

* `manifest.json`
* `serviceworker.js`

> \[!NOTE]
>
> The name of the serviceworker file must be `serviceworker.js`. Please contact [MoEngage support](mailto:support@moengage.com) if you want to give your serviceworker file a different name.

#### 2.b Add link to manifest in HTML (HTTPS)

Add the following line in the `<head>` tag of your page.

```html
<head>
  ...
	<link rel="manifest" href="/manifest.json">
  ...
</head>
```

#### 2.c Use your existing manifest or serviceworker file (HTTPS)

If you already have these files,

1. **Manifest** - Add the sender ID you saved on MoEngage dashboard as the `gcm_sender_id`. If you've used `MoEngage Shared Project` while setting up, your sender ID is `540868316921`. Edit your `manifest.json` as follows:

```json
{
  ...
  "gcm_sender_id": "GCM_SENDER_ID",
  ...
}
```

2. **Service Worker** - Add the following line to the top of your `serviceworker.js` file.

```js
importScripts("//cdn.moengage.com/webpush/releases/serviceworker_cdn.min.latest.js?date="+
new Date().getUTCFullYear()+""+new Date().getUTCMonth()+""+new Date().getUTCDate());
```

### Identify

Use [Identify](/docs/segment/connections/sources/catalog/libraries/website/javascript#identify) to track user specific attributes. This is equal to [tracking user attributes](https://developers.moengage.com/hc/en-us/articles/360061114832-Web-SDK-User-Attributes-Tracking) on MoEngage. MoEngage supports traits supported by Segment as well as custom traits.

> \[!NOTE]
>
> MoEngage supports anonymous identifiers in device-mode only. If you use the MoEngage destination in cloud-mode, use a known user identifier.

### Track

Use [Track](/docs/segment/connections/sources/catalog/libraries/website/javascript#track) to track events and user behavior in your app. This sends the event to MoEngage with the associated properties. Tracking events is essential and helps you create segments for engaging users.

### Reset

If your website supports the ability for a user to logout and login with a new identity, then you need to call [reset](/docs/segment/connections/sources/catalog/libraries/website/javascript#reset-logout) method in `analytics.js`.

### Test mode and debugging

While updating the MoEngage settings on the Segment Dashboard, you can enable the logging functionality of the MoEngage SDK to see the SDK logs on the browser console. Just set `Enable Debug Logging` to `On` and the SDK loads in debug mode.

> \[!TIP]
>
> When you enable debug mode, Segment sends the events and user attributes to the `TEST` environment of your MoEngage App.

## MoEngage Web SDK features

For information about optional features, see the documentation below:

* [Configure opt-in type](https://help.moengage.com/hc/en-us/articles/210224063-Configure-Web-Push-Settings#configure-web-push-opt-in-0-6)
* [Self-handled opt-ins](https://developers.moengage.com/hc/en-us/articles/360061219351-Configure-Self-Handled-Opt-In)
* [SDK callbacks](https://developers.moengage.com/hc/en-us/articles/4401950701076-Opted-Out-Users)

### On-Site messaging

On-site messaging campaigns allow you to show personalized pop-ups and non-intrusive banners on your website.

Web SDK integration for On-site Messaging automatically starts working on all the pages where the web SDK is integrated.

For more information, refer to [Configure and Integrate On-site Messaging](https://developers.moengage.com/hc/en-us/articles/360061573232-Configure-and-Integrate-On-site-Messaging).

### Web personalization

Web personalization is used to personalize the website experience for each user. A few popular use cases for web personalization include the home page banner personalization basis user behavior, localizing the website content basis user geography, testing the performance of new page layouts for improved performance, modifying the content shown on any webpage as per the user behavior.

For more information, refer to MoEngage's documentation on how to [configure and integrate web personalization](https://developers.moengage.com/hc/en-us/articles/360062008891-Configure-and-Integrate-Web-Personlization).

## Use Twilio Engage with MoEngage

You can send [Computed traits](/docs/segment/unify/traits/computed-traits) and [Audiences](/docs/segment/audiences/audiences/) to MoEngage as custom attributes or custom events.

* Traits and audiences sent using the Identify call appear in MoEngage as *Tracked Custom Attributes* with value as *True*.
* Traits and audiences sent using the Track call appear in MoEngage as *Tracked User Events*.

When connecting the calculated trait or audience to the MoEngage destination, you can select the method of your choice (or opt to use both).

### Sync time

The default integration for MoEngage \<> Twilio Engage connection is **Real Time.** But there are some filters that disqualify the persona from syncing in real-time, including some time-based filters which restrict your audience's size at the time of message send.

### Computed traits using Identify calls

To generate custom attributes in MoEngage, you may provide Computed Traits defined in Engage as Identify calls. The computed trait's value is used to set the custom attribute.

### Create a Segment Computed Trait

1. In Segment, navigate to the **Computed Traits** in Engage.
2. Click **New Computed Trait**.
3. Create your computed trait. A lightning bolt in the top corner of the page will indicate if the computation updates in real-time.

   ![Configure and Preview Your Trait page with the "Include anonymous users" box checked.](https://docs-resources.prod.twilio.com/0a829bd373d4c766fdd3d95bd4ed7d4c8966ff7a60697d4be1c5e814dfd74729.png)
4. Next, select **MoEngage** as your destination.

   ![MoEngage (Actions) destination settings in Segment.](https://docs-resources.prod.twilio.com/38486e8d21c818ccec0e11502a7cd58c3f757b9125506edc2ea83ee9535d472a.png)
5. Preview by clicking **Review & Create**.
   > By default, Segment queries all historical data to set the current value of the computed trait and audience. To omit this data, uncheck **Historical Backfill**.
   >
   > ![Review and Create step showing audience name 'Email Opened 30 Days' and key 'email\_opened\_30\_days'.](https://docs-resources.prod.twilio.com/947148c864175a186008c4f3a54a291e8e451095046370c8a54bbb3af6367fde.png)
6. In the computed trait, adjust the connection settings based on how you would like your data sent to MoEngage.

### Create a Segment Audience

1. In Segment, navigate to the **Audience** in Engage.
2. Click **New**.
3. Create your audience. A lightning bolt indicates if the computation updates in real-time.

   ![Configure and Preview Your Trait page with audience containing users who completed an order at least once, within 7 days.](https://docs-resources.prod.twilio.com/6b1ba199b606d6a48d675ec80295207a9cf5030e15f56083ce775defb7da42d4.png)
4. Next, select **MoEngage** as your destination.

   ![Screenshot of MoEngage (Actions) destination page in Segment.](https://docs-resources.prod.twilio.com/0d63d223910bc63d3ec322f34bad29584f929ca0b4a3569ef57294a3e929a6a3.png)
5. Preview your audience by clicking **Review & Create**.
   > By default, Segment queries all historical data to set the current value of the audience. To omit this data, uncheck **Historical Backfill**.
   >
   > ![Review and Create page.](https://docs-resources.prod.twilio.com/3fd392997e0cd165de5ed442570ef294619b7f8f608f7eea84099892bfb322c6.png)
6. In the computed trait or audience settings, adjust the connection settings based on how you would like your data sent to MoEngage.

   ![Connection settings with toggles for Send Identify and Send Track, and fields for Audience Entered and Exited events.](https://docs-resources.prod.twilio.com/19ef31885a8ea50637be28089b19862e8bfaeac7f299f1db1713df573e761775.png)

## Connect Twilio Engage to MoEngage

First, link MoEngage to Twilio Engage to send Computed Traits or Audiences. The first time you generate new Computed Trait or Audience, you can choose MoEngage as the destination for the Engage data.

1. Go to the Destinations tab in your space.
2. Search for MoEngage and add the MoEngage Destination to your Space.
3. On the set up screen, enter your `App Id`, `App Key`, and your `Endpoint Region`.

## Segment users in MoEngage

To create a segment of these users, navigate to **Segments > Create Segment**. Next, based on which call you used:

* **Identify**: Select **User Property** and select the specific attribute.

  ![MoEngage UI showing user behavior filter with event selection for trait computation.](https://docs-resources.prod.twilio.com/93177ed8ebcb8a4b85872aa37ac246fa21a326036d80e5d491b7c17ae8db6d66.png)
* **Track**: Select **User Behaviour** and select the specific event.

  ![Screenshot of User behavior filter in MoEngage UI.](https://docs-resources.prod.twilio.com/96242d87715ffdbca1d5f4ce469d4230ca4ac01e3dc585208d2de0600162a236.png)

## Settings

Segment lets you change these destination settings from the Segment app without having to touch any code.

| Field                | Description                                                                                                                                                                 | Required | Type    |
| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------- |
| APP ID               | You can find the APP\_ID key under App Settings on the MoEngage dashboard. Please make sure you have uploaded the pem file for sending push on iOS and GCM Key for Android. | Yes      | string  |
| Enable Debug Logging | If you are in TEST mode and would like debug logs in your browser console, enable this setting. You should not have this option enabled for your production sources.        | No       | boolean |
