Integrate the Fraud Detection SDK for Android

Updated at:

This topic describes the integration process of the Device Fraud Detection SDK (Android).

Usage notes

The Device Fraud Detection SDK runs on Android 4.4 and later (minSdkVersion 19 or later).

The Android SDK has the following limits:

  • Only mobile smart devices (phones or tablets) running Android 4.4 or later are supported.

  • The arm, armv7, and arm64 architectures are currently supported.

Prerequisites

  • To fulfill the privacy compliance obligations of integrating third-party SDKs and reduce privacy violation risks, use the latest version of the product published on the Alibaba Cloud Documentation Center. Before using Device Fraud Detection, understand the personal information processing regulations and the Fraud Detection SDK Privacy Policy, and integrate according to the SDK compliance guidelines.

Permissions

The SDK requires the following permissions to enhance fraud detection:

Permission

Required

Description

android.permission.INTERNET

Yes

Allows the SDK to access the internet.

android.permission.ACCESS_NETWORK_STATE

Yes

Used to obtain the device network status.

android.permission.READ_PHONE_STATE

No (recommended)

These permissions must be requested dynamically at runtime on Android 6.0 and later. After you enable these permissions, ensure that your app has been granted them before integrating the SDK and calling the initWithOptions initialization method.

android.permission.WRITE_EXTERNAL_STORAGE

No (recommended)

android.permission.READ_EXTERNAL_STORAGE

No (recommended)

Dependency configuration

  • Download the Android SDK and extract it. The SDK is distributed as a standard Android .aar package.

  • A single-architecture .so file is approximately 2.5 MB.

  • The Device Fraud Detection SDK has strong built-in code protection and data encryption mechanisms, so the package size is relatively large.

  • Copy the extracted .aar file to the libs directory of your project and add the following dependency to the build.gradle file of your app:

// Device Fraud Detection SDK
implementation files('libs/Android-AliyunDevice-<version>.aar')

Interface obfuscation configuration (important)

If your project uses code obfuscation, add the following rules to the proguard-rules.pro file of your app to prevent interfaces from being obfuscated and causing abnormal functionality.

-keep class net.security.device.api.** {*;}
-dontwarn net.security.device.api.**

Call the SDK

After completing the preceding configurations, complete client-side integration in the following four steps:

  • AndroidManifest.xml configuration (optional)

  • Initialize (initWithOptions)

  • Obtain the client token (getDeviceToken)

  • Send the token to your business server

1. AndroidManifest.xml configuration (optional)

<!--
    Optional enhancement: adding an AppZygote process and a service can improve fraud detection capabilities.
    1. Add the android:zygotePreloadName attribute to the existing <application> tag.
    2. Add a <service> declaration inside the <application> tag.
-->
<application android:zygotePreloadName="net.security.device.api.compat.CompatPreloader"
  <service
    android:name="net.security.device.api.compat.CompatBridgeService"
    android:exported="false"
    android:isolatedProcess="true"
    android:useAppZygote="true" />
</application>

2. Initialize (initWithOptions)

This method completes SDK initialization and information collection. When performing Fraud Detection, call it as early as possible while meeting compliance requirements. You need to call it only once per app launch.

  • Function prototype

public interface SecurityInitListener {
  // code indicates the API call status code
  void onInitFinish(int code);
}
public void initWithOptions(Context ctx, String appKey,
                            Map<String, String> options,
                            SecurityInitListener securityInitListener);
  • Parameters

    • ctx: The current Application Context or Activity Context.

    • appKey: Used to identify the user. You can apply for it in Device App Management of the Alibaba Cloud console.

    • options: Optional information collection settings. Defaults to null. The available options are as follows.

      Field

      Description

      Example

      IPv6

      Whether to use an IPv6 domain to report device information. 0 (default): uses an IPv4 domain. 1: uses an IPv6 domain.

      "0"

      CustomUrl

      Sets the domain name of the data reporting server. Used when reporting to a specific site. No configuration is required by default.

      "https://cloudauth-device.aliyuncs.com"

      CustomHost

      Sets the host of the data reporting server. Must be used together with CustomUrl. Neither CustomHost nor CustomUrl needs to be set by default.

      "cloudauth-device.aliyuncs.com"

      DataType

      Sets the types of device data not to collect. Empty by default (recommended), which collects all data. The configurable values are listed in the following table.

      Single selection: NO_UNIQUE_DEVICE_DATA Multiple selection: NO_UNIQUE_DEVICE_DATA | NO_IDENTIFY_DEVICE_DATA

      DataType parameter description

      Type of data collected

      Description

      Device information field details

      NO_UNIQUE_DEVICE_DATA

      Resettable unique device identifiers

      Includes: Open Anonymous Device Identifier (OAID), Google Advertising ID, Android ID.

      NO_IDENTIFY_DEVICE_DATA

      Non-resettable unique device identifiers

      Includes: International Mobile Equipment Identity (IMEI), International Mobile Subscriber Identity (IMSI), SimSerial, BuildSerial (SN), MAC address.

      NO_BASIC_DEVICE_DATA

      Basic device information

      Includes: OS version, device model, screen resolution.

      NO_EXTRA_DEVICE_DATA

      Device extended information

      Includes: black/gray market app list, local area network (LAN) IP, DNS IP, connected Wi-Fi information (SSID, BSSID), nearby Wi-Fi list, and location (to detect virtual location).

      CustomUrl and CustomHost parameter description

      To report to a specific site, set CustomUrl and CustomHost to the corresponding region. No configuration is required by default.

      Region

      Address

      China (default)

      CustomUrl: https://cloudauth-device.aliyuncs.com
      CustomHost: cloudauth-device.aliyuncs.com

  • Example

public class CustomApplication extends Application {
  // Created in the Alibaba Cloud Fraud Detection console under Developer Center > Device App Management
  private static String appKey = "<Obtain after creating an application in the console>";

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

    Map<String, String> options = new HashMap<>();
    // Privacy collection switch: no configuration is required by default. To disable a scope on the client, combine multiple options with | then convert to a string.
    // If you want to disable only a specific field instead of a DataType scope, you can also contact us to disable it through server-side delivery.
    // options.put("DataType",  String.valueOf(NO_UNIQUE_DEVICE_DATA | NO_IDENTIFY_DEVICE_DATA));
    // Set a custom data reporting region (not required by default; used only when a specific site is needed)
    // options.put("CustomUrl", "https://cloudauth-device.aliyuncs.com");
    // options.put("CustomHost", "cloudauth-device.aliyuncs.com");

    // Method 1: Standard call (recommended when the initialization result is not concerned)
    SecurityDevice.getInstance().initWithOptions(this, appKey, options, null);

    // Method 2: Callback call (used when the initialization result needs to be monitored)
    SecurityDevice.getInstance().initWithOptions(this, appKey, options, new SecurityInitListener() {
      @Override
      public void onInitFinish(int code) {
        if (SecurityCode.SC_SUCCESS != code) {
          Log.d("AliyunDeviceRisk", "Initialization failed. Code=" + code);
        } else {
          Log.d("AliyunDeviceRisk", "Initialization succeeded");
        }
      }
    });
  }
}

3. Obtain the client token (getDeviceToken)

Obtain the client token and report it to your business server. Then, obtain device risk information through the server-side Server-side API integration.

Important
  • Ensure that the interval between calling the initWithOptions interface and the getDeviceToken interface is at least 2 seconds.

  • When calling getDeviceToken, we recommend that you pass a bizId to bind the current token with a business-unique ID. When querying results on the server, pass the same ID to ensure that the bizId passed by the client and the ID passed by the server are consistent, so you can verify the risk of token tampering.

  • We recommend that you call the getDeviceToken interface on a non-main thread of the app to avoid crashes that may be caused by the time consumed by the interface call.

  • Function prototype

public SecurityToken getDeviceToken();
// Recommended: pass bizId to associate the business ID with the deviceToken
public SecurityToken getDeviceToken(String bizId)

  public class SecurityToken {
  // API call status code
  public int code;

  // Token string used to query results on the server side.
  public String token;
}
Important

In scenarios with good network conditions, the token string is approximately 600 bytes. In scenarios with poor network conditions, the returned length is approximately 2.5 KB and carries a special identifier:

  • China: connected network "Tkxxxx", weak network "UFxxxx";

If a large number of long tokens appear in your business:

  • First, ensure that the client network is connected.

  • Second, ensure that the interval between calling the SDK initWithOptions interface and the getDeviceToken interface is at least 2 seconds.

  • Example

// Recommended to call on a non-main thread to avoid blocking the UI and causing ANR
new Thread() {
  @Override
  public void run() {
    // Recommended: pass bizId to bind the token with the business ID.
    // Pass the same bizId when querying results on the server to verify whether the token has been tampered with or replaced.
    String bizId = "1234567890abcdef1234567890ab";
    SecurityToken deviceToken = SecurityDevice.getInstance().getDeviceToken(bizId);
    if(null != deviceToken){
      if(SecurityCode.SC_SUCCESS == deviceToken.code){
        Log.d("AliyunDevice", "token: " + deviceToken.token);
      } else {
        Log.e("AliyunDevice", "getDeviceToken error, code: " + deviceToken.code);
      }
    } else {
      Log.e("AliyunDevice", "getDeviceToken is null.");
    }
  }
}.start();

4. Send the token to your business server

After successfully obtaining the deviceToken, pass the deviceToken as a parameter to your business server. The server then calls the Alibaba Cloud Device Fraud Detection API, passes in the deviceToken, and queries and verifies device risk information.

Status return values

SecurityCode

Code

Description

SC_SUCCESS

10000

SDK initialization succeeded.

SC_NOT_INIT

10001

SDK not initialized.

SC_NOT_PERMISSION

10002

The basic Android permissions required by the SDK are not fully granted.

SC_UNKNOWN_ERROR

10003

Unknown system error.

SC_NETWORK_ERROR

10004

Network error.

SC_NETWORK_ERROR_EMPTY

10005

Network error. The returned content is an empty string.

SC_NETWORK_ERROR_INVALID

10006

The format of the network response is invalid.

SC_PARSE_SRV_CFG_ERROR

10007

Failed to parse the server configuration.

SC_NETWORK_RET_CODE_ERROR

10008

The gateway returned a failure.

SC_APPKEY_EMPTY

10009

AppKey is empty.

SC_PARAMS_ERROR

10010

Other parameter errors.

SC_FGKEY_ERROR

10011

Key calculation error.

SC_APPKEY_ERROR

10012

The SDK version does not match the AppKey version.

Complete code example

import net.security.device.api.SecurityDevice;
import net.security.device.api.SecurityInitListener;
import net.security.device.api.SecurityToken;
import net.security.device.api.SecurityCode;
import static net.security.device.api.SecurityDevice.NO_UNIQUE_DEVICE_DATA;
import static net.security.device.api.SecurityDevice.NO_IDENTIFY_DEVICE_DATA;

public class MainActivity extends AppCompatActivity {
  // Created in the Alibaba Cloud Fraud Detection console under Developer Center > Device App Management
  private static final String APP_KEY = "<Obtain after creating an application in the console>";

  // Minimum interval between initWithOptions and getDeviceToken: 2 seconds for the China site and 3 seconds for international sites
  private static final long INIT_TO_TOKEN_INTERVAL_MS = 2000L;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Choose one: doInitWithSleep() or doInitWithCallback()
    doInitWithSleep();
    // doInitWithCallback();
  }

  // ==================== Method 1: Ensure the time difference ====================
  // Simple and direct. Used when the initialization result is not concerned.
  private void doInitWithSleep() {
    doInit(null);

    new Thread(() -> {
      try {
        // Simulate waiting here to ensure that initialization is complete. If you obtain the deviceToken before initialization is complete, a downgraded deviceToken is returned.
        Thread.sleep(INIT_TO_TOKEN_INTERVAL_MS);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      // Obtain the deviceToken
      doGetToken();
    }).start();
  }

  // ==================== Method 2: Initialization callback ====================
  // Used when the initialization result needs to be monitored. The onInitFinish callback is triggered after the first-stage initialization,
  private void doInitWithCallback() {
    doInit(code -> {
      if (SecurityCode.SC_SUCCESS != code) {
        Log.e("AliyunDevice", "Initialization failed, code: " + code);
        return;
      }
      // After initialization is complete, you can immediately call getDeviceToken
      doGetToken();
    });
  }

  /** Initialize the SDK (asynchronous; call it only once during the app lifecycle; we recommend that you call it in Application.onCreate()) */
  private void doInit(SecurityInitListener listener) {
    Map<String, String> options = new HashMap<>();
    // Privacy collection switch: no configuration is required by default. To disable a scope on the client, combine multiple options with | then convert to a string.
    // If you want to disable only a specific field instead of a DataType scope, you can also contact us to disable it through server-side delivery.
    // options.put("DataType",  String.valueOf(NO_UNIQUE_DEVICE_DATA | NO_IDENTIFY_DEVICE_DATA));
    SecurityDevice.getInstance().initWithOptions(this, APP_KEY, options, listener);
  }

  /** Obtain the DeviceToken. We recommend that you call it on a non-main thread */
  private void doGetToken() {
    // bizId binds the token with the business ID. Pass the same bizId when querying results on the server to verify anti-tampering.
    // Use a real business transaction ID in the production environment. Do not hardcode it.
    String bizId = "1234567890abcdef1234567890ab";
    SecurityToken deviceToken = SecurityDevice.getInstance().getDeviceToken(bizId);
    if (null == deviceToken) {
      Log.e("AliyunDevice", "deviceToken is null");
    } else if (SecurityCode.SC_SUCCESS != deviceToken.code) {
      Log.e("AliyunDevice", "Failed to obtain the token, code: " + deviceToken.code);
    } else {
      Log.d("AliyunDevice", "Token obtained successfully, token: " + deviceToken.token);
      // Pass deviceToken.token to your business server, which then calls the Fraud Detection API
        }
    }
}

Call the Fraud Detection API

Pass the deviceToken and other parameters, and request the Fraud Detection API for detection by referring to Server-side API integration.

FAQ

For frequently asked questions about the Device Fraud Detection SDK, see FAQ.