Integrate the Device Fraud Detection SDK into your HarmonyOS app to collect device signals and retrieve a device token for server-side fraud analysis.
Prerequisites
Before you begin, make sure you have:
HarmonyOS Next 0.0.71 or later, with a minimum API version of 12
A physical device for testing — simulator debugging is not supported
Bytecode packaging enabled — only bytecode packaging is supported
The latest SDK version downloaded from the Alibaba Cloud official website, to meet privacy compliance requirements
Before using Device Fraud Detection, read the regulations on personal information processing and the Privacy Policy of Fraud Detection SDK.
Permissions
The SDK requires the following permissions. Grant all recommended permissions to maximize detection accuracy.
| Permission | Required | Purpose | Impact if not granted |
|---|---|---|---|
| ohos.permission.INTERNET | Yes | Connect to the internet | SDK cannot report device data; token retrieval fails |
| ohos.permission.GET_NETWORK_INFO | Yes | Read network status | SDK cannot adapt to network conditions |
| ohos.permission.STORE_PERSISTENT_DATA | Recommended | Store persistent data | Reduces device fingerprint stability |
| ohos.permission.DISTRIBUTED_DATASYNC | Recommended | Enable multi-device coordination | Reduces detection accuracy in multi-device scenarios |
| ohos.permission.APP_TRACKING_CONSENT | Recommended | Read Identifiers for Advertisers (IDFAs) | Reduces device ID stability |
Install the SDK
Download the HarmonyOS SDK and extract the archive. The SDK is packaged as a standard HarmonyOS
.harfile.Copy the
.harfile to your project'slibsdirectory. In theoh-package.json5file at your project root, add the version dependency for the authentication package:
In the
oh-package.json5file for your project module, addaliyundeviceto thedependenciessection:{ "dependencies": { "aliyundevice": "file:../libs/HarmonyOS-AliyunDevice-xxx.har" } }
Obfuscation configuration
The .har package includes an obfuscation.txt file that prevents SDK APIs from being obfuscated. Do not remove this file — removing it causes functional failures.
API reference
The SDK provides two core methods: initWithOptions for initialization and getDeviceToken for token retrieval.
Initialize the SDK
Call initWithOptions as early as possible when your app starts — ideally in your entry Ability. Call it once per app lifecycle, on the main thread.
Function signature
export class SecurityInitListener {
// code: status code of the initialization result
onInitFinish(code: number): void {}
}
public initWithOptions(ctx: Context,
userAppKey: string,
options: Map<string, string>,
securityInitListener: SecurityInitListener): void;Parameters
| Parameter | Description |
|---|---|
ctx | Context of the current Ability |
userAppKey | App identifier obtained from Device App Management in the Alibaba Cloud console |
options | Optional initialization parameters (default: null). See the table below. |
securityInitListener | Callback that receives the initialization status code. See Status codes. |
Optional parameters (`options`)
| Field | Description | Example |
|---|---|---|
IPv6 | Domain name protocol for reporting. 0 (default): IPv4. 1: IPv6. | "1" |
Return value: None.
Get the device token
Call getDeviceToken to retrieve the device token, then submit it to your server for fraud analysis.
Function signature
export class SecurityToken {
/**
* Status code — see SecurityCode for meanings
*/
public code: number = 0;
/**
* Device token returned by the SDK
*/
public token: string = "";
}
public getDeviceToken(): SecurityTokenReturn value
Returns a SecurityToken object with the following fields:
| Field | Description |
|---|---|
code | Status code indicating whether the call succeeded. See Status codes. |
token | Device token string to submit to your server for fraud analysis queries |
Token length: approximately 1 KB on a good network connection, approximately 2 KB on a poor connection.
Follow these constraints when calling getDeviceToken: 1. Wait at least 2 seconds after calling initWithOptions before calling getDeviceToken, to allow data reporting to complete. 2. Starting from SDK version 2.0.0, getDeviceToken is a synchronous call. Update any asynchronous code from earlier versions.
Status codes
| SecurityCode | Code | Description |
|---|---|---|
| SC_SUCCESS | 10000 | Data collection successful |
| SC_NOT_INIT | 10001 | Data collection failed |
| SC_NOT_PERMISSION | 10002 | One or more required HarmonyOS permissions are not granted |
| SC_UNKNOWN_ERROR | 10003 | Unknown system error |
| SC_NETWORK_ERROR | 10004 | Network error |
| SC_NETWORK_ERROR_EMPTY | 10005 | Network error — return value is an empty string |
| SC_NETWORK_ERROR_INVALID | 10006 | Response format is invalid |
| SC_PARSE_SRV_CFG_ERROR | 10007 | Failed to parse server settings |
| SC_NETWORK_RET_CODE_ERROR | 10008 | Gateway returned an error |
| SC_APPKEY_EMPTY | 10009 | The appKey parameter is empty |
| SC_PARAMS_ERROR | 10010 | Other parameter error |
| SC_FGKEY_ERROR | 10011 | Failed to calculate the key |
| SC_APPKEY_ERROR | 10012 | SDK version does not match the appKey version |
Sample code
The following example shows a complete integration. ALIYUN_APPKEY is the app identifier — get it from Device App Management in the Alibaba Cloud console.
All calls use SecurityDevice.getInstance() as the single entry point.
import { SecurityCode, SecurityToken, SecurityDevice } from 'aliyundevice';
@Entry
@Component
struct Index {
@State message: string = 'Aliyun Device';
@State ALIYUN_APPKEY: string = "<your-appkey>";
build() {
Row() {
Column() {
Button(this.message)
.fontSize(18)
.fontWeight(FontWeight.Bold)
.onClick((event: ClickEvent) => {
// Initialize the SDK on app start, once per lifecycle
SecurityDevice.getInstance().initWithOptions(getContext(), this.ALIYUN_APPKEY, null, null);
// Wait at least 2 seconds before retrieving the token
setTimeout(() => {
let tokenObj: SecurityToken = SecurityDevice.getInstance().getDeviceToken();
if (tokenObj.code == SecurityCode.SC_SUCCESS) {
console.log("Aliyun Token: " + tokenObj.token);
} else {
console.log("Aliyun Code: " + tokenObj.code);
}
}, 2000);
})
.margin({ top: 10 })
}
.width('100%')
}
.height('100%')
}
}Replace <your-appkey> with your actual app key from the console.
In business scenarios that require fraud detection — such as account registration, login, and promotional activities — retrieve the device token and submit it to your server before calling the Fraud Detection API.
What's next
Use the device token to call the Fraud Detection API. The following references describe the request parameters and response fields for each scenario: