Integrating with an iframe

Updated at:

The financial-grade ID Verification H5 solution includes a Web SDK for verification in browsers and embedded WebViews. This topic describes how to integrate the Web SDK into PC and mobile H5 pages using an iframe.

Browser compatibility

Browser

Android version

iOS version

Edge

Android 4.0 or later

iOS 14.3 or later

FireFox

Chrome

Opera

QQ

Baidu

Android Browser 5.0+

Safari

Not supported

iOS 11.3 or later

UC

Android 4.0 or later

Not supported

UC Turbo

Quark Browser

Android 7.0 or later

Not supported

Vendor-specific built-in browsers

Supported on some models, such as Xiaomi and Samsung.

Due to browser fragmentation, we recommend that you guide users to a recommended browser to complete the authentication.

  • If you integrate the solution into a mobile app, you may encounter compatibility issues with the embedded browser. To resolve these issues, refer to Compatibility configurations for integrating the H5 SDK for mobile apps or integrate a native SDK.

  • If you integrate the solution in a WeChat official account or mini program, unavoidable compatibility issues may occur due to WeChat's operational review rules. We recommend using server-side API integration.

Face scan verification

To improve the face scan verification experience, the CertifyUrl includes a guide page by default. After a user agrees to the authentication, they can start the face scan verification. For WeChat official accounts, the guide page is mandatory. Otherwise, the camera cannot be activated, which causes a black screen. To customize the UI, refer to the server-side API parameter UiCustomUrl.

Integrate with a custom iframe

If you want to control the style and layout of the iframe container, you can directly embed the CertifyUrl into an iframe. Set the ReturnUrl parameter to the fixed value iframe. After the authentication is complete, the result is sent using the postMessage method.

Use cases

  • You need to embed the authentication area in a specific position on the page instead of in full-screen mode.

  • You need to customize the style of the iframe, such as the size, border, and layer.

Procedure

  1. Import the following JS file into your code and call the getMetaInfo() function to get MetaInfo.

    <script type="text/javascript" src="https://o.alicdn.com/yd-cloudauth/cloudauth-cdn/jsvm_all.js" ></script>
    Important
    • When you call the server-side ID Verification API to initiate an authentication request, you must pass the real-time MetaInfo value.

    • This value changes dynamically based on the browser and device environment. You must also pass the real-time value during the testing phase. Do not use hard-coded test data. Otherwise, you may fail to get the CertifyUrl.

  2. Call your server-side initialization API to get the CertifyUrl. When you call the API, include the following parameters in the request:

    • CertifyUrlStyle: "L" — Gets the authentication URL in a long-link format.

    • ReturnUrl: "iframe" — Sends the authentication result to the parent page using the postMessage mechanism.

      // Request parameters for a WeChat mini program
      {
        ...
        "CertifyUrlStyle": "L",
        "ReturnUrl":"iframe",
        ...
      }
    • The default CertifyUrl for a mini program does not support iframe embedding. You must change the URL path to enable iframe support.

      // Replace "/h5?" with "/h5iframe?" in certifyUrl.
      function replaceH5ToIframe(url) {
        if (url.includes('/h5?')) {
          return url.replace('/h5?', '/h5iframe?');
        }
        if (url.includes('/h5') && !url.includes('/h5iframe')) {
          return url.replace('/h5', '/h5iframe');
        }
        return url;
      }
  3. Create an iframe element on the page and assign the returned CertifyUrl to the src attribute.

    <!-- Sample CertifyUrl: https://rp-proxy.antdigital.com/onex/proxy/h5?clientcfg=eyJ6... -->
    <iframe
      id="idv-iframe"
      src="{CertifyUrl}"
      allow="camera"
      style="width: 100%; height: 600px; border: 0;"
    ></iframe>
  4. Listen for the message event to receive the authentication result.

Result data structure

When the authentication process is complete, the child page sends the result to the parent page using postMessage. The following code shows the data structure of the result:

{
  "code": "XXXX",
  "subCode": "XXXX",
  "extInfo": {
    "certifyId": "XXXXXX"
  }
}

Field

Type

Description

code

String

The result code. For more information, see Result codes.

subCode

String

The sub-result code. For more information, see Sub-result codes.

extInfo

Object

The extended information.

extInfo.certifyId

String

The authentication ID, which is used for subsequent server-side queries.

Full code example

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover" />
    <title>Financial-grade ID Verification</title>
    <!--   Import this JS file to inject the getMetaInfo method globally.   -->
    <script src="https://o.alicdn.com/yd-cloudauth/cloudauth-cdn/jsvm_all.js"></script>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        html,
        body {
            width: 100%;
            height: 100%;
        }

        #idv-container {
            width: 100%;
            height: 100vh;
            background: #fff;
        }

        #idv-container iframe {
            width: 100%;
            height: 100%;
            border: 0;
        }

        .error {
            padding: 16px;
            color: #d93026;
            text-align: center;
        }
    </style>
</head>

<body>
    <div id="idv-container"></div>

    <script>
        (() => {
            const containerElement = document.getElementById('idv-container');
            let messageListener = null;

            function showError(message) {
                containerElement.innerHTML = `<div class="error">${message}</div>`;
            }

            // Replace "/h5?" in the certifyUrl with "/h5iframe?".
            function replaceH5ToIframe(url) {
                if (url.includes('/h5?')) {
                    return url.replace('/h5?', '/h5iframe?');
                }
                if (url.includes('/h5') && !url.includes('/h5iframe')) {
                    return url.replace('/h5', '/h5iframe');
                }
                return url;
            }

            async function initAuth() {
                try {
                    if (!window.getMetaInfo) {
                        throw new Error('getMetaInfo is not injected. Check whether the SDK script is loaded.');
                    }

                    const metaInfo = window.getMetaInfo();
                    const response = await fetch('https://your-server-side-initialization-api-endpoint', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            metaInfo,
                            certifyUrlStyle: 'L',
                            returnUrl: 'iframe'
                        })
                    });

                    if (!response.ok) {
                        throw new Error(`Initialization API error: ${response.status}`);
                    }

                    const result = await response.json();

                    if (!result?.resultObject?.certifyUrl) {
                        throw new Error('Failed to obtain certifyUrl.');
                    }
                  
                    const certifyUrl = replaceH5ToIframe(result?.resultObject?.certifyUrl);

                    const allowedOrigin = new URL(certifyUrl).origin;

                    const iframeElement = document.createElement('iframe');
                    iframeElement.src = certifyUrl;
                    iframeElement.allow = 'camera;microphone;fullscreen';
                    iframeElement.setAttribute('allowusermedia', 'true');
                    containerElement.innerHTML = '';
                    containerElement.appendChild(iframeElement);

                    messageListener = async (event) => {
                        if (event.origin !== allowedOrigin) return;

                        const payload = typeof event.data === 'string'
                            ? (() => { try { return JSON.parse(event.data); } catch { return null; } })()
                            : event.data;

                        if (!payload || typeof payload !== 'object' || payload.code === undefined) return;

                        console.log('Authentication callback:', payload);

                        window.removeEventListener('message', messageListener);
                    };

                    window.addEventListener('message', messageListener, { passive: true });
                } catch (error) {
                    console.error('[IDV] init error:', error);
                    showError('Failed to load the authentication page. Please refresh and try again.');
                }
            }

            window.addEventListener('beforeunload', () => {
                if (messageListener) {
                    window.removeEventListener('message', messageListener);
                }
            });

            initAuth();
        })();
    </script>
</body>

</html>
Note
  • You must deploy the page over HTTPS and set the allow="camera" attribute for the iframe. Otherwise, the page cannot access the camera.

  • When you call the InitFaceVerify API, you must set the ReturnUrl parameter to iframe, and the parent page must listen for the message event to receive the authentication result.

  • After the authentication is complete, the system checks whether the current environment is an iframe and verifies whether the ReturnUrl parameter is set to iframe. If both conditions are met, the system sends the authentication result to the parent page.

  • To prevent risks such as hotlinking and data tampering, we recommend making a server-side request to get the final verification result after you parse the client-side result. For more information, see DescribeFaceVerify-Get detailed authentication data.

Error codes

Result codes

Code

Billing

Message

1000

Yes

The face scan is successful.

Note

Indicates that the user has completed the face scan process and the recommended authentication result is 'pass'.

This result is for reference only. The final authentication result is determined by the server-side DescribeFaceVerify API response.

1001

No

A system error occurred.

1003

No

The verification was interrupted.

2002

No

A network error occurred.

2003

No

The client-side device time is incorrect.

2006

Yes (Billed only if authentication fails)

Face scan data submission failed, or the verification failed.

Note

This result is for reference only. The final authentication result is determined by the server-side DescribeFaceVerify API response.

Sub-result codes

Code

Sub-code

Description

1000

Z5050

Face verification is successful.

1001

-

A system error occurred.

1003

Z5051

Failed to upload face scan images.

Z5052

A data error or program exception occurred.

Z5053

A network error occurred.

Z5054

The camera permission is not granted or camera data could not be accessed.

Z5055

The user exited the process.

Z5056

Too many retries.

Z5058

The video format is invalid.

Z5059

No valid face is detected in the video.

Z5060

The page is in a degraded waiting state. After the user confirms that the face recognition is complete, you can call the server-side API to query the authentication result and proceed to the next step.

2002

-

A network error occurred.

2003

-

The client-side device time is incorrect.

2006

Z5128

Z5128 (Billed): Face recognition failed, resulting in a failed verification. Call a server-side query API for the exact reason.

Z5052

Z5052 (Not billed): An exception occurred during the client-side submission of authentication data. The authentication process was not initiated.