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.

Initialization

The JavaScript API may be initialized as follows:

var options = new Sybrin.Identity.Options({
    apiKey: 'your-api-key-here', 
    authorizationEndpoint: 'your-auth-endpoint-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.

Configuration Options

The following properties are exposed as configuration options:

Required

  • apiKey (string): Your API key as provided by Sybrin.

  • 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 authentication 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 authentication 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 authentication API call.

  • authToken (string): Provides an alternative to the apiKey property. Renders the apiKey property unused and it is thus not required anymore. Only to be used if authentication is being handled externally.

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

  • 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).

  • 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"

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

  • thresholdAdjustFactor (number): The factor at which to apply the confidence 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.

  • tokenTimeout (number): The duration (in milliseconds) that a token is valid and will be reused for before a new authentication 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.

Component text and localization

  • messageBlurry (string): Text prompt to display when the video feed is too blurred. Default "Image too blurry"

  • messageIncompatible (string): Text to display in modal that warns the user if the browser is not supported. Default "Browser is not supported."

  • messageIncompatibleSafari (string): Text to display in modal that warns the user and prompts them to switch to Safari if the third party browser is not supported on an iOS environment, but Safari might be. Default "Browser is not supported. Please open in Safari."

  • messageLightingBright (string): Text prompt to display when the video feed is overexposed. Default "Lighting conditions too bright"

  • messageLightingDark (string): Text prompt to display when the video feed is underexposed. Default "Lighting conditions too dark"

  • messagePrepareBack (string): Text prompt to display while waiting for the user to flip the document over and prepare the back for capture.

    Default "Please flip the document over for rear photo"

  • messagePrepareFront (string): Text prompt to display while waiting for the user to prepare the front of a document for capture. Default "Please hold the document up to the camera"

  • messagePreparing (string): Text prompt to display while initializing the video stream. Default "Preparing..."

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; }): 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:

  • 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:

Translation KeyDescriptionDefault/Source

sy-i-translation-41

Text prompt to display while document scan is initializing

Preparing...

sy-i-translation-42

Text prompt to display when the SDK is looking for the front side of the ID document

Please hold the document up to the camera

sy-i-translation-43

Text prompt to display when the SDK is looking for the rear side of the ID document

Please flip the document over for rear photo

sy-i-translation-44

Text prompt to display when more light is needed

Lighting conditions too dark

sy-i-translation-45

Text prompt to display when there is too much light

Lighting conditions too bright

sy-i-translation-46

Text prompt to display when the image is not clear enough

Image too blurry

sy-i-translation-47

Alert message to show if the SDK detects that the browser is not supported

Browser is not supported.

sy-i-translation-48

Alert message to show if the SDK detects that the user is using a third party browser on an Apple device that doesn't allow camera access to third party browsers.

Browser is not supported. Please open in Safari.

sy-i-translation-68

Caption of the button that dismisses the alert window that is shown when a compatibility issue is detected

Ok

Last updated