Server-side integration

更新时间:
复制 MD 格式

The Captcha service distinguishes between human and machine requests and uses graphical interactions to block abnormal machine traffic. This helps businesses identify and defend against machine traffic during operations such as registrations, flash sales, and queries. This topic describes how to use the Captcha feature by calling a server-side API.

Demo download

You can download the demo for your preferred language. Follow the instructions in the README.md file to run the demo and start the project.

Integration flow

  1. Add an authentication solution in the Captcha Management Console to obtain the key parameters: appId and appKey.

  2. Configure the appId and appKey parameters on the server-side.

  3. After a user passes the Captcha on the client, the client generates validation parameters.

  4. The server-side business API obtains the user's business request and validation parameters, generates a signature, and uploads the parameters to the secondary authentication API to validate the user's authentication.

Sample code

The following is sample code for server-side integration:

def post(self):
    # 1. Initialize the authentication key parameters.
    # Enter the appId and appKey generated after you create an authentication solution in the console.
    captcha_id = "<YOUR_APP_ID>"  # Enter your appId.
    captcha_key = "<YOUR_APP_KEY>"  # Enter your appKey.
    api_server = "https://captcha.alicaptcha.com"

    # 2. Obtain the validation parameters passed from the frontend after user authentication.
    lot_number = self.get_argument("lot_number", "")
    captcha_output = self.get_argument("captcha_output", "")
    pass_token = self.get_argument("pass_token", "")
    gen_time = self.get_argument("gen_time", "")

    # 3. Generate a signature.
    # The signature is generated using the standard HMAC algorithm. The lot_number from the user's completed authentication is used as the original message.
    # The SHA256 hash algorithm is used to perform a one-way hash on the message and key to generate the final signature.
    lotnumber_bytes = lot_number.encode()
    prikey_bytes = captcha_key.encode()
    sign_token = hmac.new(prikey_bytes, lotnumber_bytes, digestmod="SHA256").hexdigest()

    # 4. Upload the validation parameters to the secondary authentication API of the validation service to check the user's authentication status.
    query = {
        "lot_number": lot_number,
        "captcha_output": captcha_output,
        "pass_token": pass_token,
        "gen_time": gen_time,
        "sign_token": sign_token,
    }
    # We recommend appending the captcha_id parameter to the URL. This helps you quickly locate request exceptions in logs based on the ID.
    url = api_server + "/validate" + "?captcha_id={}".format(captcha_id)
    # Handle API exceptions. If the request to the secondary authentication API fails or the response status is not 200, perform the appropriate exception handling.
    # This ensures that the business flow is not blocked by request timeouts or unresponsive services.
    try:
         # The requests library automatically encodes data in the application/x-www-form-urlencoded format.
        res = requests.post(url, data=query)
        assert res.status_code == 200
        msg = json.loads(res.text)
    except Exception as e:
        msg = {"result": "success", "reason": "request api fail"}

    # 5. Implement your business logic based on the user authentication status returned by the secondary authentication API.
    if msg["result"] == "success":
        self.write({"login": "success", "reason": msg["reason"]})
    else:
        self.write({"login": "fail", "reason": msg["reason"]})

Secondary authentication API

After a user completes authentication, upload the validation parameters from your server to the secondary authentication API to validate the user's Captcha operation.

API information

Description

API endpoint

https://captcha.alicaptcha.com/validate

Protocol Support

HTTP/HTTPS

Request method

GET/POST

Request format

application/x-www-form-urlencoded

Return type

JSON

Request parameters

Important
  • Send the request body in application/x-www-form-urlencoded format. In the sample code provided in this topic, the requests library automatically encodes the request data in application/x-www-form-urlencoded format.

  • If you do not use the sample code from this topic and encounter an illegal gen_time error during debugging, check that the format of the parameters for the secondary authentication request is correct.

Request parameter

Type

Description

lot_number

String

The authentication serial number.

captcha_output

String

Verify the output.

pass_token

String

The token that indicates the authentication is passed.

gen_time

String

The timestamp when the authentication is passed.

captcha_id

String

The authentication ID.

sign_token

String

The authentication signature.

Response examples

Successful response example

{
    "status": "success", // The request status.
    "result": "success", // The result of the secondary authentication.
    "reason": "", // The description of the authentication result.
    "captcha_args": { // The authentication output parameters.
        "used_type": "icon",
        "user_ip": "127.0.0.1",
        "lot_number": "4dc3cfc2cdff448cad8d13107198d473",
        "scene": "Anti-crawler",
        "referer": "http://127.0.0.1:8077/"
        // ...
    }
}

Failed response example

{
    "status": "success", // The request status.
    "result": "fail", // The result of the secondary authentication.
    "reason": "pass_token expire", // The description of the authentication result.
    "captcha_args": { // The authentication output parameters.
        "used_type": "icon",
        "user_ip": "127.0.0.1",
        "lot_number": "4dc3cfc2cdff448cad8d13107198d473",
        "scene": "Anti-crawler",
        "referer": "http://127.0.0.1:8077/"
        // ...
    }
}

Abnormal response example

{
    "status": "error", // The request status.
    "code": "-50005", // The error code.
    "msg": "illegal gen_time", // The error message.
    "desc": { // The error description.
        "type": "defined error"
    }
}

Error codes

The following table describes the server-side error codes.

Error code

Error description

Error details

-50000

runtime error

An undefined error caused by an abnormal flow.

-50001

illegal risk_type

An invalid risk_type parameter was passed in risk control mode.

-50002

param decrypt error

The decryption process is abnormal due to an invalid encrypted parameter.

-50003

illegal verify

Repeated authentication.

-50004

jsonp xss

XSS exception.

-50005

illegal gen_time

The gen_time parameter is abnormal. Check the secondary authentication parameters and the request format.

-50101

not captcha_id

The authentication ID is missing.

-50102

illegal captcha_id

The authentication ID is invalid.

-50103

not captcha

The authentication ID does not exist.

-50104

captcha_id deleted

The authentication ID has been deleted.

-50105

captcha_id paused

The authentication ID has been paused.

-50301

not proof

The serial number information does not exist. The cache has expired.

-50302

not lot_number

The serial number is missing.

-50303

illegal lot_number

The serial number is invalid.

-50304

lot_number not match

The serial number does not match.

-50305

lot_number Expried

The serial number has expired.

-50306

process_token Error

The process_token is incorrect.

-50307

payload Error

The payload parameter is incorrect.

-50308

payload Used

The payload parameter has expired.