All Products
Search
Document Center

Fraud Detection:Device Fraud Detection SDK for HarmonyOS

Last Updated:Mar 31, 2026

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.

PermissionRequiredPurposeImpact if not granted
ohos.permission.INTERNETYesConnect to the internetSDK cannot report device data; token retrieval fails
ohos.permission.GET_NETWORK_INFOYesRead network statusSDK cannot adapt to network conditions
ohos.permission.STORE_PERSISTENT_DATARecommendedStore persistent dataReduces device fingerprint stability
ohos.permission.DISTRIBUTED_DATASYNCRecommendedEnable multi-device coordinationReduces detection accuracy in multi-device scenarios
ohos.permission.APP_TRACKING_CONSENTRecommendedRead Identifiers for Advertisers (IDFAs)Reduces device ID stability

Install the SDK

  1. Download the HarmonyOS SDK and extract the archive. The SDK is packaged as a standard HarmonyOS .har file.

  2. Copy the .har file to your project's libs directory. In the oh-package.json5 file at your project root, add the version dependency for the authentication package:

    image.png

  3. In the oh-package.json5 file for your project module, add aliyundevice to the dependencies section:

    {
      "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

ParameterDescription
ctxContext of the current Ability
userAppKeyApp identifier obtained from Device App Management in the Alibaba Cloud console
optionsOptional initialization parameters (default: null). See the table below.
securityInitListenerCallback that receives the initialization status code. See Status codes.

Optional parameters (`options`)

FieldDescriptionExample
IPv6Domain 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(): SecurityToken

Return value

Returns a SecurityToken object with the following fields:

FieldDescription
codeStatus code indicating whether the call succeeded. See Status codes.
tokenDevice 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.

Important

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

SecurityCodeCodeDescription
SC_SUCCESS10000Data collection successful
SC_NOT_INIT10001Data collection failed
SC_NOT_PERMISSION10002One or more required HarmonyOS permissions are not granted
SC_UNKNOWN_ERROR10003Unknown system error
SC_NETWORK_ERROR10004Network error
SC_NETWORK_ERROR_EMPTY10005Network error — return value is an empty string
SC_NETWORK_ERROR_INVALID10006Response format is invalid
SC_PARSE_SRV_CFG_ERROR10007Failed to parse server settings
SC_NETWORK_RET_CODE_ERROR10008Gateway returned an error
SC_APPKEY_EMPTY10009The appKey parameter is empty
SC_PARAMS_ERROR10010Other parameter error
SC_FGKEY_ERROR10011Failed to calculate the key
SC_APPKEY_ERROR10012SDK 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: