Device Risk SDK iOS Integration

更新时间:
复制 MD 格式

This topic describes how to integrate the Alibaba Cloud Device Risk SDK for iOS.

Prerequisites

Important

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 Risk Detection, carefully review the personal information processing rules and the Fraud Detection SDK Privacy Policy, and integrate the SDK following the SDK compliance guidelines.

  • iOS 9.0 or later is required.

Permissions

To improve risk detection accuracy, add the following fields and descriptions to your app's Info.plist before publishing to the App Store. Otherwise, your app may fail App Store review.

Permission

Required

Description

NSLocalNetworkUsageDescription

No (recommended)

Obtains device connectivity within the local network to detect risks such as device farms and group control.

NSLocationWhenInUseUsageDescription

No (recommended)

Obtains device location information to detect risks such as fake location spoofing.

NSUserTrackingUsageDescription

No (recommended)

Obtains IDFA information to improve device fingerprint stability.

Configure dependencies

  1. Download the iOS SDK (a standard static framework for Xcode) and generate an AppKey in the download console.

    Note
    • The single-architecture framework file is approximately 2.5 MB.

    • To ensure anti-reverse engineering capabilities and data security during network transmission, the SDK includes extensive interleaving, padding, and encryption operations, resulting in a larger file size.

  2. Copy deviceiOS.framework from the SDK package to your iOS project directory.

  3. In project settings, navigate to Build Phases -> Link Binary With Libraries, and add deviceiOS.framework along with its dependencies:

    deviceiOS.framework
    CoreTelephony.framework
    CoreLocation.framework
    Security.framework
    libresolv.tbd
    libz.tbd
    libc++.tbd
    // Add the following for the IDFA version
    AppTrackingTransparency.framework
    AdSupport.framework
  4. Based on your business requirements, choose whether to use an SDK version that collects sensitive data such as idfa. For details, see the SDK download list.

Use the SDK

Initialize the SDK

The SDK performs internal initialization and data collection. Make sure the user has agreed to the Fraud Detection SDK Privacy Policy before collecting data. Initialize the SDK as early as possible in your risk scenarios.

  • Function prototype

@interface SecurityDevice : NSObject
/**
 * Initialize the device fingerprint SDK.
 */
- (void)initDevice:(NSString *)userAppKey :(void (^)(int))initCallback;

/**
 * Initialize the SDK with options.
 */
- (void)initDevice:(NSString *)userAppKey withOptions:(NSMutableDictionary *)options callback:(void (^)(int))initCallback;

@end
  • userAppKey: Identifies the user. This is the product AppKey assigned by Alibaba Cloud (different from an AccessKey). You can obtain it from Device App Management in the Alibaba Cloud console.

  • options: Optional data collection parameters. Default: nil. Available options:

Parameter

Description

Example

IPv6

Specifies whether to use an IPv6 domain name to report device information.

  • 0 (default): Use an IPv4 domain name.

  • 1: Use an IPv6 domain name.

"1"

CustomUrl

Sets the data reporting server domain name.

"https://cloudauth-device.aliyuncs.com"

CustomHost

Sets the data reporting server host.

"cloudauth-device.aliyuncs.com"

Note

To report to a specific region, set both CustomUrl and CustomHost to the corresponding China endpoint. No configuration is needed by default.

Default service endpoints:

  • initCallback: Initialization callback listener. You can use the callback to check whether initialization succeeds. Default: nil. For valid values of the code field, see the status codes table.

  • Return value: none.

  • Example

NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
[options setValue:@"0" forKey:@"IPv6"];       // Set to IPv4
// Set a custom data reporting region
// [options setValue:@"xxx" forKey:@"CustomUrl"];  Set the reporting URL
// [options setValue:@"xxx" forKey:@"CustomHost"]; Set the reporting host

// Standard call (recommended)
[[SecurityDevice sharedInstance] initDevice:@"******" withOptions:options callback:nil];

// Callback call
[[SecurityDevice sharedInstance] initDevice:@"******" withOptions:options callback:^(int code) {
    NSString * initResult = [NSString stringWithFormat: @"Initialization result: %d", code];
    NSLog(@"%@", initResult);

    if (SC_SUCCESS != code) {
        NSLog(@"Initialization failed");
    } else {
        NSLog(@"Initialization successful");
    }
}];

Obtain the client token

Obtain the client token and report it to your business server. The server then calls the Device Risk Detection API to retrieve device risk information.

Important
  • Ensure an interval of at least 2 seconds between calling initDevice and getDeviceToken.

  • We recommend passing bizId when calling getDeviceToken to bind the token to a unique business ID. Pass the same ID when querying results on the server to verify that the token has not been tampered with.

  • Call getDeviceToken on a non-main thread to avoid potential crashes from long call durations.

  • Function prototype

@interface SecurityDevice : NSObject
- (SecurityToken *)getDeviceToken;
- (SecurityToken *)getDeviceToken:(NSString *)bizId;
@end
  • bizId: The client business ID. Used to associate a business ID with a token. Optional.

  • Return value: a SecurityToken object, defined as follows:

@interface SecurityToken : NSObject

/**
 * The session operation result.
 */
@property(atomic) int code;

/**
 * The token result string.
 */
@property(copy, atomic) NSString *token;

@end
  • code: The API call status code. Used to determine whether the call succeeded. Valid values:

    FaceSecCode

    Code

    Description

    SC_SUCCESS

    10000

    The SDK is initialized.

    SC_NOT_INIT

    10001

    The SDK is not initialized.

    SC_NOT_PERMISSION

    10002

    Required permissions are not fully granted.

    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 body is empty.

    SC_NETWORK_ERROR_INVALID

    10006

    The 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 a failure response.

    SC_APPKEY_EMPTY

    10009

    The AppKey is empty.

    SC_PARAMS_ERROR

    10010

    A parameter error occurred.

    SC_FGKEY_ERROR

    10011

    A key calculation error occurred.

    SC_APPKEY_ERROR

    10012

    The AppKey is invalid.

  • token: The token string returned to the client. Used for subsequent queries to the Alibaba Cloud Device Risk Detection API.

Important

Under good network conditions, the token string is approximately 600 bytes. Under poor network conditions, the returned length is approximately 2.5 KB, with the following special prefixes:

  • China site: connected "Tkxxxx", weak network "UFxxxx".

If a large number of long tokens appear in your business:

  • Ensure that the client network is stable.

  • Ensure an interval of at least 2 seconds between calling initDevice and getDeviceToken.

Re-obtain the token each time you need to query risk information. The token is valid for 7 days.

  • Example

// We recommend passing bizId to prevent deviceToken tampering.
NSString *bizId = @"1234567890abcdef******";
SecurityToken *deviceToken = [[SecurityDevice sharedInstance] getDeviceToken:bizId];

if (deviceToken == nil || SC_SUCCESS != deviceToken.code) {
    NSLog(@"Failed to obtain token. The result cannot be used for risk tag queries.");
} else {
    NSLog(@"Successfully obtained token. You can query risk tags. Token: %@", deviceToken.token);
}

Send the token to your server

After obtaining the deviceToken, send it to your business server for risk result queries and verification.

Complete code example

static NSString *USER_APP_KEY = @"<Obtain from the console>";

- (void)viewDidLoad {
    [super viewDidLoad];

    // Integration example
    [self doStandard];
}

- (void)doStandard {
    // Initialize the SDK.
    // Call only once during the app lifecycle.
    [self doInit];

    dispatch_async(dispatch_get_global_queue(NULL, NULL), ^{
        // This simulates the required 2-second wait. Do not add this in production.
        [NSThread sleepForTimeInterval:2.0];

        // Obtain the token.
        [self doGetToken];
    });
}


- (void)doInit {
    NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
    [options setValue:@"0" forKey:@"IPv6"];         // Set to IPv4
    // Set a custom reporting region
    // [options setValue:@"https://cloudauth-device.aliyuncs.com" forKey:@"CustomUrl"];
    // [options setValue:@"cloudauth-device.aliyuncs.com" forKey:@"CustomHost"];
    [[SecurityDevice sharedInstance] initDevice:USER_APP_KEY withOptions:options callback:nil];
}

- (void)doGetToken {
    // We recommend passing bizId to prevent deviceToken tampering.
    NSString *bizId = @"1234567890abcdef******";
    SecurityToken *deviceToken = [[SecurityDevice sharedInstance] getDeviceToken:bizId];

    if (deviceToken == nil || SC_SUCCESS != deviceToken.code) {
        NSLog(@"Failed to obtain token. The result cannot be used for risk tag queries.");
    } else {
        NSLog(@"Successfully obtained token. You can query risk tags. Token: %@", deviceToken.token);
    }
}
Important
  • To use IDFA or location information, follow Apple's privacy policy: in addition to declaring the corresponding permissions in your app's plist, you must prompt the user for authorization. Ensure your development environment uses Xcode 12 or later.

  • In scenarios that require risk detection (such as registration or promotional campaigns), obtain the client token and report it to your business server for risk queries.

Call the Fraud Detection API

Send the deviceToken along with other parameters to the Fraud Detection API. For more information, see API integration.

FAQ

For frequently asked questions about the Device Risk SDK, see FAQ.