HTTPS native call

Updated at:

This topic describes how to integrate Financial-grade Real Person Authentication on the server-side by using HTTPS native calls.

Request details

  • service endpoint: https://saf.cn-shanghai.aliyuncs.com

  • Protocol: HTTPS

  • HTTP method: POST

  • QPS limit: Each API has a dedicated limit. See Server-side API QPS limits.

    Important

    The Financial-grade Real Person Authentication service does not currently support hard caps or automatic suspension based on the number of calls. To control costs and prevent unexpected charges, configure consumption alert rules immediately after integration:

    1. Configure consumption alerts: Set high-value consumption alerts to monitor your spending in real time.

    2. Monitor your resource plan balance: If you have purchased a resource plan, set a resource plan balance alert so you can top up the plan or adjust your call strategy promptly.

    3. Configure business monitoring: See Alert notification settings to monitor for business anomalies and request fluctuations.

Initiate an authentication request

To initiate an authentication request, pass the common parameters and include the following fields in the ServiceParameters JSON string:

Parameter

Type

Required

Description

Example

method

String

Yes

The operation to initiate a verification request.

Valid value: init.

init

sceneId

String

Yes

The verification scene ID. This ID is automatically generated after you Create a Verification Scene in the console.

10000*****

outerOrderNo

String

Yes

A unique business identifier, defined on your server-side, for issue tracking and troubleshooting.

The value must be a unique string of up to 32 letters and digits.

e0c34a77f5ac40a5aa5e6ed20c********

bizCode

String

Yes

The verification scene code. The value depends on the client used for verification:

  • When a merchant initiates authentication on the iOS or Android platform, the authentication scenario code is FACE_SDK.

  • When a merchant initiates authentication on an H5 page within a mini program, the authentication scene code is FACE.

FACE

identityType

String

Yes

The identity information type. Must be set to CERT_INFO.

CERT_INFO

certType

String

Yes

This parameter specifies the user's identity document type. For supported document types, see solution overview.

Valid values:

  • IDENTITY_CARD: Chinese mainland resident ID card and residence permits for residents of Hong Kong, Macao, and Taiwan.

  • HOME_VISIT_PERMIT_HK_MC: Mainland Travel Permit for Hong Kong and Macao Residents.

  • HOME_VISIT_PERMIT_TAIWAN: Mainland Travel Permit for Taiwan Residents.

  • PERMANENT_RESIDENCE_FOREIGNER: Foreigner's Permanent Residence Card.

IDENTITY_CARD

certNo

String

Yes

The user's ID document number. This value must correspond to the certType.

330103xxxxxxxxxxxx

certName

String

Yes

The user's name as it appears on the ID document.

Zhang San

returnUrl

String

Yes

The URL of your business page to which the user is redirected.

  • If no redirect is needed, pass an empty string.

  • To return users to your app after verification in the app-to-Alipay H5 flow, pass your app's scheme in this parameter. For more information, see Call Alipay H5 Page from an External App.

https://www.aliyun.com

callbackUrl

String

No

The callback URL to receive asynchronous verification results. It must be an HTTPS URL. After verification, the platform sends a request to this URL with the certifyId and passed parameters appended.

https://www.aliyun.com

callbackToken

String

No

A security token you provide to prevent replay attacks and tampering. If provided, this token is included in the callback request as the CallbackToken field.

NMjvQanQgplBSaEI0sL********

encryptType

String

No

The encryption type. If you leave this parameter empty, no encryption is used.

To enable encrypted transmission, you must specify an encryption algorithm. Currently, only the SM2 algorithm is supported.

If you need to pass an encryption algorithm, you must encrypt certName and certNo and then pass the resulting ciphertext.

For more information about parameter encryption, see Parameter Encryption.

Note

Currently, sample code for enabling encrypted transmission is available only for Java. For more information, see SDK call examples.

SM2

The service returns a response with the following parameters.

Parameter

Type

Required

Description

Example

certifyId

String

Yes

The authentication ID, which uniquely identifies the authentication session.

Warning

The certifyId is used for billing statistics. To facilitate bill reconciliation, you must store this ID.

The certifyId returned by the initialization API is valid for 30 minutes and can be used for only one authentication submission. It cannot be reused.

7eff3ad26a9c7b68c511b9f35eb1****

certifyUrl

String

Yes

The URL that starts the authentication flow.

Important

The certifyUrl returned by the initialization API is valid for 30 minutes and can be used for only one authentication submission. It cannot be reused.

https://picker.antcloudauth.aliyuncs.com/gateway.do?...

Sample response:

{
    "code": 200,
    "requestId": "5CD69C04-8A6B-4CC3-A0C9-D18D5FEFA788",
    "data": {
        "certifyUrl": "https://picker.antcloudauth.aliyuncs.com/gateway.do?...",
        "certifyId": "7eff3ad26a9c7b68c511b9f35eb1****"
    },
    "message": "OK"
}

Query the authentication result

To query the authentication result, pass the common parameters and include the following fields in the ServiceParameters JSON string:

Parameter

Type

Required

Description

Example

method

String

Yes

The operation to query the authentication result.

Set the value to query.

query

certifyId

String

Yes

The authentication ID. This must be the same certifyId returned by the initiation request.

7eff3ad26a9c7b68c511b9f35eb1****

sceneId

String

Yes

The authentication scenario ID. This must be the same sceneId that you passed when you initiated the authentication request.

100000*****

encToken

String

No

An AES-256 key that is encrypted with a public key and then Base64-encoded. This parameter is used to retrieve encrypted images. This feature is available only to licensed financial clients for Know Your Customer (KYC) image retention. To learn how to encrypt an AES key with an RSA public key, see Key encryption for Alipay mini program or H5 solutions.

l1tmZUQKdclKdGHzy2hljqltxPYPRo42JjRL04JVHxh9wWP19xHZpVvlKy9lxXRXCiWTKfJAaDfw4pKlZfetvZHdVdjroiXaLt7jx68rpp24wCeWo8wgjMF1lBwJmYZGcTrCVJ+Tonn7CHN7ur11Pn9d4IdkbTi5rBoOx8JITTn6krEH6ssZ5Cj3xFJ4/3PyvloU8UX+FQIPpskYR36jHcqs+Nt4EeTK/wWsAQItl6RfI9FN+8UJ42RVNt/IWHuk3U9aQNxzt7Z+7hbvqpBf/uKp4sgP6fbyYhZ+2tM+KXF1ODOYGenQ65wliaS/C1fTqjUJYcONMEW61T**********

The service returns a response with the following parameters.

Parameter

Type

Required

Description

Example

passed

String

Yes

Indicates whether the authentication passed. Valid values:

  • T: The authentication passed.

  • F: The authentication did not pass (it either failed or was not submitted).

T

identityInfo

String

No

This field is reserved and is empty by default.

N/A

materialInfo

String

No

This field is reserved and is empty by default.

N/A

Common parameters

Server-side HTTPS calls to the Financial-grade Real Person Authentication service must include the following common parameters:

Parameter

Type

Required

Description

Format

String

Yes

The format of the response. Valid values:

  • JSON (default)

  • XML

Version

String

Yes

The API version. The value is in YYYY-MM-DD format. Set this to 2017-03-31.

AccessKeyId

String

Yes

The AccessKey ID provided by Alibaba Cloud for service access. For more information, see Create an AccessKey.

Signature

String

Yes

The signature string. For information about how to calculate the signature, see Integrate the Financial-grade Real Person Authentication service.

SignatureMethod

String

Yes

The signature algorithm. Set the value to HMAC-SHA1.

Timestamp

String

Yes

The request timestamp. The value must be in the ISO 8601 format and in UTC. The format is YYYY-MM-DDThh:mm:ssZ.

Example: 2022-07-29T12:00:00Z is 20:00:00 on July 29, 2022, in Beijing time (UTC+8).

SignatureVersion

String

Yes

The signature algorithm version. Set the value to 1.0.

SignatureNonce

String

Yes

A unique random value (nonce) to prevent replay attacks. Each request must use a unique value.

Action

String

Yes

The name of the API operation. Set the value to ExecuteRequest.

Service

String

Yes

The name of the service to call. Set the value to fin_face_verify.

ServiceParameters

String

Yes

A JSON-formatted string containing the service-specific parameters. For the definitions of these parameters, see the parameter tables in the preceding sections.

Note

To use different services and features, you pass the corresponding service-specific parameters in the ServiceParameters field.

The service returns a response code. The following table lists the common response codes.

Code

Message

200

Success.

401

Invalid parameter.

402

Application configuration does not exist.

403

Account ******* is not authorized to call the fin_face_verify service. This may be because the service has expired, the traffic limit has been reached, or the service has not been purchased.

404

The authentication scenario configuration does not exist.

406

Invalid certifyId.

407

Authentication expired.

408

The authentication ticket has expired.

501

System error.

502

System busy.

503

System error.

Complete code example (Java)

Add POM dependencies:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>19.0</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
</dependency>
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>credentials-java</artifactId>
    <version>0.2.11</version>
</dependency>

The following code shows how to call the API to initiate an authentication request and query the result:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SimpleTimeZone;
import java.util.UUID;

import com.google.common.io.BaseEncoding;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;

public class SafTest {
    public static void main(String[] args) throws Throwable {
        // An Alibaba Cloud account's AccessKey has permissions for all APIs. We recommend that you use a RAM user for API calls or daily O&M.
        // For security, do not hardcode your AccessKey ID and AccessKey Secret in your project code. This can lead to the leak of your AccessKey pair and compromise the security of all resources under your account.
        // This example shows how to use the Alibaba Cloud Credentials tool to retrieve the AccessKey from environment variables for authentication. For information on how to configure environment variables, see https://help.aliyun.com/document_detail/378657.html.
        com.aliyun.credentials.Client credentialClient = new com.aliyun.credentials.Client();
        String appKey = credentialClient.getAccessKeyId();
        String appSecret = credentialClient.getAccessKeySecret();        

        // Set service-specific parameters.
        Map<String, String> serviceParameters = new HashMap<String, String>();
        // To initiate an authentication request:
        serviceParameters.put("method",  "init");
        serviceParameters.put("sceneId",  "100000****");
        serviceParameters.put("outerOrderNo",  "e0c34a77f5ac40a5aa5e6ed20c35****");
        serviceParameters.put("bizCode", "FACE");
        serviceParameters.put("identityType", "CERT_INFO");
        serviceParameters.put("certType", "IDENTITY_CARD");
        serviceParameters.put("certNo", "1******************9");
        serviceParameters.put("certName", "John Doe");
        serviceParameters.put("returnUrl", "https://www.aliyun.com");

        /*
        // To enable encryption for personal information:
        serviceParameters.put("encryptType", "SM2");
        serviceParameters.put("certNo", "BMjsstxK3S4b1YH*****Pet8ECObfxmLN92SLsNg==");
        serviceParameters.put("certName", "BCRD/7ZkNy7Q*****M1BMBezZe8GaYHrLwyJv558w==");
        */

        /*
        // To query the authentication result:
        serviceParameters.put("method",  "query");
        serviceParameters.put("certifyId", "7eff3ad26a9c7b68c511b9f35eb1****");
        serviceParameters.put("sceneId", "100000****");
        */

        Map<String, String> params = new HashMap<>();
        // API service name. The value is fixed as fin_face_verify.
        params.put("Service", "fin_face_verify");

        // Add the service-specific parameters. The service parameters are passed as a JSON-formatted string.
        params.put("ServiceParameters", com.alibaba.fastjson.JSON.toJSONString(serviceParameters));

        doPOPRequest(appKey, appSecret, safUrl, "ExecuteRequest", "2017-03-31", params);
    }

    public static String doPOPRequest(String appKey, String appSecret, String url, String action, String version, Map<String, String> parameters) throws Throwable {
        String encoding = "UTF-8";
        Map<String, String> paramsForPOP = new HashMap<>();

        // Set common parameters.
        paramsForPOP.put("AccessKeyId", appKey);
        paramsForPOP.put("Format", "JSON");
        paramsForPOP.put("SignatureMethod", "HMAC-SHA1");
        paramsForPOP.put("Timestamp", formatIso8601Date(new Date()));// The format must be YYYY-MM-DDThh:mm:ssZ.
        paramsForPOP.put("SignatureVersion", "1.0");
        paramsForPOP.put("SignatureNonce", UUID.randomUUID().toString());// Generate a unique random value for each request.
        paramsForPOP.put("Version", version);
        paramsForPOP.put("Action", action);

        if (parameters != null) {
            parameters.remove("Signature");
            paramsForPOP.putAll(parameters);
        }

        String signature = computeSignature(paramsForPOP, appSecret, encoding);
        paramsForPOP.put("Signature", signature);// Append the signature to the POST parameters.

        String result = httpPost(url, paramsForPOP, encoding);
        // Print the response.
        System.out.println(result);
        return result;
    }

    private static String httpPost(String url, Map<String, String> paramsForPOP, String encoding) throws IOException {

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);

        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        for (Entry<String, String> entry: paramsForPOP.entrySet()) {
            urlParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(urlParameters, Consts.UTF_8));
        CloseableHttpResponse response = httpClient.execute(httpPost);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        return result.toString();
    }

    private static String formatIso8601Date(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        df.setTimeZone(new SimpleTimeZone(0, "GMT"));// Use GMT time.
        return df.format(date);
    }

    public static String computeSignature(Map<String, String> parameters, String secret, String encoding)
        throws Exception {
        // Sort the parameter keys in alphabetical order.
        String[] sortedKeys = parameters.keySet().toArray(new String[] {});
        Arrays.sort(sortedKeys);

        String separator = "&";
        boolean first = true;

        // Generate the canonicalized query string.
        StringBuilder sb = new StringBuilder();
        for (String key : sortedKeys) {
            if (first) {
                first = false;
            } else {
                sb.append("&");
            }

            sb.append(encode(key, encoding)).append("=").append(encode(parameters.get(key), encoding));
        }

        // Generate the string-to-sign.
        StringBuilder toSign = new StringBuilder();
        toSign.append("POST").append(separator);
        toSign.append(encode("/", encoding)).append(separator);
        toSign.append(encode(sb.toString(), encoding));

        return getSignature("HmacSHA1", (secret + separator).getBytes(encoding), toSign.toString().getBytes(encoding));
    }

    private static String encode(String value, String encoding) throws UnsupportedEncodingException {
        if (value == null) { return null; }

        // After encoding with URLEncoder.encode, replace "+", "*", and "%7E" to meet the API's encoding specifications.
        return URLEncoder.encode(value, encoding).replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
    }

    public static String getSignature(String algorithm, byte[] secret, byte[] data) {
        try {
            javax.crypto.Mac mac = javax.crypto.Mac.getInstance(algorithm);
            mac.init(new javax.crypto.spec.SecretKeySpec(secret, algorithm));

            return BaseEncoding.base64().encode(mac.doFinal(data));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}