The Device Fraud Detection SDK collects Android device fingerprints to identify device risks. This topic describes the complete integration process, from permission configuration and dependency import to initialization calls and token acquisition, and provides code examples and troubleshooting for common issues.
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:
-
Emulator debugging is not supported.
-
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 three steps:
-
Initialize (initWithOptions)
-
Obtain the client token (getDeviceToken)
-
Send the token to your business server
1. 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.
-
securityInitListener: The initialization callback. You can use the callback to check whether initialization succeeds. Default value: null. For valid values of the code field, see Status return values.
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.
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
Singapore (default)
CustomUrl: https://cloudauth-device.ap-southeast-1.aliyuncs.com
CustomHost: cloudauth-device.ap-southeast-1.aliyuncs.comChina (Hong Kong)
CustomUrl: https://cloudauth-device.cn-hongkong.aliyuncs.com
CustomHost: cloudauth-device.cn-hongkong.aliyuncs.comGermany
CustomUrl: https://cloudauth-device.eu-central-1.aliyuncs.com
CustomHost: cloudauth-device.eu-central-1.aliyuncs.comUS
CustomUrl: https://cloudauth-device.us-west-1.aliyuncs.com
CustomHost: cloudauth-device.us-west-1.aliyuncs.com -
Example
public class CustomApplication extends Application {
// Obtain this after creating an application in Device App Management of the Alibaba Cloud console
private static String appKey = "<Obtain after creating an application in the console>";
@Override
public void onCreate() {
super.onCreate();
Map<String, String> options = new HashMap<>();
options.put("IPv6", "0"); // Set to IPv4. Change to "1" to use IPv6.
// Add a privacy data collection switch. For multiple selections, use | for bitwise OR, then convert to a string.
//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 for specific sites)
// 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");
}
}
});
}
}
2. 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.
-
Ensure that the interval between calling the
initWithOptionsinterface and thegetDeviceTokeninterface is at least 3 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 threadof 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;
}
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:
-
International: connected network "U0dfTkxxxx", weak network "U0dfUFxxxx";
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
initWithOptionsinterface and thegetDeviceTokeninterface is at least 3 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.
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();
3. 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 empty. |
|
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_EXTRA_DEVICE_DATA;
public class MainActivity extends AppCompatActivity {
// Obtain this after creating an application in Device App Management of the Alibaba Cloud console
private static String appKey = "<Obtain after creating an application in the console>";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
doStandard();
}
private void doStandard() {
// Step 1: Initialize the SDK. This is an asynchronous method.
// Call only once during the entire app lifecycle. We recommend that you call it in Application.onCreate().
doInit();
// Do not call getDeviceToken synchronously right after initialization. If initialization has not finished, a downgraded deviceToken is returned.
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Step 2: Obtain the DeviceToken
// The interval between initWithOptions and getDeviceToken must be at least 2 seconds (at least 3 seconds for international sites)
// This example demonstrates calling in a child thread to avoid blocking the main thread.
new Thread() {
@Override
public void run() {
doGetToken();
}
}.start();
}
/**
* Initialize the SDK and collect device information
*/
private void doInit() {
Map<String, String> options = new HashMap<>();
options.put("IPv6", "0"); // Set to IPv4. Change to "1" to use IPv6.
// Add a privacy data collection switch. No configuration is required by default. For multiple selections, use | for bitwise OR, then convert to a string.
//options.put("DataType", String.valueOf(NO_UNIQUE_DEVICE_DATA | NO_IDENTIFY_DEVICE_DATA));
SecurityDevice.getInstance().initWithOptions(this, appKey, options, null);
}
/**
* Obtain the DeviceToken. This must be called on a non-main thread.
*/
private void doGetToken() {
// Pass bizId to bind the token with the business ID. Pass the same bizId on the server when querying results to verify anti-tampering.
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 token, code: " + deviceToken.code);
} else {
Log.d("AliyunDevice", "Token obtained successfully, token: " + deviceToken.token);
// Step 3: Pass deviceToken.token to your business server, which then calls the Fraud Detection API
}
}
}
Call the Device Fraud Detection API
Pass the deviceToken and other parameters, and request the Fraud Detection API interface for detection by referring to Server-side API integration.
FAQ
For frequently asked questions about the Device Fraud Detection SDK, see FAQ.