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
Add an authentication solution in the Captcha Management Console to obtain the key parameters:
appIdandappKey.Configure the
appIdandappKeyparameters on the server-side.After a user passes the Captcha on the client, the client generates validation parameters.
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
Send the request body in
application/x-www-form-urlencodedformat. In the sample code provided in this topic, therequestslibrary automatically encodes the request data inapplication/x-www-form-urlencodedformat.If you do not use the sample code from this topic and encounter an
illegal gen_timeerror 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 |
|
| An undefined error caused by an abnormal flow. |
|
| An invalid risk_type parameter was passed in risk control mode. |
|
| The decryption process is abnormal due to an invalid encrypted parameter. |
|
| Repeated authentication. |
|
| XSS exception. |
|
| The gen_time parameter is abnormal. Check the secondary authentication parameters and the request format. |
|
| The authentication ID is missing. |
|
| The authentication ID is invalid. |
|
| The authentication ID does not exist. |
|
| The authentication ID has been deleted. |
|
| The authentication ID has been paused. |
|
| The serial number information does not exist. The cache has expired. |
|
| The serial number is missing. |
|
| The serial number is invalid. |
|
| The serial number does not match. |
|
| The serial number has expired. |
|
| The process_token is incorrect. |
|
| The payload parameter is incorrect. |
|
| The payload parameter has expired. |