React (create-react-app)

Follow these steps to get started with ReactJS.

  1. Set up the workspace by running the following command:

    npx create-react-app livenesstest

    A folder/directory named livenesstest should appear and the folder/ directory structure should look like this:

    livenesstest/
        |
        +-- node_modules/
        |
        +-- public/
        |    |
        |    +-- favicon.ico
        |    |
        |    +-- index.html
        |    |
        |    +-- logo192.png
        |    |
        |    +-- logo512.png
        |    |
        |    +-- manifest.json
        |    |
        |    \-- robots.txt
        |
        +-- src/
        |    |
        |    +-- App.css
        |    |
        |    +-- App.js
        |    |
        |    +-- App.test.js
        |    |
        |    +-- index.css
        |    |
        |    +-- index.js
        |    |
        |    +-- logo.svg
        |    |
        |    +-- reportWebVitals.js
        |    |
        |    \-- setupTests.js
        |
        +-- .gitignore
        |
        +-- package-lock.json
        |
        +-- package.json
        |
        \-- README.md
  2. Extract file Verihubs WebSDK Liveness [version] [organization].zip file. Rename build folder/directory inside as liveness.

  3. Put extracted liveness folder/directory that contains the liveness engine and builders like builder.js, into the public folder/directory.

  4. Add the liveness package to package.json by running this command inside livenesstest React.js project.

    npm i file:public/liveness

    This will add @verihubs/liveness dependency in package.json.

  5. Create new file with name useLiveness.js inside src folder.

    touch src/useLiveness.js
  6. Add the following code to the index.js file inside src folder.

    import * as React from 'react';
    import Builder from '@verihubs/liveness';
    
    export function useLivenessSDK() {
      const sdkRef = React.useRef(null);
      const [image, setImage] = React.useState('');
      const [data, setData] = React.useState('');
    
      React.useEffect(() => {
        sdkRef.current = new Builder()
          .setInstruction(['look_left', 'look_right'], {
            commands: ['open_mouth'],
            seedLimit: 1,
          })
          .setProxyMiddleware({
            PassiveLiveness: {
              url: 'http://localhost:8888/liveness/face',
              headers: {
                'App-ID': '<replace-me-with-app-id>',
                'API-Key': '<replace-me-with-api-key>',
              },
            },
            License: {
              url: 'http://localhost:8888/license/{license_id}/check',
              headers: {
                'App-ID': '<replace-me-with-app-id>',
                'API-Key': '<replace-me-with-api-key>',
              },
            },
          })
          .setTimeout(60000)
          .setURL('./liveness')
          .setVirtualCameraLabel(['OBS', 'Virtual'])
          .build();
    
        return () => {
          sdkRef.current?.destroy();
          sdkRef.current = null;
        };
      }, []);
    
      React.useEffect(() => {
        const listener = (event) => {
          const { subject, data } = event.data;
    
          switch (subject) {
            case 'Verification.Verbose':
              console.log('[Verbose]', data);
              break;
    
            case 'Camera.NotAllowed':
            case 'Camera.NotFound':
            case 'Camera.PermissionDenied':
            case 'ScreenOrientation.NotAllowed':
            case 'Verification.Disrupted':
            case 'Verification.Timeout':
              alert(subject);
              sdkRef.current?.destroy();
              break;
    
            case 'Verification.Success': {
              const result = data;
    
              window.setTimeout(() => {
                if (result.image?.url) {
                  setImage(`data:image/png;base64,${result.image.url}`);
                }
    
                setData(JSON.stringify(result, undefined, 2));
                sdkRef.current?.destroy();
              }, 1500);
    
              break;
            }
    
            default:
              console.log({ data, subject });
              break;
          }
        };
    
        window.addEventListener('message', listener);
    
        return () => {
          window.removeEventListener('message', listener);
        };
      }, []);
    
      const start = React.useCallback(() => {
        sdkRef.current?.start();
      }, []);
    
      const destroy = React.useCallback(() => {
        sdkRef.current?.destroy();
      }, []);
    
      return {
        start,
        destroy,
        image,
        data,
      };
    }
    

    Replace proxy middleware URLs with a URL that points to the correct endoints, and replace <replace-me-with-app-id> and <replace-me-with-api-key> with the appropriate APP-ID and APIKey for the passive liveness (remove the headers if the api doesn't need credentials or the url is pointing towards an intermediate endpoint).

    🚧

    Look Out!

    To not accidentally leak of AppID and APIKey for passive liveness, always pass them to an intermediate endpoint (like a proxy middleware) and append the AppID and APIKey header before reaching Verihubs' passive liveness service in production. Additional data can also be passed to this intermediate endpoint for end user identification.

    For more information about creating a Proxy Middleware, refer to Proxy Middleware.

    For API documentation of the Builder, refer to Builder.

    📘

    Info

    Check System Messages for full system message references.

  7. Replace App.js by the code below:

    import './App.css';
    import { useLivenessSDK } from './useLiveness';
    
    function App() {
      const { start, image, data } = useLivenessSDK();
    
      return (
        <main>
          <button type="button" onClick={start}>
            Start Liveness
          </button>
    
          {image && <img src={image} alt="Liveness result" />}
    
          {data && <pre>{data}</pre>}
        </main>
      );
    }
    
    export default App;
    

To try the above implementation you can run the following command from the liveness project:

npm run dev

Did this page help you?