JavaScript API

If you wish to use the functionality provided by the Sybrin Identity Web SDK but create your own UI entirely, you may achieve this by simply creating an instance of the JavaScript API and using the functions exposed by it.

Authorization

The web SDK offers two methods of authorization.

  • The first, most preferred and most secure method is to implement the authorization step in your backend solution and then provide the token to the front-end web SDK component. This is the Token Method.

  • The second method is to allow the web SDK to execute authorization from the UI. This is the API Key Method.

Warning: The API Key Method is extremely unsecure and is not recommended for production environments.

Token Method

Contrary to what the name implies, you will still require an API key for this approach. The only difference is that the web SDK will never directly make use of the API key and will instead only receive a token.

Sybrin will provide you with an orchestration API endpoint, along with a personalized API key (If you have not received this, please contact us).

To use this method:

  • Excute a POST call to the authorization endpoint provided to you by Sybrin, adding your API key to an apiKey header on the request. The response will include a token (AuthToken property).

  • Provide the token returned from the API request to your front-end solution.

  • Set the token on the authToken property of your Sybrin.Identity.Options instance.

API Key Method

This method is much simpler, but also much less secure.

To use this approach:

  • Set the API key provided to you by Sybrin on the apiKey property of your Sybrin.Identity.Options instance.

  • Set the authorization endpoint provided to you by Sybrin on the authEndpoint property of your Sybrin.Identity.Options instance.

Initialization

Token Method

This is the preferred approach.

Please follow the steps described here. The JavaScript API may then be initialized as follows:

var options = new Sybrin.Identity.Options({
    authToken: 'your-auth-token-here',
    dataExtractionEndpoint: 'your-data-extraction-endpoint-here'
});

var identity = new Sybrin.Identity.Api();

identity.initialize(options);

The options object may be used to configure the API as desired.

API Key Method

This approach is not secure and is not recommended for production environments.

Please follow the steps described here. The JavaScript API may then be initialized as follows:

var options = new Sybrin.Identity.Options({
    apiKey: 'your-api-key-here', 
    authEndpoint: 'your-auth-endpoint-here'
    dataExtractionEndpoint: 'your-data-extraction-endpoint-here'
});

var identity= new Sybrin.Identity.Api();

identity.initialize(options);

Configuration Options

The following properties are exposed as configuration options:

Required

  • authToken (string): Please see the authorization section for details on how to use this property. Not required if the apiKey and authEndpoint properties are used.

  • apiKey (string): Your API key as provided by Sybrin. Please see the authorization section for details on how to use this property. Not required if the authToken property is used.

  • authEndpoint (string): The endpoint that will be used to authorize. Only required when the integrationMode property is set to 0 (direct).

  • dataExtractionEndpoint (string): The endpoint that will be used to execute data extraction.

Optional

  • assetHeadersCallback (function): A callback function that may be used to modify the headers of the assets HTTP request. As parameters, this function provides the headers object before modification. The function expects the modified headers object to be returned.

  • authBodyCallback (function): A callback function that may be used to modify the body of the authorization API call. As parameters, this function provides the body object before modification. The function expects the modified body object to be returned.

  • authHeadersCallback (function): A callback function that may be used to modify the headers of the authorization API call. As parameters, this function provides the headers object before modification. The function expects the modified headers object to be returned.

  • authHttpMethod (string: GET | POST | PUT): Overrides the HTTP method type for the authorization API call.

  • blurThreshold (number): The threshold that the blur detection algorithm must pass for the image to be considered clear enough. A higher value is stricter. A lower value is less strict. Default 6.7

  • blurThresholdMobileModifier (number): The factor by which blur threshold is adjusted on mobile devices. A higher value makes blur detection stricter on mobile. Default 1.25.

  • dataExtractionBodyCallback (function): A callback function that may be used to modify the body of the data extraction API call. As parameters, this function provides the body object before modification as well as a SnapshotData object (please see Middleware section for more details). The function expects the modified body object to be returned.

  • dataExtractionHeadersCallback (function): A callback function that may be used to modify the headers of the data extraction API call. As parameters, this function provides the headers object before modification as well as a SnapshotData object (please see Middleware section for more details). The function expects the modified headers object to be returned.

  • dataExtractionHttpMethod (string: GET | POST | PUT): Overrides the HTTP method type for the data extraction API call.

  • debugInfoEndpoint (string): The endpoint that will be used to post debug information to upon using the upload debug info function.

  • encryptionKey (string): The 32-character AES encryption key that will be used for encrypting network traffic from the SDK to the backend API. This value must match the key used by the decryption algorithm in the backend.

  • videoInterval (number): The interval (in milliseconds) at which document detection should run on the video feed. Default 500.

  • instructionTextPosition (string: top | bottom | topandbottom): Location of the instruction text while the video feed is being processed. The default value is "topandbottom".

  • integrationMode (0 - direct | 1 - middleware): Sets how the web SDK integrates with backend services to extract document data. If you wish to use the companion API included with the SDK, or your own middleware implementation, please see the Middleware section. Default 0 (direct).

  • maxUploadFileSize (integer): The maximum size, in bytes, that uploaded files may be. Default 5242880

  • mediaStreamRetryCount (integer): The number of times that the SDK must retry gaining access to the camera if it fails the first time.

  • mediaStreamRetryDelay (integer): The duration that the SDK must wait before retrying gaining access to the camera if it fails the first time.

  • mediaStreamStartTimeout (integer): The time (in milliseconds) that the SDK is given to enable and hook onto the user's camera before it times out. The default value is 6000.

  • overexposedThreshold (number): The percentage of overexposed pixels that should be present for an image to be considered overexposed. Default 50.

  • overexposedValue (number): The grayscale RGB value (0-255) that a pixel's color must be larger than in order to be considered overexposed. Default 220.

  • recordDebugInfo (string: never | always | onerror | onsuccess): Sets whether and when debug info should be recorded for use by download or upload functionality. The default value is "never".

    • never: No debug info is ever recorded.

    • always: Debug info is recorded after every data extraction attempt.

    • onerror: Debug info is only recorded when an error occurs.

    • onsuccess: Debug info is only recorded on a successful data extraction.

  • samplesPath (string): Path to the samples used for document detection. Default "assets/samples"

  • showDebugOverlay (boolean): Sets whether or not the debug overlay should be shown.

  • takePictureDelay (number): The delay (in milliseconds) before the photo is taken once a document is detected in frame. Default 5000.

  • thresholdAdjustAmount (number): The amount by which blur threshold will be adjusted if face detection is taking a long time. Default value is 1.

  • thresholdAdjustFactor (number): The factor at which to apply the image matching threshold adjustment when it occurs. Default 0.8.

  • thresholdAdjustInterval (number): The interval (in milliseconds) at which to adjust the confidence threshold on the current document. Default 4000.

  • thresholdAdjustMaximum (number): The maximum amount that the image matching threshold may be adjusted by. Default 0.5.

  • tokenTimeout (number): The duration (in milliseconds) that a token is valid and will be reused for before a new authorization call is made. Default 120000.

  • underexposedThreshold (number): The percentage of underexposed pixels that should be present for an image to be considered underexposed. Default 40.

  • underexposedValue (number): The grayscale RGB value (0-255) that a pixel's color must be smaller than in order to be considered underexposed. Default 30.

  • useCutout (boolean): Sets whether or not the document cutout overlay must be displayed over the video feed. Default true.

Functionality

The Sybrin Identity Javascript API provides multiple ways of running data extraction on identity documents and other functions to control the Web SDK.

These include:

  • Extract Data Using Camera

  • Extract Data Using File Upload

  • Cancel

Additionally, the API provides:

  • Set Translations

  • Version Information Retrieval

  • Client Information Retrieval

  • Compatibility Check

  • Get Video Input Devices

  • Debug Information Download

  • Debug Information Upload

  • Get Supported Country Codes

Extract Data Using Camera

To use the camera for data extraction, you may make use of the openScanDocument function exposed by the JavaScript API.

Signature:

openScanDocument(params?: { id?: string; element?: HTMLElement; documentTypeId?: string; documentTypeName?: string; countryCode?: string; correlationId?: string; deviceId?: string; }): Promise<DocumentScanResult>

An argument, passed as an object literal, is required for this function call. The object literal must have these required properties:

  • documentTypeId (string): The ID that points to a unique document type for a specific country. Not required if countryCode and documentTypeName are specified.

  • countryCode (string): The country that data extraction should run for. Not required if documentTypeId is specified.

  • documentTypeName (string): The document type that data extraction should run for. Not required if documentTypeId is specified.

Optionally you may also specify the following properties:

  • id (string): The ID of the element to create the video feed in. The element property takes precedence over the id property.

  • element (HTMLElement): The element to create the video feed in. Takes precedence over the id property.

  • correlationId (string): Value that is used to associate the result with a specific case.

  • deviceId (string): ID of the specific device to use for data extraction.

If no id or element property is passed on the argument, the Web SDK will temporarily inject a full screen element to display the video feed.

The function returns a promise, so you may choose to use either the asynchronous await pattern or to subscribe to the result using .then(), .catch() and .finally().

Example:

<button onclick="openScanDocument()">Start Data Extraction</button>

The result is of type DocumentScanResult and has the following properties:

  • success (boolean): Whether or not data was extracted successfully.

  • message (string): Result message.

  • data (object): A dynamic object that contains the extracted document data.

  • facingMode (string: user | environment | left | right): The direction/orientation of the camera that was used during capture.

  • images (object): A wrapper object that contains extracted images.

    • documentImage (string): Base64 encoded document front image.

    • documentBackImage (string): Base64 encoded document back image.

    • portraitImage (string): Base64 face portrait image.

Extract Data Using File Upload

To use a file upload for data extraction, you may make use of the uploadDocument function exposed by the JavaScript API.

Signature:

uploadDocument(params?: { file?: File; base64?: string; documentTypeId?: string; documentTypeName?: string; countryCode?: string; correlationId?: string; loaderContainer?: HTMLElement; uploadModalContainer: HTMLElement }): Promise<DocumentScanResult>

An argument, passed as an object literal, is required for this function call. The object literal must have these required properties:

  • documentTypeId (string): The ID that points to a unique document type for a specific country. Not required if countryCode and documentTypeName are specified.

  • countryCode (string): The country that data extraction should run for. Not required if documentTypeId is specified.

  • documentTypeName (string): The document type that data extraction should run for. Not required if documentTypeId is specified.

  • uploadModalContainer (HTMLElement): The HTML element that must be used to contain

Optionally you may also specify the following properties:

  • frontFile (File): The front image file to run data extraction on.

  • backFile (File): The back image file to run data extraction on.

  • frontBase64 (string): A base64 string of the front image to run data extraction on.

  • backBase64 (string): A base64 string of the back image to run data extraction on.

  • correlationId (string): Value that is used to associate the result with a specific case.

  • loaderContainer (HTMLElement): The HTML element to display a loader inside while processing.

The frontFile, backFile, frontBase64 and backBase64 properties offer an opportunity to implement your own method of obtaining files for upload. If none of these are passed, the Web SDK will invoke the default file explorer window provided by the browser to allow for front (as well as back, if required for the document type) file selection.

If you wish to provide the front file, only one parameter between frontFile and frontBase64 is required.

If you wish to provide the back file where applicable, only one parameter between backFile and backBase64 is required.

The function returns a promise, so you may choose to use either the asynchronous await pattern or to subscribe to the result using .then(), .catch() and .finally().

Example:

<button onclick="uploadDocument()">Upload Document</button>

Cancel

A function to cancel any action that the identity Web SDK is currently executing. This is useful if you wish to add a cancel button to the UI so that the user may stop data extraction while it's in progress.

Signature:

cancel(): void

Example:

<button onclick="cancel()">Cancel</button>

Set Translations

This function may be used to set translations on a JavaScript API level.

Signature:

setTranslations(translations: { [key: string]: string }): void

Usage example:

biometrics.setTranslations({
    'sy-i-translation-41': 'Preparing'
});

Version Information Retrieval

To get all version info regarding the Web SDK and its components, the API exposes a function called getVersionInfo.

Signature:

getVersionInfo(): Promise<any>

Usage example:

identity.getVersionInfo().then(function(result) {
    console.log(result);
}).catch(function(error) {
    console.log('An error occurred: ', error);
}).finally(function() {
    console.log('Done');
});

The result has the following properties:

  • webSdkVersion (string): The semantic version number of the JavaScript web SDK that is currently in use.

Client Information Retrieval

To get all version info regarding the client environment in which the application is currently running, the API exposes a function called getClientInfo.

Signature:

getClientInfo(): Promise<ClientInfo>

Usage example:

identity.getClientInfo().then(function(result) {
    console.log(result);
}).catch(function(error) {
    console.log('An error occurred: ', error);
}).finally(function() {
    console.log('Done');
});

The result is of type ClientInfo and has the following properties:

  • isMobile (boolean): Whether or not the client environment is mobile (tablet or phone).

  • isMobileAndroid (boolean): Whether or not the client environment is running Android.

  • isMobileBlackberry (boolean): Whether or not the client environment is running Blackberry.

  • isIphone (boolean): Whether or not the client environment is running on an iPhone.

  • isIpad (boolean): Whether or not the client environment is running on an iPad.

  • isIpadPro (boolean): Whether or not the client environment is running on an iPad Pro.

  • isIpod (boolean): Whether or not the client environment is running on iPod.

  • isMobileIos (boolean): Whether or not the client environment is running iOS.

  • isMobileOpera (boolean): Whether or not the client environment is mobile Opera.

  • isMobileWindows (boolean): Whether or not the client environment is Windows Mobile.

  • isMac (boolean): Whether or not the client environment is running on Mac.

Compatibility Check

This function checks compatibility of the web SDK with the environment in which it is running (device, operating system, browser etc.) and reports back on it.

Signature:

checkCompatibility(handleIncompatibility?: boolean): Promise<CompatibilityInfo>

Optionally, you may pass down true to signal for the web SDK to handle incompatibility internally. This will result in a modal prompt with an appropriate message automatically being shown if the function finds incompatibility with the environment.

Usage example:

identity.checkCompatibility().then(function(result) {
    console.log(result);
}).catch(function(error) {
    console.log('An error occurred: ', error);
}).finally(function() {
    console.log('Done');
});

The result is of type CompatibilityInfo and has the following properties:

  • compatible (boolean): Whether or not the web SDK is compatible with the client environment.

  • mediaStream (boolean): Whether or not the client environment supports media stream access.

  • message (string): An appropriate message that describes the related incompatibility if detected.

Get Video Input Devices

This function returns a list of all video input devices that can be used.

Signature:

getVideoInputDevices(showLoader?: boolean, loaderContainer?: HTMLElement): Promise<VideoInputDevice[]>

The optional showLoader parameter sets whether or not the UI must be blocked with a loader. When used in conjunction with the optional loaderContainer parameter, the specific element will be blocked with a loader.

The function returns a promise, so you may choose to use either the asynchronous await pattern or to subscribe to the result using .then(), .catch() and .finally().

Usage example:

identity.getVideoInputDevices().then(function(result) {
    console.log(result);
}).catch(function(error) {
    console.log('An error occurred: ', error);
}).finally(function() {
    console.log('Done');
});

The result is an array of type VideoInputDevice and each instance has the following properties:

  • deviceId (string): ID of the device.

  • groupId (string): Group that the device belongs to.

  • type (string: Camera | Webcam | Device): The type of device.

  • direction (string: Front | Back | Integrated): The direction of the device.

  • label (string): A short description of the device.

  • counter (number): Number indicator for the device. Value is 0 unless there are multiple devices of the same type and direction available.

Debug Information Download

Before using this function, please ensure that the recordDebugInfo configuration option has been set.

Signature:

downloadDebugInfo(): void

This is for debug and diagnostic purposes only and can only be used once debug functionality has been configured. It can be used after a liveness scan to download an HTML file containing information relating to the scan attempt.

Usage example:

identity.downloadDebugInfo();

Debug Information Upload

Before using this function, please ensure that the recordDebugInfo configuration option has been set.

Signature:

uploadDebugInfo(): Promise<boolean>

This is for debug and diagnostic purposes only and can only be used once debug functionality has been configured. It can be used after a liveness scan to upload an HTML file containing information relating to the scan attempt. The file is uploaded to the endpoint configured in the debugInfoEndpoint configuration option.

This function sends a POST message to the configured endpoint and the payload is a string on the form body, called debugInfo.

IMPORTANT: The HTML file includes the selfie taken during the scan attempt. Please keep the POPI act in mind when making use of this feature. Sybrin accepts no responsibility for any breach of the POPI act should this function be used to upload data to your own custom hosted service.

Usage example:

identity.uploadDebugInfo().then(function() {
    console.log('Upload complete');
}).catch(function(error) {
    console.log('An error occurred: ', error);
}).finally(function() {
    console.log('Done');
});

Get Supported Country Codes

The SDK provides two functions to retrieve lists of supported country codes, one for a list of Alpha-3 codes and another for a list of Alpha-2 codes.

These functions are:

  • getCountryAlpha3Codes - Returns an array of 3 character strings.

  • getCountryAlpha2Codes - Returns an array of 2 character strings.

Signatures:

getCountryAlpha3Codes(): string[]

getCountryAlpha2Codes(): string[]

Usage examples:

var alpha3Codes = identity.getCountryAlpha3Codes();
console.log('Supported Alpha-3 country codes:');
console.log(alpha3Codes);

var alpha2Codes = identity.getCountryAlpha2Codes();
console.log('Supported Alpha-2 country codes:');
console.log(alpha2Codes);

Translations

The JavaScript API is affected by the following translation keys:

Last updated