Amplitude

How to integrate OneSignal with Amplitude to send events and receive cohorts

1940

Illustration showing Amplitude and OneSignal Integration Flow

In this tutorial you’ll learn how to set up OneSignal with Amplitude to send events over and receive back intelligent behavioral cohorts.

Amplitude provides actionable, 360-degree-insight into your entire digital product and customer experience delivered across every digital team. Now you can integrate with OneSignal to send intelligent and timely notifications based on your users’ actions and behaviors.

1. Send data to Amplitude: send all of your users’ responses to your messages. This includes data across Push, In-App Messages, Email, and SMS.

2. Receive Cohorts from Amplitude: Within Amplitude you can create a whole set of cohorts based on your users' behavior and actions. Now you can sync this hourly, daily, or weekly with OneSignal.

This integration can be set up on an application basis, to ensure you have control over what application data is synced from and to Amplitude.

Use Cases

  1. Action-driven Onboarding: Prompt your user to complete signup, or other onboarding actions, through syncing a relevant cohort, to ensure they become a converted user

  2. Gamification: Provide positive reinforcement when a user completes an action within your application, for example. submitting a post or article for the first time.

Requirements

  1. Accounts: If you don't already have them, sign up for an Amplitude and a OneSignal account. Amplitude's Quick Start Guide will walk you through how to set up your Amplitude organization and create your first project. To create a OneSignal account, visit www.onesignal.com.

  2. OneSignal Pricing Plan: In order to use our Amplitude Integration, we ask you to please be on a Growth Plan or higher. If you need help with pricing, please check out our Pricing Page and reach out to us with any questions.

  3. Amplitude Pricing: Find out more about Amplitude Price Plans.

  4. The OneSignal Mobile SDK and/or Web SDK from which you want to send data. Email or SMS only integrations do not require the SDK.


Step 1. Turn on Integration

In OneSignal, navigate to Dashboard > Settings > Analytics > Amplitude and click Activate.

678

Image. Showing Amplitude Integration card

Step 2. Add Amplitude Token in OneSignal Dashboard

You can find your Amplitude API Key Token under Settings > Projects. Copy-paste the API Key into OneSignal.

1376

Image showing Amplitude API Key

If you are using Amplitude EU servers, select Send events exclusively to Amplitude EU data center.

Once done Activate your integration.

700

Image. Showing modal to add Amplitude card to enter in API Key

Step 3. Add OneSignal to Amplitude Integrations

Within OneSignal, navigate to Settings > Keys & IDs. Copy the "App ID" and the "REST API key".

2310

Image showing keys and ids within your Settings to copy the OneSignal API Key

In Amplitude, navigate to Data Destinations and add OneSignal to your project.

534 734

To connect to OneSignal, name the connection (to recognize later) and copy-paste the "App Id" and "REST API Key" from the OneSignal dashboard.

Important: The User ID section refers to any Amplitude property that you want to use and needs to sync to the OneSignal External User ID. This can be any property available but we recommend using the "User Id" set to Amplitude within their setUserId property.

Click Save when finished.

612

Image showing where to paste your OneSignal API Key in Amplitude

Step 4. Sync Amplitude & OneSignal User Id

Syncing user data across OneSignal and Amplitude requires setting the OneSignal External User Id property to the "User Id" property set in Amplitude during step 3.

OneSignal's External User Id is user-level identifier to associate across different OneSignal Channel Records (Push, Email, In-App Messages, and/or SMS). The below examples show how to set the OneSignal External User Id for the push, email, and sms phone number channel record when collected through our SDK.

The Push/In-App Message Channel Record is created when the user subscribes to push on your website or opens your mobile app with the OneSignal SDK.

The Email and SMS Channel Record needs to be sent to OneSignal using the setEmail SDK Method and setSMSNumber SDK Method shown below.

//Get the User Id
var userId = "12345";
//Set Amplitude User Id
amplitude.getInstance().setUserId(userId);

//Set the OneSignal External User Id same as Amplitude User Id
OneSignal.push(function() {
  OneSignal.setExternalUserId(userId);
});

//Example creating Email record in OneSignal
OneSignal.push(function() {
  OneSignal.setEmail("[email protected]")          
    .then(function() {
      OneSignal.setExternalUserId(userId);
   }); 
});

//Example creating SMS record in OneSignal
OneSignal.push(function() {
  OneSignal.setSMSNumber("+11234567890")
    .then(function() {
      OneSignal.setExternalUserId(userId);
   });
});
//Set Amplitude User Id
client.setUserId("USER_ID");

//Set email to OneSignal
OneSignal.setEmail("[email protected]");

//Set phone number to OneSignal
OneSignal.setSMSNumber("+11234567890");

//Set the OneSignal External User Id same as Amplitude User Id
OneSignal.setExternalUserId("USER_ID", new OneSignal.OSExternalUserIdUpdateCompletionHandler() {
    @Override
    public void onSuccess(JSONObject results) {
        try {
            if (results.has("push") && results.getJSONObject("push").has("success")) {
                boolean isPushSuccess = results.getJSONObject("push").getBoolean("success");
                OneSignal.onesignalLog(OneSignal.LOG_LEVEL.VERBOSE, "Set external user id for push status: " + isPushSuccess);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            if (results.has("email") && results.getJSONObject("email").has("success")) {
                boolean isEmailSuccess = results.getJSONObject("email").getBoolean("success");
                OneSignal.onesignalLog(OneSignal.LOG_LEVEL.VERBOSE, "Set external user id for email status: " + isEmailSuccess);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            if (results.has("sms") && results.getJSONObject("sms").has("success")) {
                boolean isSmsSuccess = results.getJSONObject("sms").getBoolean("success");
                OneSignal.onesignalLog(OneSignal.LOG_LEVEL.VERBOSE, "Set external user id for sms status: " + isSmsSuccess);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(OneSignal.ExternalIdError error) {
        // The results will contain channel failure statuses
        // Use this to detect if external_user_id was not set and retry when a better network connection is made
        OneSignal.onesignalLog(OneSignal.LOG_LEVEL.VERBOSE, "Set external user id done with error: " + error.toString());
    }
});
//Set Amplitude User Id
Amplitude.instance().setUserId("USER_ID")

//Set email to OneSignal
OneSignal.setEmail("[email protected]")

//Set phone number to OneSignal
OneSignal.setSMSNumber("+11234567890")

//Set the OneSignal External User Id same as Amplitude User Id
OneSignal.setExternalUserId("USER_ID", withSuccess: { results in
    // The results will contain push and email success statuses
    print("External user id update complete with results: ", results!.description)
    // Push can be expected in almost every situation with a success status, but
    // as a pre-caution its good to verify it exists
    if let pushResults = results!["push"] {
        print("Set external user id push status: ", pushResults)
    }
    if let emailResults = results!["email"] {
        print("Set external user id email status: ", emailResults)
    }
    if let smsResults = results!["sms"] {
        print("Set external user id sms status: ", smsResults)
    }
}, withFailure: {error in
    print("Set external user id done with error: " + error.debugDescription)
})
//Set Amplitude User Id
[[Amplitude] instance] setUserId:@"USER_ID"];

//Set email to OneSignal
[OneSignal setEmail:@"[email protected]"];

//Set phone number to OneSignal
[OneSignal setSMSNumber:@"+11234567890"];
  
//Set the OneSignal External User Id same as Amplitude User Id
[OneSignal setExternalUserId:@"USER_ID", withSuccess:^(NSDictionary *results) {
  // The results will contain push and email success statuses
  NSLog(@"External user id update complete with results: %@", results.description);
  // Push can be expected in almost every situation with a success status, but
  // as a pre-caution its good to verify it exists
  if (results["push"] && results["push"]["success"])
    NSLog(@"Set external user id push status: %@", results["push"]["success"]);
  // Verify the email is set or check that the results have an email success status
  if (results["email"] && results["email"]["success"])
    NSLog(@"Set external user id email status: %@", results["email"]["success"]);
  // Verify the number is set or check that the results have an sms success status
  if (results["sms"] && results["sms"]["success"])
    NSLog(@"Set external user id sms status: %@", results["sms"]["success"]);
}];
//Set Amplitude User Id
Amplitude.getInstance().setUserId("USER_ID");

//Set email to OneSignal
OneSignal.setEmail("[email protected]");

//Set phone number to OneSignal
OneSignal.setSMSNumber("+11234567890");

//Set the OneSignal External User Id same as Amplitude User Id
OneSignal.setExternalUserId("USER_ID", (results) => {
  // The results will contain push and email success statuses
  console.log('Results of setting external user id');
  console.log(results);
  
  // Push can be expected in almost every situation with a success status, but
  // as a pre-caution its good to verify it exists
  if (results.push && results.push.success) {
    console.log('Results of setting external user id push status:');
    console.log(results.push.success);
  }
  
  // Verify the email is set or check that the results have an email success status
  if (results.email && results.email.success) {
    console.log('Results of setting external user id email status:');
    console.log(results.email.success);
  }
  
    // Verify the sms phone number is set or check that the results have an sms success status
  if (results.sms && results.sms.success) {
    console.log('Results of setting external user id sms status:');
    console.log(results.sms.success);
  }
});
//Set Amplitude User Id
Amplitude.instance().setUserId("USER_ID");

//Set email to OneSignal
OneSignal.setEmail("[email protected]");

//Set phone number to OneSignal
OneSignal.setSMSNumber("+11234567890");

//Set the OneSignal External User Id same as Amplitude User Id
OneSignal.shared.setExternalUserId("USER_ID").then((results) {
  log(results.toString());
}).catchError((error) {
  log(error.toString());
});
//Set Amplitude User Id
Amplitude.Instance.setUserId("USER_ID");

//Set email to OneSignal
OneSignal.SetEmail("[email protected]");

//Set phone number to OneSignal
OneSignal.SetSMSNumber("+11234567890");

//Set the OneSignal External User Id same as Amplitude User Id
OneSignal.Current.SetExternalUserId("USER_ID", OneSignalSetExternalUserId);

private static void OneSignalSetExternalUserId(Dictionary<string, object> results)
{
  // The results will contain push and email success statuses
  Debug.WriteLine("External user id updated with results: " + Json.Serialize(results));
  // Push can be expected in almost every situation with a success status, but
  // as a pre-caution its good to verify it exists
  if (results.ContainsKey("push"))
  {
    Dictionary<string, object> pushStatusDict = results["push"] as Dictionary<string, object>;
    if (pushStatusDict.ContainsKey("success"))
    {
      Debug.WriteLine("External user id updated for push with results: " + pushStatusDict["success"] as string);
    }
  }
  // Verify the email is set or check that the results have an email success status
  if (results.ContainsKey("email"))
  {
    Dictionary<string, object> emailStatusDict = results["email"] as Dictionary<string, object>;
    if (emailStatusDict.ContainsKey("success"))
    {
      Debug.WriteLine("External user id updated for email with results: " + emailStatusDict["success"] as string);
    }
  }
  // Verify the number is set or check that the results have an sms success status
  if (results.ContainsKey("sms"))
  {
    Dictionary<string, object> smsStatusDict = results["sms"] as Dictionary<string, object>;
    if (smsStatusDict.ContainsKey("success"))
    {
      Debug.WriteLine("External user id updated for sms with results: " + smsStatusDict["success"] as string);
    }
  }
}

Moving Current Amplitude Subscriptions to OneSignal

You may Import Email Addresses and Import Phone Numbers into OneSignal to immediately message your userbase. Using the CSV imports or API allows you to set the external_user_id property which must match the selected User Id property in Amplitude.

Step 5. Syncing your Cohorts

  1. To export users from Amplitude to OneSignal, first create the cohort of users you wish to export. You can read more about cohorts in Amplitude here.
  2. Once you have created the cohort, click Sync to export these users to OneSignal. You can then go into your OneSignal dashboard to use these cohorts within your segments.
1189

Image showing where to view your Active Integrations to Sync with OneSignal

  1. Note that you can select how frequently you’d like to sync your cohorts with OneSignal. These can be done as a One-Time Sync, or on a Scheduled basis.
1102

Image showing how you can set a sync for your cohorts with OneSignal


Step 6. How to use an Amplitude Cohort within your Segment

  1. Navigating to Segments
    Open Audience > Segments select New Segment. If you’d like to know more about Segments, Read More here

2: Selecting your Amplitude Cohort
Select Amplitude within the list of Rules for the Segment. Choose from the dropdown which cohort you’d like to use within this Segment.

1027

Image showing the ability to create a segment

Now select Save Segment or alternatively continue on to filter the segment.

1027

Image showing how to create a segment from an Amplitude Cohort


FAQ

What Events are sent?

Below we have a table showing you what events are sent per channel.

OneSignal EventAmplitude EventAmplitude Message Event Property
Push Notification Clicked Which Opens the App/Website[OneSignal] Push ClickedMessage Name = The name of the message.

Message = Push Notification Title/Headings

Message Contents = Push Notification Message/Contents

delivery_id = OneSignal Notification Id.

message_type = push
Push Notification Sent from OneSignal[OneSignal] Push DeliveredMessage Name = The name of the message.

Message = Push Notification Title/Headings

Message Contents = Push Notification Message/Contents

delivery_id = OneSignal Notification Id.

message_type = push
Push Notification Received on Device (Confirmed Deliveries)[OneSignal] Push Confirmed deliveryMessage Name = The name of the message.

Message = Push Notification Title/Headings

Message Contents = Push Notification Message/Contents

delivery_id = OneSignal Notification Id.

message_type = push
In-App Message Clicked[OneSignal] IAM ClickedMessage Name set within OneSignal Dashboard - does not track what was clicked. Use the Click Action ID to send event to Amplitude.

message_type = in-app
In-App Message Impression (shown to user)[OneSignal] IAM DisplayedMessage Name set within OneSignal Dashboard

message_type = in-app
Email sent from OneSignal[OneSignal] Email DeliveredMessage Name = The name of the message.

Message = Subject of the email sent from OneSignal

delivery_id = OneSignal Notification Id.

message_type = email
Email opened/viewed from OneSignal[OneSignal] Email OpenedMessage Name = The name of the message.

Message = Subject of the email sent from OneSignal

delivery_id = OneSignal Notification Id.

message_type = email
Email Link Clicked[OneSignal] Email ClickedMessage Name = The name of the message.

Message = Subject of the email sent from OneSignal

delivery_id = OneSignal Notification Id.

message_type = email
SMS sent from OneSignal[OneSignal] SMS DeliveredMessage Name = The name of the message.

Message = Contents of the SMS sent from OneSignal

Message Contents = Contents of the SMS sent from OneSignal

delivery_id = OneSignal Notification Id.

message_type = sms
SMS delivered to device[OneSignal] SMS Confirmed deliveryMessage Name = The name of the message.

Message = Contents of the SMS sent from OneSignal

Message Contents = Contents of the SMS sent from OneSignal

delivery_id = OneSignal Notification Id.

message_type = sms

How can we pass Subscription events?

Subscription events are not currently being sent automatically. This can be done with the OneSignal SDK Subscription Observer Methods. See Subscription Tracking for more details.

What ID should we use?

In order to sync your data effectively between OneSignal and Amplitude, we use External ID. This allows you to recognize your user from Amplitude to OneSignal.

Additionally, External ID can be used across other integrations to ensure you have a connected data ecosystem.

Why do we set up the integration on an Application level as opposed to Organization Level?

We set up the Amplitude on an Application level, as this allows you some control over what is synced and the amount of data synced both to and from Amplitude.

Why do my cohort user counts not match the OneSignal segment counts?

There are a couple reasons for this:

  • OneSignal tracks devices while Amplitude tracks users. A single Amplitude User may have 1+ devices within OneSignal.
  • OneSignal's segments only show devices that are subscribed. Unsubscribed devices are not counted or shown in segments.
  • The channel record must already exist within OneSignal and each record needs the external_user_id Property to match the corresponding property in Amplitude.

Why does my delivery data not match between Amplitude and OneSignal?

There may be a couple reasons for this:

  • The Amplitude User Id property specified and OneSignal's External User Id property needs to be set for message data of that device to be tracked.
  • Amplitude measures Users, OneSignal measures Devices. If a user has multiple devices, the sent, clicked and confirmed events will be higher in OneSignal.