Harmony integration

Updated at:

The Financial-grade Real Person Authentication service offers a Harmony client SDK for implementing the face verification feature in your app. This document guides you through integrating the SDK and includes sample code.

Limitations

  • The face verification app must run on Harmony Next 4.1 or later.

  • Debugging in emulator mode is not supported.

  • We recommend integrating this SDK on mobile phones. It is not optimized for tablets and may have compatibility issues.

Permissions

The Harmony SDK requires the following permissions:

Permission

Required

Description

ohos.permission.INTERNET

Yes

Allows the app to connect to the internet. The SDK requires a network connection to function.

ohos.permission.GET_NETWORK_INFO

No

Allows the app to check the network status. The SDK uses this information to improve performance.

ohos.permission.CAMERA

Yes

Allows access to the camera for face verification.

Dependency configuration

Method 1: Dependency through the OpenHarmony package repository (Recommended)

Pull published HAR packages directly from the OpenHarmony package repository. This method eliminates local artifact management and requires only version number changes for upgrades.

  1. In the entry/oh-package.json5 file, declare the directly referenced modules in the dependencies node:

    {
      "name": "entry",
      "version": "1.0.0",
      "dependencies": {
        "@antdigital/authbase": "2.3.50-26062401",
        "@antdigital/aliyunfacade": "2.3.50-26062401"
      }
    }
    Note
    • You only need to explicitly declare modules that are directly imported in your source code. For example, @antdigital/aliyunfacade automatically brings in livenessverify and ocrverify as transitive dependencies, so you do not need to list them here.

    • The oh-package.json5 file in the root directory does not require the overrides field.

  2. Run the following command to complete the installation:

    ohpm install

Method 2: Local HAR integration

  1. Download and unzip the Harmony SDK.

    The SDK is a Harmony har package.

  2. Place the SDK build artifacts in the libs/ folder under the project root directory. The directory structure example is as follows:

    libs/
    ├── authbase.har
    ├── livenessverify.har
    ├── ocrverify.har
    └── aliyunfacade.har
  3. In the root directory oh-package.json5 file, add the overrides field to force dependency resolution to local HAR packages:

    {
      "modelVersion": "5.0.0",
      "name": "facedemo",
      "version": "1.0.0",
      "dependencies": {},
      "devDependencies": {
        "@ohos/hypium": "1.0.11"
      },
      "overrides": {
        "@antdigital/authbase": "file:./libs/authbase.har",
        "@antdigital/livenessverify": "file:./libs/livenessverify.har",
        "@antdigital/ocrverify": "file:./libs/ocrverify.har",
        "@antdigital/aliyunfacade": "file:./libs/aliyunfacade.har"
      }
    }
  4. In entry/oh-package.json5, declare the dependencies. You can keep the remote version number string (the system will prioritize the overrides rule to pull from local), or directly use file: relative paths.

  5. Run the following command to complete the installation:

    ohpm install

API reference

The Harmony SDK includes three core APIs: initialization (init and initIPv6), getting meta information (getMetaInfos), and starting verification (verify).

Initialize the SDK

  • Call this API to initialize the SDK. You must delay initialization until after the user agrees to the Privacy Policy and just before starting the face recognition process.

  • Function prototype:

    public init(context: Context, params?: HashMap<string, string>): number
    public initIPv6(context: Context, params?: HashMap<string, string>): number
    Note

    Use init for IPv4 networks and initIPv6 for IPv6 networks.

  • Parameters:

    Parameter

    Type

    Description

    context

    Context

    The Context of the current Ability.

    params

    HashMap<string, string>

    Custom parameters. This is optional.

  • Returns a Number. A value of 0 indicates successful initialization.

Get metainfos

  • Gets the device's environment information (MetaInfos), which is required for risk assessment during face detection.

    • You must get the MetaInfos for each verification attempt.

    • After obtaining the MetaInfos on the client, send it as a string to your server. Your server must then pass this string as a parameter when calling the InitFaceVerify API.

  • Function prototype:

    public static getMetaInfos(context: Context, params?: HashMap<string, string>): string
  • Parameters:

    Parameter

    Type

    Description

    context

    Context

    The Context of the current Ability.

    params

    HashMap<string, string>

    Custom parameters. This is optional.

  • Returns a JSON String containing the mobile device's environment and SDK information.

    {
     "deviceType": "harmony",
     "osVersion": "2",
     "osFullName": "2.1.6.1(Beta1)",
     "deviceModel": "NOH-AN00",
     "appName": "com.dtf.faceverify",
     "appVersion": "1.0.0",
     "nfcSupport": "N",
     "bioMetaInfo": "7.1.2:393216,0",
     "apdidToken": "",
     "sdkVersion": "1.1.0",
     "securityVersion": "",
     "zimVer": "",
     "voiceSdkVersion": ""
    }

Start authentication

  • Call this API to start the real person authentication process.

  • Function prototype:

    public static verify(context: UIContext | Context, certifyID: string, callBack: ZimCallBack, params?: HashMap<string, string>): void
  • Parameters:

    Parameter

    Type

    Description

    context

    UIContext or Context

    The UIContext or Context of the current Ability.

    Important

    We recommend passing UIContext to prevent potential Harmony compatibility issues.

    certifyID

    String

    The certification ID. You can get this parameter by calling the server-side InitFaceVerify API.

    callBack

    ZimCallBack

    The callback for the verification result, defined as follows:

    export interface ZimCallBack {
      onComplete: (response: ZimResponse) => void;
      encrypt: (content: string) => string;
    }

    For the definition of the ZimResponse class, see Verification results and error codes.

    params

    HashMap<string, string> 

    Custom parameters. For a list of valid keys and values, see Table 2. params values.

    Table 1. ZimCallBack callback description

    Method

    Description

    Example value

    onComplete

    SDK verification result callback.

    See the ZimResponse class definition.

    Table 2. params values

    Value

    Description

    Example value

    ext_params_key_use_message_box

    Controls whether the SDK's built-in dialog box is used to display face verification errors.

    • true: The SDK displays a dialog box with a message and then returns the error code after the user clicks OK.

    • false: The SDK directly returns the error code without displaying a dialog box. The app decides how to display the message.

    true

    ext_params_key_open_full_screen

    Specifies whether to enable full-screen display after the SDK starts authentication. By default, the SDK enables full-screen display to ensure proper rendering. This setting takes effect only once.

    • true: Enables full-screen display.

    • false: Disables full-screen display.

    true

    ext_params_key_use_video

    Specifies whether to return the liveness detection video. Valid values:

    • true: You can get the video path from response.videoPath or by calling the server-side query API.

    • false: Does not return the liveness detection video (default).

    true or false

    ext_params_key_hsp_module_name

    Use this parameter to pass the Multi-HAP's Module Name to the SDK. This is required when the real person authentication module is in a Multi-HAP and the HSP does not have a dependency on it.

    Note

    The default value is empty.

    alidemoshared

    ext_params_key_force_use_portrait

    Specifies whether to force portrait mode. Valid values:

    • true (default): Forces authentication to start in portrait mode.

    • false: Follows the app's orientation without adjustment.

    true

    ext_params_key_wave_animate_close

    Specifies whether to enable the ripple loading animation. Valid values:

    • true: Disables the ripple loading animation and uses the original loading animation.

    • false (default): Enables the ripple loading animation.

    true

    ext_params_key_face_circle_size

    Specifies the size of the face detection viewfinder frame. Valid values:

    • S: Small preview circle.

    • M (default): Medium preview circle.

    • L: Large preview circle.

    M

  • Return value: None.

Verification results and error codes

The verify API returns the verification result in a ZimResponse object, which is defined as follows:

/*
 * Result response
 */
export class ZimResponse {
 /**
 * Main result code
 */
 public code: string;

 /**
 * Sub-result code
 */
 public subCode: string;

 /**
 * Error reason
 */
 public msg: string;

 /**
 * Video evidence path
 */
 public videoPath: string;
}

Error code

Billed

Error message

Description

1000

Yes

Face verification successful

The user completed the face verification process. The recommended authentication result is 'pass'.

This result is for reference only. Call the server-side DescribeFaceVerify API to get the final authentication result.

1001

No

System error

A system error occurred.

1003

No

Verification interrupted

The verification process was interrupted.

2002

No

Network error

A network error occurred.

2003

No

Client-side device time error

The time on the client-side device is incorrect.

2006

Yes (billed only for failed authentications)

Failed to submit authentication data, or face verification failed.

This result is for reference only. Call the server-side DescribeFaceVerify API to get the final authentication result and the specific reason for the failure.

For more information about subCode error codes, see Client-side error codes for financial-grade services - Harmony.

API obfuscation configuration

To avoid functional issues caused by API obfuscation, review the configuration in the har package's obfuscation.txt file. Do not remove this file. Also, add the following configuration to the obfuscation-rules.txt file in your application's main project:

ctx
userAppKey
options
securityInitListener
initRaw
getSessionRaw
getSessionIdRaw
setInitStatusRaw
getInitStatusRaw
setOptionsRaw

Sample code

import { ZimConstant, ZimFacade, ZimResponse } from '@alipay/aliyunfacade';
import { HashMap } from '@kit.ArkTS';
import { JSONUtil, StringUtil } from '@alipay/authbase';

@Entry
@Component
struct Index {
  @State message: string = 'Start authentication';
  @State certifyID: string = ''

  build() {
    Row() {
      Column() {
        // The certifyID is obtained from the return value of the InitFaceVerify API on the server. You must pass MetaInfo to the server each time you obtain it.
        // Note: Each certifyID is valid for only 30 minutes.
        TextInput({ placeholder: 'Enter certifyID', text: this.certifyID })
          .onChange((value: string) => {
            this.certifyID = value;
          })
          .margin({ left: 20, right: 20 })
        Button(this.message)
          .fontSize(18)
          .fontWeight(FontWeight.Bold)
          .onClick((event: ClickEvent) => {
            let params: HashMap<string, string> = new HashMap();
            // Enable SDK full-screen display. The default value is true.
            params.set(ZimConstant.KEY_NEED_FULL_SCREEN, 'true');
            // Enable SDK dialog box display. The default value is true.
            params.set(ZimConstant.KEY_USE_MESSAGE_BOX, 'true');
            ZimFacade.verify(this.getUIContext(), this.certifyID, {
              onComplete: (response: ZimResponse) => {
                let result: HashMap<string, string> = new HashMap();
                result.set('code', response.code);
                result.set('subCode', response.subCode);
                result.set('msg', response.msg);
                result.set('certifyID', this.certifyID);
                this.certifyID = '';
                if (response.faceImage) {
                  result.set('faceImage', 'data:image/jpg;base64,' + StringUtil.base64Uint8Array(response.faceImage))
                } else {
                  result.set('faceImage', '');
                }
                let showParams: string = JSONUtil.parseMapToString(result);
                console.log("Aliyun", showParams);
              }
            }, params)
          })
          .margin({ top: 10 })
      }
      .width('100%')
    }
    .height('100%')
  }

  aboutToAppear(): void {
    ZimFacade.init(getContext());
  }
}

Demo package

Download the latest Harmony Demo

Enable the secure camera feature

Starting from version 1.3.2, the Harmony SDK supports the secure camera feature. To use this feature, you must enable the following configurations for your app on the official Harmony website:

  • Trusted Application Service

    Sample email application format for Trusted Application Service

    [Your Business Name] is applying to use the Trusted Application Service. The application materials are as follows:

    Developer ID: [Your Developer ID]

    Company Name: [Your Company Name] Co., Ltd.

    App Name: com.xxxxxx ([Your App Name])

    Requested Service: Trusted Application Service

    Use Case: Enhanced security for real person authentication, including liveness detection and face verification.

  • App and Device Status Check

  • Security Check Service

For specific instructions, see the official Harmony documentation: Enable the Device Security service.