ReactNative

Integration Requirements 

Compliance

1.1 According to the user's information protection regulations, before your users start the App for the first time and start collecting information, your company should fully inform the user of the purpose, method, and scope of collecting, using, and sharing the user's personal information with a third party through an interactive interface or design (such as a pop-up window of the privacy policy), and obtain the express consent of the end user.

1.2 To provide business security and risk control services to your company, the TrustDecision SDK will collect, process, and use the identification information IDFA, AndroidID, OAID, MAC address, Wireless IP address, WIFI list, wireless router identification (BSSID, SSID),device type, device model, system type, geographical location(Rough location information, precise location information), login IP address and other device information of the user's device. To ensure compliance with your use of related services, the aforementioned privacy policy should cover the authorization of TrustDecision SDK to provide services and collect, process, and use relevant information. The following terms are for your reference. The specific expression can be determined by your company according to the overall framework and content of your privacy agreement:

TrustDecision SDK: For business security and risk control, our company uses the TrustDecision SDK. The SDK needs to obtain the information of your devices, such as IDFA, AndroidID, OAID, GAID,MAC address, Wireless IP address, WIFI list, wireless router identification (BSSID, SSID),device type, device model, system type, geographical location(Rough location information, precise location information), login IP address, application list, running process, network type,device software version,sensor information(light sensor, gravity sensor, magnetic field sensor, acceleration sensor, gyroscope sensor) and other related device information, for fraud risk identification.

Privacy Policy: https://www.trustdecision.com/legal/privacy-policy

Data Safety Requirements for Google Play

For every app that is uploaded to the Google Play Store, Google requires that the app's privacy and security practices are made available to all its users. For this reason, when an app (or a new version) is uploaded to the Play Store, Google requires app developers to fill out a data safety form. See Provide information for Google Play's Data safety section for more information.

If your app includes our Android SDK, then you can use the table below as a reference to fill out the data safety form:

Question in Google Play Console's data safety formResponse
Does your app collect or share any of the required user data types?Yes.
What type of data is collected?Device or other identifiers.
Is this data collected, shared, or both?Collected.
Is this data processed ephemerally?Yes.
Why is this user data collected?Fraud Prevention, Security, and Compliance.

Compliance Notice (TDBehavior)

The privacy policy of apps that integrate the TDBehavior module should be updated based on our Privacy Agreement with the following additional information:

(1) Function Description: To identify machine behavior fraud risks, the SDK needs to obtain relevant behavior information from you or your end users.

(2) Necessary Personal Information: Touch, scroll, swipe, screen edge swipe, scale behavior information; input behavior information (input type, number of times, input speed, input time); application foreground/background behavior information; browsing page names and dwell time behavior information; device orientation behavior information; gyroscope sensor behavior information; accelerometer sensor behavior information; mouse behavior information (web); keyboard behavior information (web)

(3) Other Optional Personal Information: None

Environment Requirements

PlatformSupported VersionsSupported Architectures
AndroidAndroid 5.0 and laterarmeabi-v7a, arm64-v8a, x86
iOSiOS 9.0 and laterarmv7, arm64, x86_64

Integration

Install the React Native Plugin

Run the following command in the root directory of your React Native project:

npm install --save [email protected]

React Native 0.60 and later support autolinking. You do not need to register the native module manually.

After installation, run the following commands for the iOS project:

cd ios
pod install
cd ..

Open the following workspace in Xcode:

ios/<YourApp>.xcworkspace

Do not open the .xcodeproj file directly.

Behavior Collection SDK Integration

The React Native plugin provides the start, collect, and stop bridge methods. However, the native behavior collection SDK for Android and iOS must be integrated separately by the host App.

This prevents applications that only use device fingerprinting from being forced to include the behavior collection SDK.

Android Behavior Collection Dependency

Add the following dependency to the host App's android/app/build.gradle:

dependencies {
    implementation 'com.trustdecision.android:behavior:1.5.1'
}

After changing a native dependency, rebuild and reinstall the App.

For example:

npm run android

Alternatively:

cd android
./gradlew installDebug

iOS Behavior Collection Dependency

The iOS behavior collection SDK is integrated through Swift Package Manager. It is no longer automatically included through the React Native plugin's Podspec.

Swift Package Manager Integration

  1. Open the host App workspace in Xcode:

    ios/<YourApp>.xcworkspace
    
  2. Select:

    File > Add Package Dependencies...
    
  3. Enter the repository URL:

    https://github.com/trustdecision/TDBehavior_spm
    
  4. Set Dependency Rule to:

    Exact Version
    
  5. Enter the following version:

    1.5.2
    
  6. For Add to Target, select the host App Target.

  7. Click Add Package.

Add the TDBehavior product to the host App Target. Do not add it to the Pods Project or a Pod Target.

The React Native plugin itself is still autolinked through CocoaPods.

Android Permissions

Declare the following permissions in the application Module's AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <!-- Required permissions -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

    <!--
      Add this permission if the application targets overseas markets
      and is distributed through Google Play.
    -->
    <uses-permission android:name="com.google.android.gms.permission.AD_ID"/>

    <!--
      The following permissions are optional.
      If they are not declared, some device information will not be collected,
      which may affect device fingerprinting accuracy.
    -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

    <!--
      This permission is required to obtain the installed application list
      on Android 11 and later.

      Collection of the installed application list involves compliance
      requirements. The application owner should decide whether to request
      this permission based on actual business requirements.
    -->
    <uses-permission
        android:name="android.permission.QUERY_ALL_PACKAGES"
        tools:ignore="QueryAllPackagesPermission"/>

</manifest>

Permission Descriptions

PermissionRequirementDescription
INTERNETRequiredAllows the application to access the network and communicate with the server
ACCESS_NETWORK_STATERequiredObtains the current network connection status
ACCESS_WIFI_STATERequiredObtains the current Wi-Fi connection status and WLAN hotspot information
AD_IDRequired for overseas applicationsObtains the Google Advertising ID
ACCESS_COARSE_LOCATIONOptionalObtains approximate location information
ACCESS_FINE_LOCATIONOptionalObtains precise location information
READ_PHONE_STATEOptionalObtains SIM-card-related information
QUERY_ALL_PACKAGESOptionalObtains the installed application list

Get the TrustDevice Module

It is recommended to obtain the module directly from NativeModules:

import {NativeModules} from 'react-native';

const TrustDevice = NativeModules.TrustDevice;

The plugin's default export can also be used:

import TrustDevice from 'react-native-trustdevice';

Initialize the SDK

Important Notes

  • Initialize the SDK only after the user has agreed to the privacy policy.

  • Behavior collection must also be started only after the user has agreed to the privacy policy.

  • partner, appKey, and dataCenter are required.

  • In a Debug build, debug must be set to true.

  • Before publishing a Release build, set debug to false.

Initialization Example

import {NativeModules} from 'react-native';

const TrustDevice = NativeModules.TrustDevice;

function initWithOptions() {
  const options = {
    partner: 'Enter your partnerCode',
    appKey: 'Enter your appKey',
    appName: 'Enter your appName',
    dataCenter: 'Enter your data center',
    debug: false,
  };

  if (__DEV__) {
    options.debug = true;
  }

  TrustDevice.initWithOptions(options);
}

Get blackBox

Important Notes

  • Call getBlackBox or getBlackBoxAsync after initWithOptions.

  • Do not cache blackBox in the App for an extended period.

  • Obtain blackBox from the SDK whenever it is required.

  • It is recommended to use getBlackBoxAsync for the first request.

  • After the first asynchronous request succeeds, getBlackBox can be used at the relevant business stage.

Get blackBox Asynchronously

async function getBlackBoxAsync() {
  try {
    const blackBox = await TrustDevice.getBlackBoxAsync();
    console.log('blackBox:', blackBox);
    return blackBox;
  } catch (error) {
    console.error('getBlackBoxAsync failed:', error);
    throw error;
  }
}

Get blackBox

async function getBlackBox() {
  try {
    const blackBox = await TrustDevice.getBlackBox();
    console.log('blackBox:', blackBox);
    return blackBox;
  } catch (error) {
    console.error('getBlackBox failed:', error);
    throw error;
  }
}

Business Integration Example

async function register() {
  const blackBox = await TrustDevice.getBlackBox();

  const requestBody = {
    username: 'example',
    blackBox,
  };

  // Call the registration API.
  // await requestRegister(requestBody);
}

Behavior Collection

Behavior Collection Methods

The React Native plugin provides the following methods:

async function start(): Promise<void>;

async function collect(): Promise<{
  code: number;
  payload: string;
  msg: string;
}>;

async function stop(): Promise<void>;

Method Descriptions

start

Starts behavior collection and writes the collected behavior data to the SDK's internal container.

Call this method when the user enters a business page where user behavior needs to be identified, such as:

  • Login page

  • Registration page

  • Password recovery page

  • Payment confirmation page

  • Important information modification page

await TrustDevice.start();

collect

Returns the behavior data currently collected by the SDK.

const result = await TrustDevice.collect();

Example response:

{
  code: 0,
  payload: 'Collected behavior data',
  msg: ''
}

Field descriptions:

FieldTypeDescription
codenumberResult code. 0 indicates success
payloadstringBehavior collection result. Submit this value to the business server when collection succeeds
msgstringError message returned when collection fails

stop

Stops behavior collection and clears any data that has not yet been retrieved through collect.

await TrustDevice.stop();

Call this method when the user leaves the business page or behavior collection is no longer required.

Complete Behavior Collection Flow

The standard behavior collection sequence is:

The user agrees to the privacy policy
        ↓
initWithOptions
        ↓
Enter the business page
        ↓
start
        ↓
The user performs real actions such as typing, tapping, or swiping
        ↓
collect
        ↓
Submit the payload with the business request
        ↓
Leave the business page
        ↓
stop

There must be actual user interaction between start and collect, such as typing, tapping, scrolling, or swiping.

If no behavior data is generated, collect may return error code 104.

Complete React Native Example

import React, {useEffect, useRef, useState} from 'react';
import {
  Button,
  NativeModules,
  Text,
  TextInput,
  View,
} from 'react-native';

const TrustDevice = NativeModules.TrustDevice;

const SDK_OPTIONS = {
  partner: 'Enter your partnerCode',
  appKey: 'Enter your appKey',
  appName: 'Enter your appName',
  dataCenter: 'cn',
  debug: __DEV__,
};

export default function LoginPage() {
  const [username, setUsername] = useState('');
  const [resultText, setResultText] = useState('');
  const collectingRef = useRef(false);

  useEffect(() => {
    TrustDevice.initWithOptions(SDK_OPTIONS);

    return () => {
      if (collectingRef.current) {
        TrustDevice.stop().catch(error => {
          console.error('Failed to stop behavior collection:', error);
        });
      }
    };

  }, []);


  const startBehavior = async () => {
    try {
      await TrustDevice.start();
      collectingRef.current = true;
      setResultText('Behavior collection started');
    } catch (error) {
      console.error('start failed:', error);
      setResultText(`Failed to start behavior collection: ${String(error)}`);
    }
  };

  const submitLogin = async () => {
    try {
      const blackBox = await TrustDevice.getBlackBoxAsync();
      const behaviorResult = await TrustDevice.collect();

      if (behaviorResult.code !== 0) {
        console.error(
          'collect failed:',
          behaviorResult.code,
          behaviorResult.msg,
        );

        setResultText(
          `Behavior collection failed: ${behaviorResult.code} ${
            behaviorResult.msg
          }`,
        );
        return;
      }

      const requestBody = {
        username,
        blackBox,
        behaviorPayload: behaviorResult.payload,
      };

      console.log('Login request:', requestBody);

      // Submit blackBox and behaviorPayload with the business request.
      // await requestLogin(requestBody);

      setResultText('Behavior data collected successfully');
    } catch (error) {
      console.error('Login submission failed:', error);
      setResultText(`Login processing failed: ${String(error)}`);
    }
  };

  const stopBehavior = async () => {
    try {
      await TrustDevice.stop();
      collectingRef.current = false;
      setResultText('Behavior collection stopped');
    } catch (error) {
      console.error('stop failed:', error);
      setResultText(`Failed to stop behavior collection: ${String(error)}`);
    }
  };

  return (
    <View>
      <Button
        title="Enter login flow and start collection"
        onPress={startBehavior}
      />

      <TextInput
        value=USERNAME
        onChangeText={setUsername}
        placeholder="Enter username"
      />

      <Button
        title="Log in"
        onPress={submitLogin}
      />

      <Button
        title="Stop collection"
        onPress={stopBehavior}
      />

      <Text>{resultText}</Text>
    </View>
  );
}

Behavior Collection Result Codes

CodeDescriptionRecommended Action
0SuccessUse the returned payload
100initWithOptions has not been calledInitialize the SDK before calling a behavior collection method
101The network authentication result has not yet been returnedCheck the network connection and call collect again later
102A network error occurred during authenticationCheck the network connection and retry
103The authentication API returned a non-200 status codeCheck parameters such as partner. If the problem persists, provide msg to your TrustDecision contact
104No behavior data exists in the SDK's internal containerEnsure that start has been called and that the user has typed, tapped, scrolled, or swiped before collect
109All behavior collection switches are disabledProvide the returned msg to your TrustDecision contact for investigation
110collect was called before startCall the methods in the order start → user interaction → collect

Get the SDK Version

async function getSDKVersion() {
  const version = await TrustDevice.getSDKVersion();
  console.log('SDK version:', version);
}

Android Obfuscation Configuration

If the Android project uses ProGuard or R8, add the following rule:


-keep class com.trustdecision.** { *; }

Initialization Options

OptionDescriptionPlatformExample
partnerPartner code. Contact your TrustDecision representative to obtain itAlloptions["partner"] = "your partner code"
appKeyApplication identifierAlloptions["appKey"] = "your appKey"
dataCenterData center: cn for China, sg for Singapore, us for North America, fra for Europe, and idna for IndonesiaAlloptions["dataCenter"] = "cn"
appNameApplication name. Contact your TrustDecision representative to obtain itAlloptions["appName"] = "App"
debugAnti-debugging configuration. Enable during development and disable before releaseAlloptions["debug"] = true
timeLimitNetwork request timeout in seconds. The default value is 15 secondsAlloptions["timeLimit"] = 5
locationWhether to collect location information. Enabled by defaultAlloptions["location"] = true
IDFAWhether to collect the advertising identifier. Enabled by defaultiOSoptions["IDFA"] = true
deviceNameWhether to collect the device name. Enabled by defaultiOSoptions["deviceName"] = true
runningTasksWhether to collect running task information. Enabled by defaultAndroidoptions["runningTasks"] = true
sensorWhether to collect sensor information. Enabled by defaultAndroidoptions["sensor"] = true
readPhoneWhether to collect information associated with the READ_PHONE_STATE permission. Enabled by defaultAndroidoptions["readPhone"] = true
installPackageListWhether to collect the installed application list. Enabled by defaultAndroidoptions["installPackageList"] = true

Troubleshooting

Android Reports That a Behavior Class Cannot Be Found

Confirm that the dependency has been added to the host App Module:

dependencies {
    implementation 'com.trustdecision.android:behavior:1.5.1'
}

After adding the dependency, clean and rebuild the project:

cd android
./gradlew clean
cd ..
npm run android

iOS Reports That TDBehavior Is Unavailable

Verify the following:

  1. The package has been added through Swift Package Manager:

    https://github.com/trustdecision/TDBehavior_spm
    
  2. The dependency rule is set to Exact Version 1.5.2.

  3. The TDBehavior product has been added to the host App Target.

  4. The project is opened through the .xcworkspace file.

  5. The App has been rebuilt and reinstalled after changing the dependency.