Token Management on
Android

Token Management

This guide walks you through how to add Button to your Android application. In this guide, we'll:

  1. Add the Button Merchant Library
  2. Attribute Users from Incoming Deeplinks
  3. Pass the Button Attribution Token to your Checkout API (Server)
  4. Configure Button Links

Add the Button Merchant Library

Add the Button Merchant Library to your build.gradle file in the dependencies.

implementation 'com.usebutton.merchant:button-merchant:1+'

In your launch activity class file, import the Button Merchant Library at the top of your activity and start it within the onCreate() method. This should be called when your application class is created.

import com.usebutton.sdk.ButtonMerchant

class MyApplication : Application() {
  override fun onCreate() {
    super.onCreate()

    // Replace app-xxxxxxxxxxxxxxxx with your App ID from the Button Dashboard https://app.usebutton.com
    ButtonMerchant.configure(this, "app-xxxxxxxxxxxxxxxx")
  }
}
import com.usebutton.sdk.ButtonMerchant;

public class MyApplication extends Application {
  @Override
  public void onCreate() {
      super.onCreate();

      // Replace app-xxxxxxxxxxxxxxxx with your App ID from the Button Dashboard https://app.usebutton.com
      ButtonMerchant.configure(context, "app-xxxxxxxxxxxxxxxx");
  }
}

Note: The Button Merchant Library is disabled by default. No user activity is reported and no data is collected until configured with an application id. Initialization can be deferred by simply not calling this method until ready to do so.

In the Activity onCreate() method for whichever activity is started on first launch, handle any post-install deeplinks.

import com.usebutton.sdk.ButtonMerchant

class MainActivity : Activity() {
  override fun onCreate() {
    super.onCreate()

    ButtonMerchant.handlePostInstallIntent(this) { intent, t ->
            if (intent != null) {
                startActivity(intent)
            } else if (t != null) {
                Log.e(TAG, "Error checking post install intent", t)
            }
        }
    })

  }
}

import com.usebutton.sdk.ButtonMerchant;

public class MainActivity extends Activity {
  @Override
  public void onCreate() {
      super.onCreate();

      ButtonMerchant.handlePostInstallIntent(this, new PostInstallIntentListener() {
          @Override
          public void onComplete(@Nullable Intent intent, @Nullable Throwable t) {
              if (intent != null) {
                  startActivity(intent);
              } else if (t != null) {
                  Log.e(TAG, "Error checking post install intent", t);
              }
          }
      });
  }
}

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.

This is achieved using a single call in the Merchant library — the Merchant library will ensure that this network call is only performed when it is possible to have a response (e.g. after first open) so you can safely call it as much as is needed.

The Merchant library will automatically store the attribution from the received URL, so there’s no need to pass it back to trackIncomingURL, but you will need to route the user to the url that is returned, if present.

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 *; }

Attribute Users from Incoming Deeplinks

Whenever a user deep links into your app, the incoming URL should be passed to the Merchant library so that the library can extract and store the token. This method should be called from the onCreate() method in your launch activity or whatever activity handles the deep link. For example, if you use Verified App to directly open the product activity, trackIncomingIntent(context, intent) should be called from ProductActivity.onCreate().

Incoming URLs are reported and attributed by calling the trackIncomingIntent method.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // Handle custom scheme deep links and App Links
    ButtonMerchant.trackIncomingIntent(this, intent)
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Handle custom scheme deep links and App Links
    ButtonMerchant.trackIncomingIntent(this, getIntent());

Pass the Button Attribution Token to your Checkout API (Server)

When an order has been placed in your app, and just before the request to your own Checkout API (server) is made, fetch the Button Attribution token via the Button Merchant Library.

// Obtain Attribution Token
val btnRef = ButtonMerchant.getAttributionToken(context)
// Obtain Attribution Token
final String btnRef = ButtonMerchant.getAttributionToken(context);

  • It is a case-sensitive ASCII-encoded string
  • It is under 256 bytes
  • It is an uninterpretable random value, corresponding to the impression which drove the most recent app or mobile website visit (do not attempt to parse or interpret its contents)
  • Although most attribution tokens include the string prefix srctok-, this prefix is not guaranteed to exist; do not test for or rely on this

Then execute a call to your Checkout API just like you currently do, adding the Button Attribution Token retrieved to the request payload along with the order details:

val url = URL("https://api.yourcompany.com")
val urlConnection = url.openConnection() as HttpURLConnection
urlConnection.doOutput = true

val json = JSONObject()
json.put("btn_ref", btnRef)
json.put("price", 34.90)
json.put("location", "New York")

val out = BufferedOutputStream(urlConnection.getOutputStream())
writeStream(out, json)
URL url = new URL("https://api.yourcompany.com");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);

JSONObject json = new JSONObject();
json.put("btn_ref", btnRef);
json.put("price", 34.90);
json.put("location", "New York");

OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
writeStream(out, json);

Configure Button Links

This section ensures you can support Button's mobile web Publishers.

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.

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 Button Merchant Library 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.