mParticle Integration Guide on
Android

mParticle Integration Guide

mParticle users can integrate Button using our mParticle ButtonKit. Once completed, you will be enabled to receive users from the Button Marketplace. In this guide, we will:

  1. Add the ButtonKit
  2. Hook Up mParticle
  3. Report Orders to Button via mParticle
  4. Report Adjustments and Cancellations to Button
  5. Other Configurations
  6. Test Your Integration

What is a Button integration via mParticle?

For merchants that already work with mParticle, the mParticle SDK provides an option to send orders to Button through your existing partnership with minimal integration work.

If you're unsure if this is the correct integration path for your company, please talk to your Button Partner Success Manager.

The ButtonKit

The ButtonKit provides features on top of the standard mParticle SDK. These features are required to enable Button's linking and affiliation products. They are

  • Post-install deeplinking
  • Automatic user attribution collection

Including the ButtonKit will also include the base mParticle SDK.

Requirements

Before we begin, you should have the following:


Add the ButtonKit

Import the ButtonKit dependency in your application’s build.gradle. You must use a version greater than or equal to 5.3.2 and we recommend using the latest version: ButtonKit SDK Version

implementation 'com.mparticle:android-button-kit:+' // Use the latest version from the badge above

Please note that you do not need to import the core mParticle SDK as it is a transitive dependency within the ButtonKit

Handle incoming Intents either in your main Activity or your Application sub-class:

public class App extends Application implements AttributionListener {

  @Override
  public void onCreate() {
    super.onCreate();

    // mParticle core initialization
    MParticleOptions options = MParticleOptions.builder(this)
        .credentials(BuildConfig.MP_KEY, BuildConfig.MP_SECRET)
        .environment(MParticle.Environment.AutoDetect)
        .logLevel(MParticle.LogLevel.VERBOSE)
        .build();
    MParticle.start(options);
  }

  @Override
  public void onResult(AttributionResult result) {
    if (result != null && result.getServiceProviderId() == MParticle.ServiceProviders.BUTTON) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(result.getLink()));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
  }

  @Override
  public void onError(AttributionError error) {
    if (error != null && error.getServiceProviderId() == MParticle.ServiceProviders.BUTTON) {
      Log.e(TAG, "Attribution error: " + error.getMessage());
    }
  }

}

Proguard Rules

If your app is using Proguard (minifyEnabled true in your build.gradle) make sure that the proguard rules below are in effect in your rules file. This file is usually located in yourapp/proguard-rules.pro, or its location is specified in build.gradle, look for proguardFiles in your default or variant configuration (note: this can be multiple files).

-keepattributes Exceptions,InnerClasses,EnclosingMethod
-keep class com.usebutton.** { *; }
-keepclassmembers class * implements android.os.Parcelable {
    static ** CREATOR;
}
-keep class com.google.android.gms.ads.identifier.AdvertisingIdClient { public *; }

Our mParticle integration is configured to require your customer IDs, advertising IDs (IDFA, Google AID, Android ID), IP, and user location. We use these in our dashboard and do not share them with anyone. Read more about data Button collects.

Traffic from the Google Play store can result in users opening your app without any deeplink path or parameters. Button's Deferred Deeplink product closes this gap by recovering the link the user was originally following based on device fingerprinting.

After a fresh install, the user may both have an attributed source, and a destination deep link which needs to be retrieved from the Button API.

Hook Up mParticle

Connect your Android workspace to Button. You will need to input your Button Application ID, which you can access from your organization’s Button dashboard. For more information on setting up a new mParticle connection, see the Platform Guide.

Reporting Orders

To report orders with a mParticle integration, you must use the mParticle SDK to report eCommerce Events

mParticle provides thorough documentation of these methods in their SDK documentation. A merchant can construct MPCommerceEvents in the mParticle SDK via the checkout API or manually. Which method a merchant chooses is not relevant to Button as long as the required fields are included.

Button requires the reporting of a subset of the eCommerce event fields. The taxonomy of fields Button expects is as follows.

A merchant must report a CommerceEvent containing

transactionAttributes is an instance of TransactionAttributes and must include

products is an array of Product and each element must include


Report Adjustments and Cancellations to Button

Button requires all mParticle integrated merchants to report returns, adjustments, and cancellations via a batch file upload. This section details the process to deliver and format this file correctly.

The enclosed CSV snippets refer to the following sample order data:

This is an example mParticle payload that would be received by Button. We'll be referencing and adjusting this order in the following sections.

[
   {
      "currencycode":"USD",
      "type":"PRODUCT_ACTION",
      "transactionid":"1112224788",
      "products":[
         {
            "quantity":"1.0",
            "totalamount":"10.99",
            "price":"10.99",
            "name":"Colombian Supremo Coffee, Single-Serve Cups (100 ct.)",
            "attributes":{
            },
            "id":"202091",
            "position":"0",
            "category":"ci16953338243"
         },
         {
            "quantity":"3.0",
            "totalamount":"60.45",
            "price":"20.15",
            "name":"Comfort Care Baby Diapers, Size 4, 22 - 37 lbs. (210 ct.)",
            "attributes":{
            },
            "id":"894036055",
            "position":"0",
            "category":"ci16953331111"
         }
      ],
      "shippingamount":"0.0",
      "totalamount":"73.65",
      "action":"PURCHASE",
      "taxamount":"2.21",
      "attributes":{
         "fulfillment":"delivery"
      },
   }
]

This will create a Button transaction that you can query which looks as such (this only includes relevant fields for brevity):

{
   "order_total":6982,
   "order_line_items":[
      {
         "quantity":1,
         "total":1099,
         "sku":"202091",
         "description":"Member's Mark Colombian Supremo Coffee, Single-Serve Cups (100 ct.)"
      },
      {
         "quantity":3,
         "total":6045,
         "sku":"894036055",
         "description":"Member's Mark Comfort Care Baby Diapers, Size 4, 22 - 37 lbs. (210 ct.)"
      }
   ]
}

General Guidelines

  • Button will provide you with a dedicated SFTP directory for uploading your batch files
  • The batch file name should include the upload date in its file name
  • Batch files should be delivered in a comma-separated value (CSV) format, dropped to the SFTP site on a recurring basis at a mutually agreed upon interval (e.g. daily)
  • The file should contain all adjusted and cancelled orders that occurred since the previous upload (e.g. the previous day from 00:00:00 UTC to 23:59:59 UTC)
    • For the first upload, the file should contain records from the previous interval (e.g. yesterday, last week)
  • Each [Order ID/Line Item] combination should have its own row entry (i.e. if there are 3 items in the order, there should be 3 rows: 1 for each line item)
  • All values are on a line item (product in mParticle) basis except for Order ID

All of these scenarios must be accounted for:

  • Line Item quantity decrease
  • Line Item cancellation (removal)
  • Full order cancellations
  • Removing fraudulent orders (i.e. orders Button has that do not exist in your OMS)

The shorthand products[].X is used to indicate that field X is present on each item in the products array reported to mParticle. For example, products[].id represents the ID field on an item in the product array.

CSV Headers and Definitions

  • DATE_UPDATED: date & time the order was adjusted (RFC3339 format in UTC time)
  • ORDER_ID: Your merchant order ID. This value must be unique within your organization (if it is not, please notify your Button contact). Must be the same value as the transactionid field reported to mParticle in the original commerce event.
  • PRODUCT_REVENUE (integer): total revenue for the line item (xx.xx). This will replace the products[].totalamount field reported to mParticle in the original order.
  • CURRENCY (string): currency used for the purchase (String in ISO ALPHA-3 format)
  • PRODUCT_SKU (string): The SKU for the product item sold. Must be the same value as the products[].id field reported to mParticle in the original order.
  • PRODUCT_DESCRIPTION (string): description of the line-item, e.g. “large t-shirt”. This will replace the products[].name field reported to mParticle in the original order.
  • PRODUCT_QTY (integer): number of line item units purchased. This will replace the products[].quantity field reported to mParticle in the original order.
  • ACTION (string): The action to apply to the order or line item, as relevant. The possible values are as follows:
    • invalidate: This tells Button to delete an unverified order
    • cancel: This tells Button to remove a fully returned/cancelled order. Note: Only use this action when you intend to cancel an entire order. Partial returns are considered order adjustments and should follow that format.
    • adjust: This tells Button to replace the current state of the line item with what’s in the CSV file
    • <empty>: Leaving this column empty tells Button the listed line item was not adjusted and is still valid for an otherwise-adjusted order. Note: this case only occurs for orders that have other line items with adjust action(s)

Reporting Adjustments

  1. Extract Orders Adjusted From OMS Since Last Batch File Upload - Extract details for all orders were adjusted since the last Batch File Upload (e.g. from 00:00:00-23:59:59 UTC yesterday)
  2. Write Adjustments to New Batch File - Following the conventions outlined above, write all order adjustments to the new batch file. Refer to the below example.

An order is considered an "Adjusted Order" when at least one line item in the order has changed, but the entire order has not been cancelled. We expect Adjusted orders to be reported in their current state (not the delta). Per the below examples, the following scenarios must be accounted for:

  • Line items where quantity changes. Report the new quantity with an adjust action.
  • Line items that are fully returned/cancelled. Omit these items from the CSV. Do not use a cancel action.
  • Remaining, unadjusted line items. Include these line items in their current state, with no action specified.

If the purchasing user returns the coffee, we would expect the coffee be omitted in the CSV. Note that that the diapers are still present since they did not change. The example row is as follows:

DATE_UPDATED,ORDER_ID,PRODUCT_REVENUE,CURRENCY,PRODUCT_SKU,PRODUCT_DESCRIPTION,PRODUCT_QTY,ACTION
2018-09-01T00:00:00Z,1112224788,60.45,USD,894036055,"Member's Mark Comfort Care Baby Diapers, Size 4, 22 - 37 lbs. (210 ct.)",3,

If the purchasing user returned the coffee and two of the diapers (they bought 3) we would expect the coffee line item to be omitted, and the new state of the diaper item (not the delta) to show up with an adjust action. The resulting single example row is as follows:

DATE_UPDATED,ORDER_ID,PRODUCT_REVENUE,CURRENCY,PRODUCT_SKU,PRODUCT_DESCRIPTION,PRODUCT_QTY,ACTION
2018-09-01T00:00:00Z,1112224788,20.15,USD,894036055,"Member's Mark Comfort Care Baby Diapers, Size 4, 22 - 37 lbs. (210 ct.)",1,adjust

If the user only returned two of the diapers (they bought 3) we would expect the coffee line item to be included with no changes, and the new state of the diaper item (not the delta) to show up with an adjust action. The example rows are as follows:

DATE_UPDATED,ORDER_ID,PRODUCT_REVENUE,CURRENCY,PRODUCT_SKU,PRODUCT_DESCRIPTION,PRODUCT_QTY,ACTION
2018-09-01T00:00:00Z,1112224788,10.99,USD,202091,"Member's Mark Colombian Supremo Coffee, Single-Serve Cups (100 ct.)",1,
2018-09-01T00:00:00Z,1112224788,20.15,USD,894036055,"Member's Mark Comfort Care Baby Diapers, Size 4, 22 - 37 lbs. (210 ct.)",1,adjust

Reporting Cancellations

  1. Extract Orders Cancelled From OMS Since Last Batch File Upload - Extract details for all orders that were cancelled since the last Batch File Upload (e.g. from 00:00:00-23:59:59 UTC yesterday)
  2. Write Cancellations to New Batch File - Following the conventions outlined above, write all order cancellations to the new batch file. Refer to the below example.

If the purchasing user returned the whole order, we would expect the order to show up in the file with a cancel action. The example row is as follows.

DATE_UPDATED,ORDER_ID,PRODUCT_REVENUE,CURRENCY,PRODUCT_SKU,PRODUCT_DESCRIPTION,PRODUCT_QTY,ACTION
2018-09-01T00:00:00Z,1112224788,,,,,,cancel

Reporting Invalidations

  1. Extract All Orders From OMS Since Last Batch File Upload - Extract details for all orders that were placed or modified since the last Batch File Upload (e.g. from 00:00:00-23:59:59 UTC yesterday). Orders can be retrieved through the Export Tool in your dashboard, or they can be retrieved from our Transactions API.
  2. Cross Reference Button Orders with OMS Orders - Compare orders in the Button extract with orders in your OMS. Orders present in Button but missing from your OMS should be invalidated.
  3. Write Invalidations to New Batch File - Following the conventions outlined here in the resources, write all order invalidations to the new batch file. Refer to the below example.

If the order was fraudulent, we would expect the order to show up with an invalidate action. The example rows are as follows.

DATE_UPDATED,ORDER_ID,PRODUCT_REVENUE,CURRENCY,PRODUCT_SKU,PRODUCT_DESCRIPTION,PRODUCT_QTY,ACTION
2018-09-01T00:00:00Z,1112224788,,,,,,invalidate

Upload New Batch File to SFTP Site

  1. Upload New Batch File to the SFTP Site - place the newly-generated CSV batch file in the /uploads directory on uploads.usebutton.com. Your password is your API key. This is a sensitive key, which can be obtained on the Button Dashboard Developer Page.

Other Configurations

The following subsections - along with the section completed above implementing post-install deeplinking - will enable you for Button's mobile web Publishers.

Configure Button Links

In the Button Dashboard, navigate to "Merchant" > "Apps" & click on the App you want to configure a Button Links domain for. Once on the App details page, click on the "Add a Button Links Domain" button in the "Button Links Domains" section. Simply fill out the details in the popup modal to complete the configuration.

Configure Universal Links

To support App Links for the Button domain (to stop any browser redirecting) you need to add intent filters for the http and https scheme for the Button subdomain (yourdomain.bttn.io) you registered. If you already registered an intent filter for your domain, you can simply add another to the same activity declaration.

We support verified web associated App Links so make sure to add the autoVerify="true" attribute to your intent filter. Note: this support is part of Android Marshmallow (6.0), so you'll also need to build against this target ButtonKit level.

<activity name=".MainActivity">
            <intent-filter android:autoVerify="true">
                <action android:name="android.intent.action.VIEW"/>
                <data android:scheme="https"/>
                <data android:host="yourdomain.bttn.io"/>
                <data android:pathPattern=".*"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>
            </intent-filter>
...
</activity>

Button hosts the Digital Asset Links JSON file for your bttn.io subdomain. You can add your package name and sha256 certificate fingerprints to your app configuration in the Button dashboard.

Web Links

Use the following command to generate the fingerprint via the Java keytool:

keytool -list -printcert -jarfile  <APK_FILE>  | grep SHA256

Now, your link should open your app without ever opening your browser when the app is installed. Note: by supporting web associated app links you will prevent the Intent Chooser when opening the URL and your app will open automatically.


Test Your Integration

You can test the mParticle side of the integration by performing the following actions in development mode, and following along in the mParticle live stream. You should see the following as both inbound and outbound data to Button, for each mParticle workspace connection:

  • Application Install
  • Application open from deep link. You can verify that the mParticle SDK automatically collects the btn_ref within each Application State Transition message, specifically within the “launch referrer” property.
  • eCommerce Purchases

To test the full Button integration, download our Partner test app from the Play Store. This app allows you to mimic a Publisher so you may test the Button flow. Login with your Button Dashboard credentials and you will see any Buttons you have associated with your account. After completing a purchase through the Button flow, you can verify it went through Button here in the Dashboard.

Note: If you do not see any Buttons after logging into the Partner test app, reach out to your Button point of contact and they will populate this for you.