This topic describes how to integrate the Device Fraud Detection SDK into your HarmonyOS application. By integrating the SDK, you can collect device fingerprints for use in business fraud detection scenarios.
Prerequisites
Before you begin, make sure that you have:
A development environment that supports HarmonyOS NEXT (0.0.71) or later, with a minimum API version of 12.
An Alibaba Cloud account and an application created in the Device Fraud Detection console.
To help fulfill the privacy compliance obligations related to integrating third-party SDKs in your product, reduce privacy violation risks, and achieve compliant operation of your product, ensure that you use the latest version published on the Alibaba Cloud documentation center. Before using Device Fraud Detection, carefully review the personal information processing rules and the Fraud Detection SDK Privacy Policy, and integrate the SDK following the SDK compliance guidelines.
The SDK has the following limitations:
Simulator support — Debugging in simulator mode is not supported.
Packaging method — Only the bytecode packaging method is supported.
Permissions
To enhance fraud detection accuracy, the SDK requires the following HarmonyOS permissions:
Permission | Required | Description |
| Yes | Internet access. The SDK requires an internet connection to function. |
| Yes | Network status check. The SDK provides better service based on network conditions. |
| No (recommended) | Allows the app to store persistent data. The SDK uses this to improve device fingerprint stability. |
| No (recommended) | Multi-device collaboration. The SDK detects multi-device status to enhance security. |
| No (recommended) | Access to the advertising identifier. The SDK obtains the IDFA to improve device ID stability. |
Download and configure the HarmonyOS SDK
Download the HarmonyOS SDK and extract the archive. The SDK is provided as a standard HarmonyOS
.harpackage.Copy the
.harfile to the directory in your project where.harpackages are stored. We recommend placing it in thelibsdirectory, following the HarmonyOS official documentation. Then, add the dependency management for the package version in theoh-package.json5file at the project root.Modify the
oh-package.json5file in your project and add theAliyunDevicedependency to thedependenciessection:{ "dependencies": { "aliyundevice": "file:../libs/HarmonyOS-AliyunDevice-xxx.har" } }Configure interface obfuscation. To prevent functional errors caused by interface obfuscation, check the
obfuscation.txtfile within the.harpackage and do not remove it. If the obfuscation configuration cannot be merged in certain compiler versions, add theobfuscation-rules.txtfile from the.harpackage to your main project and include the obfuscation configuration there.
Initialize the SDK
Call the initialization function as early as possible during app startup. In multi-threaded scenarios, call the initialization API on the main thread and call it only once during the application lifecycle.
Function prototype
export class SecurityInitListener {
// code indicates the API call status code
onInitFinish(code: number): void {}
}
public initWithOptions(ctx: Context,
userAppKey: string,
options: Map<string, string>,
securityInitListener: SecurityInitListener): void;Parameters
ctx: the Context of the current Ability.
userAppKey: identifies your application. You can apply for it under Device App Management in the Alibaba Cloud console.
options: optional information collection parameters. Default value is null. The following table lists the available options.
Parameter | Description | Example |
IPv6 | Specifies whether to use an IPv6 domain name to report device information. Valid values: |
|
CustomUrl | Sets the data reporting server domain name. Note For site-specific reporting, set CustomUrl and CustomHost to the designated endpoint for your region. By default, no custom configuration is needed. Chinese mainland (default): https://cloudauth-device.aliyuncs.com | "https://cloudauth-device.aliyuncs.com" |
CustomHost | Sets the data reporting server host. | "cloudauth-device.aliyuncs.com" |
securityInitListener: initialization callback interface. You can use the callback to check whether initialization succeeds. Default value is null. For valid values of the code field, see the Return codes section.
export class SecurityInitListener {
// code indicates the API call status code
onInitFinish(code: number): void {}
}Return value
None.
Example
@State USER_APP_KEY: string = "123e4567e89b12d3a45642661417****";
let options: Map<string, string> = new Map<string, string>();
options.set("IPv6", "0"); // Set to IPv4
// Set a custom data reporting endpoint
// options.set("CustomUrl", "xxx"); Set the reporting site URL
// options.set("CustomHost", "xxx"); Set the reporting site host
SecurityDevice.getInstance().initWithOptions(getContext(),
this.USER_APP_KEY, options, null);Obtain the client token
Starting from SDK version 2.0.0, getDeviceToken is a synchronous call. Legacy asynchronous code must be updated.
Obtain the client token and report it to your server. You can then use the server-side device fraud detection API to retrieve device risk information.
Ensure an interval of at least 2 seconds between calling
initWithOptionsandgetDeviceToken.We recommend that you pass in a
bizIdwhen callinggetDeviceToken. This binds the token to a unique business ID. When querying results on the server side, pass in the same ID to detect token tampering.Call
getDeviceTokenon a non-main thread to avoid potential crashes caused by long execution times.Call
initWithOptionson the main thread, and call it only once during the application lifecycle.
Function prototype
export class SecurityToken {
/**
* Result code. Refer to SecurityCode for meanings.
*/
public code:number = 0;
/**
* deviceToken returned by the SDK
*/
public token:string = "";
}
// It is recommended to pass bizId
public getDeviceToken(bizId?: string): SecurityTokenParameters
bizId: the business ID of the client. Used to associate the business ID with the token. Optional.
Return value
Returns a SecurityToken object, which contains the following fields:
code: the API call status code. Used to determine whether the call succeeded. For valid values, see the Return codes section.token: the token string. Used for subsequent queries to the Alibaba Cloud device fraud detection API.ImportantUnder good network conditions, the token string is approximately 600 bytes in length. Under poor network conditions, the returned length is approximately 2.5K, with the following special prefixes:
China site:
"Tkxxxx"for connected,"UFxxxx"for weak network.
If a large number of long tokens appear in your business, ensure the client network is stable and that the interval between
initWithOptionsandgetDeviceTokenis at least 2 seconds.
Example
// Example with bizId. bizId is the client's business ID, which is optional.
let bizId = "1234567890abcdef1234567890ab****";
let tokenObj: SecurityToken = SecurityDevice.getInstance().getDeviceToken(bizId);
if (tokenObj.code == SecurityCode.SC_SUCCESS) {
console.log("Aliyun Token: " + tokenObj.token);
} else {
console.log("Aliyun Code: " + tokenObj.code);
}Return codes
SecurityCode | Code | Description |
SC_SUCCESS | 10000 | The SDK successfully collected information. |
SC_NOT_INIT | 10001 | The SDK has not completed information collection. |
SC_NOT_PERMISSION | 10002 | The required HarmonyOS basic permissions are not fully authorized. |
SC_UNKNOWN_ERROR | 10003 | An unknown system error occurred. |
SC_NETWORK_ERROR | 10004 | A network error occurred. |
SC_NETWORK_ERROR_EMPTY | 10005 | A network error occurred. The response is empty. |
SC_NETWORK_ERROR_INVALID | 10006 | The network response format is invalid. |
SC_PARSE_SRV_CFG_ERROR | 10007 | Failed to parse the server configuration. |
SC_NETWORK_RET_CODE_ERROR | 10008 | The gateway returned an error. |
SC_APPKEY_EMPTY | 10009 | The AppKey is empty. |
SC_PARAMS_ERROR | 10010 | Other parameter error. |
SC_FGKEY_ERROR | 10011 | Key calculation error. |
SC_APPKEY_ERROR | 10012 | The SDK version and AppKey version do not match. |
Complete code example
The following example shows how to initialize the SDK and obtain a device token.
You can apply for the USER_APP_KEY under Device App Management in the Alibaba Cloud console.
import { SecurityCode, SecurityToken, SecurityDevice } from 'aliyundevice';
@Entry
@Component
struct Index {
@State message: string = 'Aliyun Device';
@State USER_APP_KEY: string = "XXX";
build() {
Row() {
Column() {
Button(this.message)
.fontSize(18)
.fontWeight(FontWeight.Bold)
.onClick((event: ClickEvent) => {
// Initialize the SDK
SecurityDevice.getInstance().initWithOptions(getContext(), this.USER_APP_KEY, null, null);
// Wait 3 seconds before getting 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);
}
}, 3000);
})
.margin({ top: 10 })
}
.width('100%')
}
.height('100%')
}
}Call the device fraud detection API
After obtaining the deviceToken, send it to your business server for verification. Refer to the API integration to build requests and call the device fraud detection API.
FAQ
For frequently asked questions about the Device Fraud Detection SDK, see the FAQ.