Java SDK call examples

更新时间:
复制 MD 格式

This topic explains how to download and integrate the SDK. It also provides a sample workflow that calls an OpenAPI to integrate Financial-grade Real Person Authentication on the server side.

OpenAPI operations for server-side integration

Server-side integration for Financial-grade Real Person Authentication supports both photo-based and video-based authentication.

Note

Before you develop your application based on Alibaba Cloud OpenAPI, you can use the debugging tools provided by the OpenAPI Portal (web or CLI) to test API requests, check parameters, and view results. The portal provides troubleshooting suggestions to help you quickly learn how to use the OpenAPI operations.

Debugging portal for ContrastFaceVerify (photo or video)

Step 1: Activate the service

Before you use the Financial-grade Real Person Authentication service, you must activate it. For more information, see Activate the Financial-grade Real Person Authentication service.

Step 2: Create and authorize a RAM user

For fine-grained access control, create a RAM user to call the service API. Before you integrate the SDK, obtain the required access credentials for this user and grant them permissions to access cloud resources. For information about how to create and authorize a RAM user and generate an AccessKey for API calls, see Authorize a RAM user to access the service.

Step 3: Add an authentication scenario

An authentication scenario defines a specific context in which your users complete real person authentication, such as during login or payment. You can add one or more scenarios and configure different authentication methods for each. You must pass the authentication scenario ID when you call the InitFaceVerify operation to initiate an authentication request. For information about how to add an authentication scenario and obtain its ID, see Add an authentication scenario.

Note

When you add an authentication scenario, you can authorize Alibaba Cloud to access a specified Object Storage Service (OSS) bucket to store authentication images. For more information, see Enable and authorize OSS storage.

Step 4: Integrate the SDK and write code

Service endpoints

The following table lists the supported regions and their endpoints.

Important

We recommend that you follow the sample code in this topic to configure primary and backup region endpoints. If the primary endpoint fails, the system automatically switches to the backup endpoint to ensure high availability.

Region

Public endpoint

VPC endpoint

Global endpoint

China (Shanghai)

IPv4: cloudauth.cn-shanghai.aliyuncs.com

cloudauth-vpc.cn-shanghai.aliyuncs.com

  • IPv4: cloudauth.aliyuncs.com

  • IPv6: cloudauth-dualstack.aliyuncs.com

IPv6: cloudauth-dualstack.aliyuncs.com

China (Beijing)

IPv4: cloudauth.cn-beijing.aliyuncs.com

cloudauth-vpc.cn-beijing.aliyuncs.com

IPv6: cloudauth-dualstack.cn-beijing.aliyuncs.com

SDK installation and source code

Select and integrate the appropriate SDK for your technology stack.

Language

SDK download URL

GitHub source code

Java

Download Java SDK

Alibaba Cloud Green SDK for Java

Python

Download Python SDK

Alibaba Cloud Green SDK for Python

Typescript

Download TypeScript SDK

Alibaba Cloud Green SDK for Typescript

Go

Download Go SDK

Alibaba Cloud Green SDK for Go

PHP

Download PHP SDK

Alibaba Cloud Green SDK for PHP

C#

Download C# SDK

Alibaba Cloud Green SDK for C#

C++

Download C++ SDK

Alibaba Cloud Green SDK for C++

Write code (Java example)

The following example uses the Java language. JDK 1.8 or later is required.

  1. Add the following dependencies to your pom.xml file to use the SDK in your Maven project. For the latest version and other installation methods, see Download Java SDK.

    • Java SDK dependency

      <dependency>
       <groupId>com.aliyun</groupId>
       <artifactId>cloudauth20190307</artifactId>
       <version>2.1.1</version>
      </dependency>
    • Authentication dependency. See ChangeLog.txt for a list of all released versions. We recommend that you use the latest version.

      Important

      The authentication dependency may be integrated directly into the SDK. Check the SDK usage instructions to determine whether you need to add it manually. See Java SDK.

      <dependency>
         <groupId>com.aliyun</groupId>
         <artifactId>credentials-java</artifactId>
         <version>LATEST</version>
      </dependency>
      Note

      This example uses Alibaba Cloud Credentials to read the AccessKey from environment variables for API authentication. For information about how to configure environment variables, see Manage access credentials.

  2. Sample code.

    Important

    The code sample demonstrates basic API calls. For production use, optimize and refactor the code.

    For example, we recommend that you implement the singleton pattern for common objects such as credentialClient, config, and client to improve performance. These objects are marked with comments in the sample code.

    • Example for photo-based real person authentication

      import com.aliyun.cloudauth20190307.Client;
      import com.aliyun.cloudauth20190307.models.ContrastFaceVerifyRequest;
      import com.aliyun.cloudauth20190307.models.ContrastFaceVerifyResponse;
      import com.aliyun.teaopenapi.models.Config;
      import com.aliyun.teautil.models.RuntimeOptions;
      
      import java.util.Arrays;
      import java.util.List;
      
      public class ContrastFaceVerifyWithPicture {
          // Use the singleton pattern to optimize performance.
          private static com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();
      
          public static void main(String[] args) throws Exception {
      
              // Create an API request and set the parameters.
              ContrastFaceVerifyRequest request = new ContrastFaceVerifyRequest();
      
              // Fixed value.
              request.setProductCode("ID_MIN");
              // Fixed value.
              request.setCertType("IDENTITY_CARD");
              request.setCertName("John Doe");
              request.setIp("The user's IP address");
              request.setMobile("The user's mobile number");
              request.setDeviceToken("The deviceToken obtained from the device fingerprint");
              request.setUserId("The user ID");
              request.setCertNo("The 18-digit ID card number");
              request.setOuterOrderNo("A unique identifier for the merchant's request");
              // The scene ID, suffixed with 'L'.
              request.setSceneId(0L);
              request.setModel("FRONT_CAMERA_LIVENESS");
      
              // Choose one of the following four methods.
              // 1. The Base64-encoded photo.
              // 2. The OSS bucket name and object name for the photo.
              // 3. The URL of the photo in an OSS bucket.
              // 4. The CertifyId from a previous successful authentication.
      
              // Method 1: Base64-encoded photo.
              request.setFaceContrastPicture("The Base64-encoded face photo");
              // Method 2: The OSS bucket name and object name for the photo.
              //request.setOssBucketName("cn-shanghai-aliyun-cloudauth-xxxxx");
              //request.setOssObjectName("verify/xxxxx/xxxxxx.jpeg");
              // Method 3: The URL of the photo in an OSS bucket. The URL must be publicly accessible.
              //request.setFaceContrastPictureUrl("https://cn-shanghai-aliyun-cloudauth-xxxxxx.oss-cn-shanghai.aliyuncs.com/verify/xxxxx/xxxxx.jpeg")
              // Method 4: The CertifyId from a previous successful authentication.
              //request.setCertifyId("0bfa7c493f850e5178b9f8613634c9xx");
      
              // To enable encrypted transmission of personal information.
              // request.setEncryptType("SM2");
              // request.setCertName("BCRD/7ZkNy7Q*****M1BMBezZe8GaYHrLwyJv558w==");
              // request.setCertNo("BMjsstxK3S4b1YH*****Pet8ECObfxmLN92SLsNg==");
      
              // Recommended. Supports service routing.
              ContrastFaceVerifyResponse response = contrastFaceVerifyAutoRoute(request);
      
              // Does not support automatic service routing.
              //ContrastFaceVerifyResponse response = contrastFaceVerify("cloudauth.cn-shanghai.aliyuncs.com", request);
      
              System.out.println(response.getBody().getRequestId());
              System.out.println(response.getBody().getCode());
              System.out.println(response.getBody().getMessage());
              System.out.println(response.getBody().getResultObject() == null ? null
                      : response.getBody().getResultObject().getPassed());
              System.out.println(response.getBody().getResultObject() == null ? null
                      : response.getBody().getResultObject().getSubCode());
              System.out.println(response.getBody().getResultObject() == null ? null
                      : response.getBody().getResultObject().getIdentityInfo());
              System.out.println(response.getBody().getResultObject() == null ? null
                      : response.getBody().getResultObject().getMaterialInfo());
          }
      
          private static ContrastFaceVerifyResponse contrastFaceVerifyAutoRoute(ContrastFaceVerifyRequest request) {
              // The first endpoint is for the primary region, and the second is for the backup region.
              List<String> endpoints = Arrays.asList("cloudauth.cn-shanghai.aliyuncs.com", "cloudauth.cn-beijing.aliyuncs.com");
              ContrastFaceVerifyResponse lastResponse = null;
              for (int i=0; i<endpoints.size(); i++) {
                  try {
                      ContrastFaceVerifyResponse response = contrastFaceVerify(endpoints.get(i), request);
                      lastResponse = response;
      
                      // If a server-side error occurs, switch to the next region.
                      if(response != null){
                          if(500 == response.getStatusCode()){
                              continue;
                          }
                          if(response.getBody() != null){
                              if("500".equals(response.getBody().getCode())){
                                  continue;
                              }
                          }
                      }
      
                      return response;
                  } catch (Exception e) {
                      e.printStackTrace();
                      if(i == endpoints.size()-1){
                          throw new RuntimeException(e);
                      }
                  }
              }
      
              return lastResponse;
          }
      
          private static ContrastFaceVerifyResponse contrastFaceVerify(String endpoint, ContrastFaceVerifyRequest request)
                  throws Exception {
              // An AccessKey of an Alibaba Cloud account has permissions to call all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M.
              // We strongly recommend that you do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and all resources in your account may be exposed to security risks.
              // This example uses Alibaba Cloud Credentials to read the AccessKey from environment variables for API authentication. For information about how to configure environment variables, see https://help.aliyun.com/document_detail/378657.html.
              // We recommend using the singleton pattern.
              Config config = new Config();
              config.setCredential(credentialClient);
              config.setEndpoint(endpoint);
              // Set the HTTP proxy.
              //config.setHttpProxy("http://xx.xx.xx.xx:xxxx");
              // Set the HTTPS proxy.
              //config.setHttpsProxy("http://xx.xx.xx.xx:xxxx");
              // We recommend using the singleton pattern.
              Client client = new Client(config);
      
              // Create a RuntimeOptions instance and set the runtime parameters.
              RuntimeOptions runtime = new RuntimeOptions();
              runtime.readTimeout = 10000;
              runtime.connectTimeout = 10000;
      
              return client.contrastFaceVerifyWithOptions(request, runtime);
          }
      }
    • Example for video-based real person authentication

      • Using a local file (recommended)

        import com.aliyun.cloudauth20190307.Client;
        import com.aliyun.cloudauth20190307.models.ContrastFaceVerifyAdvanceRequest;
        import com.aliyun.cloudauth20190307.models.ContrastFaceVerifyResponse;
        import com.aliyun.teaopenapi.models.Config;
        import com.aliyun.teautil.models.RuntimeOptions;
        
        import java.io.FileInputStream;
        import java.io.InputStream;
        import java.util.Arrays;
        import java.util.List;
        
        public class ContrastFaceVerifyWithVideoFile {
            // Use the singleton pattern to optimize performance.
            private static com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();
        
            public static void main(String[] args) throws Exception {
        
                // Create an API request and set the parameters.
                ContrastFaceVerifyAdvanceRequest request = new ContrastFaceVerifyAdvanceRequest();
        
                // The scene ID, suffixed with 'L'.
                request.setSceneId(1L);
        
                request.setOuterOrderNo("A unique identifier for the merchant's request");
                request.setProductCode("ID_MIN_VIDEO");
                // The liveness detection type. Fixed value.
                request.setModel("FRONT_CAMERA_LIVENESS");
                // The document type. Fixed value.
                request.setCertType("IDENTITY_CARD");
                request.setCertName("John Doe");
                request.setCertNo("xxxx");
                //request.setDeviceToken("xxxx");
                //request.setMobile("130xxxxxxxx");
                //request.setIp("114.xxx.xxx.xxx");
                //request.setUserId("12345xxxx");
                // To enable encrypted transmission of personal information.
                // request.setEncryptType("SM2");
                // request.setCertName("BCRD/7ZkNy7Q*****M1BMBezZe8GaYHrLwyJv558w==");
                // request.setCertNo("BMjsstxK3S4b1YH*****Pet8ECObfxmLN92SLsNg==");
        
                InputStream inputStream = null;
                try {
                    // Set the path to the local file.
                    inputStream = new FileInputStream("test.mp4");
                    request.setFaceContrastFileObject(inputStream);
        
                    // Recommended. Supports service routing.
                    ContrastFaceVerifyResponse response = contrastFaceVerifyAutoRoute(request);
        
                    // Does not support automatic service routing.
                    //ContrastFaceVerifyResponse response = contrastFaceVerify("cloudauth.cn-shanghai.aliyuncs.com", request);
        
                    System.out.println(response.getBody().getRequestId());
                    System.out.println(response.getBody().getCode());
                    System.out.println(response.getBody().getMessage());
                    System.out.println(response.getBody().getResultObject() == null ? null
                            : response.getBody().getResultObject().getPassed());
                    System.out.println(response.getBody().getResultObject() == null ? null
                            : response.getBody().getResultObject().getSubCode());
                    System.out.println(response.getBody().getResultObject() == null ? null
                            : response.getBody().getResultObject().getIdentityInfo());
                    System.out.println(response.getBody().getResultObject() == null ? null
                            : response.getBody().getResultObject().getMaterialInfo());
                } finally {
                    if(inputStream != null){
                        inputStream.close();
                    }
                }
            }
        
            private static ContrastFaceVerifyResponse contrastFaceVerifyAutoRoute(ContrastFaceVerifyAdvanceRequest request) {
                // The first endpoint is for the primary region, and the second is for the backup region.
                List<String> endpoints = Arrays.asList("cloudauth.cn-shanghai.aliyuncs.com", "cloudauth.cn-beijing.aliyuncs.com");
                ContrastFaceVerifyResponse lastResponse = null;
                for (int i=0; i<endpoints.size(); i++) {
                    try {
                        ContrastFaceVerifyResponse response = contrastFaceVerify(endpoints.get(i), request);
                        lastResponse = response;
        
                        // If a server-side error occurs, switch to the next region.
                        if(response != null){
                            if(500 == response.getStatusCode()){
                                continue;
                            }
                            if(response.getBody() != null){
                                if("500".equals(response.getBody().getCode())){
                                    continue;
                                }
                            }
                        }
        
                        return response;
                    } catch (Exception e) {
                        e.printStackTrace();
                        if(i == endpoints.size()-1){
                            throw new RuntimeException(e);
                        }
                    }
                }
        
                return lastResponse;
            }
        
            private static ContrastFaceVerifyResponse contrastFaceVerify(String endpoint, ContrastFaceVerifyAdvanceRequest request)
                    throws Exception {
                // An AccessKey of an Alibaba Cloud account has permissions to call all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M.
                // We strongly recommend that you do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and all resources in your account may be exposed to security risks.
                // This example uses Alibaba Cloud Credentials to read the AccessKey from environment variables for API authentication. For information about how to configure environment variables, see https://help.aliyun.com/document_detail/378657.html.
                // We recommend using the singleton pattern.
                Config config = new Config();
                config.setCredential(credentialClient);
                config.setEndpoint(endpoint);
                // Set the HTTP proxy.
                //config.setHttpProxy("http://xx.xx.xx.xx:xxxx");
                // Set the HTTPS proxy.
                //config.setHttpsProxy("http://xx.xx.xx.xx:xxxx");
                
                // We recommend using the singleton pattern.
                Client client = new Client(config);
        
                // Create a RuntimeOptions instance and set the runtime parameters.
                RuntimeOptions runtime = new RuntimeOptions();
                runtime.readTimeout = 10000;
                runtime.connectTimeout = 10000;
        
                return client.contrastFaceVerifyAdvance(request, runtime);
            }
        
        }
      • Using Object Storage Service (OSS)

        import com.aliyun.cloudauth20190307.Client;
        import com.aliyun.cloudauth20190307.models.ContrastFaceVerifyRequest;
        import com.aliyun.cloudauth20190307.models.ContrastFaceVerifyResponse;
        import com.aliyun.teaopenapi.models.Config;
        import com.aliyun.teautil.models.RuntimeOptions;
        
        import java.util.Arrays;
        import java.util.List;
        
        public class ContrastFaceVerifyWithVideoOSS {
            // Use the singleton pattern to optimize performance.
            private static com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();
        
            public static void main(String[] args) throws Exception {
        
                // Create an API request and set the parameters.
                ContrastFaceVerifyRequest request = new ContrastFaceVerifyRequest();
        
                // The scene ID, suffixed with 'L'.
                request.setSceneId(0L);
        
                request.setOuterOrderNo("A unique identifier for the merchant's request");
                request.setProductCode("ID_MIN_VIDEO");
                // The liveness detection type. Fixed value.
                request.setModel("FRONT_CAMERA_LIVENESS");
                // The document type. Fixed value.
                request.setCertType("IDENTITY_CARD");
                request.setCertName("John Doe");
                request.setCertNo("xxxx");
                //request.setDeviceToken("xxxx");
                //request.setMobile("130xxxxxxxx");
                //request.setIp("114.xxx.xxx.xxx");
                //request.setUserId("12345xxxx");
                request.setOssBucketName("xxxxx");
                request.setOssObjectName("xxxxx");
                // To enable encrypted transmission of personal information.
                // request.setEncryptType("SM2");
                // request.setCertName("BCRD/7ZkNy7Q*****M1BMBezZe8GaYHrLwyJv558w==");
                // request.setCertNo("BMjsstxK3S4b1YH*****Pet8ECObfxmLN92SLsNg==");
        
                // Recommended. Supports service routing.
                ContrastFaceVerifyResponse response = contrastFaceVerifyAutoRoute(request);
        
                // Does not support automatic service routing.
                //ContrastFaceVerifyResponse response = contrastFaceVerify("cloudauth.cn-shanghai.aliyuncs.com", request);
        
                System.out.println(response.getBody().getRequestId());
                System.out.println(response.getBody().getCode());
                System.out.println(response.getBody().getMessage());
                System.out.println(response.getBody().getResultObject() == null ? null
                        : response.getBody().getResultObject().getPassed());
                System.out.println(response.getBody().getResultObject() == null ? null
                        : response.getBody().getResultObject().getSubCode());
                System.out.println(response.getBody().getResultObject() == null ? null
                        : response.getBody().getResultObject().getIdentityInfo());
                System.out.println(response.getBody().getResultObject() == null ? null
                        : response.getBody().getResultObject().getMaterialInfo());
            }
        
            private static ContrastFaceVerifyResponse contrastFaceVerifyAutoRoute(ContrastFaceVerifyRequest request) {
                // The first endpoint is for the primary region, and the second is for the backup region.
                List<String> endpoints = Arrays.asList("cloudauth.cn-shanghai.aliyuncs.com", "cloudauth.cn-beijing.aliyuncs.com");
                ContrastFaceVerifyResponse lastResponse = null;
                for (int i=0; i<endpoints.size(); i++) {
                    try {
                        ContrastFaceVerifyResponse response = contrastFaceVerify(endpoints.get(i), request);
                        lastResponse = response;
        
                        // If a server-side error occurs, switch to the next region.
                        if(response != null){
                            if(500 == response.getStatusCode()){
                                continue;
                            }
                            if(response.getBody() != null){
                                if("500".equals(response.getBody().getCode())){
                                    continue;
                                }
                            }
                        }
        
                        return response;
                    } catch (Exception e) {
                        e.printStackTrace();
                        if(i == endpoints.size()-1){
                            throw new RuntimeException(e);
                        }
                    }
                }
        
                return lastResponse;
            }
        
            private static ContrastFaceVerifyResponse contrastFaceVerify(String endpoint, ContrastFaceVerifyRequest request)
                    throws Exception {
                // An AccessKey of an Alibaba Cloud account has permissions to call all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M.
                // We strongly recommend that you do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and all resources in your account may be exposed to security risks.
                // This example uses Alibaba Cloud Credentials to read the AccessKey from environment variables for API authentication. For information about how to configure environment variables, see https://help.aliyun.com/document_detail/378657.html.
                // We recommend using the singleton pattern.
                Config config = new Config();
                config.setCredential(credentialClient);
                config.setEndpoint(endpoint);
                // Set the HTTP proxy.
                //config.setHttpProxy("http://xx.xx.xx.xx:xxxx");
                // Set the HTTPS proxy.
                //config.setHttpsProxy("http://xx.xx.xx.xx:xxxx");
                // We recommend using the singleton pattern.
                Client client = new Client(config);
        
                // Create a RuntimeOptions instance and set the runtime parameters.
                RuntimeOptions runtime = new RuntimeOptions();
                runtime.readTimeout = 10000;
                runtime.connectTimeout = 10000;
        
                return client.contrastFaceVerifyWithOptions(request, runtime);
            }
        
        }